Skip to content

feat(craft): add the framework-independent runtime - #29

Open
innkuika wants to merge 1 commit into
mainfrom
craft/engine-runtime
Open

innkuika wants to merge 1 commit into
mainfrom
craft/engine-runtime

Conversation

@innkuika

@innkuika innkuika commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Description

Adds the runtime to the Craft engine core: it expands a template, with its arguments, data and local state, into a tree of host primitives, and handles events. Stacked on #28. Same three parts as the other engine PRs: a blueprint, conformance cases and the code. The Flutter adapter that renders this tree is the next PR.

  • Blueprint: craft/blueprints/features/craft_runtime.blueprint.md.
  • Framework-independent expansion (lib/src/runtime.dart, expansion.dart): CraftRuntime produces a canonical expansion tree, so any engine can check the runtime's behavior without a UI framework:
    • nodes for widgets (fully evaluated arguments), errors, builders, events, state setters, handler calls and host handlers;
    • templates leave no node of their own, and positions are paths;
    • the output also lists local states and errors.
  • Semantics:
    • template arguments are evaluated lazily, in the caller's scope;
    • an error replaces only the innermost primitive whose arguments failed, and is reported, never thrown;
    • recursion through other templates is detected;
    • local state belongs to a template instance by position. It survives data and argument updates and resets when its library is registered again;
    • handler lists, call, setters and events have defined order and argument precedence;
    • switches use the equality rules from the functions feature.
  • Fixes carried over from the prototype: handler lists keep host callbacks; state survives a data update and resets on reload; a null list item renders as absent.
  • Tests: 67 conformance cases in craft/conformance/craft/craft_runtime.yaml, written as scenarios (expand, then data updates and events, with the expected tree after each), plus unit tests.
  • Not in this PR: keyed state for reordered items (state follows position, as in Flutter without keys), theme and media references (later features), depth limits (limits).

The behavior follows RFW's runtime and Yegor's prototype runtime, hence the co-author. An independent review checked the blueprint against the tests and the code, including mutations.

Pre-launch Checklist

One time:

For this PR:

  • I updated/added relevant documentation.
  • My code changes (if any) have tests.
  • License checks pass (python3 ./scripts/fix_licenses.py --check).
  • Format checks pass (./scripts/fix_format.sh --check).

@innkuika innkuika mentioned this pull request Nov 21, 2026
6 tasks done

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request implements the framework-independent 'Runtime' feature for the Craft engine, expanding templates into a tree of primitive calls and managing local state and event firing. It includes the feature specification, conformance test cases, Dart implementation, and unit tests. The review feedback highlights several critical type-safety issues where strict type checks on Map<String, Object> and List in pattern matching, property lookups, and serialization could cause unexpected runtime failures when dealing with nullable reified types (e.g., from JSON decoding). It is recommended to update these checks to use Object? as suggested.

Comment on lines +309 to +316
case (final Map<String, Object> map, final String key)
when map.containsKey(key):
if (last) map[key] = value;
current = map[key]!;
case (final List<Object> list, final int index)
when index >= 0 && index < list.length:
if (last) list[index] = value;
current = list[index];

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Using Map<String, Object> and List<Object> in pattern matching is fragile because if any nested map or list is reified as Map<String, Object?> or List<Object?> (which is common for host-provided data or decoded JSON), the pattern match will fail and return unknownState. Using Map<String, Object?> and List<Object?> makes the pattern matching robust and prevents unexpected runtime failures.

Suggested change
case (final Map<String, Object> map, final String key)
when map.containsKey(key):
if (last) map[key] = value;
current = map[key]!;
case (final List<Object> list, final int index)
when index >= 0 && index < list.length:
if (last) list[index] = value;
current = list[index];
case (final Map<String, Object?> map, final String key)
when map.containsKey(key):
if (last) map[key] = value;
current = map[key]!;
case (final List<Object?> list, final int index)
when index >= 0 && index < list.length:
if (last) list[index] = value;
current = list[index]!;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The state being walked is toValue(owner.value) (two lines above) and the new value is toValue(...), so nested collections always have these exact types. Tested with a host function that returns jsonDecode output, then a deep set into it.

