Skip to content

feat(craft): add libraries and name resolution - #24

Merged
innkuika merged 1 commit into
mainfrom
craft/engine-names
Dec 3, 2026
Merged

innkuika merged 1 commit into
mainfrom
craft/engine-names

Conversation

@innkuika

@innkuika innkuika commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Description

Adds the libraries and names feature to the Craft engine core: how a name in a template denotes exactly one widget or function. Stacked on #23. Same three parts as every engine PR: a blueprint, conformance cases for it, and the code.

  • Blueprint: craft/blueprints/features/craft_libraries_and_names.blueprint.md.

  • Text format (lib/src/rfw/text.dart, model.dart):

    • qualified call names lib::Name and a.b::Name; the qualified string is the call's name, so the binary format doesn't change;
    • export widget X = ...;, which marks a declaration as exported. The canonical JSON form carries "exported": true.

    No source that RFW accepts changes meaning; RFW's own tests still pass.

  • Name resolution (lib/src/name_resolution.dart):

    • a library's own declarations come first, but a declaration never resolves to itself (widget Button = Button(...) wraps core's Button);
    • then core, when imported;
    • names from any other import must be qualified, so adding a name to a library can never change or break an existing template;
    • imports are not transitive, and other libraries' private (not exported) declarations are invisible;
    • only exported declarations of a catalog library are agent-facing components;
    • function names follow the same rules.
  • Tests: 45 conformance cases in craft/conformance/craft/craft_libraries_and_names.yaml (parse cases and resolution queries; failures are pinned by reason, not message). Every rejection case has a control case that differs only in the name. Unit tests are in test/name_resolution_test.dart.

An independent review checked the blueprint against the tests and the code, including code mutations.

Next: the binary format (versioning, extension tags, the exported flag).

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 implements the 'Libraries and Names' feature, which introduces qualified names, the export keyword, and explicit name resolution rules for template and primitive libraries. The changes include adding a detailed feature blueprint, updating the text format specification, defining shared conformance test cases, and implementing the NameResolver and parser updates in Dart. The reviewer suggested an optimization in NameResolver.visibleNames to deduplicate scopes using a Set before iterating, which avoids redundant lookups and name resolutions.

Comment on lines +308 to +316
return <String, NameResolution>{
for (final LibraryName scope in <LibraryName>[..._importsOf(from), from])
for (final String name in _namesIn(scope)) ...<String, NameResolution>{
'$scope$qualifierSeparator$name': resolveName(
'$scope$qualifierSeparator$name',
),
name: resolveName(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.

medium

Deduplicating the scopes using a Set before iterating avoids redundant lookups and name resolutions if there are duplicate imports or if the library imports itself.

    final Set<LibraryName> scopes = <LibraryName>{..._importsOf(from), from};
    return <String, NameResolution>{
      for (final LibraryName scope in scopes)
        for (final String name in _namesIn(scope)) ...<String, NameResolution>{
          '$scope$qualifierSeparator$name': resolveName(
            '$scope$qualifierSeparator$name',
          ),
          name: resolveName(name),
        },
    };

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 result is the same either way (duplicate keys collapse, and each name resolves the same way), and visibleNames is only used by the conformance harness. Leaving it as is.

@innkuika
innkuika marked this pull request as ready for review November 24, 2026 23:10
@innkuika
innkuika requested a review from ditman November 24, 2026 23:10
@innkuika
innkuika added this pull request to stack #51 December 1, 2026 19:57
Base automatically changed from craft/engine-text-format to main December 1, 2026 20:35
Adds the craft_libraries_and_names feature to craft/packages/a2ui_craft:
how a name in a template denotes exactly one widget or function.

- Text format (lib/src/rfw/text.dart, model.dart): qualified call names
  `lib::Name` and `a.b::Name` (the qualified string is the call's name, and
  a qualified name followed by `.` is a symbol reference; qualifier parts
  and the name after `::` must be identifiers that are not reserved words),
  and `export widget X = ...;`, which sets WidgetDeclaration.exported. The
  canonical JSON form carries `"exported": true` on exported declarations.
  RFW's own tests still pass unchanged.
- lib/src/name_resolution.dart: NameResolver resolves names from a library
  (own declarations first, never the one being bound; then core when
  imported; other imports must be qualified; imports are not transitive;
  other libraries' private declarations are invisible), among imports only,
  as catalog components (exported declarations only), and maps function
  names to their registered keys.
- craft/blueprints/features/craft_libraries_and_names.blueprint.md
  specifies the rules;
  craft/conformance/craft/craft_libraries_and_names.yaml holds 45 shared
  cases (parse cases and resolution queries, failures pinned by reason),
  run by test/conformance/libraries_and_names_test.dart, plus unit tests
  in test/name_resolution_test.dart.
- Conformance: the resolve_names action (resolution_cases.dart) and the
  F-CRAFT-NAMES-01 to 12 feature IDs.

Taken from our earlier Craft prototype: the `::` tokenizing and qualified
name parsing, the `export` keyword and the exported flag, the resolution
rules and their resolver (with its unit tests). Left out: the prototype's
native replacement of templates, migration hints for former core widgets
and its name lint. Changed while porting: a qualified self-reference is
also skipped, imported-only resolution hides the library's own declarations
even when qualified, qualifiers reject strings and reserved words, the
name after `::` follows the same rule, candidates are deduplicated, and
core-qualified function keys are never callable.

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

🤖 Clean, well-specified implementation of qualified names, export widget, and non-transitive name resolution. The blueprint, 45 conformance cases, and unit tests are thorough and easy to follow.

Approving to keep the stack moving — please address the items below (and the inline comments) in a follow-up PR down the line:

  1. Self-import bug when from == coreLibrary (name_resolution.dart): _resolve checks if (imports.contains(coreLibrary)) without guarding from != coreLibrary (unlike candidates right below it). If a template library registered as core imports itself (import core;), resolve(coreLibrary, 'Button', excluding: 'Button') resolves Button to itself (violating Req 3) and resolveImported(coreLibrary, 'Button') returns core's own declaration (violating Req 8). Adding from != coreLibrary && fixes both; reproducer test inline.
  2. Post-stack barrel tightening reminder (lib/a2ui_craft.dart): Per our agreement on #23, just a reminder to include src/name_resolution.dart in the follow-up PR that switches the barrel to explicit show lists.
  3. API & cleanup questions: replacing the _cache raw tuple + _importedOnly magic string sentinel with a named typedef or small value class, checking whether splitQualifiedName should throw a Craft parsing error on malformed inputs like '::Card' / 'a::b::c', and noting null::Card()'s map-vs-list error position (analogous to null.x in #23).

(Also noted that ui:/*c*/:Card() comment-between-colons handling is already fixed in #38 on top of the stack, so I left that out of this review.)

library;

export 'src/canonical_json.dart';
export 'src/name_resolution.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/name_resolution.dart when switching the barrel to explicit show lists (e.g., NameResolver, NameResolution, ResolvedName, UnresolvedName, UnresolvedReason, PrimitiveLibrary, coreLibrary, qualifierSeparator, splitQualifiedName).

Comment on lines +198 to +203
if (imports.contains(coreLibrary)) {
if (_lookupIn(coreLibrary, bare, from: from, excluding: null)
case final ResolvedName core) {
return core;
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🤖 When from == coreLibrary (a template library registered as core) and core imports itself (import core;), this branch calls _lookupIn(coreLibrary, bare, from: from, excluding: null) without checking from != coreLibrary. That breaks two blueprint requirements:

  1. Req 3 (no self-resolution): resolve(coreLibrary, 'Button', excluding: 'Button') skips Button in ownDeclarations and then resolves Button to itself here because excluding: null is passed.
  2. Req 8 (imported-only skips own declarations): resolveImported(coreLibrary, 'Button') skips ownDeclarations and then returns core's own declaration here.

Notice candidates right below (line 206) already guards if (import != from && ...). Guarding this check with if (from != coreLibrary && imports.contains(coreLibrary)) fixes both cases.

Reproducer test:

test('core template library importing itself never self-resolves or leaks in resolveImported', () {
  libs[coreLibrary] = parseLibraryFile('''
    import core;
    export widget Button = Button();
  ''');
  resolver.invalidate();

  // Req 3: declaration being bound must not resolve to itself
  expect(
    resolver.resolve(coreLibrary, 'Button', excluding: 'Button'),
    isA<UnresolvedName>().having(
      (UnresolvedName e) => e.reason,
      'reason',
      UnresolvedReason.notFound,
    ),
  );

  // Req 8: resolveImported must ignore own declarations
  expect(
    resolver.resolveImported(coreLibrary, 'Button'),
    isA<UnresolvedName>().having(
      (UnresolvedName e) => e.reason,
      'reason',
      UnresolvedReason.notFound,
    ),
  );
});

Comment on lines +125 to +128
// Keyed by (from, name, excluding); [_importedOnly] marks resolveImported.
final Map<(LibraryName, String, String?), NameResolution> _cache =
<(LibraryName, String, String?), NameResolution>{};
static const String _importedOnly = '\u0000imported';

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: instead of using a raw positional tuple as the map key together with the magic _importedOnly = '\u0000imported' string sentinel, could we introduce a named typedef (e.g., typedef _ResolutionKey = ({LibraryName from, String name, String? excluding, bool importedOnly});) or a small value class? That makes the cache key self-documenting and eliminates any theoretical collision if a programmatic caller ever passes that sentinel string as excluding.

Comment on lines +26 to +33
(LibraryName?, String) splitQualifiedName(String name) {
final int at = name.indexOf(qualifierSeparator);
if (at < 0) return (null, name);
return (
LibraryName(name.substring(0, at).split('.')),
name.substring(at + qualifierSeparator.length),
);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Since splitQualifiedName is public API, malformed strings from hand-crafted ASTs or binary blobs (e.g., '::Card' or 'a::b::c') currently return (LibraryName(['']), 'Card') / (LibraryName(['a']), 'b::c'). Is silently splitting malformed inputs the behavior we want here, or should splitQualifiedName throw a Craft parsing/format error (e.g., FormatException or ParserException) instead?

Comment on lines 2923 to +2926
);
}
return _withSourceRange(
SymbolReference(identifier, _readParts()),
start,
);
final List<_Token> partTokens = <_Token>[];
final List<Object> parts = _readParts(tokens: partTokens);

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 note (analogous to null.x in #23): in map/argument value positions (nullOk: true), Box(a: null::Card()) takes the identifier == 'null' && nullOk branch at line 2822 first, consumes null as missing, and fails later on :: rather than reporting 'A qualified name may only contain identifiers that are not reserved words' on null (as Box(a: [null::Card()]) does). It is still rejected as the blueprint requires, so only worth tightening if you also adjust the null.x branch from #23.

Drop-in regression test (e.g. for test/name_resolution_test.dart or test/rfw/text_test.dart):

test('null::Card() reports reserved-word qualifier error in map/arg value position', () {
  expect(
    () => parseLibraryFile('''
      widget r = Box(
        a: null
          ::Card(),
      );
    '''),
    throwsA(
      isA<ParserException>().having(
        (ParserException e) => '$e',
        'message',
        allOf(
          contains(
            'A qualified name may only contain identifiers that are not reserved words',
          ),
          contains('at line 2 '),
        ),
      ),
    ),
  );
});

@innkuika
innkuika merged commit b07517a into main Dec 3, 2026
21 checks passed
@innkuika
innkuika deleted the craft/engine-names branch December 3, 2026 02:07
innkuika added a commit that referenced this pull request Dec 3, 2026
# Description

Adds the **binary format** to the Craft engine core: the compact form a
host ships and loads at runtime. Stacked on #24. As in the other engine
PRs, it has a blueprint, conformance cases and the code.

- **Blueprint**:
`craft/blueprints/features/craft_binary_format.blueprint.md`, a
byte-level, language-agnostic spec: signatures, versioning and
compatibility, every tag and encoding, declaration flags, extension tags
and error kinds with offsets. It is complete enough that an independent
reviewer wrote a decoder from it alone; that decoder agreed with the
Dart decoder on all cases and on 200,000 random and mutated blobs.
- **Code**: `lib/src/rfw/binary.dart`, forked from RFW 2.0.0:
- Yegor's encodings for theme, media and symbol references
(yjbanov/a2ui_craft at `aece53f`);
- a versioned format: Craft signatures with a version and a minimum
reader version. RFW blobs still decode as version 0;
  - a flags field on declarations (bit 0 = exported);
- extension tags (0x80–0xEF) that older readers skip; other unknown tags
are rejected;
- typed errors with offsets; lengths are checked before anything is
allocated;
- new rules: repeated map keys and switch cases are rejected, and a
leading byte order mark is preserved. The blueprint lists where this
differs from RFW's decoder.
- **Tests**:
- 98 conformance cases in
`craft/conformance/craft/craft_binary_format.yaml`, with annotated hex.
They include encoder cases (source → exact bytes, round trip, re-encode)
and decoder cases (bytes → canonical JSON or error kind and offset).
- RFW 2.0.0's binary tests (32) pass. The only changes are that expected
encodings now start with the Craft header, and the changes needed to run
outside Flutter; the file header lists them.

An independent review checked the blueprint against the tests and the
code, including mutations and the independent decoder.

Next: the language additions (conditional elements, local values,
handler calls and more).

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