Repository navigation
feat(craft): add libraries and name resolution - #24
Conversation
There was a problem hiding this comment.
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.
| 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), | ||
| }, | ||
| }; |
There was a problem hiding this comment.
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),
},
};There was a problem hiding this comment.
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.
4c425e7 to
149f737
Compare
149f737 to
2e4b268
Compare
2e4b268 to
9c0e639
Compare
9c0e639 to
0560e25
Compare
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.
0560e25 to
f7ddaa8
Compare
ditman
left a comment
There was a problem hiding this comment.
🤖 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:
- Self-import bug when
from == coreLibrary(name_resolution.dart):_resolvechecksif (imports.contains(coreLibrary))without guardingfrom != coreLibrary(unlikecandidatesright below it). If a template library registered ascoreimports itself (import core;),resolve(coreLibrary, 'Button', excluding: 'Button')resolvesButtonto itself (violating Req 3) andresolveImported(coreLibrary, 'Button')returnscore's own declaration (violating Req 8). Addingfrom != coreLibrary &&fixes both; reproducer test inline. - Post-stack barrel tightening reminder (
lib/a2ui_craft.dart): Per our agreement on #23, just a reminder to includesrc/name_resolution.dartin the follow-up PR that switches the barrel to explicitshowlists. - API & cleanup questions: replacing the
_cacheraw tuple +_importedOnlymagic string sentinel with a namedtypedefor small value class, checking whethersplitQualifiedNameshould throw a Craft parsing error on malformed inputs like'::Card'/'a::b::c', and notingnull::Card()'s map-vs-list error position (analogous tonull.xin #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'; |
There was a problem hiding this comment.
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).
| if (imports.contains(coreLibrary)) { | ||
| if (_lookupIn(coreLibrary, bare, from: from, excluding: null) | ||
| case final ResolvedName core) { | ||
| return core; | ||
| } | ||
| } |
There was a problem hiding this comment.
🤖 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:
- Req 3 (no self-resolution):
resolve(coreLibrary, 'Button', excluding: 'Button')skipsButtoninownDeclarationsand then resolvesButtonto itself here becauseexcluding: nullis passed. - Req 8 (imported-only skips own declarations):
resolveImported(coreLibrary, 'Button')skipsownDeclarationsand then returnscore'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,
),
);
});| // Keyed by (from, name, excluding); [_importedOnly] marks resolveImported. | ||
| final Map<(LibraryName, String, String?), NameResolution> _cache = | ||
| <(LibraryName, String, String?), NameResolution>{}; | ||
| static const String _importedOnly = '\u0000imported'; |
There was a problem hiding this comment.
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.
| (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), | ||
| ); | ||
| } |
There was a problem hiding this comment.
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?
| ); | ||
| } | ||
| return _withSourceRange( | ||
| SymbolReference(identifier, _readParts()), | ||
| start, | ||
| ); | ||
| final List<_Token> partTokens = <_Token>[]; | ||
| final List<Object> parts = _readParts(tokens: partTokens); |
There was a problem hiding this comment.
🤖 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 '),
),
),
),
);
});# 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>
# 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 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):lib::Nameanda.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):widget Button = Button(...)wraps core'sButton);core, when imported;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 intest/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:
python3 ./scripts/fix_licenses.py --check)../scripts/fix_format.sh --check).