Repository navigation
feat(craft): add language extensions (absent, call, ...if, let) - #26
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces the language_extensions feature to the Craft engine, adding support for four new text format constructs: the absent value, handler application with call, conditional list elements with ...if, and local values with let. The changes include detailed feature blueprints, updates to existing blueprints (such as libraries_and_names and text_format), comprehensive conformance test cases, and the Dart implementation of the parser and name resolver to support these constructs. Unit and conformance tests have also been added to verify the new functionality and ensure binary round-trip compatibility. There are no review comments, and I have no feedback to provide.
945eade to
a0f2e2f
Compare
a0f2e2f to
d160a42
Compare
d160a42 to
6c59956
Compare
6c59956 to
25e08bb
Compare
25e08bb to
bed9a88
Compare
ditman
left a comment
There was a problem hiding this comment.
🤖 Very clean design — desugaring absent, call, ...if, and let directly into existing RFW node kinds keeps the binary format and canonical JSON unchanged, and the 43-case conformance suite with mandatory binary round-trips is thorough.
Approving to keep the stack moving — please address the items below (and the inline comments) in a follow-up PR down the line:
- Post-stack barrel tightening reminder (
lib/src/rfw/text.dart): Per our agreement on #23, please make suresrc/rfw/text.dartis included in the post-stack barrel-tightening pass (#39still leavesexport 'src/rfw/text.dart';as a wildcard), especially since addingconstructCallNamesandisExcludedFromQualifiedNameshere leaks internal RFW parser helpers onto the public API. - AST aliasing in
let(lib/src/rfw/text.dart): Returning the same_letValues[name]object reference at each use leaks object identity into_readSwitchduplicate-key checks (let x = Text() in switch args.k { x: 1, x: 2 }throws, whereas inlinedText()parses); regression test inline. - Minor nits: duplicated comma/bracket check in
_readList(already refactored in #38) and double-parsingsourceinparse_cases.dartforbinary_round_trip.
(Noted that nested ...for/...if elements and clearer let-misuse messages are already queued in #38, and exponential let DAG node limits are already enforced and tested in #33, so those are intentionally left out here.)
| /// The names of the calls that `absent` and `call` parse to. They always | ||
| /// mean those constructs and never name a widget. | ||
| const Set<String> constructCallNames = <String>{'absent', 'call'}; | ||
|
|
||
| /// Whether [name] is a word that cannot be written after `::` in a qualified | ||
| /// name, because in a value position it starts some other construct. | ||
| bool isExcludedFromQualifiedNames(String name) => | ||
| _qualifierExcludedWords.contains(name); |
There was a problem hiding this comment.
Reminder for the post-stack barrel-tightening pass agreed in #23: please make sure export 'src/rfw/text.dart'; in lib/a2ui_craft.dart is switched to an explicit show list (parseDataFile, parseLibraryFile, ParserException). Right now #39 still leaves src/rfw/text.dart as a wildcard export, so adding constructCallNames and isExcludedFromQualifiedNames here leaks internal RFW parser helpers onto the public package:a2ui_craft/a2ui_craft.dart API.
| } | ||
| if (_letValues.containsKey(name)) { | ||
| throw ParserException._fromToken( | ||
| 'Duplicate let binding "$name"', | ||
| nameToken, | ||
| ); | ||
| } | ||
| _expectSymbol(_SymbolToken.equals); | ||
| _letValues[name] = _readValue(extended: true); | ||
| } while (_maybeReadSymbol(_SymbolToken.comma)); | ||
| _expectIdentifier('in'); | ||
| } | ||
|
|
||
| /// Reads a use of a `let` binding, which stands for the bound value itself. | ||
| Object _readLetUse() { | ||
| final Object value = _letValues[_readIdentifier()]!; | ||
| if (_foundSymbol(_SymbolToken.dot) || | ||
| _foundSymbol(_SymbolToken.openParen) || |
There was a problem hiding this comment.
🤖 Because _letValues[name] stores the parsed AST node and _readLetUse() returns the exact same object reference at each use, object-identity aliasing leaks into _readSwitch duplicate-key checks (since non-primitive AST nodes like ConstructorCall, List, and Map use identity equality):
widget r = let x = Text() in switch args.k { x: 1, x: 2 };throwsSwitch has duplicate cases for key Text()(same forlet x = [1])widget r = switch args.k { Text(): 1, Text(): 2 };parses
This diverges from Requirement 4 ("The library contains Vi at each use and nothing for the binding itself") and from engines that clone Vi on substitution.
Drop-in regression test for test/language_extensions_test.dart:
test('let binding in switch cases matches inlined behavior without AST aliasing', () {
final RemoteWidgetLibrary inlined = parseLibraryFile(
'widget r = switch args.k { Text(): 1, Text(): 2 };',
);
final RemoteWidgetLibrary viaLet = parseLibraryFile(
'widget r = let x = Text() in switch args.k { x: 1, x: 2 };',
);
expect(canonicalLibrary(viaLet), canonicalLibrary(inlined));
});| if (_foundSymbol(_SymbolToken.comma)) { | ||
| _advance(); | ||
| } else if (!_foundSymbol(_SymbolToken.closeBracket)) { | ||
| throw ParserException._expected('comma', _source.current); | ||
| } | ||
| continue; | ||
| } |
There was a problem hiding this comment.
🤖 Nit: these comma / close-bracket checks duplicate the identical lines at the bottom of _readList — turning the for branch into an else would avoid the repetition (looks like #38 already cleans this up when adding nested ...for/...if).
| expect(<String, Object?>{kind: parse()}, expected); | ||
| if (c['binary_round_trip'] == true) { | ||
| final RemoteWidgetLibrary decoded = decodeLibraryBlob( | ||
| encodeLibraryBlob(parseLibraryFile(source)), | ||
| ); | ||
| expect( | ||
| canonicalLibrary(decoded), | ||
| expected['library'], | ||
| reason: 'binary round trip', | ||
| ); |
There was a problem hiding this comment.
🤖 Nit: this calls parseLibraryFile(source) a second time instead of reusing the library already parsed in parse(). Reusing the parsed RemoteWidgetLibrary avoids double-parsing and ensures the exact same instance is round-tripped.
Adds the craft_language_extensions feature to craft/packages/a2ui_craft:
four constructs that the Craft prototype added to the language (L3, L4,
L6 and L10). Each one parses to node kinds the text format already has,
so the canonical JSON form and the binary format are unchanged.
- lib/src/rfw/text.dart:
- `absent` / `absent()` in a value position parses to the call `absent()`
with no arguments.
- `call <handler> { arguments }` parses to the call
`call(handler: ..., arguments: {...})`.
- `absent` and `call` become reserved words, which also excludes them
from qualified names.
- `...if cond: element` in a list parses to the loop over
`switch cond { true: [true], default: [] }`, whose unnamed loop
variable shifts outer loop references in the element.
- `let a = v, b = w in root` at the start of a declaration's body,
when `let` is followed by a name. Otherwise `let` still starts the
root call's name (`let(...)`, `let::Card()`). The parser substitutes
each value at its uses; loop variables and builder arguments shadow a
binding.
Changes from the prototype: `let` starts bindings only before a name;
binding names follow the qualifier-part rule, not just the reserved
words; and a use followed by "(" or "::" gets the same explicit error as
".". The prototype's model and evaluator code for `call` (HandlerCall,
runHandler) is left to the craft_runtime feature.
- lib/src/name_resolution.dart: the names `absent` and `call` never
resolve to a widget or a catalog component, so the constructs always win
over a declaration of that name. Standard functions named by a word that can't follow `::`
(such as `absent`) are callable and listed only bare, not as `core::`.
- craft/blueprints/features/craft_language_extensions.blueprint.md
specifies exactly what each construct parses to and how the construct
names resolve, and lists the sources whose meaning changes.
craft_text_format, craft_libraries_and_names (reserved words, the
resolution exception and requirement 11), the module layer table and
the codebase blueprint are updated to match.
- craft/conformance/craft/craft_language_extensions.yaml holds 43 cases:
parse cases, whose accepted libraries are also checked to survive the
binary round trip, and one resolution case.
craft_libraries_and_names.yaml gains function-key queries for `absent`
and `call`. Scalars that YAML 1.1 reads as booleans are quoted here
and in craft_text_format.yaml.
- test/language_extensions_test.dart ports the prototype's parse-level unit
tests to the library model.
- Conformance: parse_library cases may set `binary_round_trip`; the
F-CRAFT-LANG-01 to 06 feature IDs.
Not included, because they are not parse-level: the standard functions
orElse, isSet, contains, listWith and listWithout (L1, L2, L8;
craft_functions feature), and the runtime behavior of handler lists,
actions held as data and mode-dependent colors (L7, L9, L11;
craft_runtime). L5, the conditional wrapper, adds no syntax.
bed9a88 to
c261d9c
Compare
# 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. - **Blueprint**: `craft/blueprints/features/craft_functions.blueprint.md`. It covers: - how a call is classified as a function call or a widget call (using the name rules from #24); - argument rules: unknown names are rejected, every argument is evaluated in order, missing means absent, and the wrong kind makes the call absent; - four error kinds: `unknownFunction`, `invalidArgument`, `functionFailed` and `notEvaluated`. Templates are untrusted, so a host function that throws or returns a non-value is contained; - exact semantics for each of the 28 standard functions, including every argument type: arithmetic with exact integer/double rules and 64-bit overflow → absent, comparisons, logic, strings, lists, `isSet` and `orElse`. - **Code**: `lib/src/functions.dart`, `standard_functions.dart`, `evaluator.dart`. Most standard functions come from yjbanov/a2ui_craft at `aece53f`, hence the co-author. - `absent` evaluates as a literal. The value of widget calls, loops, switches, `call` and theme, media and symbol references is defined by later features (runtime, media context, template registry), not here. - **Tests**: 103 conformance cases (193 expressions) in `craft/conformance/craft/craft_functions.yaml`, including a `classify` query for the function-or-widget decision, plus unit tests. Two claims were checked against JavaScript: `concat` formats numbers like JavaScript's `String(x)` (checked on 20,000+ doubles against Node), and the `trim` whitespace 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 `limits` feature (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: - [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 four language extensions to the Craft text format. Stacked on #25. Same three parts as the other engine PRs: a blueprint, conformance cases and the code.
None of them adds a node kind, tag or binary-format version. Each parses to calls, loops and switches that already exist:
absentnull, it is not dropped from maps)absentwith no argumentscall H { M }callwithhandlerandarguments...if C: Eswitch C { true: [true], default: [] }with bodyElet N = V, ... in Rcraft/blueprints/features/craft_language_extensions.blueprint.md. It also lists exactly which previously valid sources change meaning (for examplecall(x: 1)in a value position). How these constructs evaluate is specified by the functions and runtime features.absentandcallbecome reserved words and construct names. They can't be loop variables, builder arguments or qualified names, and they never resolve to a widget, solibraries_and_namesis updated to match.An independent review checked the blueprints against the tests and the code, including mutations and probes of previously valid sources.
Next: functions (host-registered pure functions and the standard library).
Pre-launch Checklist
One time:
For this PR:
python3 ./scripts/fix_licenses.py --check)../scripts/fix_format.sh --check).