Skip to content

feat(craft): add language extensions (absent, call, ...if, let) - #26

Merged
innkuika merged 1 commit into
craft/engine-binaryfrom
craft/engine-language
Dec 3, 2026
Merged

innkuika merged 1 commit into
craft/engine-binaryfrom
craft/engine-language

Conversation

@innkuika

@innkuika innkuika commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

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:

Syntax Meaning Parses to
absent the "no value" literal (unlike null, it is not dropped from maps) a call named absent with no arguments
call H { M } apply a handler to arguments a call named call with handler and arguments
...if C: E a conditional list element a loop over switch C { true: [true], default: [] } with body E
let N = V, ... in R local values at the start of a declaration substituted at parse time; nothing of the binding stays in the library
  • Blueprint: craft/blueprints/features/craft_language_extensions.blueprint.md. It also lists exactly which previously valid sources change meaning (for example call(x: 1) in a value position). How these constructs evaluate is specified by the functions and runtime features.
  • absent and call become reserved words and construct names. They can't be loop variables, builder arguments or qualified names, and they never resolve to a widget, so libraries_and_names is updated to match.
  • Tests: 43 conformance cases with 71 sources. Every accepted library also goes through the binary round trip, and every rejection has a control case. The prototype's parse-level unit tests are ported.

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:

  • 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).

@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 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.

@innkuika
innkuika force-pushed the craft/engine-language branch from 945eade to a0f2e2f Compare November 23, 2026 21:00
@innkuika
innkuika force-pushed the craft/engine-language branch from a0f2e2f to d160a42 Compare November 23, 2026 22:05
@innkuika
innkuika force-pushed the craft/engine-language branch from d160a42 to 6c59956 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-language branch from 6c59956 to 25e08bb 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-language branch from 25e08bb to bed9a88 Compare December 1, 2026 20:35

@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.

🤖 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:

  1. Post-stack barrel tightening reminder (lib/src/rfw/text.dart): Per our agreement on #23, please make sure src/rfw/text.dart is included in the post-stack barrel-tightening pass (#39 still leaves export 'src/rfw/text.dart'; as a wildcard), especially since adding constructCallNames and isExcludedFromQualifiedNames here leaks internal RFW parser helpers onto the public API.
  2. AST aliasing in let (lib/src/rfw/text.dart): Returning the same _letValues[name] object reference at each use leaks object identity into _readSwitch duplicate-key checks (let x = Text() in switch args.k { x: 1, x: 2 } throws, whereas inlined Text() parses); regression test inline.
  3. Minor nits: duplicated comma/bracket check in _readList (already refactored in #38) and double-parsing source in parse_cases.dart for binary_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.)

Comment on lines +665 to +672
/// 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);

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 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.

Comment on lines +3205 to +3222
}
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) ||

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🤖 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 }; throws Switch has duplicate cases for key Text() (same for let 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));
});

Comment on lines +2694 to +2700
if (_foundSymbol(_SymbolToken.comma)) {
_advance();
} else if (!_foundSymbol(_SymbolToken.closeBracket)) {
throw ParserException._expected('comma', _source.current);
}
continue;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🤖 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).

Comment on lines 65 to +74
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',
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🤖 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.
@innkuika
innkuika force-pushed the craft/engine-language branch from bed9a88 to c261d9c Compare December 2, 2026 19:58
@innkuika
innkuika merged commit c279339 into main Dec 3, 2026
41 of 50 checks passed
@innkuika
innkuika deleted the craft/engine-language branch December 3, 2026 02:07
innkuika added a commit that referenced this pull request Dec 3, 2026
# 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>
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