Comment on lines +706 to +710
(final Map<String, Object> map, final String key) =>
map[key] ?? missing,
(final List<Object> list, final int index)
when index >= 0 && index < list.length =>
list[index],

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Using Map<String, Object> and List<Object> in _read will cause property lookups to silently fail and return missing if any nested map or list is reified as Map<String, Object?> or List<Object?>. Using Map<String, Object?> and List<Object?> ensures robust property resolution.

Suggested change
(final Map<String, Object> map, final String key) =>
map[key] ?? missing,
(final List<Object> list, final int index)
when index >= 0 && index < list.length =>
list[index],
(final Map<String, Object?> map, final String key) =>
map[key] ?? missing,
(final List<Object?> list, final int index)
when index >= 0 && index < list.length =>
list[index] ?? missing,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Every root _read sees is converted first: args, data, builder arguments, state and function results all go through _hostValue/toValue. Reads through jsonDecode args and data work in a test.

Comment on lines +720 to +726
case List<Object>():
for (final Object e in value) {
_values(e, handlers: handlers);
}
case Map<String, Object>():
for (final Object e in value.values) {
_values(e, handlers: handlers);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Using List<Object> and Map<String, Object> in _values will cause the validation to silently skip elements of any list or map reified as List<Object?> or Map<String, Object?>. This allows invalid nested values (like widgets or builders) to bypass validation. Using List<Object?> and Map<String, Object?> ensures all nested values are correctly validated.

Suggested change
case List<Object>():
for (final Object e in value) {
_values(e, handlers: handlers);
}
case Map<String, Object>():
for (final Object e in value.values) {
_values(e, handlers: handlers);
case List<Object?>():
for (final Object? e in value) {
if (e != null) _values(e, handlers: handlers);
}
case Map<String, Object?>():
for (final Object? e in value.values) {
if (e != null) _values(e, handlers: handlers);
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_values only sees results of eval, whose collections are built as List<Object>/Map<String, Object> or come from converted input, which can't hold widgets or builders.

Comment on lines +758 to +763
if (arguments is! Map<String, Object>) {
throw _Failure(
ExpansionErrorKind.invalidValue,
'The arguments of call are not a map.',
);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Checking arguments is! Map<String, Object> will throw an invalidValue exception if the arguments map is reified as Map<String, Object?>, even if it is a valid map. Checking arguments is! Map<String, Object?> prevents this unexpected failure.

Suggested change
if (arguments is! Map<String, Object>) {
throw _Failure(
ExpansionErrorKind.invalidValue,
'The arguments of call are not a map.',
);
}
if (arguments is! Map<String, Object?>) {
throw _Failure(
ExpansionErrorKind.invalidValue,
'The arguments of call are not a map.',
);
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

arguments comes from eval, which builds map literals as Map<String, Object> and reads converted values, so a Map<String, Object?> can't reach this check.

Comment on lines +285 to +291
List<Object>() => <Object?>[
for (final Object e in value) canonicalExpansionValue(e),
],
Map<String, Object>() => <String, Object?>{
for (final MapEntry<String, Object> e in value.entries)
e.key: canonicalExpansionValue(e.value),
},

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Using List<Object> and Map<String, Object> in canonicalExpansionValue will cause any list or map reified as List<Object?> or Map<String, Object?> to fall through to canonicalValue, which does not know how to serialize expansion nodes like WidgetNode or ErrorNode and will fail. Using List<Object?> and Map<String, Object?> ensures correct serialization.

Suggested change
List<Object>() => <Object?>[
for (final Object e in value) canonicalExpansionValue(e),
],
Map<String, Object>() => <String, Object?>{
for (final MapEntry<String, Object> e in value.entries)
e.key: canonicalExpansionValue(e.value),
},
List<Object?>() => <Object?>[
for (final Object? e in value) if (e != null) canonicalExpansionValue(e),
],
Map<String, Object?>() => <String, Object?>{
for (final MapEntry<String, Object?> e in value.entries)
if (e.value != null) e.key: canonicalExpansionValue(e.value!),
},

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Inputs are the runtime's own expansion output and template arguments, both built with these exact types. Also, the suggestion would silently drop nulls from lists.

@innkuika
innkuika force-pushed the craft/engine-runtime branch from 330fe61 to f5434ee Compare November 23, 2026 21:00
@innkuika
innkuika force-pushed the craft/engine-runtime branch from f5434ee to cb39096 Compare November 23, 2026 22:05
@innkuika
innkuika force-pushed the craft/engine-runtime branch from cb39096 to 44bb03b Compare November 23, 2026 23:19
@innkuika
innkuika marked this pull request as ready for review November 24, 2026 23:11
@innkuika
innkuika requested a review from ditman November 24, 2026 23:11
@innkuika
innkuika force-pushed the craft/engine-runtime branch from 44bb03b to 54d0d39 Compare December 1, 2026 19:56
@innkuika
innkuika added this pull request to stack #51 December 1, 2026 19:57
@innkuika
innkuika force-pushed the craft/engine-runtime branch from 54d0d39 to 8d18efb Compare December 1, 2026 20:35
@ditman ditman mentioned this pull request Dec 2, 2026
6 tasks done

@ditman ditman left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Really clean framework-independent runtime — lazy caller-scoped template arguments, innermost-primitive error isolation, document-order state/error tracking, and 67 scenario-based conformance cases make the semantics easy to verify without a UI framework.

A few items to address:

  1. _setState doesn't check registry.generation on reload (runtime.dart): If a template's library is registered again in TemplateRegistry and a previously expanded SetStateValue is fired before expand() (or refresh(), which #39 updates to prune stale instances), _setState still mutates the stale instance and reports stateChanged: true. Checking owner.generation != registry.generation(owner.widget.library) inside _setState makes stale setters fail immediately with unknownState.
  2. Post-stack barrel tightening reminder (lib/a2ui_craft.dart): Per our agreement on #23, please include src/evaluator.dart, src/expansion.dart, and src/runtime.dart in the post-stack barrel-tightening PR (#39 hides checkCallArguments but still leaves invokeFunction, canonicalExpansionValue, widgetNameString, and expansion.dart/runtime.dart wildcard-exported).
  3. isRunnableHandler and fire only match List<Object>, not List<Object?> (runtime.dart): Unlike internal _Pass collections, these are public entrypoints; passing a List<Object?> / List<dynamic> from a host or adapter silently returns false / does nothing.
  4. Uncaught FormatException on non-value initialState (runtime.dart): _instance calls toValue(declaration.initialState) without converting FormatException into _Failure(ExpansionErrorKind.invalidValue, ...), so a programmatic/binary initialState containing a non-value (e.g. a DataReference AST node or Object()) escapes _Pass.guard.
  5. Mutable internal state exposed (runtime.dart, expansion.dart): CraftRuntime.args/data return mutable internal collections directly (bypassing validation and _notify() if mutated), and StateInstance.value is a public mutable field despite its doc saying only the runtime replaces it.

(Noted that nested ...for/...if flattening and expansion error locations are already queued in #38, and CraftRuntime.refresh() state pruning on reload is in #39, so those aren't repeated here.)

Comment on lines +292 to +300
FireErrorKind.unknownState,
'The template instance is no longer expanded.',
);
}
if (setter.value is Missing) {
return FireError(
FireErrorKind.absentValue,
'state.${parts.join('.')} was not set to an absent value.',
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 _setState checks identical(_instances[...], owner), but does not check whether the declaring library's generation has changed in registry.

If a host re-registers the template's library and fires a SetStateValue from the previous expansion before calling expand() (or refresh(), which #39 updates to prune stale instances), _setState still mutates the stale instance, sets stateChanged: true, and notifies listeners.

Reproducer:

test('firing a setter after library reload fails even before expand/refresh', () {
  final TemplateRegistry registry = _registry(
    parseLibraryFile(
      'import core; widget root { n: 0 } = Button(onPressed: set state.n = 1);',
    ),
  );
  final CraftRuntime runtime = CraftRuntime(registry, library: _main, widget: 'root');
  final WidgetNode button = runtime.expand().root as WidgetNode;
  final Object setter = button.arguments['onPressed']!;

  // Reload the library without calling expand() or refresh() yet:
  registry.setTemplateLibrary(
    _main,
    parseLibraryFile(
      'import core; widget root { n: 0 } = Button(onPressed: set state.n = 1);',
    ),
  );

  final FireResult result = runtime.fire(setter);
  expect(result.stateChanged, isFalse);
  expect(result.errors.single.kind, FireErrorKind.unknownState);
});

Adding owner.generation != registry.generation(owner.widget.library) to the guard here ensures stale setters are rejected immediately on reload regardless of whether refresh() was wired up.

Comment on lines 20 to 31
export 'src/canonical_json.dart';
export 'src/dependencies.dart';
export 'src/evaluator.dart';
export 'src/expansion.dart';
export 'src/functions.dart';
export 'src/name_resolution.dart';
export 'src/rfw/binary.dart';
export 'src/rfw/model.dart';
export 'src/rfw/text.dart';
export 'src/runtime.dart';
export 'src/standard_functions.dart';
export 'src/template_registry.dart';

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reminder for the post-stack barrel-tightening pass agreed in #23: please include src/evaluator.dart, src/expansion.dart, and src/runtime.dart when switching lib/a2ui_craft.dart to explicit show lists.

In this PR, promoting checkCallArguments and invokeFunction to top-level functions in src/evaluator.dart and adding bare export 'src/expansion.dart'; / export 'src/runtime.dart'; leaks internal/conformance helpers (checkCallArguments, invokeFunction, canonicalExpansionValue, widgetNameString) onto package:a2ui_craft/a2ui_craft.dart (#39 only hides checkCallArguments and leaves invokeFunction and the rest wildcard-exported).

Comment on lines +99 to +104
bool isRunnableHandler(Object? value) => switch (value) {
EventValue() || SetStateValue() || HostHandler() => true,
HandlerCallValue() => isRunnableHandler(value.handler),
List<Object>() => value.any(isRunnableHandler),
_ => false,
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Unlike internal _Pass collections, isRunnableHandler(Object? value) (and fire(Object handler, ...) at line 276) are public APIs that hosts/adapters may call with a List<Object?> or List<dynamic> (for example [eventValue] inferred as List<Object?>). Matching List<Object?>() here and in fire (skipping null entries in fire) avoids silently treating such lists as non-runnable / no-ops.

Regression test for test/runtime_test.dart (fails on the current branch, passes once fixed):

test('isRunnableHandler and fire accept List<Object?> handler lists', () {
  final CraftRuntime runtime = _parsed(
    'import core; widget root = Button(onPressed: event "tap" {});',
  );
  final WidgetNode button = runtime.expand().root as WidgetNode;
  final List<Object?> handlers = <Object?>[button.arguments['onPressed']];

  expect(isRunnableHandler(handlers), isTrue);
  final FireResult result = runtime.fire(handlers);
  expect(result.events, hasLength(1));
  expect((result.events.single as TemplateEvent).name, 'tap');
});

Comment on lines +352 to +358
toValue(declaration.initialState) as Map<String, Object>,
);
}

static String _instanceKey(
ExpansionPath path,
FullyQualifiedWidgetName widget,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 If declaration.initialState (from a binary or programmatically constructed WidgetDeclaration) contains a non-value such as a DataReference AST node or an arbitrary Object(), toValue(declaration.initialState) throws a FormatException. Because _Pass.guard only catches _Failure and EvaluationException, that FormatException escapes expand() instead of producing an ErrorNode.

Catching FormatException here and throwing _Failure(ExpansionErrorKind.invalidValue, ...) keeps expand() consistent with the blueprint's guarantee that template expansion failures become error nodes rather than throwing.

Regression test for test/runtime_test.dart (throws uncaught FormatException on the current branch, passes once fixed):

test('non-value initialState produces an invalidValue ErrorNode', () {
  final CraftRuntime runtime = _boxOf(
    0,
    state: <String, Object?>{'x': const DataReference(<Object>['a'])},
  );
  final Expansion expansion = runtime.expand();
  expect(
    expansion.root,
    isA<ErrorNode>().having(
      (ErrorNode e) => e.kind,
      'kind',
      ExpansionErrorKind.invalidValue,
    ),
  );
});

Comment on lines +144 to +155

/// The data that `data.` references read: a value.
Object get data => _data;
set data(Object? value) {
_data = _hostData(value);
_notify();
}

/// Calls [listener] whenever an expansion may have changed: after a change
/// of [args] or [data], a [fire] that set state, and [refresh].
void addListener(void Function() listener) => _listeners.add(listener);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Minor: args and data return the internal mutable _args and _data collections directly, so mutating runtime.args['x'] = ... bypasses _hostArguments validation and skips _notify(). Wrapping _args (e.g. Map<String, Object>.unmodifiable) or documenting them as read-only would prevent accidental misuse.

Regression test for test/runtime_test.dart (fails on the current branch, passes once wrapped in unmodifiable views):

test('args and data getters cannot be mutated directly', () {
  final CraftRuntime runtime = CraftRuntime(
    _registry(parseLibraryFile('import core; widget root = Box(value: args.x);')),
    library: _main,
    widget: 'root',
    args: <String, Object?>{'x': 1},
    data: <String, Object?>{'y': 2},
  );
  expect(() => runtime.args['x'] = 99, throwsUnsupportedError);
  expect(
    () => (runtime.data as Map<String, Object>)['y'] = 99,
    throwsUnsupportedError,
  );
});

Comment on lines +123 to +125
/// The current state. The runtime replaces it, never changes it in place,
/// so an expansion that read it keeps what it read.
Map<String, Object> value;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Minor: StateInstance.value is a public mutable field even though the doc comment says only the runtime replaces it. If StateInstance is exported from the package, consider making value a read-only getter externally (or keeping StateInstance internals off the public barrel) so external callers can't mutate state in place and break expansion snapshots.

Adds the craft_runtime feature: expanding a template, with its
arguments, data and local state, into a tree of primitive calls, and
firing the handlers in that tree.

- craft/blueprints/features/craft_runtime.blueprint.md: the expansion
  and its canonical JSON form (primitive, error and builder nodes,
  handler nodes, paths), primitive and template calls (arguments
  evaluated on first read in the scope of the call), references, loops
  and `...if`, switches, handlers (event, set state, `call`, host
  handlers, handler lists), firing, local state (per path and template;
  kept across data updates, reset when the template's library is
  registered again), widget builders, errors as placeholder nodes at the
  innermost widget, and updates.
- craft/conformance/craft/craft_runtime.yaml: 67 cases, each an initial
  expansion and steps (fire a value at a path, replace data or
  arguments, register a library again, expand a builder's output),
  checking the canonical tree, states, errors and emitted events.
- packages/a2ui_craft: lib/src/expansion.dart (nodes and canonical form)
  and lib/src/runtime.dart (CraftRuntime); evaluator.dart now shares
  checkCallArguments and invokeFunction with the runtime, and
  TemplateRegistry counts each library name's registrations (generation),
  so state resets even when the same library object is registered again.
  Unit tests cover nodes only the binary format can hold, host input,
  reloads, notifications and snapshots.
- craft_functions.blueprint.md: says that no feature defines theme
  references yet; the module layer table describes the runtime's output.
- Conformance: the expand_template action (runtime_engine.dart, which
  later suites share) and the F-CRAFT-RT-01 to 13 feature IDs.

The code is new. Its semantics follow RFW 2.0.0's runtime and the Craft
prototype's runtime, including the prototype's fixes: handler lists keep
host callbacks, state survives a data update and resets on a template
reload, and a null list item is absent. Unlike both, the runtime builds no
widgets; a framework adapter renders the expansion.

Co-authored-by: Yegor <yegor.jbanov@gmail.com>
@innkuika
innkuika force-pushed the craft/engine-runtime branch from ed7d805 to 9a7accc Compare December 3, 2026 19:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants