Repository navigation
Conversation
There was a problem hiding this comment.
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.
| 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]; |
There was a problem hiding this comment.
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.
| 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]!; |
There was a problem hiding this comment.
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.
| (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], |
There was a problem hiding this comment.
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.
| (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, |
There was a problem hiding this comment.
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.
| 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); |
There was a problem hiding this comment.
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.
| 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); | |
| } |
There was a problem hiding this comment.
_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.
| if (arguments is! Map<String, Object>) { | ||
| throw _Failure( | ||
| ExpansionErrorKind.invalidValue, | ||
| 'The arguments of call are not a map.', | ||
| ); | ||
| } |
There was a problem hiding this comment.
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.
| 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.', | |
| ); | |
| } |
There was a problem hiding this comment.
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.
| 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), | ||
| }, |
There was a problem hiding this comment.
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.
| 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!), | |
| }, |
There was a problem hiding this comment.
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.
330fe61 to
f5434ee
Compare
f5434ee to
cb39096
Compare
cb39096 to
44bb03b
Compare
44bb03b to
54d0d39
Compare
54d0d39 to
8d18efb
Compare
ditman
left a comment
There was a problem hiding this comment.
🤖 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:
_setStatedoesn't checkregistry.generationon reload (runtime.dart): If a template's library is registered again inTemplateRegistryand a previously expandedSetStateValueis fired beforeexpand()(orrefresh(), which #39 updates to prune stale instances),_setStatestill mutates the stale instance and reportsstateChanged: true. Checkingowner.generation != registry.generation(owner.widget.library)inside_setStatemakes stale setters fail immediately withunknownState.- Post-stack barrel tightening reminder (
lib/a2ui_craft.dart): Per our agreement on #23, please includesrc/evaluator.dart,src/expansion.dart, andsrc/runtime.dartin the post-stack barrel-tightening PR (#39hidescheckCallArgumentsbut still leavesinvokeFunction,canonicalExpansionValue,widgetNameString, andexpansion.dart/runtime.dartwildcard-exported). isRunnableHandlerandfireonly matchList<Object>, notList<Object?>(runtime.dart): Unlike internal_Passcollections, these are public entrypoints; passing aList<Object?>/List<dynamic>from a host or adapter silently returnsfalse/ does nothing.- Uncaught
FormatExceptionon non-valueinitialState(runtime.dart):_instancecallstoValue(declaration.initialState)without convertingFormatExceptioninto_Failure(ExpansionErrorKind.invalidValue, ...), so a programmatic/binaryinitialStatecontaining a non-value (e.g. aDataReferenceAST node orObject()) escapes_Pass.guard. - Mutable internal state exposed (
runtime.dart,expansion.dart):CraftRuntime.args/datareturn mutable internal collections directly (bypassing validation and_notify()if mutated), andStateInstance.valueis 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.)
| 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.', | ||
| ); |
There was a problem hiding this comment.
🤖 _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.
| 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'; |
There was a problem hiding this comment.
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).
| bool isRunnableHandler(Object? value) => switch (value) { | ||
| EventValue() || SetStateValue() || HostHandler() => true, | ||
| HandlerCallValue() => isRunnableHandler(value.handler), | ||
| List<Object>() => value.any(isRunnableHandler), | ||
| _ => false, | ||
| }; |
There was a problem hiding this comment.
🤖 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');
});| toValue(declaration.initialState) as Map<String, Object>, | ||
| ); | ||
| } | ||
|
|
||
| static String _instanceKey( | ||
| ExpansionPath path, | ||
| FullyQualifiedWidgetName widget, |
There was a problem hiding this comment.
🤖 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,
),
);
});|
|
||
| /// 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); | ||
|
|
There was a problem hiding this comment.
🤖 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,
);
});| /// 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; |
There was a problem hiding this comment.
🤖 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.
8d18efb to
649492a
Compare
649492a to
dc76c72
Compare
dc76c72 to
ed7d805
Compare
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>
ed7d805 to
9a7accc
Compare
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.
craft/blueprints/features/craft_runtime.blueprint.md.lib/src/runtime.dart,expansion.dart):CraftRuntimeproduces a canonical expansion tree, so any engine can check the runtime's behavior without a UI framework:call, setters and events have defined order and argument precedence;craft/conformance/craft/craft_runtime.yaml, written as scenarios (expand, then data updates and events, with the expected tree after each), plus unit tests.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:
python3 ./scripts/fix_licenses.py --check)../scripts/fix_format.sh --check).