Repository navigation
feat(craft): add functions and the standard library - #27
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces the 'Functions' feature blueprint along with its complete Dart implementation, including the evaluator, function registry, standard functions, and extensive conformance and unit tests. The feedback suggests replacing the platform-dependent String.trim() with a custom RegExp-based trim to ensure U+FEFF is correctly removed as required by the blueprint, and removing a redundant null assertion operator in functions.dart for cleaner code.
| implementation: (DynamicMap arguments) => | ||
| '${_display(arguments['a'])}${_display(arguments['b'])}', | ||
| ), | ||
| 'trim': _unaryString((String s) => s.trim()), |
There was a problem hiding this comment.
Relying on the platform-dependent String.trim() is risky and violates the deterministic requirement of the blueprint. On the Dart VM, String.trim() does not remove U+FEFF (BOM), whereas the blueprint explicitly requires U+FEFF to be removed. To ensure exact compliance and platform-independence across VM, JS, and Wasm, use a custom RegExp-based trim.
| 'trim': _unaryString((String s) => s.trim()), | |
| 'trim': _unaryString((String s) => s.replaceAll(RegExp(r'^[\u0009-\u000D\u0020\u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]+|[\u0009-\u000D\u0020\u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]+$'), '')), |
There was a problem hiding this comment.
Dart's String.trim() strips exactly the blueprint's set, U+FEFF included. A test of every listed character (and the three that must be kept) passes on the VM and on JS, and the conformance suite covers each character on its own.
| List<Object?>() => <Object>[for (final Object? e in value) toValue(e)], | ||
| Map<Object?, Object?>() when isStringKeyed(value) => <String, Object>{ | ||
| for (final MapEntry<Object?, Object?> e in value.entries) | ||
| e.key! as String: toValue(e.value), |
There was a problem hiding this comment.
There was a problem hiding this comment.
Agreed, dropped the ! in the latest push (and the same pattern in limits.dart in #33).
13f415a to
ac61ad5
Compare
ac61ad5 to
772423d
Compare
772423d to
e25b368
Compare
e25b368 to
b6bb163
Compare
b6bb163 to
818fac0
Compare
ditman
left a comment
There was a problem hiding this comment.
🤖 Really well-structured evaluator and standard library — the strict untrusted-input containment, exact numeric model, and 103-case conformance suite (including JS-checked concat formatting and per-character trim coverage) are great.
One High-priority dart2js bug to fix before landing, plus a few smaller items:
- Infinite recursion on
dart2jsincompareNumbers(lib/src/functions.dart): Underdart2js, every integer is also adouble(1 is int == trueand2 is double == true), socompareNumbers(1, 2)entersif (a is int && b is double) return -compareNumbers(b, a);and recurses infinitely untilRangeError: Maximum call stack size exceeded. This crashes every integer/whole-number comparison (equals,notEquals,min,max,greaterThan,lessThan,greaterThanOrEqual,lessThanOrEqual,contains,listWith,listWithout) when compiled withdart compile js. CI didn't catch it becausedart compile jsonly checks compilation whiledart testruns on the VM. _toInteger(round/floor/ceil) andabsondart2js(lib/src/standard_functions.dart): Because1e20 is intistrueondart2js,_toInteger(1e20, ...)returns1e20instead ofnull(bypassing the 64-bit range check), andabs(-9223372036854775808.0)returnsnullinstead of9223372036854775808.0.- Post-stack barrel tightening reminder (
lib/a2ui_craft.dart): Per our agreement on #23, please includesrc/evaluator.dart,src/functions.dart, andsrc/standard_functions.dartin the post-stack barrel-tightening PR (#39still leavesfunctions.dartandstandard_functions.dartas bare wildcards, leaking 6 internal value helpers onto the public barrel). - Minor
FunctionRegistry/valueEqualsnits:standardkeys aren't validated likehostkeys (regression test inline), and unintentionally exportingvalueEqualsfrom the main barrel exposes aMap<dynamic, dynamic>vs.Map<String, Object?>mismatch (keeping barrel exports minimal makes this a non-issue).
| int compareNumbers(num a, num b) { | ||
| if (a is int && b is double) return -compareNumbers(b, a); | ||
| if (a is double && b is int) { | ||
| if (a.isInfinite) return a > 0 ? 1 : -1; | ||
| final double floor = a.floorToDouble(); | ||
| final int whole = BigInt.from(floor).compareTo(BigInt.from(b)); | ||
| if (whole != 0) return whole; | ||
| return a > floor ? 1 : 0; | ||
| } | ||
| return a < b ? -1 : (a > b ? 1 : 0); | ||
| } |
There was a problem hiding this comment.
🤖 High (crash on dart2js): Under dart2js, int and double are both JavaScript numbers, so for any integer (or whole-number double), a is int is true and b is double is true.
Tracing compareNumbers(1, 2) on dart2js:
a = 1(is int == true),b = 2(is double == true) → enters line 178 → calls-compareNumbers(2, 1).a = 2(is int == true),b = 1(is double == true) → enters line 178 again → calls-compareNumbers(1, 2).- Unconditional infinite recursion →
RangeError: Maximum call stack size exceeded.
This breaks every numeric comparison and equality call (greaterThan, lessThan, greaterThanOrEqual, lessThanOrEqual, min, max, equals, notEquals, contains, listWith, listWithout) when compiled with dart compile js. CI passes only because presubmit-craft.yml runs dart compile js without executing tests on JS.
On dart2js, all num values are already IEEE-754 doubles, so </> is exact without BigInt:
int compareNumbers(num a, num b) {
if (identical(1, 1.0)) return a < b ? -1 : (a > b ? 1 : 0);
if (a is int && b is double) return -compareNumbers(b, a);
...
}Regression test for test/functions_test.dart (fails with RangeError: Maximum call stack size exceeded under dart compile js / dart test -p chrome before fix, passes after):
test('compareNumbers and numeric comparisons do not recurse infinitely on dart2js', () {
expect(compareNumbers(1, 2), -1);
expect(compareNumbers(2, 1), 1);
expect(compareNumbers(1, 1.0), 0);
expect(
_evaluate(_call('greaterThan', const <String, Object?>{'a': 1, 'b': 2})),
isFalse,
);
expect(
_evaluate(_call('equals', const <String, Object?>{'a': 1, 'b': 1})),
isTrue,
);
});There was a problem hiding this comment.
Fixed in 34b8712: on JavaScript numbers now compare as doubles (exact there), so equals, min/max, the ordering functions and contains/listWith/listWithout no longer recurse; your regression test is in. To keep this class of bug out, 1c6cf94 adds a CI step that runs a2ui_craft's tests with dart test -p node (cases that depend on int/double distinctions or integers beyond 2^53 are listed as JS-only skips, checked on the VM).
| int? _toInteger(num a, double Function(double) round) { | ||
| if (a is int) return a; | ||
| final double rounded = round(a as double); | ||
| if (!rounded.isFinite || rounded < -_twoTo63 || rounded >= _twoTo63) { | ||
| return null; | ||
| } | ||
| return rounded.toInt(); | ||
| } |
There was a problem hiding this comment.
🤖 Another dart2js is int edge case: on dart2js, any integral double like 1e20 or 9223372036854775808.0 (2^63) satisfies a is int == true, so line 152 returns a directly and bypasses the 64-bit range check (rounded < -_twoTo63 || rounded >= _twoTo63). As a result, round(1e20), floor(1e20), and ceil(1e20) return 1e20 instead of absent on dart2js.
Guarding line 152 with if (!identical(1, 1.0) && a is int) return a; keeps the VM/dart2wasm fast path while ensuring dart2js still enforces the 64-bit range check. (Note: abs(-9223372036854775808.0) on line 36 has the dual issue on dart2js, returning null instead of 9223372036854775808.0.)
Regression test for test/functions_test.dart (fails under dart compile js / dart test -p chrome before fix, passes after):
test('round and abs enforce 64-bit integer bounds on dart2js', () {
expect(
_evaluate(_call('round', const <String, Object?>{'value': 1e20})),
missing,
);
expect(
_evaluate(_call('floor', const <String, Object?>{'value': 1e20})),
missing,
);
expect(
_evaluate(_call('ceil', const <String, Object?>{'value': 1e20})),
missing,
);
expect(
_evaluate(
_call('abs', const <String, Object?>{'value': -9223372036854775808.0}),
),
9223372036854775808.0,
);
});There was a problem hiding this comment.
Fixed in 34b8712: on JavaScript the standard functions follow the double rules where they differ from the integer ones (round/floor/ceil of 1e20 are absent, abs(-2^63) is 2^63), add/subtract/multiply no longer go through BigInt (which also threw on infinities in JS), and the codebase blueprint documents what differs on the web. Your test is added.
| export 'src/canonical_json.dart'; | ||
| export 'src/evaluator.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/standard_functions.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/functions.dart, and src/standard_functions.dart when switching lib/a2ui_craft.dart to explicit show lists. Right now #39 still leaves functions.dart and standard_functions.dart as bare wildcards, leaking internal helpers (isNumber, toValue, isStringKeyed, valueEquals, compareNumbers, numberToDisplayString) onto package:a2ui_craft/a2ui_craft.dart alongside the public API (Evaluator, CallKind & subclasses, EvaluationException, EvaluationErrorKind, LocalFunction, LocalFunctionImplementation, FunctionArgType, FunctionRegistry, standardFunctions).
There was a problem hiding this comment.
Will do in the barrel-tightening PR on top of the stack (explicit show lists for all barrels, internal helpers off the public API).
| FunctionRegistry({ | ||
| required Map<String, LocalFunction> standard, | ||
| Map<String, LocalFunction> host = const <String, LocalFunction>{}, | ||
| }) : _functions = <String, LocalFunction>{...standard} { | ||
| for (final MapEntry<String, LocalFunction> entry in host.entries) { | ||
| _checkHostKey(entry.key); | ||
| _functions[entry.key] = entry.value; | ||
| } | ||
| } |
There was a problem hiding this comment.
Nit: host keys are strictly validated via _checkHostKey, but standard keys are copied without validation — a caller passing standard: {'core::add': ...} or standard: {'absent': ...} would silently register uncallable or construct-colliding keys. Worth either validating bare non-excluded standard keys or defaulting standard to standardFunctions if custom standard maps aren't needed.
Drop-in regression test for group('FunctionRegistry', ...) in test/functions_test.dart:
for (final String key in <String>['core::add', 'absent', 'call', '1bad']) {
test('rejects invalid standard key $key', () {
expect(
() => FunctionRegistry(standard: <String, LocalFunction>{key: echo()}),
throwsArgumentError,
);
});
}There was a problem hiding this comment.
Fixed in 34b8712: standard keys are now validated like host keys (core::add, absent, call, 1bad are rejected); your test is added.
| if (a is Map<String, Object?> && b is Map<String, Object?>) { | ||
| if (a.length != b.length) return false; | ||
| for (final MapEntry<String, Object?> entry in a.entries) { | ||
| if (!b.containsKey(entry.key) || | ||
| !valueEquals(entry.value ?? missing, b[entry.key] ?? missing)) { | ||
| return false; | ||
| } | ||
| } | ||
| return true; | ||
| } |
There was a problem hiding this comment.
Because we unintentionally export valueEquals from the main barrel (lib/a2ui_craft.dart), external callers can pass an untyped Map<dynamic, dynamic> (which toValue and Evaluator._read accept via isStringKeyed) and silently get false instead of comparing equal. Keeping the barrel exports controlled and minimal (so valueEquals stays internal, where Evaluator has already normalized maps via toValue) would make this a non-issue.
Drop-in test for test/functions_test.dart (only needed if valueEquals stays public):
test('valueEquals handles untyped string-keyed maps like toValue does', () {
expect(
valueEquals(<dynamic, dynamic>{'a': 1}, <String, Object?>{'a': 1}),
isTrue,
);
});There was a problem hiding this comment.
Fixed in 34b8712: valueEquals now compares string-keyed maps of any static key type, with your test. It also goes off the barrel in the barrel PR.
818fac0 to
1c6cf94
Compare
Adds the craft_functions feature to craft/packages/a2ui_craft: host-registered pure functions that templates call in value positions, the standard functions, and an evaluator for the values that need no runtime. - lib/src/functions.dart: LocalFunction (parameters with a FunctionArgType and an implementation), FunctionRegistry (standard functions under bare names, host functions under lib::name keys, which it checks), and the shared value helpers: conversion of host values (null is absent), equality, exact number comparison and number display. - lib/src/standard_functions.dart: 28 standard functions: add, subtract, multiply, divide, mod, min, max, abs, round, floor, ceil, greaterThan, lessThan, greaterThanOrEqual, lessThanOrEqual, equals, notEquals, and, or, not, concat, trim, length, contains, listWith, listWithout, isSet, orElse. - lib/src/evaluator.dart: evaluates literals, lists, maps, `absent`, args/data/state references over caller-supplied values, and function calls. Evaluator.classify tells what a call denotes: `absent`, a handler application (`call`), a widget call when its name resolves to a widget (craft_libraries_and_names), a function call when NameResolver.functionKey maps it, or unknown. Every failure is an EvaluationException of one of four kinds: unknownFunction, invalidArgument, functionFailed (a host function threw or returned a non-value) and notEvaluated (nodes whose value the runtime defines: widget calls, loops, switches, handlers, `call`, and loop, builder, theme, media and symbol references). - `absent` is a literal, not a function: a call named `absent` evaluates to the absent value without any lookup; no standard function is named `absent` or `call`. craft_language_extensions now points to this feature. - craft_text_format and craft_binary_format now say that their requirements hold for inputs nested within the engine's limits, which the craft_limits feature defines; deeper nesting is not handled yet by the parser, the decoder or the evaluator. - craft/blueprints/features/craft_functions.blueprint.md specifies values, call classification, arguments, host functions, errors, the number model and every standard function on every kind of argument including absent. It leaves the value of runtime nodes to the craft_runtime feature. - craft/conformance/craft/craft_functions.yaml holds 103 cases (193 expressions) with a fixed set of test host functions documented in its header; cases expect a value, an error kind or a call's classification. test/conformance/functions_test.dart runs them. test/functions_test.dart covers host key registration, notEvaluated for runtime nodes, NaN, null, untyped maps and non-values in supplied values, argument copies and number display. - Conformance: the evaluate and classify actions and the F-CRAFT-FUNC-01 to 13 feature IDs. Taken from the prototype (functions.dart, evaluator.dart and the shared expression vectors): the standard function set and the semantics of most functions (strict kinds, absent instead of throwing, division and mod by zero absent, list functions as sets, isSet/orElse, number display). Changed: argument kinds are checked for every argument at every call (the prototype checked literals only, in debug builds), unknown argument names are errors, a host function that throws is functionFailed instead of escaping, integer overflow and non-finite results are absent, numbers compare exactly, equals compares lists and maps by content, and a widget name that fails to resolve no longer hides a function. Left out: atLeast (media context), the introspection functions (hasWidget, hasWidgetArg, hasFunction, hasFunctionArg, hasArg, meta, runtimeVersion, appVersion; template registry), uppercase/lowercase (the platform case mapping is not a stable Unicode mapping), and switch, loop and handler evaluation (runtime). Co-authored-by: Yegor <yegor.jbanov@gmail.com>
- compareNumbers recursed forever under dart2js, where a whole number is both an int and a double, so every comparison and equality crashed there. JavaScript numbers now compare as doubles, which is exact. - Under dart2js the standard functions follow the double rules wherever they differ from the integer rules: round, floor and ceil of 1e20 are absent, abs of -2^63 is 2^63, and add, subtract and multiply no longer go through BigInt (which threw for infinities). numberToDisplayString shows negative zero as 0 there too. The codebase blueprint says what differs on JavaScript. - FunctionRegistry rejects a standard key that is not an identifier usable in a qualified name (core::add, absent, call, 1bad), as it does for host keys. - valueEquals compares string-keyed maps whatever their static key type.
CI only compiled the engine with dart2js, so a crash that happens only there (compareNumbers recursing forever) went unnoticed. CI now also runs `dart test -p node` in a2ui_craft. - The conformance harness reads files through a small layer with a dart:io and a Node.js fs implementation, so the suites load and run compiled to JavaScript; the harness self-test stays on the VM. - js_skips.dart lists the 18 cases that cannot pass there because JavaScript numbers do not tell integers from doubles or hold integers beyond 2^53; a VM test checks that each listed case exists.
1c6cf94 to
a79bacb
Compare
ditman
left a comment
There was a problem hiding this comment.
🤖 Thanks for the fixes — compareNumbers and the standard functions on dart2js, FunctionRegistry standard key validation, and valueEquals for string-keyed maps all look solid, and adding dart test -p node to CI is a great safeguard. LGTM!
# Description Adds the **template registry** to the Craft engine core: where a host registers template libraries, primitive libraries and host functions, how templates ask what the host supports, and which components may be offered to the agent. Stacked on #27. Same three parts as the other engine PRs: a blueprint, conformance cases and the code. - **Blueprint**: `craft/blueprints/features/craft_template_registry.blueprint.md`. - **Registration**: `TemplateRegistry` takes template libraries, primitive libraries (with metadata) and host functions (`lib::name`). It owns the name resolver and the function tables, and drops cached results on every change. A rejected registration leaves the registry unchanged. - **Introspection**: `hasWidget`, `hasWidgetArg`, `hasFunction`, `hasFunctionArg`, `hasArg`, `meta` and `runtimeVersion`, plus symbol references such as `Location.args.latLong`. They answer from the calling library's imports, so they report what the host provides, not a template's own stand-ins. This is how a template adapts to hosts with different capabilities. - **Dependency gating**: a library declares optional imports and widget, function and argument requirements, for the whole library or per component. The registry computes which libraries and components are available: libraries that import each other are available together, unavailability carries through imports, and only available components are offered to the agent. - **Tests**: 42 conformance cases in `craft/conformance/craft/craft_template_registry.yaml`, plus unit tests. - Not in this PR: catalog JSON schemas for the agent (they're A2UI-specific, so they move to the A2UI integration PR), and load-time constant folding (a pure optimization). The introspection functions come from yjbanov/a2ui_craft at `aece53f`, hence the co-author. An independent review checked the blueprint against the tests and the code, including mutations. Next: the runtime (expanding templates into primitives, local state, events). ## Pre-launch Checklist One time: - [x] I signed the [CLA]. - [x] I read the [Contributors Guide]. For this PR: - [x] I updated/added relevant documentation. - [x] My code changes (if any) have tests. - [x] License checks pass (`python3 ./scripts/fix_licenses.py --check`). - [x] Format checks pass (`./scripts/fix_format.sh --check`). <!-- Links --> [CLA]: https://cla.developers.google.com/ [Contributors Guide]: https://github.com/a2ui-project/a2ui-labs/blob/main/CONTRIBUTING.md Co-authored-by: Yegor <yegor.jbanov@gmail.com>
Description
Adds functions to the Craft engine core: host-registered pure functions, the standard library, and an evaluator over plain values. Stacked on #26. Same three parts as the other engine PRs: a blueprint, conformance cases and the code.
craft/blueprints/features/craft_functions.blueprint.md. It covers:unknownFunction,invalidArgument,functionFailedandnotEvaluated. Templates are untrusted, so a host function that throws or returns a non-value is contained;isSetandorElse.lib/src/functions.dart,standard_functions.dart,evaluator.dart. Most standard functions come from yjbanov/a2ui_craft ataece53f, hence the co-author.absentevaluates as a literal. The value of widget calls, loops, switches,calland theme, media and symbol references is defined by later features (runtime, media context, template registry), not here.craft/conformance/craft/craft_functions.yaml, including aclassifyquery for the function-or-widget decision, plus unit tests. Two claims were checked against JavaScript:concatformats numbers like JavaScript'sString(x)(checked on 20,000+ doubles against Node), and thetrimwhitespace set is tested character by character.Known limitation: deeply nested input (for example 10,000 nested lists) still overflows the stack in the parser, decoder and evaluator. The
limitsfeature (a later PR) will add depth checks; the blueprints now defer to it.An independent review checked the blueprint against the tests and the code, including mutations.
Next: the template registry (introspection such as
hasWidget, and dependency gating).Pre-launch Checklist
One time:
For this PR:
python3 ./scripts/fix_licenses.py --check)../scripts/fix_format.sh --check).