Repository navigation
feat(core): fold registered call-form intrinsics — per-intrinsic opt-in (#1044) - #1097
Merged
Merged
Conversation
…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.
Contributor
Author
|
Orchestrator verification, measurements re-run independently:
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. |
This was referenced Jul 27, 2026
Merged
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #1044.
What I was asked to do, restated
A registered lexicon intrinsic written as a plain call (
Ref(...),GetAtt(...), azureConcat(...)) should be able to fold the way a registered tagged template already does. Specifically:IntrinsicDefcarries an explicit foldability marker for the call form, default off; nothing folds by inference fromisTag, from the name, or from the call's shape..map(...)/any method call, a user function, a name shadowed by a local binding, a name the file never imported.subset.tsregistry question is resolved explicitly, in writing — the shared predicate takes the registry as an optional parameter (exact with, conservative without).EXPECTED_FOLDupdated by name; measured as a per-entry diff, not a summary count.Design: how the opt-in is declared, and why the door stays closed
IntrinsicDefgainsreadonly 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, becausefold()always knows which authored form it is looking at and the two must not leak into each other:fold()'sCallExpressioncase 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 ownconst, and the name is in the active lexicons' registered set with the opt-in set. It reduces to{ __intrinsic, args }— same__intrinsickey as{ __intrinsic, strings, values }, distinguished by which payload key is present — and executes nothing.fold-import.tsrevives both through the same branch:Fn(...args)for a call,Fn(strings, ...values)for a tag, whereFnis resolved through the folding file's ownimportbindings. 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":
intrinsics(), reviewable as such.chant dev check-lexiconfails a registration that claims bothisTagandfoldsAsCall, so the opt-in cannot be declared on a tagged template.aws.Ref(...),cidrs.map(...),Object.fromEntries(...)have no case at all, registered name or not."Ref" is not a resolvable import) and the file falls back. A localconst Ref = ...wins and rejects.requireLiveRefs. An intrinsic inspects what it is handed (RefcallsgetLogicalName,Subdoesinstanceofchecks), 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 idiomaticRef(...), and that is the one directionsubset.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 thanfold(): 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 lintkeeps flaggingRef(...)in a resource's props exactly as it does onmain— 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 changesrunLint'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: thewillFold(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)whereenvironmentis aParameterin 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-identifiedParameter.isUnresolvedSymbolChainnow consultsexternals, so a chain fold can resolve is not treated as unresolved. Tested by identity (toBe), not equality.planFoldTaintgains 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" — andlexicons/aws/examples/lambda-apicrashed on exactly that the momentRef(...)could fold:health-api.tsfolded and capturedparams.ts'sParameter;params.tswas 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 alreadyrun-fallback.Per-lexicon audit
aws — all 8 plain calls opted in:
Ref,GetAtt,If,Join,Select,Split,Base64,GetAZs. Each constructs its*Intrinsicclass and stores arguments verbatim; nothing is evaluated locally (Base64("x")emits{"Fn::Base64": "x"}for the deployment to encode).Joinvalidates 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/ListKeysname a deployment-time read rather than performing one.Deliberately out of scope: gitlab
reference(), githubCheckout, helminclude/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 ownnode_modulesand generated lexicon artifacts. Sorted per-entry lines, diffed: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 wasRef(...)used as a value.EXPECTED_FOLDupdated by name; the generated coverage block intypescript-as-data.mdxregenerated vianpm run generate:fold-coverage.Per-file blocker census (whole reason blocks parsed, both wordings)
Entries blocked by nothing but a call: 21 → 9. All 39
Refblocks and bothConcatblocks are gone; zero remain. What is left is githubCheckout(8 blocks, 6 entries), helminclude/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 itsRefnow reports the next blocker behind it.The measured AWS/Azure ceiling (acceptance criterion 7)
docs-snippets) — not by intrinsics. Two of them (shared-alb-api,shared-alb-ui) cleared theirRefblocker and stopped on a nestednew Parameter(...)as a composite argument, a pre-existing feat(core): fold — opt-in build path with run-fallback for composites #1022-era shape gap.Concat(...)cleared it and stopped onAzure.ResourceGroupLocationused as a plain value. All 13 azure entries' only remaining blocker is cross-file: feat(core): fold cross-file references into lexicon package exports (Azure/GCP pseudo-params, action constants) #1063, a lexicon-package namespace access. Azure's fold coverage is capped at zero by feat(core): fold cross-file references into lexicon package exports (Azure/GCP pseudo-params, action constants) #1063, and nothing feat(core): fold registered plain-call intrinsics (per-intrinsic opt-in) — DECIDED: yes #1044 could have done would move it.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
Also checked by hand, since both have bitten before: no module-init-time filesystem probing was added anywhere under
packages/core/src/discoveryorfold(subset.ts's new import of../lexiconis two pure predicates plus types; everyfold-import.tschange is inside a function body), and the--sandboxdifferential over the same corpus passes, including all the aws/azure entries this PR moves.Open uncertainties
liveSourcesis coarse on purpose. Any non-primitive counts as identity-bearing, rather than deep-walking for aDeclarable. 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 alreadyrun-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.Subfrom 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.Checkout, 6 entries) and helm (include/printf, 3 entries) are measured headroom, unaudited here. helm's is the less obvious one —include/printfrender Go-template text, so whether the call is a pure envelope constructor needs reading, not assuming.