Skip to content

feat(core): fold registered call-form intrinsics — per-intrinsic opt-in (#1044) - #1097

Merged
lex00 merged 5 commits into
mainfrom
feat/1044-call-form-intrinsics
Jul 27, 2026
Merged

lex00 merged 5 commits into
mainfrom
feat/1044-call-form-intrinsics

Conversation

@lex00

@lex00 lex00 commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

Closes #1044.

What I was asked to do, restated

A registered lexicon intrinsic written as a plain call (Ref(...), GetAtt(...), azure Concat(...)) should be able to fold the way a registered tagged template already does. Specifically:

  1. IntrinsicDef carries an explicit foldability marker for the call form, default off; nothing folds by inference from isTag, from the name, or from the call's shape.
  2. An opted-in call reduces to the same envelope family the tagged-template form produces, so serialization and revival learn nothing new and output stays byte-identical to the run path.
  3. Everything else still rejects, with a test each: an unregistered call, a registered-but-not-opted-in intrinsic, .map(...)/any method call, a user function, a name shadowed by a local binding, a name the file never imported.
  4. The subset.ts registry question is resolved explicitly, in writing — the shared predicate takes the registry as an optional parameter (exact with, conservative without).
  5. Per-lexicon audit for aws and azure: every intrinsic gets a yes/no with a reason.
  6. Corpus must not regress 24/98 with zero drift, and should grow; EXPECTED_FOLD updated by name; measured as a per-entry diff, not a summary count.
  7. A measured statement of what fold coverage can now reach for the AWS and Azure corpora specifically, so feat(core): fold — resolve identifiers across the module graph #1020/feat(core): fold cross-file references into lexicon package exports (Azure/GCP pseudo-params, action constants) #1063's remaining value can be judged on its own.
  8. bug(core): --fold never threads lexicon intrinsics through, so intrinsic tagged templates never fold in production #1039's "single biggest lever" framing corrected wherever docs repeat it.

Design: how the opt-in is declared, and why the door stays closed

IntrinsicDef gains readonly foldsAsCall?: boolean. Absent means not opted in — which is what every registration written before this PR means, so nothing changes by omission. Three predicates replace the old single one, because fold() always knows which authored form it is looking at and the two must not leak into each other:

intrinsicTagFolds(def)   // def.isTag === true
intrinsicCallFolds(def)  // def.isTag !== true && def.foldsAsCall === true
intrinsicFolds(def)      // either — the doc-facing "Folds?" predicate

fold()'s CallExpression case gains a second exception next to #1082's authoring helpers. A call folds only when the callee is a bare identifier, the file has not shadowed it with its own const, and the name is in the active lexicons' registered set with the opt-in set. It reduces to { __intrinsic, args } — same __intrinsic key as { __intrinsic, strings, values }, distinguished by which payload key is present — and executes nothing. fold-import.ts revives both through the same branch: Fn(...args) for a call, Fn(strings, ...values) for a tag, where Fn is resolved through the folding file's own import bindings. That last part is the load-bearing half: the function invoked while folding is the one the source itself named, so a folded call and a run call are the same call.

Four independent things each keep this from generalizing into "calls fold":

  • Registration is per intrinsic and written by hand. Adding a name is a diff in a lexicon's intrinsics(), reviewable as such. chant dev check-lexicon fails a registration that claims both isTag and foldsAsCall, so the opt-in cannot be declared on a tagged template.
  • Bare-identifier callee only. aws.Ref(...), cidrs.map(...), Object.fromEntries(...) have no case at all, registered name or not.
  • The file's own imports decide. A registered name that this file never imported throws ("Ref" is not a resolvable import) and the file falls back. A local const Ref = ... wins and rejects.
  • Arguments are revived with requireLiveRefs. An intrinsic inspects what it is handed (Ref calls getLogicalName, Sub does instanceof checks), so a symbolic {__attrRef} look-alike is rejected rather than passed along. Ref(sameFileBucket.arn) falls back instead of serializing something wrong.

On the #1019 boundary: the enforced rule was never "no calls" — composite factory calls (#1023) and registered tags have been resolved-and-invoked through the file's own import graph since before this. This is narrower than the composite rule, which has no registry-membership test at all.

subset.ts: the registry is an optional parameter (option 1)

findSubsetViolation(node, intrinsics?). With the registry, the answer for a call is exact. Without it, every call is a violation — the pre-#1044 answer.

Deciding this by omission would have made the shared predicate systematically stricter than fold() for idiomatic Ref(...), and that is the one direction subset.ts's own module doc says it must not be wrong in (its only existing divergence in that direction, flow-insensitivity, is documented as a wart). It also keeps the predicate usable by anything other than fold(): a consumer that has a registry can ask "will this fold?" without running fold, and one that doesn't degrades to "assume it runs", which is safe and cheap.

What I did not do, deliberately: EVL still calls the predicate without a registry, so chant lint keeps flagging Ref(...) in a resource's props exactly as it does on main — no behavior change for any user, but now a divergence where fold accepts what EVL flags. Closing it means handing the lint engine the active lexicons' intrinsics, which changes runLint's signature and three CLI call sites — lint's own surface, not #1044's. It is recorded as a tested property (subset.test.ts, "registry-less EVL is now STRICTER than fold on an opted-in call") and in the EVL divergence list in the docs, rather than left to be discovered. Also not done: the willFold(node, { intrinsics }) wrapper floated in the issue thread — the predicate's violation-shaped surface is unchanged.

Two fixes the corpus forced out

Intrinsic interiors prefer an already-resolved cross-file binding. Ref(environment) where environment is a Parameter in a sibling file must capture the instance the fold session built for that file. Routing it through {__symbol} instead re-imports the defining module and builds a second, differently-identified Parameter. isUnresolvedSymbolChain now consults externals, so a chain fold can resolve is not treated as unresolved. Tested by identity (toBe), not equality.

planFoldTaint gains reverse edges. Forward taint covered "a run-fallback file imports a folded file". It did not cover "a folded file captured the objects of a file that later got forced to run" — and lexicons/aws/examples/lambda-api crashed on exactly that the moment Ref(...) could fold:

Error: Logical name not set on entity of type "AWS::CloudFormation::Parameter"
    at getLogicalName (packages/core/src/utils.ts:70:11)
    at RefIntrinsic.toJSON (lexicons/aws/src/intrinsics.ts:58:19)

health-api.ts folded and captured params.ts's Parameter; params.ts was forced to run because a different sibling (data-bucket.ts) imports it and falls back; discovery collected the run instance and serialized the folded one. A successful fold now records which files' objects it consumed (FoldFileResult.liveSources — non-primitives only; a plain string has no identity to disagree about), and a tainted file invalidates every fold that captured one. Entry-level coverage is unaffected: taint is seeded only by non-folding files, so a fully-folding entry has none, and a mixed entry is already run-fallback.

Per-lexicon audit

aws — all 8 plain calls opted in: Ref, GetAtt, If, Join, Select, Split, Base64, GetAZs. Each constructs its *Intrinsic class and stores arguments verbatim; nothing is evaluated locally (Base64("x") emits {"Fn::Base64": "x"} for the deployment to encode). Join validates its second argument and throws on a bad one — deterministic in its arguments, and the run path throws the same error.

Not opted in, with reason: aws Sub — a tagged template, whose form already folds; Sub(...) as a plain call is not its authoring form, and the contract check now rejects a registration claiming both.

azure — all 9 opted in: ResourceId, Reference, Concat, ResourceGroup, Subscription, UniqueString, Format, If, ListKeys. Each renders an ARM bracket expression at serialization time. UniqueString(x) emits [uniqueString(x)] for ARM to hash — it does not hash at build time. Reference/ListKeys name a deployment-time read rather than performing one.

Deliberately out of scope: gitlab reference(), github Checkout, helm include/printf/toYaml/…, docker, temporal, fly. Each needs its own audit, and github/helm's are measured below as real headroom rather than assumed. Explicitly still rejected everywhere, by construction: .map()/.filter() and any array method taking a closure, and any user-defined function.

Corpus: exact before/after

Measured in a fresh clone (/tmp/chant-1044) with its own node_modules and generated lexicon artifacts. Sorted per-entry lines, diffed:

$ diff baseline.lines after.lines
7a8,14
> [identical] fold         lexicons/aws/examples/lambda-dynamodb
> [identical] fold         lexicons/aws/examples/lambda-eventbridge
> [identical] fold         lexicons/aws/examples/lambda-function
> [identical] fold         lexicons/aws/examples/lambda-s3
> [identical] fold         lexicons/aws/examples/lambda-scheduled
> [identical] fold         lexicons/aws/examples/lambda-sns
> [identical] fold         lexicons/aws/examples/lambda-sqs
9a17
> [identical] fold         lexicons/aws/examples/rds-postgres
44,51d51
< [identical] run-fallback lexicons/aws/examples/lambda-dynamodb
< [identical] run-fallback lexicons/aws/examples/lambda-eventbridge
< [identical] run-fallback lexicons/aws/examples/lambda-function
< [identical] run-fallback lexicons/aws/examples/lambda-s3
< [identical] run-fallback lexicons/aws/examples/lambda-scheduled
< [identical] run-fallback lexicons/aws/examples/lambda-sns
< [identical] run-fallback lexicons/aws/examples/lambda-sqs
< [identical] run-fallback lexicons/aws/examples/rds-postgres

$ grep -c 'fold ' baseline.lines after.lines
baseline: 24
after:    32

24/98 → 32/98, zero drift — every one of the 98 lines is still [identical], before and after. Eight entries move, exactly the eight whose only blocker was Ref(...) used as a value. EXPECTED_FOLD updated by name; the generated coverage block in typescript-as-data.mdx regenerated via npm run generate:fold-coverage.

Per-file blocker census (whole reason blocks parsed, both wordings)

cause before after
cross-file (#1063/#1020) 110 116
call-as-a-value 77 37
shape/other 60 71
taint (derivative) 28 20

Entries blocked by nothing but a call: 21 → 9. All 39 Ref blocks and both Concat blocks are gone; zero remain. What is left is github Checkout (8 blocks, 6 entries), helm include/printf (3 blocks, 3 entries), array .map/.flatMap (14), composite factories, and project-local helpers. cross-file and shape counts rise because a file that used to stop at its Ref now reports the next blocker behind it.

The measured AWS/Azure ceiling (acceptance criterion 7)

That is also the correction to #1039's framing, which is now stated on the concepts page instead of the old "by far the largest single gap" line: the intrinsics wiring called "the single biggest lever" moved one entry (#1042); the call form moved eight; and for the azure corpus the lever is a third issue neither of them touched. Cross-file-into-lexicon-package (#1063) is now the largest remaining cause at 116 file-blocks across 36 entries.

Gate evidence

$ just build          # npx tsc --noEmit -p packages/core/tsconfig.json
(clean)

$ just lint           # npx eslint packages/
(clean)

$ just test
 Test Files  756 passed | 1 skipped (757)
      Tests  8692 passed | 18 skipped (8710)

$ just fold-differential
 Test Files  1 passed (1)
      Tests  101 passed (101)
   -> 32 of 98 fold, every entry [identical]

$ just check-lexicons
aws — 17/17 tier-1 checks passing
azure — 17/17 tier-1 checks passing
17 known, tracked tier-1 failure(s)
No untracked tier-1 failures.

$ npm run build -w @intentius/chant-lexicon-azure
(clean; aws is vitest-gated and covered by `just test`)

Also checked by hand, since both have bitten before: no module-init-time filesystem probing was added anywhere under packages/core/src/discovery or fold (subset.ts's new import of ../lexicon is two pure predicates plus types; every fold-import.ts change is inside a function body), and the --sandbox differential over the same corpus passes, including all the aws/azure entries this PR moves.

Open uncertainties

  • liveSources is coarse on purpose. Any non-primitive counts as identity-bearing, rather than deep-walking for a Declarable. That can taint a file that merely imported a plain object constant from a tainted file. It costs no entry-level coverage (a mixed entry is already run-fallback) and the alternative is a deep walk whose only payoff is per-file counts inside entries that fall back anyway — but it is a judgement call worth a second opinion.
  • Provenance for call intrinsics follows the tag rule, not feat(core): chant's own authoring helpers (phase, output, Parameter) are unfoldable — caps real-app coverage #1082's. A registered, opted-in name must be bound by the file's own import, but the specifier is not required to be a lexicon package — exactly what the tagged-template path has always done (its own test fixtures import Sub from a local module). feat(core): chant's own authoring helpers (phase, output, Parameter) are unfoldable — caps real-app coverage #1082's helpers additionally require a chant-owned specifier because that allowlist is chant's rather than a lexicon's. Making the call form stricter than the tag form inside the same revival branch seemed worse than matching it; a lexicon-package provenance check for both forms is a coherent follow-up if we want it.
  • github (Checkout, 6 entries) and helm (include/printf, 3 entries) are measured headroom, unaudited here. helm's is the less obvious one — include/printf render Go-template text, so whether the call is a pure envelope constructor needs reading, not assuming.
  • helm's generated intrinsics page was already stale by 16 intrinsics before this branch; regenerating for the changed "Folds?" explanation picks that up. Called out so it does not read as something this PR changed.

lex00 added 5 commits July 26, 2026 20:38
…ic opt-in

`fold()` has no general CallExpression case, and that stays true. What
changes is that a lexicon can now declare, one intrinsic at a time, that a
plain call to it folds: `IntrinsicDef.foldsAsCall` (default off, never
inferred). A registered, opted-in call reduces to the same `{__intrinsic}`
envelope family the tagged-template form already produces — positional
`args` instead of `strings`/`values` — executing nothing; fold-import
resolves the name through the folding file's own imports and invokes the
real function, exactly as it already does for a registered tag.

subset.ts, the shared fold/EVL predicate, takes the registry as an OPTIONAL
parameter: supply it and the answer for a call is exact, omit it and every
call is a violation as before. Keeping the case out of the shared predicate
would make it systematically stricter than fold() for idiomatic `Ref(...)`,
which is the one direction that module is not allowed to be wrong in, and
would leave downstream tooling unable to ask "will this fold?" without
running fold.

Two supporting fixes the corpus forced out:

- An intrinsic's interior (a tag interpolation, now also a call argument)
  prefers an already-resolved cross-file binding over a `{__symbol}` the
  bridge re-imports, so `Ref(environment)` captures the shared Parameter
  instance rather than a second copy of it.
- planFoldTaint gains reverse edges. Forward taint covered "a run file
  imports a folded file"; a folded file that captured a now-tainted file's
  objects was uncovered, and `lexicons/aws/examples/lambda-api` crashed on
  it with "Logical name not set" the moment `Ref(...)` could fold. Folds
  now record which files' objects they consumed, and a tainted file
  invalidates them.

`chant dev check-lexicon` fails a registration that claims both `isTag` and
`foldsAsCall` — a tagged template has no plain-call authoring form.
Audited one at a time against the criterion on IntrinsicDef.foldsAsCall:
the call must be a pure function of its arguments that builds a
deterministic data envelope. All 8 aws plain calls (Ref, GetAtt, If, Join,
Select, Split, Base64, GetAZs) and all 9 azure ones (ResourceId, Reference,
Concat, ResourceGroup, Subscription, UniqueString, Format, If, ListKeys)
qualify: each stores its arguments and renders the intrinsic at
serialization time. Nothing is evaluated locally — Base64("x") emits
{"Fn::Base64": "x"} for the deployment to encode, UniqueString(x) emits
[uniqueString(x)] for ARM to hash.

aws `Sub` is the one intrinsic not opted in, and cannot be: it is a tagged
template, whose form already folds.

The packaged manifests carry the flag through verbatim, for the same reason
they carry isTag — the manifest is what a consumer reads to learn which
intrinsics fold, so recomputing it would be a second source of truth.
… to 32

Reducer unit tests pair every folding case with its near-miss: a registered
intrinsic with no opt-in, an opted-in name from an inactive lexicon, a tag
called as a function, a call-form intrinsic used as a tag, `ns.Ref(...)`,
`.map(...)`, a user function, a shadowing local const, an unfoldable
argument, a same-file resource as an argument.

End-to-end tests prove the envelope is revived by invoking the file's own
import (a sentinel `throw` at module top level never runs), that a call form
folds inside a tag's interpolation, and that a cross-file resource argument
arrives as the SAME instance the defining file's fold produced — identity,
not equality, which is what the taint fix exists to protect.

subset.ts gets its own block: with the registry the answer is exact, without
it every call is still a violation, and the resulting EVL-stricter-than-fold
divergence is recorded as a tracked property with a test rather than left to
be discovered.

Corpus: 24 -> 32 entries fold, zero drift. The eight are the AWS examples
whose only blocker was `Ref(...)` as a value (seven lambda-*, rds-postgres).
… framing

typescript-as-data gains a "Registered intrinsic calls" section (with a
subset-doc-parity test, the only one that needs the registry to classify),
the fold-capability list gains the call form, and the "function call as a
value is the largest remaining gap" line is replaced by what is actually
left: array `.map(...)`, project-local helpers, and lexicons not yet
audited.

The measured-blockers paragraph is re-measured and now reports per lexicon,
because that is what makes #1020/#1063's remaining value judgeable
separately: AWS went 4/18 -> 12/18 entries folding; Azure went 0/13 -> 0/13,
its two `Concat`-only entries both stopping on `Azure.ResourceGroupLocation`
as a plain value, which is #1063. #1039 called the intrinsics wiring "the
single biggest lever" and it moved one entry; this moved eight; for Azure
neither is the lever.

aws's intrinsics guide said a plain call cannot fold "today" — it can now,
for every intrinsic on that page. The generated Folds? column follows the
lexicon's own registration, so aws and azure regenerate to Yes. gitlab and
helm regenerate too since the column's explanation changed; helm's page was
also stale by 16 intrinsics from an earlier registration change, which that
regeneration picks up.

Also: sandbox.mdx's fold-coverage count (15 -> 32), the EVL divergence list
(EVL has no intrinsic registry, so it is stricter than fold on an opted-in
call), and check-lexicon's documented checks.
…signatures

intrinsicTagFolds takes { isTag?: boolean } deliberately, so an object
literal carrying foldsAsCall is an excess property. Bind the fixture once
and pass it, which is what a real caller with a full IntrinsicDef does.
tsc catches this; vitest does not.
@lex00

lex00 commented Jul 27, 2026

Copy link
Copy Markdown
Contributor Author

Orchestrator verification, measurements re-run independently:

  • fold-differential: 32/98, drift 0 (confirmed in 5 separate full-suite runs on the branch clone)
  • full suite: 5 consecutive clean runs (30–52s, 8692 passed), no hang-class regression
  • loomster, migrated tree + this branch's core and aws lexicon via npm-pack tarballs: every Ref block is gone (was 7 files). Headline count moved 13 → 9 folds — deliberately kept: the four newly run-fallback files are all would fold in isolation taint holds from this PR's reverse-edge fix, i.e. folds that were previously unsound (fold and run each constructing their own instances — the exact class that crashed lambda-api in the corpus). Loomster's direct blockers are now: sn() ×7 (loomster#157), user helpers, arrows — with 17 files taint-held behind them, so the sn() migration cascades.

Merging. The EVL-vs-fold divergence on call-form intrinsics (lint still flags Ref(...)) and the both-forms provenance follow-up are noted for the diagnostics pass.

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.

feat(core): fold registered plain-call intrinsics (per-intrinsic opt-in) — DECIDED: yes

1 participant