@mettascript/fuzz 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,3665 @@
1
+ // src/index.ts
2
+ import { registerBuiltinModule } from "@mettascript/core";
3
+
4
+ // src/generated/module.ts
5
+ var FUZZ_MODULE_SRC = "; SPDX-FileCopyrightText: 2026 MesTTo\n;\n; SPDX-License-Identifier: MIT\n\n; Private grounded kernel data.\n(: FuzzRng Type)\n(: FuzzDraw Type)\n(: FuzzKernelError Type)\n\n(: _fuzz-rng-init (-> Number Atom))\n(: _fuzz-draw-int (-> Atom Number Number Atom))\n(: _fuzz-atom-key (-> Symbol Atom Atom))\n(: _fuzz-deduplicate-exact (-> Expression Atom))\n(: _fuzz-deduplicate-replay (-> Expression Atom))\n(: _fuzz-exact-member (-> Atom Expression Atom))\n(: _fuzz-replay-member (-> Atom Expression Atom))\n(: _fuzz-make-variable (-> Number Variable))\n(: _fuzz-variable-marker (-> Number Atom))\n(: _fuzz-contains-variable-marker (-> Atom Bool))\n(: _fuzz-materialize-grammar-sample (-> Atom Atom Atom %Undefined%))\n(: _fuzz-expression-append (-> Expression Atom Atom))\n(: _fuzz-expression-concat (-> Expression Expression Expression))\n(: _fuzz-grammar-summary-alternatives (-> Expression Atom Atom))\n(: _fuzz-grammar-summary-replace (-> Expression Atom Expression Atom))\n(: _fuzz-expression-view (-> Atom Atom))\n(: _fuzz-grammar-field-expressions (-> Atom Atom))\n(: _fuzz-grammar-replace-fields (-> Atom Expression Atom))\n(: _fuzz-grammar-index-references (-> Atom Atom))\n(: _fuzz-grammar-template-profile (-> Atom Atom))\n(: _fuzz-grammar-validation-plan (-> Atom Atom))\n(: _fuzz-grammar-template-reference-plan (-> Atom Atom))\n(: _fuzz-atom-ground (-> Atom Bool))\n(: _fuzz-custom-replay-tree (-> Atom Atom Atom))\n(: _fuzz-custom-replay-equal (-> Atom Atom Bool))\n(: _fuzz-float64-bits (-> Number Atom))\n(: _fuzz-float64-from-bits (-> Number Number Number))\n(: _fuzz-float64-index (-> Number Atom))\n(: _fuzz-float64-from-index (-> Number Number))\n(: _fuzz-unicode-character (-> Number Symbol))\n(: _fuzz-replay-equal (-> Atom Atom Bool))\n(: _fuzz-encode-atom (-> Atom Atom))\n(: _fuzz-decode-atom (-> Atom Atom))\n\n; Public generator, driver, sample, and property data.\n(: FuzzGenerator Type)\n(: FuzzDriver Type)\n(: FuzzDecision Type)\n(: FuzzSample Type)\n(: FuzzProperty Type)\n(: FuzzRunResult Type)\n(: FuzzSample (-> Atom Atom Atom FuzzSample))\n(: CustomReplayTree (-> Atom Atom))\n(: CustomReplayProtocolError (-> Atom Expression Atom))\n\n; Reified generator constructors.\n(: gen-const (-> Atom %Undefined%))\n(: gen-bool (-> %Undefined%))\n(: gen-int (-> Number Number %Undefined%))\n(: gen-int-origin (-> Number Number Number %Undefined%))\n(: gen-sized-int (-> %Undefined%))\n(: gen-float (-> %Undefined%))\n(: gen-float-range (-> Number Number %Undefined%))\n(: gen-float-bits (-> %Undefined%))\n(: gen-char (-> %Undefined%))\n(: gen-char-ascii (-> %Undefined%))\n(: gen-char-unicode (-> %Undefined%))\n(: gen-string (-> %Undefined% Number Number %Undefined%))\n(: gen-ascii-string (-> Number Number %Undefined%))\n(: gen-unicode-string (-> Number Number %Undefined%))\n(: gen-symbol (-> %Undefined%))\n(: gen-symbol-range (-> Number Number %Undefined%))\n(: gen-syntax-token (-> %Undefined%))\n(: gen-syntax-token-range (-> Number Number %Undefined%))\n(: gen-element (-> Expression %Undefined%))\n(: gen-frequency (-> Expression %Undefined%))\n(: gen-one-of (-> Expression %Undefined%))\n(: gen-tuple (-> Expression %Undefined%))\n(: gen-list (-> %Undefined% Number Number %Undefined%))\n(: gen-option (-> %Undefined% %Undefined%))\n(: gen-map (-> Atom %Undefined% %Undefined%))\n(: gen-bind (-> Atom %Undefined% %Undefined%))\n(: gen-filter (-> %Undefined% Atom Number %Undefined%))\n(: gen-sized (-> Atom %Undefined%))\n(: gen-resize (-> Number %Undefined% %Undefined%))\n(: gen-recursive (-> %Undefined% Atom %Undefined%))\n(: gen-custom (-> Atom Expression %Undefined%))\n(: gen-grammar (-> Atom %Undefined%))\n(: gen-grammar-root (-> Atom Atom %Undefined%))\n(: gen-well-typed (-> Atom Atom %Undefined%))\n\n; Grammar schemas are syntax data. Quoted carriers and Atom or Expression parameters keep templates,\n; nonterminals, and binding sorts unreduced while MeTTa relations validate and interpret their markers.\n(: FuzzTypeConstructors (-> Expression Atom))\n(: GrammarProduction (-> Number Number Atom Atom Atom))\n(: GrammarValidationTask (-> Atom Expression Atom))\n(: GrammarFitTask (-> Atom Expression Number Atom))\n(: GrammarRequest (-> Atom Atom Expression Number Atom))\n(: StaticGrammar (-> Atom Expression Atom))\n(: StaticTypeGrammar (-> Atom Expression Atom))\n(: DynamicTypeGrammar (-> Atom Atom))\n(: GrammarResult (-> Atom Atom Number Atom Atom))\n(: GrammarChildrenResult (-> Expression Atom Number Expression Number Atom))\n(: GrammarFieldExpressions (-> Expression Atom))\n(: FuzzExpressionView (-> Atom Expression Expression Atom))\n(: FuzzAtomLeaf (-> Atom))\n(: GrammarGeneratorValidationTask (-> Atom Atom))\n(: ResolvedGrammarField (-> Atom Atom))\n(: ResolvedGrammarFields (-> Expression Atom))\n(: NormalizedGrammarTemplate (-> Atom Atom))\n(: PreparedGrammarTemplate (-> Atom Number Number Number Number Atom))\n(: ValidatedGrammarProductions (-> Expression Number Atom))\n(: ValidatedGrammar (-> Atom Atom Expression Number Atom))\n(: PreparedTypeConstructors (-> Expression Number Atom))\n(: ValidatedTypeGrammar (-> Atom Atom Expression Number Atom))\n(: GrammarRequirementAlternative (-> Expression Atom))\n(: GrammarRequirementAlternatives (-> Expression Atom))\n(: GrammarRequirementSummaryEntry (-> Atom Expression Atom))\n(: GrammarSummaryMergeState (-> Bool Expression Atom))\n(: GrammarProductivityPassState (-> Bool Expression Atom))\n(: GrammarProductivityPass (-> Bool Expression Atom))\n(: GrammarMissingTarget (-> Atom Atom))\n(: GrammarRequirementStack (-> Expression Atom))\n(: GrammarValidationPlan (-> Expression Atom))\n(: GrammarValidationState (-> Expression Expression Atom))\n(: GrammarReferenceTargets (-> Expression Atom))\n(: GrammarBindingValidationState\n (-> Expression Expression Number Atom))\n(: _fuzz-grammar-generator-validation-tasks\n (-> Expression %Undefined% %Undefined%))\n(: _fuzz-grammar-generator-child-task (-> Atom %Undefined% %Undefined%))\n(: _fuzz-grammar-frequency-validation\n (-> Expression %Undefined% Number %Undefined%))\n(: _fuzz-validate-grammar-field-generator (-> Atom %Undefined%))\n(: _fuzz-grammar-field-from-results (-> Atom Expression %Undefined%))\n(: _fuzz-resolve-grammar-field (-> Atom %Undefined%))\n(: _fuzz-resolve-grammar-fields-loop\n (-> Expression %Undefined% %Undefined%))\n(: _fuzz-normalize-grammar-template-fields (-> Atom %Undefined%))\n(: _fuzz-prepare-grammar-template (-> Atom Atom %Undefined%))\n(: _fuzz-grammar-template-switch (-> Atom Expression %Undefined%))\n(: _fuzz-normalize-grammar-productions (-> Atom Expression %Undefined%))\n(: _fuzz-build-grammar (-> Atom Atom Expression %Undefined%))\n(: _fuzz-grammar-target-member (-> Atom Expression %Undefined%))\n(: _fuzz-grammar-add-target (-> Atom Expression %Undefined%))\n(: _fuzz-grammar-reference-targets-loop\n (-> Expression Expression %Undefined%))\n(: _fuzz-grammar-reference-targets (-> Expression %Undefined%))\n(: _fuzz-validate-normalized-grammar\n (-> Atom Atom Expression Number %Undefined%))\n(: _fuzz-grammar-from-results\n (-> Atom Atom Expression %Undefined%))\n(: _fuzz-gen-grammar-root-ground\n (-> Atom Atom %Undefined%))\n(: _fuzz-normalize-type-constructors-loop\n (-> Atom Atom Expression Number %Undefined% Number %Undefined%))\n(: _fuzz-normalize-type-constructors (-> Atom Atom Expression %Undefined%))\n(: _fuzz-static-productions-for-target-loop\n (-> Expression Atom Expression %Undefined%))\n(: _fuzz-source-productions (-> Atom Atom %Undefined%))\n(: _fuzz-type-schema-from-results\n (-> Atom Atom Expression %Undefined%))\n(: _fuzz-finalize-type-grammar\n (-> Atom Atom Expression Number %Undefined%))\n(: _fuzz-build-type-grammar-prepared\n (-> Atom Atom Atom Expression Expression Expression Number Number Expression Number %Undefined%))\n(: _fuzz-build-type-grammar-available\n (-> Atom Atom Atom Expression Expression Expression Number Number Atom %Undefined%))\n(: _fuzz-build-type-grammar-type\n (-> Atom Atom Atom Expression Expression Expression Number Number %Undefined%))\n(: _fuzz-build-type-grammar-loop\n (-> Atom Atom Expression Expression Expression Number Number %Undefined%))\n(: _fuzz-build-type-grammar\n (-> Atom Atom %Undefined%))\n(: _fuzz-gen-well-typed-ground\n (-> Atom Atom %Undefined%))\n(: _fuzz-validate-grammar-template (-> Atom Atom %Undefined%))\n(: _fuzz-validate-grammar-binding-step\n (-> Atom Atom %Undefined%))\n(: _fuzz-validate-grammar-bindings (-> Expression %Undefined%))\n(: _fuzz-grammar-validation-enter-scope\n (-> Atom Expression Expression Expression %Undefined%))\n(: _fuzz-grammar-validation-exit-scope\n (-> Expression Expression %Undefined%))\n(: _fuzz-grammar-validation-event\n (-> Atom Atom Atom %Undefined%))\n(: _fuzz-grammar-validation-from-fold\n (-> Atom Atom %Undefined%))\n(: _fuzz-template-reference-targets (-> Atom %Undefined% %Undefined%))\n(: _fuzz-template-reference-target-step\n (-> Expression Atom %Undefined%))\n(: _fuzz-grammar-summary-merge-alternative\n (-> Bool Atom Expression Atom %Undefined%))\n(: _fuzz-grammar-summary-merge-step\n (-> Atom Atom Atom %Undefined%))\n(: _fuzz-grammar-summary-merge\n (-> Atom Expression Expression %Undefined%))\n(: _fuzz-grammar-template-requirements\n (-> Atom Expression %Undefined%))\n(: _fuzz-grammar-summary-has-target\n (-> Atom Expression %Undefined%))\n(: _fuzz-grammar-summary-has-closed-target\n (-> Atom Expression %Undefined%))\n(: _fuzz-first-unsummarized-target-step\n (-> Atom Atom Expression %Undefined%))\n(: _fuzz-first-unsummarized-target\n (-> Expression Expression %Undefined%))\n(: _fuzz-grammar-all-targets-summarized-step\n (-> Atom Atom Expression %Undefined%))\n(: _fuzz-grammar-all-targets-summarized\n (-> Expression Expression %Undefined%))\n(: _fuzz-grammar-productivity-result\n (-> Atom Atom Expression Expression %Undefined%))\n(: _fuzz-grammar-productivity-fixedpoint\n (-> Atom Atom Expression Expression Expression %Undefined%))\n(: _fuzz-validate-grammar-productivity\n (-> Atom Atom Expression Expression %Undefined%))\n(: _fuzz-grammar-scope-has-id-step\n (-> Bool Atom Number Bool))\n(: _fuzz-grammar-scope-has-id (-> Expression Number Bool))\n(: _fuzz-grammar-scopes-disjoint-step\n (-> Bool Atom Expression Bool))\n(: _fuzz-grammar-scopes-disjoint (-> Expression Expression Bool))\n(: _fuzz-grammar-scope-values\n (-> Expression Atom Expression %Undefined%))\n(: _fuzz-eligible-productions\n (-> Atom Atom Expression Number %Undefined%))\n(: _fuzz-generate-grammar-nonterminal\n (-> Atom Atom Expression Number Atom Number %Undefined%))\n\n; Driver constructors and one-sample entry points.\n(: fuzz-random-driver (-> Number %Undefined%))\n(: fuzz-edge-driver (-> Number %Undefined%))\n(: fuzz-replay-driver (-> Atom %Undefined%))\n(: fuzz-exhaustive-driver (-> %Undefined%))\n(: _fuzz-exhaustive-resume-driver (-> Atom %Undefined%))\n(: _fuzz-exhaustive-next-plan (-> Atom %Undefined%))\n(: _fuzz-exhaustive-plan-prefix (-> Atom Atom %Undefined%))\n(: ExhaustiveCursor (-> Atom Number Atom Atom))\n(: ExhaustiveFrame (-> Number Number Atom))\n(: ExhaustivePlan (-> Atom Atom))\n(: fuzz-enumerate (-> %Undefined% Number Number %Undefined%))\n(: FrequencyIndexChoice (-> Number Atom Atom Atom Atom))\n(: FuzzEnumerateRun (-> Atom Number Number Atom Number Number Number Atom Atom))\n(: FuzzEnumeration (-> Atom Atom Atom Atom Atom))\n(: FuzzEnumerationTruncated (-> Atom Atom Atom Atom Atom))\n(: fuzz-bytes-driver (-> Expression %Undefined%))\n(: fuzz-generate (-> %Undefined% %Undefined% Number %Undefined%))\n(: fuzz-generate-random (-> %Undefined% Number Number %Undefined%))\n(: fuzz-generate-edge (-> %Undefined% Number Number %Undefined%))\n(: fuzz-generate-bytes (-> %Undefined% Expression Number %Undefined%))\n(: fuzz-replay (-> %Undefined% Atom Number %Undefined%))\n(: _fuzz-shrink-replay (-> %Undefined% Atom Number %Undefined%))\n\n; Property outcomes and case classification.\n(: _fuzz-eval-case (-> Atom Number Number Atom Atom))\n(: fuzz-pass (-> FuzzProperty))\n(: fuzz-fail (-> Atom Atom FuzzProperty))\n(: fuzz-discard (-> Atom FuzzProperty))\n(: expect-true (-> Bool Atom FuzzProperty))\n(: expect-false (-> Bool Atom FuzzProperty))\n(: expect-atom-equal (-> %Undefined% %Undefined% FuzzProperty))\n(: expect-alpha-equal (-> %Undefined% %Undefined% FuzzProperty))\n(: expect-results-exact (-> %Undefined% %Undefined% FuzzProperty))\n(: expect-results-alpha (-> %Undefined% %Undefined% FuzzProperty))\n(: expect-results-multiset (-> %Undefined% %Undefined% FuzzProperty))\n(: expect-results-set (-> %Undefined% %Undefined% FuzzProperty))\n(: implies (-> Bool Atom FuzzProperty))\n(: classify (-> Bool %Undefined% Atom FuzzProperty))\n(: collect (-> %Undefined% Atom FuzzProperty))\n(: cover (-> Number Bool %Undefined% Atom FuzzProperty))\n(: counterexample (-> %Undefined% Atom FuzzProperty))\n(: all-results (-> Atom Atom))\n(: any-result (-> Atom Atom))\n(: fuzz-equal (-> %Undefined% %Undefined% FuzzProperty))\n(: fuzz-alpha-equal (-> %Undefined% %Undefined% FuzzProperty))\n(: fuzz-implies (-> Bool Atom FuzzProperty))\n(: fuzz-annotate (-> %Undefined% Atom FuzzProperty))\n(: fuzz-classify (-> Bool %Undefined% Atom FuzzProperty))\n(: fuzz-collect (-> %Undefined% Atom FuzzProperty))\n(: fuzz-cover (-> Number %Undefined% Bool Atom FuzzProperty))\n(: _fuzz-normalize-property-result (-> Atom %Undefined%))\n(: _fuzz-evaluate-property (-> Atom Atom Atom Number Number Atom %Undefined%))\n(: fuzz-default-config (-> %Undefined%))\n(: fuzz-check (-> Atom %Undefined% Atom %Undefined% %Undefined%))\n(: fuzz-check-exhaustive (-> Atom %Undefined% Atom %Undefined% %Undefined%))\n(: _fuzz-check-with (-> Atom %Undefined% Atom %Undefined% Atom %Undefined%))\n\n; Model-based state machines.\n(: FuzzMachine Type)\n(: gen-machine (-> Atom %Undefined%))\n(: fuzz-check-machine (-> Atom %Undefined% %Undefined%))\n(: _fuzz-machine-spec (-> Atom %Undefined%))\n(: _fuzz-machine-spec-results (-> Atom Expression %Undefined%))\n(: _fuzz-machine-call-zero (-> Atom Atom %Undefined%))\n(: _fuzz-machine-call-two (-> Atom Atom Atom Atom %Undefined%))\n(: _fuzz-machine-call-three (-> Atom Atom Atom Atom Atom %Undefined%))\n(: _fuzz-machine-bool-two (-> Atom Atom Atom Atom %Undefined%))\n(: _fuzz-machine-command-descriptor (-> Atom Atom %Undefined%))\n(: MachineDraw (-> Atom Atom Atom Atom Number Number Atom Atom))\n(: MachineCommandDrawn (-> Atom Atom Atom Atom))\n(: MachineSpec (-> Atom Atom Atom Atom Atom Atom Atom Atom Atom Atom))\n(: MachineSequence (-> Atom Atom Atom))\n(: ValidMachineSpec (-> Atom Atom))\n(: FuzzMachineRun (-> Atom Atom Atom Atom))\n(: MachineGenRun (-> Atom Atom Atom Number Atom Number Atom Atom Atom))\n(: MachineExecRun (-> Atom Atom Atom Atom Number Atom))\n(: MachineVerdict (-> Atom Atom))\n; Bounded state reachability. The search-state constructors take their payload as Atom so a state\n; or command carried across a loop iteration is never re-evaluated.\n(: fuzz-reachable (-> Atom %Undefined% Atom Atom Atom %Undefined% %Undefined%))\n(: reach-config-defaults (-> %Undefined%))\n(: FuzzReachEquivariant (-> Atom Atom))\n(: ReachSpec (-> Atom Atom Atom Atom Atom Atom Atom))\n(: ReachRun (-> Atom Atom Atom Atom Atom Number Atom Atom Atom))\n(: ReachNode (-> Atom Atom Atom))\n(: ReachCounts (-> Number Number Atom))\n(: ReachCommands (-> Atom Atom Atom Number Atom))\n(: ReachBranches (-> Atom Atom Atom Number Atom Number Atom))\n(: ReachReplay (-> Atom Atom Atom Number Atom))\n(: ReachConfigValues (-> Atom Atom Atom Atom Atom))\n(: ReachConfigFold (-> Atom Expression Atom))\n(: ReachKey (-> Atom Atom))\n(: ReachUnkeyable (-> Atom Atom Atom))\n(: ReachItem (-> Atom Atom))\n(: ReachFinite (-> Expression Atom))\n(: ReachIncomplete (-> Atom Atom))\n(: ReachMalformed (-> Atom Atom))\n(: ReachFound (-> Atom Atom Atom))\n(: ReachExhausted (-> Number Atom))\n(: ReachUnreachableWithinDepth (-> Number Atom))\n(: ReachCutoff (-> Atom Atom))\n(: ReachReplayState (-> Atom Atom))\n(: ReachReplayed (-> Atom Atom))\n(: ReachReplayFailed (-> Atom Atom))\n(: Step (-> Number Atom Number Atom))\n(: CallAll (-> Atom Atom))\n(: _fuzz-call-all-two (-> Atom Atom Atom Atom %Undefined%))\n(: _fuzz-call-all-results (-> %Undefined% Atom %Undefined%))\n(: _fuzz-pair-values (-> %Undefined% %Undefined%))\n(: _fuzz-expression-head (-> Atom %Undefined%))\n(: _fuzz-reach-bound-value (-> Atom Bool))\n(: _fuzz-reach-config-set (-> Atom Atom %Undefined%))\n(: _fuzz-reach-config-values (-> Atom %Undefined%))\n(: _fuzz-reach-config-get (-> Atom Atom %Undefined%))\n(: _fuzz-reach-state-key (-> Atom Atom %Undefined%))\n(: _fuzz-reach-command-items (-> Atom %Undefined%))\n(: _fuzz-reach-nth (-> Atom Number %Undefined%))\n(: _fuzz-reach-cutoff (-> Atom Atom %Undefined%))\n(: _fuzz-reach-searching (-> Atom Bool))\n(: _fuzz-reach-at-depth-limit (-> Number Atom Bool))\n(: _fuzz-reach-note-beyond-depth (-> Atom Atom %Undefined%))\n(: _fuzz-reach-expand (-> Atom Atom %Undefined%))\n(: _fuzz-reach-apply (-> Atom Atom Atom Number %Undefined%))\n(: _fuzz-reach-visit (-> Atom Atom Atom Number Number Atom %Undefined%))\n(: _fuzz-reach-judge (-> Atom Atom Atom Atom %Undefined%))\n(: _fuzz-reach-target (-> Atom Atom Atom Atom Atom %Undefined%))\n(: _fuzz-reach-enqueue (-> Atom Atom Atom Atom Atom %Undefined%))\n(: _fuzz-reach-confirm (-> Atom Atom Atom %Undefined%))\n(: _fuzz-reach-same-state (-> Atom Atom Atom Bool))\n(: _fuzz-reach-replay (-> Atom Atom %Undefined%))\n(: _fuzz-reach-replay-apply (-> Atom Atom Atom Number %Undefined%))\n(: _fuzz-reach-replay-transition (-> Atom Atom Atom Number Number %Undefined%))\n(: _fuzz-reach-identity-permitted (-> Atom Atom Bool))\n(: _fuzz-reach-start (-> Atom Atom Atom Atom Atom Atom %Undefined%))\n(: _fuzz-reach-run (-> Atom Atom Atom %Undefined%))\n(: _fuzz-reach-report (-> Atom %Undefined%))\n(: _fuzz-reach-witness-commands (-> Atom %Undefined%))\n(: ReachWitnessFold (-> Atom Atom Atom))\n(: FuzzPairValuesFold (-> Atom Atom Atom))\n(: FuzzLeafDistanceFold (-> Atom Atom Atom))\n(: FuzzRepeatFold (-> Atom Number Atom Atom))\n\n(: FuzzExhaustiveRun (-> Atom Atom Atom Atom Atom Atom Number Number Atom Atom))\n(: FuzzExhaustivelyVerified (-> Atom Atom Atom Atom Atom))\n(: ExhaustiveStatistics (-> Atom Atom Atom Atom))\n\n; Helpers that intentionally receive generated expressions as data.\n(: _fuzz-if-generation-error (-> %Undefined% Atom %Undefined%))\n(: _fuzz-is-integer (-> Number Bool))\n(: _fuzz-expected-integer (-> Atom Number %Undefined%))\n(: _fuzz-call-results-bind (-> %Undefined% Atom %Undefined%))\n(: _fuzz-bool-result (-> Atom Atom %Undefined%))\n(: CallOne (-> Atom Atom))\n(: _fuzz-call-one (-> Atom Atom Atom %Undefined%))\n(: _fuzz-call-bool (-> Atom Atom Atom %Undefined%))\n(: _fuzz-driver-int (-> %Undefined% Number Number Number %Undefined%))\n(: _fuzz-byte-width (-> Number Number Number Number))\n(: _fuzz-read-bytes (-> Expression Number Number Number %Undefined%))\n(: _fuzz-generate-many (-> Expression %Undefined% Number Expression Expression %Undefined%))\n(: _fuzz-generate-filter (-> %Undefined% Atom Number Number %Undefined% Number Expression %Undefined%))\n(: _fuzz-wrap-sample (-> Atom Atom Atom %Undefined% %Undefined%))\n(: _fuzz-two-children (-> Atom Atom Expression))\n(: _fuzz-repeat-generator (-> Atom Number Expression))\n(: CustomCapabilities (-> Atom Expression %Undefined%))\n(: DriveCustom (-> Atom Expression Atom Number %Undefined%))\n(: EdgeChoices (-> Atom Expression Number %Undefined%))\n(: ShrinkChoices (-> Atom Expression Atom %Undefined%))\n(: FuzzTypeSchema (-> Atom Atom %Undefined%))\n\n; ---- grammar machine ----\n; Constructors and relations of the generation machine and the productivity worklist. Every\n; slot that carries raw template syntax or generated values is Atom-typed: an Atom parameter\n; is not reduced at a call or construction, which is what keeps held user syntax unevaluated\n; through the machine.\n(: FuzzStack (-> Atom Atom Atom))\n(: FuzzStackTake (-> Expression Atom Atom))\n(: GF (-> Atom Atom Atom))\n(: FPlan (-> Expression Number Number Number Atom))\n(: FExpr (-> Number Number Number Atom))\n(: FRef (-> Atom Atom))\n(: FProd (-> Atom Number Number Atom Atom))\n(: FBind (-> Atom Number Atom Atom))\n(: FScoped (-> Expression Atom))\n(: FScope (-> Atom Atom))\n(: FuzzGenRun (-> Atom Atom Atom Number Atom Number Atom Number Atom Atom))\n(: FuzzGenCut (-> Atom Atom Atom Number Atom Number Atom Atom Atom Atom))\n(: FuzzGenDone (-> Atom Atom))\n(: GILit (-> Atom Atom))\n(: GIField (-> Atom Atom))\n(: GIRef (-> Atom Number Number Atom))\n(: GIFresh (-> Atom Atom))\n(: GIUse (-> Atom Atom))\n(: GIBind (-> Atom Expression Atom))\n(: GIScoped (-> Expression Number Atom Expression Atom))\n(: GIExprEnter (-> Number Atom))\n(: GIExprBuild (-> Atom))\n(: GrammarTemplatePlan (-> Expression Atom))\n(: GrammarAlternativesAdd (-> Bool Expression Atom))\n(: GrammarProductions (-> Expression Atom))\n(: GrammarDependents (-> Expression Atom))\n(: EligibleGrammarProductions (-> Expression Atom))\n(: FitDuplicateGrammarBindingId (-> Atom Atom))\n(: FuzzProductivityQueue (-> Expression Atom Expression Atom))\n(: _fuzz-gen-loop (-> %Undefined% %Undefined%))\n(: _fuzz-gen-finished (-> %Undefined% Bool))\n(: _fuzz-gen-step (-> %Undefined% %Undefined%))\n(: _fuzz-gen-push\n (-> Atom Atom Atom Number Atom Number Atom Number Atom Atom Atom %Undefined%))\n(: _fuzz-gen-run-step\n (-> Atom Atom Atom Number Atom Number Atom Number Atom %Undefined%))\n(: _fuzz-gen-cut-step\n (-> Atom Atom Atom Number Atom Number Atom Atom Atom %Undefined%))\n(: _fuzz-gen-instr\n (-> Atom Atom Atom Number Atom Number Atom Number Atom Atom Number %Undefined%))\n(: _fuzz-gen-insert-expr (-> Atom Number Number Number Atom))\n(: _fuzz-gen-field\n (-> Atom Atom Atom Number Atom Number Atom Number Atom Atom Atom %Undefined%))\n(: _fuzz-gen-use\n (-> Atom Atom Atom Number Atom Number Atom Number Atom Atom %Undefined%))\n(: _fuzz-gen-nonterminal\n (-> Atom Atom Atom Number Atom Number Atom Number Atom Atom Number %Undefined%))\n(: _fuzz-gen-choose\n (-> Atom Atom Atom Number Atom Number Atom Number Atom Number Expression Atom %Undefined%))\n(: _fuzz-eligible-productions (-> Atom Atom Expression Number %Undefined%))\n(: _fuzz-eligible-productions-checked (-> Expression Atom Expression Number %Undefined%))\n(: _fuzz-grammar-summary-merge-candidate\n (-> Bool Expression Expression Expression Atom %Undefined%))\n(: _fuzz-productivity-done (-> %Undefined% Bool))\n(: _fuzz-productivity-changed (-> Expression Atom Atom Expression %Undefined%))\n(: _fuzz-productivity-analyze (-> Expression Atom Expression Atom Atom %Undefined%))\n(: _fuzz-productivity-step (-> %Undefined% %Undefined%))\n(: _fuzz-productivity-loop (-> %Undefined% %Undefined%))\n(: _fuzz-grammar-template-requirements-op (-> Atom Expression Atom))\n(: _fuzz-grammar-eligible-productions-op (-> Expression Atom Expression Number Atom))\n(: _fuzz-grammar-dependents-of (-> Expression Atom Atom))\n(: _fuzz-index-stack (-> Number Atom))\n(: _fuzz-stack-take (-> Atom Number Atom))\n(: _fuzz-stack-push-all (-> Atom Expression Atom))\n(: _fuzz-grammar-template-plan (-> Atom Atom))\n(: _fuzz-grammar-alternatives-add (-> Expression Expression Atom))\n(: GrammarMachineStart (-> Atom Atom Expression Number Atom Atom))\n(: GrammarMachineResume (-> Atom Atom Atom))\n(: GrammarMachineDone (-> Atom Atom))\n(: GrammarMachineNeed (-> Atom Atom Atom))\n(: EvaluateGenerator (-> Atom Atom Number Atom))\n(: WithDriver (-> Atom Number Atom))\n(: _fuzz-grammar-machine-op (-> Atom Atom))\n(: _fuzz-gen-trampoline (-> %Undefined% %Undefined%))\n(: _fuzz-generate-grammar-nonterminal-reference\n (-> Atom Atom Expression Number Atom Number %Undefined%))\n(: FuzzDecisionLeaves (-> Expression Atom))\n(: _fuzz-decision-leaves-op (-> Atom Atom))\n(: GrammarUnproductive (-> Atom Atom))\n(: _fuzz-grammar-productivity-op (-> Expression Atom Expression Atom))\n(: _fuzz-validate-grammar-productivity-reference\n (-> Atom Atom Expression Expression %Undefined%))\n(: GrammarTargets (-> Expression Atom))\n(: GrammarMissingReference (-> Atom Atom))\n(: FuzzNormalizeWalk (-> Atom Atom Number Atom Number Atom))\n(: _fuzz-grammar-targets-op (-> Expression Atom))\n(: _fuzz-grammar-validate-references-op (-> Expression Expression Atom))\n(: _fuzz-stack-to-expression (-> Atom Atom))\n(: _fuzz-normalize-walk-done (-> %Undefined% Bool))\n(: _fuzz-normalize-walk-step (-> %Undefined% %Undefined%))\n(: _fuzz-normalize-walk-loop (-> %Undefined% %Undefined%))\n(: _fuzz-normalize-walk-prepared\n (-> Atom Atom Number Atom Number Number Atom Atom %Undefined%))\n(: _fuzz-validated-references\n (-> Atom Atom Expression Number Expression %Undefined%))\n\n; SPDX-FileCopyrightText: 2026 MesTTo\n;\n; SPDX-License-Identifier: MIT\n\n; Constructor errors remain normal MeTTa data so callers can report them without a host exception.\n(= (_fuzz-generation-error $code $details)\n (FuzzGenerationError $code (Details $details)))\n\n(= (_fuzz-generation-error $code $first $second)\n (FuzzGenerationError $code (Details $first $second)))\n\n(= (_fuzz-generation-error $code $first $second $third)\n (FuzzGenerationError $code (Details $first $second $third)))\n\n(= (_fuzz-generation-error $code $first $second $third $fourth)\n (FuzzGenerationError\n $code\n (Details $first $second $third $fourth)))\n\n(= (_fuzz-if-generation-error $candidate $otherwise)\n (switch $candidate\n (((FuzzGenerationError $code $details) $candidate)\n ($valid $otherwise))))\n\n(= (_fuzz-is-integer $value)\n (and\n (== (isnan-math $value) False)\n (and\n (== (isinf-math $value) False)\n (== $value (trunc-math $value)))))\n\n(= (_fuzz-expected-integer $parameter $value)\n (_fuzz-generation-error ExpectedInteger\n (Parameter $parameter)\n (Value $value)))\n\n(= (_fuzz-default-int-origin $lower $upper)\n (if (and (<= $lower 0) (>= $upper 0))\n 0\n (if (> $lower 0) $lower $upper)))\n\n(= (_fuzz-default-float-origin $lower-index $upper-index)\n (_fuzz-default-int-origin $lower-index $upper-index))\n\n(= (_fuzz-validated-float-index $parameter $value)\n (let $indexed (_fuzz-float64-index $value)\n (switch $indexed\n (((Float64Index $index)\n (if (and\n (<= -9218868437227405312 $index)\n (<= $index 9218868437227405311))\n (ValidatedFloatIndex $index)\n (_fuzz-generation-error\n NonFiniteFloatBound\n (Parameter $parameter)\n (Value $value))))\n ((FuzzKernelError InvalidFloat $operation ExpectedFloat)\n (_fuzz-generation-error\n ExpectedFloat\n (Parameter $parameter)\n (Value $value)))\n ((FuzzKernelError InvalidFloat $operation NaNHasNoOrderedIndex)\n (_fuzz-generation-error\n NaNFloatBound\n (Parameter $parameter)\n (Value $value)))\n ((FuzzKernelError $code $details)\n (_fuzz-generation-error\n KernelError\n (OperationResult $indexed)))\n ($bad\n (_fuzz-generation-error\n MalformedFloatIndex\n (OperationResult $bad)))))))\n\n(= (gen-const $value)\n (GenConst $value))\n\n(= (gen-bool)\n (GenBool))\n\n(= (gen-int $lower $upper)\n (if (_fuzz-is-integer $lower)\n (if (_fuzz-is-integer $upper)\n (if (<= $lower $upper)\n (GenInt $lower $upper (_fuzz-default-int-origin $lower $upper))\n (_fuzz-generation-error InvalidIntegerBounds (Bounds $lower $upper)))\n (_fuzz-expected-integer UpperBound $upper))\n (_fuzz-expected-integer LowerBound $lower)))\n\n(= (gen-int-origin $lower $upper $origin)\n (if (_fuzz-is-integer $lower)\n (if (_fuzz-is-integer $upper)\n (if (<= $lower $upper)\n (if (_fuzz-is-integer $origin)\n (if (and (<= $lower $origin) (<= $origin $upper))\n (GenInt $lower $upper $origin)\n (_fuzz-generation-error InvalidIntegerOrigin\n (Bounds $lower $upper)\n (Origin $origin)))\n (_fuzz-expected-integer Origin $origin))\n (_fuzz-generation-error InvalidIntegerBounds (Bounds $lower $upper)))\n (_fuzz-expected-integer UpperBound $upper))\n (_fuzz-expected-integer LowerBound $lower)))\n\n(= (gen-sized-int)\n (GenSized _fuzz-sized-int-generator))\n\n(: _fuzz-sized-int-generator (-> Number %Undefined%))\n(= (_fuzz-sized-int-generator $size)\n (gen-int (- 0 $size) $size))\n\n(= (gen-float)\n (GenFloatRange\n -9218868437227405312\n 9218868437227405311\n 0))\n\n(= (_fuzz-float-range-from-upper\n $lower\n $upper\n $lower-index\n $upper-result)\n (switch $upper-result\n (((FuzzGenerationError $code $details) $upper-result)\n ((ValidatedFloatIndex $upper-index)\n (if (<= $lower-index $upper-index)\n (GenFloatRange\n $lower-index\n $upper-index\n (_fuzz-default-float-origin\n $lower-index\n $upper-index))\n (_fuzz-generation-error\n InvalidFloatBounds\n (Bounds $lower $upper))))\n ($bad\n (_fuzz-generation-error\n MalformedFloatIndex\n (OperationResult $bad))))))\n\n(= (_fuzz-float-range-from-lower\n $lower\n $upper\n $lower-result)\n (switch $lower-result\n (((FuzzGenerationError $code $details) $lower-result)\n ((ValidatedFloatIndex $lower-index)\n (_fuzz-float-range-from-upper\n $lower\n $upper\n $lower-index\n (_fuzz-validated-float-index UpperBound $upper)))\n ($bad\n (_fuzz-generation-error\n MalformedFloatIndex\n (OperationResult $bad))))))\n\n(= (gen-float-range $lower $upper)\n (_fuzz-float-range-from-lower\n $lower\n $upper\n (_fuzz-validated-float-index LowerBound $lower)))\n\n(= (gen-float-bits)\n (GenFloatBits))\n\n(= (_fuzz-character-from-index $index)\n (_fuzz-unicode-character $index))\n\n(= (_fuzz-characters $characters)\n (stringToChars $characters))\n\n(= (gen-char)\n (gen-map\n _fuzz-character-from-index\n (gen-int 32 126)))\n\n(= (gen-char-ascii)\n (gen-map\n _fuzz-character-from-index\n (gen-int 0 127)))\n\n(= (gen-char-unicode)\n (gen-map\n _fuzz-character-from-index\n (gen-int 0 1112061)))\n\n(= (_fuzz-characters-to-string $characters)\n (charsToString $characters))\n\n(= (gen-string $character-generator $minimum $maximum)\n (gen-map\n _fuzz-characters-to-string\n (gen-list\n $character-generator\n $minimum\n $maximum)))\n\n(= (gen-ascii-string $minimum $maximum)\n (gen-string\n (gen-char-ascii)\n $minimum\n $maximum))\n\n(= (gen-unicode-string $minimum $maximum)\n (gen-string\n (gen-char-unicode)\n $minimum\n $maximum))\n\n(= (_fuzz-parser-safe-first-characters)\n (_fuzz-characters\n \"abcdefghijklmnopqrstuvwxyz_\"))\n\n(= (_fuzz-parser-safe-rest-characters)\n (_fuzz-characters\n \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_+-*/<>=!?\"))\n\n(= (_fuzz-symbol-from-parts $parts)\n (switch $parts\n ((($first $rest)\n (let $characters (cons-atom $first $rest)\n (let $name (charsToString $characters)\n (atom_concat $name))))\n ($bad\n (_fuzz-generation-error\n MalformedSymbolParts\n (Value $bad))))))\n\n(= (gen-symbol-range $minimum $maximum)\n (if (_fuzz-is-integer $minimum)\n (if (_fuzz-is-integer $maximum)\n (if (and\n (<= 1 $minimum)\n (<= $minimum $maximum))\n (gen-map\n _fuzz-symbol-from-parts\n (gen-tuple\n ((gen-element\n (_fuzz-parser-safe-first-characters))\n (gen-list\n (gen-element\n (_fuzz-parser-safe-rest-characters))\n (- $minimum 1)\n (- $maximum 1)))))\n (_fuzz-generation-error\n InvalidSymbolLengthBounds\n (Minimum $minimum)\n (Maximum $maximum)))\n (_fuzz-expected-integer\n MaximumLength\n $maximum))\n (_fuzz-expected-integer\n MinimumLength\n $minimum)))\n\n(= (_fuzz-symbol-at-size $size)\n (gen-symbol-range 1 (max 1 $size)))\n\n(= (gen-symbol)\n (gen-sized _fuzz-symbol-at-size))\n\n(= (_fuzz-syntax-token-characters)\n (_fuzz-characters\n \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_$!+-*/<>=?.,:@#%^&|~`'[]{}\\\\\"))\n\n(= (gen-syntax-token-range $minimum $maximum)\n (if (_fuzz-is-integer $minimum)\n (if (_fuzz-is-integer $maximum)\n (if (and\n (<= 1 $minimum)\n (<= $minimum $maximum))\n (gen-string\n (gen-element\n (_fuzz-syntax-token-characters))\n $minimum\n $maximum)\n (_fuzz-generation-error\n InvalidTokenLengthBounds\n (Minimum $minimum)\n (Maximum $maximum)))\n (_fuzz-expected-integer\n MaximumLength\n $maximum))\n (_fuzz-expected-integer\n MinimumLength\n $minimum)))\n\n(= (_fuzz-syntax-token-at-size $size)\n (gen-syntax-token-range 1 (max 1 $size)))\n\n(= (gen-syntax-token)\n (gen-sized _fuzz-syntax-token-at-size))\n\n(= (gen-element $values)\n (if (> (length $values) 0)\n (GenElement $values)\n (_fuzz-generation-error EmptyElementSet (Values $values))))\n\n(= (_fuzz-frequency-total $entries $total)\n (if (== $entries ())\n (if (> $total 0)\n (FrequencyTotal $total)\n (_fuzz-generation-error EmptyFrequency (Entries $entries)))\n (let* ((($entry $tail) (decons-atom $entries)))\n (switch $entry\n ((($weight $generator)\n (if (_fuzz-is-integer $weight)\n (if (> $weight 0)\n (_fuzz-frequency-total $tail (+ $total $weight))\n (_fuzz-generation-error InvalidFrequencyWeight\n (Weight $weight)\n (Generator $generator)))\n (_fuzz-expected-integer FrequencyWeight $weight)))\n ($bad\n (_fuzz-generation-error MalformedFrequencyEntry (Entry $bad))))))))\n\n(= (gen-frequency $entries)\n (let $total (_fuzz-frequency-total $entries 0)\n (switch $total\n (((FuzzGenerationError $code $details) $total)\n ((FrequencyTotal $weight) (GenFrequency $entries $weight))\n ($bad (_fuzz-generation-error MalformedFrequency (Value $bad)))))))\n\n(= (_fuzz-weight-one $generators)\n (if (== $generators ())\n ()\n (let* ((($generator $tail) (decons-atom $generators))\n ($rest (_fuzz-weight-one $tail)))\n (cons-atom (1 $generator) $rest))))\n\n(= (gen-one-of $generators)\n (gen-frequency (_fuzz-weight-one $generators)))\n\n(= (gen-tuple $generators)\n (GenTuple $generators))\n\n(= (gen-list $generator $minimum $maximum)\n (_fuzz-if-generation-error\n $generator\n (if (_fuzz-is-integer $minimum)\n (if (_fuzz-is-integer $maximum)\n (if (and (<= 0 $minimum) (<= $minimum $maximum))\n (GenList $generator $minimum $maximum)\n (_fuzz-generation-error InvalidListBounds\n (Minimum $minimum)\n (Maximum $maximum)))\n (_fuzz-expected-integer MaximumLength $maximum))\n (_fuzz-expected-integer MinimumLength $minimum))))\n\n(= (gen-option $generator)\n (_fuzz-if-generation-error $generator (GenOption $generator)))\n\n(= (gen-map $function $generator)\n (_fuzz-if-generation-error $generator (GenMap $function $generator)))\n\n(= (gen-bind $generator $function)\n (_fuzz-if-generation-error $generator (GenBind $generator $function)))\n\n(= (gen-filter $generator $predicate $maximum-attempts)\n (_fuzz-if-generation-error\n $generator\n (if (_fuzz-is-integer $maximum-attempts)\n (if (> $maximum-attempts 0)\n (GenFilter $generator $predicate $maximum-attempts)\n (_fuzz-generation-error InvalidFilterAttempts\n (MaximumAttempts $maximum-attempts)))\n (_fuzz-expected-integer MaximumAttempts $maximum-attempts))))\n\n(= (gen-sized $function)\n (GenSized $function))\n\n(= (gen-resize $size $generator)\n (_fuzz-if-generation-error\n $generator\n (if (_fuzz-is-integer $size)\n (if (>= $size 0)\n (GenResize $size $generator)\n (_fuzz-generation-error InvalidSize (Size $size)))\n (_fuzz-expected-integer Size $size))))\n\n(= (gen-recursive $base $step)\n (_fuzz-if-generation-error $base (GenRecursive $base $step)))\n\n(= (gen-custom $name $arguments)\n (GenCustom $name $arguments))\n\n; SPDX-FileCopyrightText: 2026 MesTTo\n;\n; SPDX-License-Identifier: MIT\n\n; Custom generators declare their supported drivers as normal MeTTa data. Replay and shrink replay are\n; mandatory because the runner records and reduces derivation trees rather than opaque output values.\n(= (_fuzz-custom-driver-mode $driver)\n (switch $driver\n (((FuzzDriver Random $state) Random)\n ((FuzzDriver Edge $state) Edge)\n ((FuzzDriver Replay $state) Replay)\n ((FuzzDriver ShrinkReplay $state) ShrinkReplay)\n ((FuzzDriver Exhaustive $state) Exhaustive)\n ((FuzzDriver Bytes $state) Bytes)\n ($bad\n (_fuzz-generation-error\n MalformedDriver\n (Driver $bad))))))\n\n(= (_fuzz-known-custom-mode $mode)\n (switch $mode\n ((Random True)\n (Edge True)\n (Replay True)\n (ShrinkReplay True)\n (Exhaustive True)\n (Bytes True)\n ($bad False))))\n\n(= (_fuzz-valid-custom-modes-loop\n $remaining\n $seen)\n (if (== $remaining ())\n True\n (let* ((($mode $tail)\n (decons-atom $remaining)))\n (if (_fuzz-known-custom-mode $mode)\n (if (is-member $mode $seen)\n False\n (_fuzz-valid-custom-modes-loop\n $tail\n (append $seen ($mode))))\n False))))\n\n(= (_fuzz-valid-custom-modes $modes)\n (if (== (get-metatype $modes) Expression)\n (and\n (_fuzz-valid-custom-modes-loop $modes ())\n (and\n (is-member Replay $modes)\n (is-member ShrinkReplay $modes)))\n False))\n\n(= (_fuzz-custom-capabilities-from-results\n $name\n $arguments\n $results)\n (switch $results\n ((()\n (_fuzz-generation-error\n MissingCustomCapabilities\n (Name $name)\n (Arguments $arguments)))\n (($single)\n (switch $single\n (((CustomCapabilities $seen-name $seen-arguments)\n (_fuzz-generation-error\n MissingCustomCapabilities\n (Name $name)\n (Arguments $arguments)))\n ((FuzzCustomCapabilities (Modes $modes))\n (if (_fuzz-valid-custom-modes $modes)\n (ValidCustomCapabilities $modes)\n (_fuzz-generation-error\n InvalidCustomCapabilities\n (Name $name)\n (Modes $modes))))\n ($bad\n (_fuzz-generation-error\n MalformedCustomCapabilities\n (Name $name)\n (Value $bad))))))\n ($many\n (_fuzz-generation-error\n AmbiguousCustomCapabilities\n (Name $name)\n (Results $many))))))\n\n(= (_fuzz-custom-capabilities $name $arguments)\n (let $results\n (collapse\n (CustomCapabilities\n $name\n $arguments))\n (_fuzz-custom-capabilities-from-results\n $name\n $arguments\n $results)))\n\n(= (_fuzz-custom-wrap\n $name\n $arguments\n $sample)\n (switch $sample\n (((FuzzSample $value $next-driver $tree)\n (let $wrapped-tree\n (Decision\n Custom\n (CustomGenerator\n (Name $name)\n (Arguments $arguments))\n ()\n ($tree))\n (if (== $name _fuzz-grammar)\n (_fuzz-materialize-grammar-sample\n $value\n $next-driver\n $wrapped-tree)\n (FuzzSample\n $value\n $next-driver\n $wrapped-tree))))\n ((FuzzGenerationDiscard\n $reason\n $next-driver\n $tree)\n (FuzzGenerationDiscard\n $reason\n $next-driver\n (Decision\n Custom\n (CustomGenerator\n (Name $name)\n (Arguments $arguments))\n ()\n ($tree))))\n ((FuzzGenerationError $code $details)\n $sample)\n ($bad\n (_fuzz-generation-error\n MalformedGenerationResult\n (Value $bad))))))\n\n; Every driver mode is deterministic (the exhaustive cursor included), so DriveCustom must\n; produce exactly one result in every mode.\n(= (_fuzz-drive-custom-results\n $name\n $arguments\n $mode\n $results)\n (switch $results\n ((()\n (_fuzz-generation-error\n MissingCustomGenerator\n (Name $name)))\n (($sample)\n (switch $sample\n (((DriveCustom\n $seen-name\n $seen-arguments\n $seen-driver\n $seen-size)\n (_fuzz-generation-error\n MissingCustomGenerator\n (Name $name)))\n ($value\n (_fuzz-custom-wrap\n $name\n $arguments\n $value)))))\n ($many\n (_fuzz-generation-error\n AmbiguousCustomGenerator\n (Name $name)\n (Mode $mode)\n (Results $many))))))\n\n(= (_fuzz-drive-custom\n $name\n $arguments\n $driver\n $size\n $mode)\n (let $results\n (collapse\n (DriveCustom\n $name\n $arguments\n $driver\n $size))\n (_fuzz-drive-custom-results\n $name\n $arguments\n $mode\n $results)))\n\n(= (_fuzz-drive-custom-validated\n $name\n $arguments\n $driver\n $size\n $mode)\n (let $original\n (_fuzz-drive-custom\n $name\n $arguments\n $driver\n $size\n $mode)\n (if (== $mode Replay)\n $original\n (let $request\n (_fuzz-custom-replay-tree\n $original\n $mode)\n (switch $request\n (((CustomReplayTree $tree)\n (let $replayed\n (fuzz-replay\n (GenCustom $name $arguments)\n $tree\n $size)\n (if (_fuzz-custom-replay-equal\n $original\n $replayed)\n $original\n (_fuzz-generation-error\n CustomReplayMismatch\n (Name $name)\n (Mode $mode)\n (Original $original)\n (Replay $replayed)))))\n ((CustomReplaySkip)\n $original)\n ((CustomReplayProtocolError\n $code\n $details)\n (FuzzGenerationError\n $code\n $details))\n ((FuzzKernelError $code $details)\n (_fuzz-generation-error\n KernelError\n (OperationResult $request)))\n ($bad-request\n (_fuzz-generation-error\n MalformedCustomReplayRequest\n (Name $name)\n (Value $bad-request)))))))))\n\n; An explicit edge hook supplies inner derivation trees. Each tree is replayed through DriveCustom before\n; it can become a sample, so an edge hook cannot bypass the generator or invent an incompatible value.\n(= (_fuzz-custom-edge-replayed\n $name\n $next-index\n $result)\n (switch $result\n (((FuzzSample $value $replay-driver $tree)\n (FuzzSample\n $value\n (FuzzDriver Edge $next-index)\n $tree))\n ((FuzzGenerationDiscard\n $reason\n $replay-driver\n $tree)\n (FuzzGenerationDiscard\n $reason\n (FuzzDriver Edge $next-index)\n $tree))\n ((FuzzGenerationError $code $details) $result)\n ($bad\n (_fuzz-generation-error\n MalformedCustomEdgeReplay\n (Name $name)\n (Value $bad))))))\n\n(= (_fuzz-custom-edge-from-choices\n $name\n $arguments\n $size\n $index\n $choices)\n (if (== $choices ())\n (_fuzz-generation-error\n EmptyCustomEdgeChoices\n (Name $name))\n (let* (($position\n (% $index (length $choices)))\n ($child-tree\n (index-atom\n $choices\n $position))\n ($tree\n (Decision\n Custom\n (CustomGenerator\n (Name $name)\n (Arguments $arguments))\n ()\n ($child-tree)))\n ($replayed\n (fuzz-replay\n (GenCustom $name $arguments)\n $tree\n $size)))\n (_fuzz-custom-edge-replayed\n $name\n (+ $index 1)\n $replayed))))\n\n(= (_fuzz-custom-edge-results\n $name\n $arguments\n $size\n $index\n $results)\n (switch $results\n ((()\n (NoCustomEdgeChoices))\n (($single)\n (switch $single\n (((EdgeChoices\n $seen-name\n $seen-arguments\n $seen-size)\n (NoCustomEdgeChoices))\n ((CustomEdgeChoices $choices)\n (if (== (get-metatype $choices) Expression)\n (_fuzz-custom-edge-from-choices\n $name\n $arguments\n $size\n $index\n $choices)\n (_fuzz-generation-error\n MalformedCustomEdgeChoices\n (Name $name)\n (Value $choices))))\n ($bad\n (_fuzz-generation-error\n MalformedCustomEdgeChoices\n (Name $name)\n (Value $bad))))))\n ($many\n (_fuzz-generation-error\n AmbiguousCustomEdgeChoices\n (Name $name)\n (Results $many))))))\n\n(= (_fuzz-custom-edge\n $name\n $arguments\n $size\n $index)\n (let $results\n (collapse\n (EdgeChoices\n $name\n $arguments\n $size))\n (_fuzz-custom-edge-results\n $name\n $arguments\n $size\n $index\n $results)))\n\n(= (_fuzz-generate-custom-supported\n $name\n $arguments\n $driver\n $size\n $mode)\n (switch $driver\n (((FuzzDriver Edge $index)\n (let $edge\n (_fuzz-custom-edge\n $name\n $arguments\n $size\n $index)\n (switch $edge\n (((NoCustomEdgeChoices)\n (_fuzz-drive-custom-validated\n $name\n $arguments\n $driver\n $size\n $mode))\n ($available $available)))))\n ($other\n (_fuzz-drive-custom-validated\n $name\n $arguments\n $driver\n $size\n $mode)))))\n\n(= (_fuzz-generate-custom-for-mode\n $name\n $arguments\n $driver\n $size\n $mode\n $capabilities)\n (switch $capabilities\n (((ValidCustomCapabilities $modes)\n (if (is-member $mode $modes)\n (_fuzz-generate-custom-supported\n $name\n $arguments\n $driver\n $size\n $mode)\n (_fuzz-generation-error\n UnsupportedCustomDriver\n (Name $name)\n (Mode $mode))))\n ((FuzzGenerationError $code $details)\n $capabilities)\n ($bad\n (_fuzz-generation-error\n MalformedCustomCapabilities\n (Name $name)\n (Value $bad))))))\n\n(= (_fuzz-generate-custom-checked\n $name\n $arguments\n $driver\n $size)\n (let $mode (_fuzz-custom-driver-mode $driver)\n (switch $mode\n (((FuzzGenerationError $code $details) $mode)\n ($valid-mode\n (_fuzz-generate-custom-for-mode\n $name\n $arguments\n $driver\n $size\n $valid-mode\n (_fuzz-custom-capabilities\n $name\n $arguments)))))))\n\n; SPDX-FileCopyrightText: 2026 MesTTo\n;\n; SPDX-License-Identifier: MIT\n\n; A dynamic generator function must have one result. This prevents its nondeterminism from being\n; confused with alternatives chosen by the active driver. The call runs under `collapse-bind`\n; and the single result is extracted purely by unification: `collapse` would re-evaluate the\n; collected results and grounded list operations resolve their arguments, either of which\n; dereferences a live value such as a state handle.\n; Flat accumulator, not recurse-then-cons: a relation may return hundreds of results and each\n; recursive-then-cons step would cost an evaluator frame.\n(= (_fuzz-pair-values $pairs)\n (_fuzz-pair-values-loop (FuzzPairValuesFold $pairs ())))\n\n(= (_fuzz-pair-values-loop $state)\n (if (_fuzz-pair-values-finished $state)\n $state\n (_fuzz-pair-values-loop (_fuzz-pair-values-step $state))))\n\n(= (_fuzz-pair-values-finished $state)\n (unify $state (FuzzPairValuesFold $pairs $reversed) False True))\n\n(= (_fuzz-pair-values-step $state)\n (unify $state\n (FuzzPairValuesFold $pairs $reversed)\n (if (== $pairs ())\n (reverse $reversed)\n (let ($head $tail) (decons-atom $pairs)\n (let $value\n (unify $head ($result $bindings) $result $head)\n (let $next (cons-atom $value $reversed)\n (FuzzPairValuesFold $tail $next)))))\n $state))\n\n(= (_fuzz-call-results-bind $pairs $context)\n (unify $pairs\n (($value $bindings))\n (CallOne $value)\n (unify $pairs\n ()\n (_fuzz-generation-error FunctionReturnedNoResults $context)\n (let $values (_fuzz-pair-values $pairs)\n (_fuzz-generation-error\n FunctionReturnedMultipleResults\n $context\n (Results $values))))))\n\n; The collapse-bind sits inside a function/chain context (the prelude's own `case` idiom) so its\n; argument reaches it RAW. As an evaluated argument the call would branch first \u2014 Hyperon-verified:\n; `(callrb (collapse-bind (f 1)) ctx)` with a two-rule f yields two singleton results in both\n; engines \u2014 and a nondeterministic user relation would slip through the cardinality check as\n; parallel single-result branches instead of being rejected.\n(= (_fuzz-call-one $function $argument $context)\n (function\n (chain (context-space) $space\n (chain (collapse-bind (metta ($function $argument) %Undefined% $space)) $pairs\n (chain (eval (_fuzz-call-results-bind $pairs $context)) $out\n (return $out))))))\n\n(= (_fuzz-bool-result $called $context)\n (switch $called\n (((CallOne True) (CallBool True))\n ((CallOne False) (CallBool False))\n ((CallOne $bad)\n (_fuzz-generation-error PredicateReturnedNonBoolean\n $context\n (Value $bad)))\n ((FuzzGenerationError $code $details) $called)\n ($bad\n (_fuzz-generation-error MalformedFunctionResult\n $context\n (Value $bad))))))\n\n(= (_fuzz-call-bool $function $argument $context)\n (_fuzz-bool-result (_fuzz-call-one $function $argument $context) $context))\n\n(= (_fuzz-wrap-sample $kind $metadata $selection $sample)\n (switch $sample\n (((FuzzSample $value $next-driver $tree)\n (let $children (cons-atom $tree ())\n (FuzzSample\n $value\n $next-driver\n (Decision $kind $metadata $selection $children))))\n ((FuzzGenerationDiscard $reason $next-driver $tree)\n (let $children (cons-atom $tree ())\n (FuzzGenerationDiscard\n $reason\n $next-driver\n (Decision $kind $metadata $selection $children))))\n ((FuzzGenerationError $code $details) $sample)\n ($bad\n (_fuzz-generation-error MalformedGenerationResult (Value $bad))))))\n\n(= (_fuzz-two-children $first $second)\n (let $tail (cons-atom $second ())\n (cons-atom $first $tail)))\n\n(= (_fuzz-choice-sample $choice)\n (switch $choice\n (((DriverChoice $value $next-driver $decision)\n (FuzzSample $value $next-driver $decision))\n ((FuzzGenerationError $code $details) $choice)\n ($bad\n (_fuzz-generation-error MalformedDriverChoice (Value $bad))))))\n\n(= (_fuzz-generate-bool $driver)\n (let $choice (_fuzz-driver-int $driver 0 1 0)\n (switch $choice\n (((DriverChoice 0 $next-driver $decision)\n (let $children (cons-atom $decision ())\n (FuzzSample\n False\n $next-driver\n (Decision Bool (Count 2) (Value False) $children))))\n ((DriverChoice 1 $next-driver $decision)\n (let $children (cons-atom $decision ())\n (FuzzSample\n True\n $next-driver\n (Decision Bool (Count 2) (Value True) $children))))\n ((FuzzGenerationError $code $details) $choice)\n ($bad\n (_fuzz-generation-error MalformedBooleanChoice (Value $bad)))))))\n\n(= (_fuzz-float-range-from-value\n $lower-index\n $upper-index\n $index\n $next-driver\n $decision\n $value)\n (switch $value\n (((FuzzKernelError $code $operation $detail)\n (_fuzz-generation-error\n KernelError\n (OperationResult $value)))\n ($float\n (let $children (cons-atom $decision ())\n (FuzzSample\n $float\n $next-driver\n (Decision\n FloatRange\n (Indices $lower-index $upper-index)\n (Index $index)\n $children)))))))\n\n(= (_fuzz-float-range-sample\n $lower-index\n $upper-index\n $origin-index\n $choice)\n (switch $choice\n (((DriverChoice $index $next-driver $decision)\n (_fuzz-float-range-from-value\n $lower-index\n $upper-index\n $index\n $next-driver\n $decision\n (_fuzz-float64-from-index $index)))\n ((FuzzGenerationError $code $details) $choice)\n ($bad\n (_fuzz-generation-error\n MalformedFloatChoice\n (Value $bad))))))\n\n(= (_fuzz-generate-float-range\n $lower-index\n $upper-index\n $origin-index\n $driver)\n (switch $driver\n (((FuzzDriver Edge $index)\n (let* (($a\n (_fuzz-edge-candidates\n $lower-index\n $upper-index\n $origin-index))\n ($b\n (_fuzz-edge-add\n -2\n $lower-index\n $upper-index\n $a))\n ($c\n (_fuzz-edge-add\n -4503599627370496\n $lower-index\n $upper-index\n $b))\n ($d\n (_fuzz-edge-add\n -4503599627370497\n $lower-index\n $upper-index\n $c))\n ($e\n (_fuzz-edge-add\n 4503599627370495\n $lower-index\n $upper-index\n $d))\n ($f\n (_fuzz-edge-add\n 4503599627370496\n $lower-index\n $upper-index\n $e))\n ($g\n (_fuzz-edge-add\n -4607182418800017409\n $lower-index\n $upper-index\n $f))\n ($candidates\n (_fuzz-edge-add\n 4607182418800017408\n $lower-index\n $upper-index\n $g))\n ($position (% $index (length $candidates)))\n ($selected\n (index-atom $candidates $position)))\n (_fuzz-float-range-sample\n $lower-index\n $upper-index\n $origin-index\n (DriverChoice\n $selected\n (FuzzDriver Edge (+ $index 1))\n (_fuzz-int-decision\n $lower-index\n $upper-index\n $origin-index\n $selected)))))\n ($other\n (_fuzz-float-range-sample\n $lower-index\n $upper-index\n $origin-index\n (_fuzz-driver-int\n $other\n $lower-index\n $upper-index\n $origin-index))))))\n\n(= (_fuzz-float-bit-edge-pairs)\n ((0 0)\n (2147483648 0)\n (1072693248 0)\n (3220176896 0)\n (0 1)\n (2147483648 1)\n (2146435071 4294967295)\n (4293918719 4294967295)\n (2146435072 0)\n (4293918720 0)\n (2146959360 0)\n (4294443008 0)\n (2146435072 1)\n (4293918720 1)\n (2146959360 23)\n (4294443008 23)\n (1048576 0)\n (2148532224 0)\n (1048575 4294967295)\n (2148532223 4294967295)))\n\n(= (_fuzz-float-bits-sample\n $high\n $low\n $next-driver\n $high-decision\n $low-decision)\n (let $value (_fuzz-float64-from-bits $high $low)\n (switch $value\n (((FuzzKernelError $code $operation $detail)\n (_fuzz-generation-error\n KernelError\n (OperationResult $value)))\n ($float\n (let $children\n (_fuzz-two-children\n $high-decision\n $low-decision)\n (FuzzSample\n $float\n $next-driver\n (Decision\n FloatBits\n (Format IEEE754Binary64)\n (Bits $high $low)\n $children))))))))\n\n(= (_fuzz-generate-float-bits-edge $index)\n (let* (($pairs (_fuzz-float-bit-edge-pairs))\n ($position (% $index (length $pairs)))\n ($pair (index-atom $pairs $position)))\n (switch $pair\n ((($high $low)\n (_fuzz-float-bits-sample\n $high\n $low\n (FuzzDriver Edge (+ $index 2))\n (_fuzz-int-decision 0 4294967295 0 $high)\n (_fuzz-int-decision 0 4294967295 0 $low)))\n ($bad\n (_fuzz-generation-error\n MalformedFloatEdge\n (Value $bad)))))))\n\n(= (_fuzz-generate-float-bits-from-low\n (DriverChoice $high $after-high $high-decision)\n $low-choice)\n (switch $low-choice\n (((DriverChoice $low $next-driver $low-decision)\n (_fuzz-float-bits-sample\n $high\n $low\n $next-driver\n $high-decision\n $low-decision))\n ((FuzzGenerationError $code $details) $low-choice)\n ($bad\n (_fuzz-generation-error\n MalformedFloatLowWordChoice\n (Value $bad))))))\n\n(= (_fuzz-generate-float-bits $driver)\n (switch $driver\n (((FuzzDriver Edge $index)\n (_fuzz-generate-float-bits-edge $index))\n ($other\n (let $high-choice\n (_fuzz-driver-int $other 0 4294967295 0)\n (switch $high-choice\n (((DriverChoice $high $after-high $high-decision)\n (_fuzz-generate-float-bits-from-low\n $high-choice\n (_fuzz-driver-int\n $after-high\n 0\n 4294967295\n 0)))\n ((FuzzGenerationError $code $details) $high-choice)\n ($bad\n (_fuzz-generation-error\n MalformedFloatHighWordChoice\n (Value $bad))))))))))\n\n(= (_fuzz-generate-element $values $driver)\n (let* (($count (length $values))\n ($choice (_fuzz-driver-int $driver 0 (- $count 1) 0)))\n (switch $choice\n (((DriverChoice $index $next-driver $decision)\n (let* (($value (index-atom $values $index))\n ($children (cons-atom $decision ())))\n (FuzzSample\n $value\n $next-driver\n (Decision Element (Count $count) (Index $index) $children))))\n ((FuzzGenerationError $code $details) $choice)\n ($bad\n (_fuzz-generation-error MalformedElementChoice (Value $bad)))))))\n\n(= (_fuzz-frequency-select $entries $ticket $offset $index)\n (if (== $entries ())\n (_fuzz-generation-error FrequencyTicketOutOfBounds\n (Ticket $ticket)\n (Offset $offset))\n (let* ((($entry $tail) (decons-atom $entries)))\n (switch $entry\n ((($weight $generator)\n (let $next-offset (+ $offset $weight)\n (if (<= $ticket $next-offset)\n (FrequencySelection $index $generator)\n (_fuzz-frequency-select\n $tail\n $ticket\n $next-offset\n (+ $index 1)))))\n ($bad\n (_fuzz-generation-error MalformedFrequencyEntry\n (Entry $bad))))))))\n\n; Weights bias only the Random ticket draw; every other driver and the recorded decision work\n; in entry-index space [0, count-1]. Exhaustive enumeration therefore visits each entry once,\n; and a replayed tree is weight-independent, exactly like grammar production choice.\n(= (_fuzz-frequency-index-choice $entries $total $driver)\n (switch $driver\n (((FuzzDriver Random $rng)\n (let $draw (_fuzz-draw-int $rng 1 $total)\n (switch $draw\n (((FuzzDraw $ticket $next-rng)\n (let $selected (_fuzz-frequency-select $entries $ticket 0 0)\n (switch $selected\n (((FrequencySelection $index $generator)\n (let* (($count (length $entries))\n ($decision (_fuzz-int-decision 0 (- $count 1) 0 $index)))\n (FrequencyIndexChoice\n $index\n $generator\n (FuzzDriver Random $next-rng)\n $decision)))\n ((FuzzGenerationError $code $details) $selected)\n ($bad\n (_fuzz-generation-error\n MalformedFrequencySelection\n (Value $bad)))))))\n ($bad\n (_fuzz-generation-error KernelError (OperationResult $bad)))))))\n ($other\n (let* (($count (length $entries))\n ($choice (_fuzz-driver-int $driver 0 (- $count 1) 0)))\n (switch $choice\n (((DriverChoice $index $next-driver $decision)\n (let $entry (index-atom $entries $index)\n (switch $entry\n ((($weight $generator)\n (FrequencyIndexChoice\n $index\n $generator\n $next-driver\n $decision))\n ($bad\n (_fuzz-generation-error\n MalformedFrequencyEntry\n (Entry $bad)))))))\n ((FuzzGenerationError $code $details) $choice)\n ($bad\n (_fuzz-generation-error\n MalformedDriverChoice\n (Value $bad))))))))))\n\n(= (_fuzz-generate-frequency $entries $total $driver $size)\n (let $choice (_fuzz-frequency-index-choice $entries $total $driver)\n (switch $choice\n (((FrequencyIndexChoice $index $generator $next-driver $decision)\n (let $child\n (fuzz-generate $generator $next-driver (max 0 (- $size 1)))\n (switch $child\n (((FuzzSample $value $final-driver $tree)\n (let $children (_fuzz-two-children $decision $tree)\n (FuzzSample\n $value\n $final-driver\n (Decision\n Frequency\n (Total $total)\n (Index $index)\n $children))))\n ((FuzzGenerationDiscard $reason $final-driver $tree)\n (let $children (_fuzz-two-children $decision $tree)\n (FuzzGenerationDiscard\n $reason\n $final-driver\n (Decision\n Frequency\n (Total $total)\n (Index $index)\n $children))))\n ((FuzzGenerationError $code $details) $child)\n ($bad\n (_fuzz-generation-error\n MalformedGenerationResult\n (Value $bad)))))))\n ((FuzzGenerationError $code $details) $choice)\n ($bad\n (_fuzz-generation-error MalformedFrequencyChoice (Value $bad)))))))\n\n(= (_fuzz-generate-many $generators $driver $size $values-reversed $trees-reversed)\n (if (== $generators ())\n (GeneratedMany\n (reverse $values-reversed)\n $driver\n (reverse $trees-reversed))\n (let* ((($generator $tail) (decons-atom $generators))\n ($sample (fuzz-generate $generator $driver $size)))\n (switch $sample\n (((FuzzSample $value $next-driver $tree)\n (let* (($next-values\n (cons-atom $value $values-reversed))\n ($next-trees\n (cons-atom $tree $trees-reversed)))\n (_fuzz-generate-many\n $tail\n $next-driver\n $size\n $next-values\n $next-trees)))\n ((FuzzGenerationDiscard $reason $next-driver $tree)\n (GeneratedManyDiscard\n $reason\n $next-driver\n (reverse (cons-atom $tree $trees-reversed))))\n ((FuzzGenerationError $code $details) $sample)\n ($bad\n (_fuzz-generation-error\n MalformedGenerationResult\n (Value $bad))))))))\n\n(= (_fuzz-generate-tuple $generators $driver $size)\n (let* (($count (length $generators))\n ($child-size (if (> $count 0) (/ $size $count) 0))\n ($generated (_fuzz-generate-many $generators $driver $child-size () ())))\n (switch $generated\n (((GeneratedMany $values $next-driver $trees)\n (FuzzSample\n $values\n $next-driver\n (Decision Tuple (Count $count) () $trees)))\n ((GeneratedManyDiscard $reason $next-driver $trees)\n (FuzzGenerationDiscard\n $reason\n $next-driver\n (Decision Tuple (Count $count) () $trees)))\n ((FuzzGenerationError $code $details) $generated)\n ($bad\n (_fuzz-generation-error MalformedTupleGeneration (Value $bad)))))))\n\n; Flat accumulator, not recurse-then-cons: a drawn list length may be in the thousands and each\n; recursive-then-cons step would cost an evaluator frame. Every element is the same generator, so\n; the accumulation order is not observable and no final reverse is needed.\n(= (_fuzz-repeat-generator $generator $count)\n (_fuzz-repeat-generator-loop (FuzzRepeatFold $generator $count ())))\n\n(= (_fuzz-repeat-generator-loop $state)\n (if (_fuzz-repeat-generator-finished $state)\n $state\n (_fuzz-repeat-generator-loop (_fuzz-repeat-generator-step $state))))\n\n(= (_fuzz-repeat-generator-finished $state)\n (unify $state (FuzzRepeatFold $generator $count $repeated) False True))\n\n(= (_fuzz-repeat-generator-step $state)\n (unify $state\n (FuzzRepeatFold $generator $count $repeated)\n (if (> $count 0)\n (let $next (cons-atom $generator $repeated)\n (FuzzRepeatFold $generator (- $count 1) $next))\n $repeated)\n $state))\n\n(= (_fuzz-generate-list $generator $minimum $maximum $driver $size)\n (let* (($effective-maximum (min $maximum (+ $minimum $size)))\n ($choice\n (_fuzz-driver-int\n $driver\n $minimum\n $effective-maximum\n $minimum)))\n (switch $choice\n (((DriverChoice $length $next-driver $length-decision)\n (let* (($child-size (if (> $length 0) (/ $size $length) 0))\n ($generators (_fuzz-repeat-generator $generator $length))\n ($generated\n (_fuzz-generate-many\n $generators\n $next-driver\n $child-size\n ()\n ())))\n (switch $generated\n (((GeneratedMany $values $final-driver $trees)\n (let $children (cons-atom $length-decision $trees)\n (FuzzSample\n $values\n $final-driver\n (Decision\n List\n (Bounds $minimum $maximum)\n (Length $length)\n $children))))\n ((GeneratedManyDiscard $reason $final-driver $trees)\n (let $children (cons-atom $length-decision $trees)\n (FuzzGenerationDiscard\n $reason\n $final-driver\n (Decision\n List\n (Bounds $minimum $maximum)\n (Length $length)\n $children))))\n ((FuzzGenerationError $code $details) $generated)\n ($bad\n (_fuzz-generation-error\n MalformedListGeneration\n (Value $bad)))))))\n ((FuzzGenerationError $code $details) $choice)\n ($bad\n (_fuzz-generation-error MalformedListChoice (Value $bad)))))))\n\n(= (_fuzz-generate-option $generator $driver $size)\n (let $choice (_fuzz-driver-int $driver 0 1 0)\n (switch $choice\n (((DriverChoice 0 $next-driver $decision)\n (let $children (cons-atom $decision ())\n (FuzzSample\n (None)\n $next-driver\n (Decision Option (Count 2) (Index 0) $children))))\n ((DriverChoice 1 $next-driver $decision)\n (let $child\n (fuzz-generate\n $generator\n $next-driver\n (max 0 (- $size 1)))\n (switch $child\n (((FuzzSample $value $final-driver $tree)\n (let $children (_fuzz-two-children $decision $tree)\n (FuzzSample\n (Some $value)\n $final-driver\n (Decision Option (Count 2) (Index 1) $children))))\n ((FuzzGenerationDiscard $reason $final-driver $tree)\n (let $children (_fuzz-two-children $decision $tree)\n (FuzzGenerationDiscard\n $reason\n $final-driver\n (Decision Option (Count 2) (Index 1) $children))))\n ((FuzzGenerationError $code $details) $child)\n ($bad\n (_fuzz-generation-error\n MalformedOptionGeneration\n (Value $bad)))))))\n ((FuzzGenerationError $code $details) $choice)\n ($bad\n (_fuzz-generation-error MalformedOptionChoice (Value $bad)))))))\n\n(= (_fuzz-generate-map $function $generator $driver $size)\n (let $source (fuzz-generate $generator $driver $size)\n (switch $source\n (((FuzzSample $value $next-driver $tree)\n (let $mapped\n (_fuzz-call-one\n $function\n $value\n (MapFunction $function))\n (switch $mapped\n (((CallOne $mapped-value)\n (let $children (cons-atom $tree ())\n (FuzzSample\n $mapped-value\n $next-driver\n (Decision Map (Function $function) () $children))))\n ((FuzzGenerationError $code $details) $mapped)\n ($bad\n (_fuzz-generation-error MalformedMapResult (Value $bad)))))))\n ((FuzzGenerationDiscard $reason $next-driver $tree)\n (_fuzz-wrap-sample\n Map\n (Function $function)\n ()\n $source))\n ((FuzzGenerationError $code $details) $source)\n ($bad\n (_fuzz-generation-error MalformedMapSource (Value $bad)))))))\n\n(= (_fuzz-generate-bind $source-generator $function $driver $size)\n (let* (($source-size (/ $size 2))\n ($dependent-size (- $size $source-size))\n ($source\n (fuzz-generate\n $source-generator\n $driver\n $source-size)))\n (switch $source\n (((FuzzSample $source-value $next-driver $source-tree)\n (let $called\n (_fuzz-call-one\n $function\n $source-value\n (BindFunction $function))\n (switch $called\n (((CallOne $dependent-generator)\n (let $dependent\n (fuzz-generate\n $dependent-generator\n $next-driver\n $dependent-size)\n (switch $dependent\n (((FuzzSample $value $final-driver $dependent-tree)\n (let $children\n (_fuzz-two-children $source-tree $dependent-tree)\n (FuzzSample\n $value\n $final-driver\n (Decision\n Bind\n (Function $function)\n ()\n $children))))\n ((FuzzGenerationDiscard\n $reason\n $final-driver\n $dependent-tree)\n (let $children\n (_fuzz-two-children $source-tree $dependent-tree)\n (FuzzGenerationDiscard\n $reason\n $final-driver\n (Decision\n Bind\n (Function $function)\n ()\n $children))))\n ((FuzzGenerationError $code $details) $dependent)\n ($bad\n (_fuzz-generation-error\n MalformedBindGeneration\n (Value $bad)))))))\n ((FuzzGenerationError $code $details) $called)\n ($bad\n (_fuzz-generation-error\n MalformedBindFunctionResult\n (Value $bad)))))))\n ((FuzzGenerationDiscard $reason $next-driver $tree)\n (_fuzz-wrap-sample\n Bind\n (Function $function)\n ()\n $source))\n ((FuzzGenerationError $code $details) $source)\n ($bad\n (_fuzz-generation-error MalformedBindSource (Value $bad)))))))\n\n(= (_fuzz-filter-total $remaining $used)\n (+ $remaining $used))\n\n(= (_fuzz-filter-discard $remaining $used $driver $trees-reversed)\n (let* (($total (_fuzz-filter-total $remaining $used))\n ($trees (reverse $trees-reversed)))\n (FuzzGenerationDiscard\n (FilterExhausted (MaximumAttempts $total))\n $driver\n (Decision\n Filter\n (MaximumAttempts $total)\n (Attempts $used)\n $trees))))\n\n(= (_fuzz-generate-filter\n $generator\n $predicate\n $remaining\n $used\n $driver\n $size\n $trees-reversed)\n (if (<= $remaining 0)\n (_fuzz-filter-discard\n $remaining\n $used\n $driver\n $trees-reversed)\n (let $sample (fuzz-generate $generator $driver $size)\n (switch $sample\n (((FuzzSample $value $next-driver $tree)\n (let $accepted\n (_fuzz-call-bool\n $predicate\n $value\n (FilterPredicate $predicate))\n (switch $accepted\n (((CallBool True)\n (let* (($attempts (+ $used 1))\n ($total\n (_fuzz-filter-total\n $remaining\n $used))\n ($trees\n (reverse\n (cons-atom $tree $trees-reversed))))\n (FuzzSample\n $value\n $next-driver\n (Decision\n Filter\n (MaximumAttempts $total)\n (Attempts $attempts)\n $trees))))\n ((CallBool False)\n (let $next-trees\n (cons-atom $tree $trees-reversed)\n (_fuzz-generate-filter\n $generator\n $predicate\n (- $remaining 1)\n (+ $used 1)\n $next-driver\n $size\n $next-trees)))\n ((FuzzGenerationError $code $details) $accepted)\n ($bad\n (_fuzz-generation-error\n MalformedFilterPredicateResult\n (Value $bad)))))))\n ((FuzzGenerationDiscard $reason $next-driver $tree)\n (let $next-trees\n (cons-atom $tree $trees-reversed)\n (_fuzz-generate-filter\n $generator\n $predicate\n (- $remaining 1)\n (+ $used 1)\n $next-driver\n $size\n $next-trees)))\n ((FuzzGenerationError $code $details) $sample)\n ($bad\n (_fuzz-generation-error\n MalformedFilterGeneration\n (Value $bad))))))))\n\n(= (_fuzz-generate-sized $function $driver $size)\n (let $called\n (_fuzz-call-one\n $function\n $size\n (SizedFunction $function))\n (switch $called\n (((CallOne $generator)\n (let $sample (fuzz-generate $generator $driver $size)\n (_fuzz-wrap-sample\n Sized\n (Size $size)\n ()\n $sample)))\n ((FuzzGenerationError $code $details) $called)\n ($bad\n (_fuzz-generation-error\n MalformedSizedFunctionResult\n (Value $bad)))))))\n\n(= (_fuzz-generate-resize $new-size $generator $driver)\n (let $sample (fuzz-generate $generator $driver $new-size)\n (_fuzz-wrap-sample\n Resize\n (Size $new-size)\n ()\n $sample)))\n\n(= (_fuzz-generate-recursive $base $step $driver $size)\n (if (<= $size 0)\n (let $sample (fuzz-generate $base $driver 0)\n (_fuzz-wrap-sample\n Recursive\n (Size 0)\n (Branch Base)\n $sample))\n (let* (($child-size (- $size 1))\n ($self\n (GenResize\n $child-size\n (GenRecursive $base $step)))\n ($called\n (_fuzz-call-one\n $step\n $self\n (RecursiveStep $step))))\n (switch $called\n (((CallOne $generator)\n (let $sample\n (fuzz-generate\n $generator\n $driver\n $child-size)\n (_fuzz-wrap-sample\n Recursive\n (Size $size)\n (Branch Step)\n $sample)))\n ((FuzzGenerationError $code $details) $called)\n ($bad\n (_fuzz-generation-error\n MalformedRecursiveStep\n (Value $bad))))))))\n\n(= (_fuzz-generate-custom $name $arguments $driver $size)\n (_fuzz-generate-custom-checked\n $name\n $arguments\n $driver\n $size))\n\n(= (fuzz-generate $generator $driver $size)\n (if (_fuzz-is-integer $size)\n (if (< $size 0)\n (_fuzz-generation-error InvalidSize (Size $size))\n (switch $generator\n (((FuzzGenerationError $code $details) $generator)\n ((GenConst $value)\n (FuzzSample\n $value\n $driver\n (Decision Const () (Value $value) ())))\n ((GenBool)\n (_fuzz-generate-bool $driver))\n ((GenInt $lower $upper $origin)\n (_fuzz-choice-sample\n (_fuzz-driver-int\n $driver\n $lower\n $upper\n $origin)))\n ((GenFloatRange $lower-index $upper-index $origin-index)\n (_fuzz-generate-float-range\n $lower-index\n $upper-index\n $origin-index\n $driver))\n ((GenFloatBits)\n (_fuzz-generate-float-bits $driver))\n ((GenElement $values)\n (_fuzz-generate-element $values $driver))\n ((GenFrequency $entries $total)\n (_fuzz-generate-frequency\n $entries\n $total\n $driver\n $size))\n ((GenTuple $generators)\n (_fuzz-generate-tuple\n $generators\n $driver\n $size))\n ((GenList $child $minimum $maximum)\n (_fuzz-generate-list\n $child\n $minimum\n $maximum\n $driver\n $size))\n ((GenOption $child)\n (_fuzz-generate-option $child $driver $size))\n ((GenMap $function $child)\n (_fuzz-generate-map\n $function\n $child\n $driver\n $size))\n ((GenBind $child $function)\n (_fuzz-generate-bind\n $child\n $function\n $driver\n $size))\n ((GenFilter $child $predicate $maximum-attempts)\n (_fuzz-generate-filter\n $child\n $predicate\n $maximum-attempts\n 0\n $driver\n $size\n ()))\n ((GenSized $function)\n (_fuzz-generate-sized\n $function\n $driver\n $size))\n ((GenResize $new-size $child)\n (_fuzz-generate-resize\n $new-size\n $child\n $driver))\n ((GenRecursive $base $step)\n (_fuzz-generate-recursive\n $base\n $step\n $driver\n $size))\n ((GenCustom $name $arguments)\n (_fuzz-generate-custom\n $name\n $arguments\n $driver\n $size))\n ($bad\n (_fuzz-generation-error\n MalformedGenerator\n (Generator $bad))))))\n (_fuzz-expected-integer Size $size)))\n\n(= (fuzz-generate-random $generator $seed $size)\n (let $driver (fuzz-random-driver $seed)\n (switch $driver\n (((FuzzGenerationError $code $details) $driver)\n ($valid\n (fuzz-generate $generator $valid $size))))))\n\n(= (fuzz-generate-edge $generator $index $size)\n (let $driver (fuzz-edge-driver $index)\n (switch $driver\n (((FuzzGenerationError $code $details) $driver)\n ($valid\n (fuzz-generate $generator $valid $size))))))\n\n(= (fuzz-generate-bytes $generator $bytes $size)\n (let $driver (fuzz-bytes-driver $bytes)\n (switch $driver\n (((FuzzGenerationError $code $details) $driver)\n ($valid\n (fuzz-generate $generator $valid $size))))))\n\n(= (_fuzz-validate-finished-replay\n $expected-tree\n $actual-tree\n $remaining\n $cursor\n $result)\n (if (== $remaining ())\n (if (_fuzz-replay-equal $expected-tree $actual-tree)\n $result\n (_fuzz-generation-error\n ReplayMismatch\n (ExpectedTree $expected-tree)\n (ActualTree $actual-tree)))\n (_fuzz-generation-error\n TrailingReplayDecisions\n (Path $cursor)\n (Remaining $remaining))))\n\n(= (_fuzz-finish-replay $expected-tree $result)\n (switch $result\n (((FuzzSample\n $value\n (FuzzDriver Replay (ReplayState $remaining $cursor))\n $actual-tree)\n (_fuzz-validate-finished-replay\n $expected-tree\n $actual-tree\n $remaining\n $cursor\n $result))\n ((FuzzGenerationDiscard\n $reason\n (FuzzDriver Replay (ReplayState $remaining $cursor))\n $actual-tree)\n (_fuzz-validate-finished-replay\n $expected-tree\n $actual-tree\n $remaining\n $cursor\n $result))\n ((FuzzGenerationError $code $details) $result)\n ($bad\n (_fuzz-generation-error\n MalformedReplayResult\n (Value $bad))))))\n\n(= (fuzz-replay $generator $decision-tree $size)\n (let $driver (fuzz-replay-driver $decision-tree)\n (switch $driver\n (((FuzzGenerationError $code $details) $driver)\n ($valid\n (_fuzz-finish-replay\n $decision-tree\n (fuzz-generate $generator $valid $size)))))))\n\n; Enumerates the generator's whole decision domain at one size with the exhaustive cursor,\n; in depth-first order. Generation discards count as enumerated attempts but not as domain\n; members. Stops at $limit attempts with FuzzEnumerationTruncated; a completed walk returns\n; (FuzzEnumeration (DomainCount n) (Enumerated m) (GenerationDiscards g) (Samples ...)).\n(= (fuzz-enumerate $generator $limit $size)\n (if (_fuzz-is-integer $limit)\n (if (> $limit 0)\n (_fuzz-enumerate-loop\n (FuzzEnumerateRun $generator $size $limit () 0 0 0 ()))\n (_fuzz-generation-error InvalidEnumerationLimit (Limit $limit)))\n (_fuzz-expected-integer EnumerationLimit $limit)))\n\n(= (_fuzz-enumerate-loop $state)\n (if (_fuzz-enumerate-finished $state)\n $state\n (_fuzz-enumerate-loop (_fuzz-enumerate-step $state))))\n\n(= (_fuzz-enumerate-finished $state)\n (unify $state\n (FuzzEnumerateRun $generator $size $limit $plan $enumerated $accepted $discards $samples)\n False\n True))\n\n(= (_fuzz-enumerate-step $state)\n (unify $state\n (FuzzEnumerateRun $generator $size $limit $plan $enumerated $accepted $discards $samples)\n (if (>= $enumerated $limit)\n (FuzzEnumerationTruncated\n (Enumerated $enumerated)\n (DomainCount $accepted)\n (GenerationDiscards $discards)\n (Samples $samples))\n (let $driver (_fuzz-exhaustive-resume-driver $plan)\n (let $result (fuzz-generate $generator $driver $size)\n (switch $result\n (((FuzzSample $value (FuzzDriver Exhaustive (ExhaustiveCursor $choices $cursor $frames)) $tree)\n (let $collected (_fuzz-expression-append $samples $result)\n (_fuzz-enumerate-advance\n $generator $size $limit $frames\n (+ $enumerated 1) (+ $accepted 1) $discards $collected)))\n ((FuzzGenerationDiscard $reason (FuzzDriver Exhaustive (ExhaustiveCursor $choices $cursor $frames)) $tree)\n (_fuzz-enumerate-advance\n $generator $size $limit $frames\n (+ $enumerated 1) $accepted (+ $discards 1) $samples))\n ((FuzzGenerationError $code $details) $result)\n ($bad\n (_fuzz-generation-error MalformedExhaustiveOutcome (Value $bad))))))))\n (_fuzz-generation-error MalformedEnumerationState (State $state))))\n\n(= (_fuzz-enumerate-advance $generator $size $limit $frames $enumerated $accepted $discards $samples)\n (let $advanced (_fuzz-exhaustive-next-plan $frames)\n (switch $advanced\n (((ExhaustivePlan $plan)\n (FuzzEnumerateRun $generator $size $limit $plan $enumerated $accepted $discards $samples))\n (ExhaustiveComplete\n (FuzzEnumeration\n (DomainCount $accepted)\n (Enumerated $enumerated)\n (GenerationDiscards $discards)\n (Samples $samples)))\n ((FuzzGenerationError $code $details) $advanced)\n ($bad\n (_fuzz-generation-error MalformedExhaustiveAdvance (Value $bad)))))))\n\n(= (_fuzz-finish-shrink-replay $result)\n (switch $result\n (((FuzzSample $value $driver $actual-tree)\n (FuzzShrinkReplay $value $actual-tree))\n ((FuzzGenerationDiscard $reason $driver $actual-tree)\n (FuzzShrinkDiscard $reason $actual-tree))\n ((FuzzGenerationError $code $details) $result)\n ($bad\n (_fuzz-generation-error\n MalformedShrinkReplayResult\n (Value $bad))))))\n\n(= (_fuzz-shrink-replay $generator $decision-tree $size)\n (let $driver (_fuzz-shrink-replay-driver $decision-tree)\n (switch $driver\n (((FuzzGenerationError $code $details) $driver)\n ($valid\n (_fuzz-finish-shrink-replay\n (fuzz-generate $generator $valid $size)))))))\n\n; SPDX-FileCopyrightText: 2026 MesTTo\n;\n; SPDX-License-Identifier: MIT\n\n(= (_fuzz-int-decision $lower $upper $origin $value)\n (Decision\n Int\n (Bounds $lower $upper)\n (Origin $origin)\n (Value $value)\n ()))\n\n(= (fuzz-random-driver $seed)\n (if (_fuzz-is-integer $seed)\n (let $rng (_fuzz-rng-init $seed)\n (switch $rng\n (((FuzzRng $algorithm $s01 $s00 $s11 $s10)\n (FuzzDriver Random $rng))\n ($bad\n (_fuzz-generation-error KernelError (OperationResult $bad))))))\n (_fuzz-expected-integer Seed $seed)))\n\n(= (fuzz-edge-driver $index)\n (if (_fuzz-is-integer $index)\n (if (>= $index 0)\n (FuzzDriver Edge $index)\n (_fuzz-generation-error InvalidEdgeIndex (Index $index)))\n (_fuzz-expected-integer EdgeIndex $index)))\n\n; One exhaustive run follows one choice vector: each integer decision reads its planned\n; offset (or defaults to zero past the plan) and records an (ExhaustiveFrame offset count)\n; newest-first. Enumeration is the odometer over recorded frames, driven by\n; `_fuzz-exhaustive-next-plan`; a lone driver generates the leftmost path deterministically.\n(= (fuzz-exhaustive-driver)\n (FuzzDriver Exhaustive (ExhaustiveCursor () 0 ())))\n\n(= (_fuzz-exhaustive-resume-driver $choices)\n (FuzzDriver Exhaustive (ExhaustiveCursor $choices 0 ())))\n\n; Odometer advance: increment the rightmost frame that has another branch and drop the\n; suffix; later decisions are reconstructed by default-zero descent, which is what keeps\n; enumeration exact for dependent generators. Frames arrive newest-first; the returned\n; (ExhaustivePlan offsets) is oldest-first. ExhaustiveComplete means the domain is done.\n(= (_fuzz-exhaustive-next-plan $frames-reversed)\n (if-decons-expr\n $frames-reversed\n $frame\n $earlier\n (switch $frame\n (((ExhaustiveFrame $offset $count)\n (if (< (+ $offset 1) $count)\n (let $bumped (+ $offset 1)\n (let $plan (_fuzz-exhaustive-plan-prefix $earlier ($bumped))\n (ExhaustivePlan $plan)))\n (_fuzz-exhaustive-next-plan $earlier)))\n ($bad\n (_fuzz-generation-error MalformedExhaustiveFrame (Frame $bad)))))\n ExhaustiveComplete))\n\n(= (_fuzz-exhaustive-plan-prefix $frames-reversed $accumulator)\n (if-decons-expr\n $frames-reversed\n $frame\n $earlier\n (switch $frame\n (((ExhaustiveFrame $offset $count)\n (let $next (cons-atom $offset $accumulator)\n (_fuzz-exhaustive-plan-prefix $earlier $next)))\n ($bad\n (_fuzz-generation-error MalformedExhaustiveFrame (Frame $bad)))))\n $accumulator))\n\n(= (_fuzz-valid-bytes $bytes)\n (if (== $bytes ())\n True\n (let* ((($byte $tail) (decons-atom $bytes)))\n (if (and\n (_fuzz-is-integer $byte)\n (and (<= 0 $byte) (<= $byte 255)))\n (_fuzz-valid-bytes $tail)\n False))))\n\n(= (fuzz-bytes-driver $bytes)\n (if (_fuzz-valid-bytes $bytes)\n (FuzzDriver Bytes (BytesState $bytes 0))\n (_fuzz-generation-error InvalidByteInput (Bytes $bytes))))\n\n(= (_fuzz-edge-add $candidate $lower $upper $candidates)\n (if (and (<= $lower $candidate) (<= $candidate $upper))\n (if (is-member $candidate $candidates)\n $candidates\n (append $candidates ($candidate)))\n $candidates))\n\n(= (_fuzz-edge-candidates $lower $upper $origin)\n (let* (($a (_fuzz-edge-add $origin $lower $upper ()))\n ($b (_fuzz-edge-add $lower $lower $upper $a))\n ($c (_fuzz-edge-add $upper $lower $upper $b))\n ($d (_fuzz-edge-add 0 $lower $upper $c))\n ($e (_fuzz-edge-add -1 $lower $upper $d))\n ($f (_fuzz-edge-add 1 $lower $upper $e))\n ($mid (/ (+ $lower $upper) 2)))\n (_fuzz-edge-add $mid $lower $upper $f)))\n\n(= (_fuzz-driver-int-random $rng $lower $upper $origin)\n (let $draw (_fuzz-draw-int $rng $lower $upper)\n (switch $draw\n (((FuzzDraw $value $next-rng)\n (DriverChoice\n $value\n (FuzzDriver Random $next-rng)\n (_fuzz-int-decision $lower $upper $origin $value)))\n ($bad\n (_fuzz-generation-error KernelError (OperationResult $bad)))))))\n\n(= (_fuzz-driver-int-edge $index $lower $upper $origin)\n (let* (($candidates (_fuzz-edge-candidates $lower $upper $origin))\n ($count (length $candidates))\n ($position (% $index $count))\n ($value (index-atom $candidates $position)))\n (DriverChoice\n $value\n (FuzzDriver Edge (+ $index 1))\n (_fuzz-int-decision $lower $upper $origin $value))))\n\n(= (_fuzz-inspect-int-decision $decision $lower $upper $origin)\n (switch $decision\n (((Decision\n Int\n (Bounds $seen-lower $seen-upper)\n (Origin $seen-origin)\n (Value $value)\n ())\n (if (and\n (== $lower $seen-lower)\n (and\n (== $upper $seen-upper)\n (== $origin $seen-origin)))\n (if (and (<= $lower $value) (<= $value $upper))\n (CompatibleIntDecision $value)\n (IntDecisionValueOutOfBounds $value))\n (IntDecisionMetadataMismatch\n (Bounds $seen-lower $seen-upper)\n (Origin $seen-origin))))\n ($bad (MalformedIntDecision $bad)))))\n\n(= (_fuzz-driver-int-replay $state $lower $upper $origin)\n (switch $state\n (((ReplayState $decisions $cursor)\n (if (== $decisions ())\n (_fuzz-generation-error ReplayMismatch\n (Path $cursor)\n (Expected\n (Decision\n Int\n (Bounds $lower $upper)\n (Origin $origin)\n (Value Any)\n ()))\n (Actual EndOfTrace))\n (let ($decision $tail) (decons-atom $decisions)\n (let $inspected\n (_fuzz-inspect-int-decision\n $decision\n $lower\n $upper\n $origin)\n (switch $inspected\n (((CompatibleIntDecision $value)\n (DriverChoice\n $value\n (FuzzDriver Replay (ReplayState $tail (+ $cursor 1)))\n $decision))\n ((IntDecisionValueOutOfBounds $value)\n (_fuzz-generation-error ReplayValueOutOfBounds\n (Path $cursor)\n (Bounds $lower $upper)\n (Value $value)))\n ((IntDecisionMetadataMismatch\n (Bounds $seen-lower $seen-upper)\n (Origin $seen-origin))\n (_fuzz-generation-error ReplayMismatch\n (Path $cursor)\n (ExpectedBounds $lower $upper)\n (ActualBounds $seen-lower $seen-upper)\n (Origins $origin $seen-origin)))\n ((MalformedIntDecision $bad)\n (_fuzz-generation-error ReplayMismatch\n (Path $cursor)\n (Expected IntDecision)\n (Actual $bad)))))))))\n ($bad-state\n (_fuzz-generation-error MalformedReplayState (State $bad-state))))))\n\n(= (_fuzz-shrink-replay-default-int\n $decisions\n $cursor\n $lower\n $upper\n $origin)\n (let $value (max $lower (min $upper $origin))\n (DriverChoice\n $value\n (FuzzDriver\n ShrinkReplay\n (ShrinkReplayState $decisions $cursor))\n (_fuzz-int-decision $lower $upper $origin $value))))\n\n(= (_fuzz-driver-int-shrink-replay-loop\n $decisions\n $cursor\n $lower\n $upper\n $origin)\n (if (== $decisions ())\n (_fuzz-shrink-replay-default-int\n ()\n $cursor\n $lower\n $upper\n $origin)\n (let ($decision $tail) (decons-atom $decisions)\n (let $next-cursor (+ $cursor 1)\n (let $inspected\n (_fuzz-inspect-int-decision\n $decision\n $lower\n $upper\n $origin)\n (switch $inspected\n (((CompatibleIntDecision $value)\n (DriverChoice\n $value\n (FuzzDriver\n ShrinkReplay\n (ShrinkReplayState $tail $next-cursor))\n $decision))\n ($incompatible\n (_fuzz-driver-int-shrink-replay-loop\n $tail\n $next-cursor\n $lower\n $upper\n $origin)))))))))\n\n(= (_fuzz-driver-int-shrink-replay $state $lower $upper $origin)\n (switch $state\n (((ShrinkReplayState $decisions $cursor)\n (_fuzz-driver-int-shrink-replay-loop\n $decisions\n $cursor\n $lower\n $upper\n $origin))\n ($bad-state\n (_fuzz-generation-error\n MalformedShrinkReplayState\n (State $bad-state))))))\n\n(= (_fuzz-driver-int-exhaustive $state $lower $upper $origin)\n (switch $state\n (((ExhaustiveCursor $choices $cursor $frames)\n (let* (($count (+ (- $upper $lower) 1))\n ($offset\n (if (< $cursor (length $choices))\n (index-atom $choices $cursor)\n 0)))\n (if (and (<= 0 $offset) (< $offset $count))\n (let* (($value (+ $lower $offset))\n ($frame (ExhaustiveFrame $offset $count))\n ($next-frames (cons-atom $frame $frames)))\n (DriverChoice\n $value\n (FuzzDriver\n Exhaustive\n (ExhaustiveCursor $choices (+ $cursor 1) $next-frames))\n (_fuzz-int-decision $lower $upper $origin $value)))\n (_fuzz-generation-error ExhaustiveResumeMismatch\n (Offset $offset)\n (Bounds $lower $upper)))))\n ($bad-state\n (_fuzz-generation-error\n MalformedExhaustiveState\n (State $bad-state))))))\n\n(= (_fuzz-byte-width $span $capacity $width)\n (if (>= $capacity $span)\n $width\n (_fuzz-byte-width $span (* $capacity 256) (+ $width 1))))\n\n(= (_fuzz-read-bytes $bytes $cursor $remaining $accumulator)\n (if (<= $remaining 0)\n (ByteRead $accumulator $cursor)\n (if (< $cursor (length $bytes))\n (let* (($byte (index-atom $bytes $cursor))\n ($next (+ (* $accumulator 256) $byte)))\n (_fuzz-read-bytes\n $bytes\n (+ $cursor 1)\n (- $remaining 1)\n $next))\n (_fuzz-generation-error BytesExhausted\n (Cursor $cursor)\n (Remaining $remaining)))))\n\n(= (_fuzz-driver-int-bytes $state $lower $upper $origin)\n (switch $state\n (((BytesState $bytes $cursor)\n (let* (($span (+ (- $upper $lower) 1))\n ($width (_fuzz-byte-width $span 256 1))\n ($read (_fuzz-read-bytes $bytes $cursor $width 0)))\n (switch $read\n (((ByteRead $raw $next-cursor)\n (let $value (+ $lower (% $raw $span))\n (DriverChoice\n $value\n (FuzzDriver Bytes (BytesState $bytes $next-cursor))\n (_fuzz-int-decision $lower $upper $origin $value))))\n ((FuzzGenerationError $code $details) $read)\n ($bad\n (_fuzz-generation-error\n MalformedByteRead\n (OperationResult $bad)))))))\n ($bad-state\n (_fuzz-generation-error MalformedByteState (State $bad-state))))))\n\n(= (_fuzz-driver-int $driver $lower $upper $origin)\n (if (> $lower $upper)\n (_fuzz-generation-error InvalidIntegerBounds (Bounds $lower $upper))\n (switch $driver\n (((FuzzDriver Random $rng)\n (_fuzz-driver-int-random $rng $lower $upper $origin))\n ((FuzzDriver Edge $index)\n (_fuzz-driver-int-edge $index $lower $upper $origin))\n ((FuzzDriver Replay $state)\n (_fuzz-driver-int-replay $state $lower $upper $origin))\n ((FuzzDriver ShrinkReplay $state)\n (_fuzz-driver-int-shrink-replay\n $state\n $lower\n $upper\n $origin))\n ((FuzzDriver Exhaustive $state)\n (_fuzz-driver-int-exhaustive $state $lower $upper $origin))\n ((FuzzDriver Bytes $state)\n (_fuzz-driver-int-bytes $state $lower $upper $origin))\n ($bad\n (_fuzz-generation-error MalformedDriver (Driver $bad)))))))\n\n; SPDX-FileCopyrightText: 2026 MesTTo\n;\n; SPDX-License-Identifier: MIT\n\n; Decision trees flatten to their Int leaves kernel-side (one linear pass); the drivers\n; only consume the resulting leaf list.\n(= (fuzz-replay-driver $decision-tree)\n (let $leaves (_fuzz-decision-leaves-op $decision-tree)\n (unify $leaves\n (FuzzDecisionLeaves $flat)\n (FuzzDriver Replay (ReplayState $flat 0))\n (unify $leaves\n (FuzzGenerationError $code $details)\n $leaves\n (unify $leaves\n $bad\n (_fuzz-generation-error MalformedDecisionTree (Decision $bad))\n Empty)))))\n\n(= (_fuzz-shrink-replay-driver $decision-tree)\n (let $leaves (_fuzz-decision-leaves-op $decision-tree)\n (unify $leaves\n (FuzzDecisionLeaves $flat)\n (FuzzDriver\n ShrinkReplay\n (ShrinkReplayState $flat 0))\n (unify $leaves\n (FuzzGenerationError $code $details)\n $leaves\n (unify $leaves\n $bad\n (_fuzz-generation-error MalformedDecisionTree (Decision $bad))\n Empty)))))\n\n; SPDX-FileCopyrightText: 2026 MesTTo\n;\n; SPDX-License-Identifier: MIT\n\n; Canonical property outcomes.\n(= (fuzz-pass)\n (Pass))\n\n(= (fuzz-fail $tag $details)\n (Fail $tag $details))\n\n(= (fuzz-discard $reason)\n (Discard $reason))\n\n(= (expect-true $condition $details)\n (if $condition\n (Pass)\n (Fail ExpectedTrue $details)))\n\n(= (expect-false $condition $details)\n (if $condition\n (Fail ExpectedFalse $details)\n (Pass)))\n\n(= (expect-atom-equal $actual $expected)\n (if (== $actual $expected)\n (Pass)\n (Fail\n NotEqual\n ((Actual $actual) (Expected $expected)))))\n\n(= (expect-alpha-equal $actual $expected)\n (if (=alpha $actual $expected)\n (Pass)\n (Fail\n NotAlphaEqual\n ((Actual $actual) (Expected $expected)))))\n\n(= (expect-results-exact $actual $expected)\n (if (== $actual $expected)\n (Pass)\n (Fail\n ResultsNotExact\n ((Actual $actual) (Expected $expected)))))\n\n(= (expect-results-alpha $actual $expected)\n (if (=alpha $actual $expected)\n (Pass)\n (Fail\n ResultsNotAlphaEqual\n ((Actual $actual) (Expected $expected)))))\n\n(= (_fuzz-remove-exact-loop $target $remaining $prefix)\n (if (== $remaining ())\n NotFound\n (let* ((($value $tail) (decons-atom $remaining)))\n (if (== $target $value)\n (Removed (append $prefix $tail))\n (_fuzz-remove-exact-loop\n $target\n $tail\n (append $prefix (cons-atom $value ())))))))\n\n(= (_fuzz-remove-exact $target $values)\n (_fuzz-remove-exact-loop $target $values ()))\n\n(= (_fuzz-results-multiset-equal $left $right)\n (if (== $left ())\n (== $right ())\n (let* ((($value $tail) (decons-atom $left))\n ($removed (_fuzz-remove-exact $value $right)))\n (switch $removed\n (((Removed $remaining)\n (_fuzz-results-multiset-equal $tail $remaining))\n (NotFound False)\n ($bad False))))))\n\n(= (_fuzz-every-member-exact $values $other)\n (if (== $values ())\n True\n (let* ((($value $tail) (decons-atom $values)))\n (if (is-member $value $other)\n (_fuzz-every-member-exact $tail $other)\n False))))\n\n(= (_fuzz-results-set-equal $left $right)\n (and\n (_fuzz-every-member-exact $left $right)\n (_fuzz-every-member-exact $right $left)))\n\n(= (expect-results-multiset $actual $expected)\n (if (_fuzz-results-multiset-equal $actual $expected)\n (Pass)\n (Fail\n ResultsNotMultisetEqual\n ((Actual $actual) (Expected $expected)))))\n\n(= (expect-results-set $actual $expected)\n (if (_fuzz-results-set-equal $actual $expected)\n (Pass)\n (Fail\n ResultsNotSetEqual\n ((Actual $actual) (Expected $expected)))))\n\n; The property argument stays lazy so a false precondition cannot run it.\n(= (implies $condition $property)\n (if $condition\n $property\n (Discard ImplicationFalse)))\n\n(= (classify $condition $label $property)\n (if $condition\n (FuzzClassified $label $property)\n $property))\n\n(= (collect $value $property)\n (FuzzCollected $value $property))\n\n(= (cover $minimum-percent $condition $label $property)\n (if (and\n (<= 0 $minimum-percent)\n (<= $minimum-percent 100))\n (FuzzCovered\n $minimum-percent\n $label\n $condition\n $property)\n (FuzzInvalidProperty\n InvalidCoveragePercentage\n (MinimumPercent $minimum-percent))))\n\n(= (counterexample $note $property)\n (FuzzAnnotated $note $property))\n\n; Compatibility aliases use the canonical outcomes.\n(= (fuzz-equal $actual $expected)\n (expect-atom-equal $actual $expected))\n\n(= (fuzz-alpha-equal $actual $expected)\n (expect-alpha-equal $actual $expected))\n\n(= (fuzz-implies $condition $property)\n (implies $condition $property))\n\n(= (fuzz-annotate $note $property)\n (counterexample $note $property))\n\n(= (fuzz-classify $condition $label $property)\n (classify $condition $label $property))\n\n(= (fuzz-collect $value $property)\n (collect $value $property))\n\n(= (fuzz-cover $minimum-percent $label $condition $property)\n (cover $minimum-percent $condition $label $property))\n\n; Quantifier wrappers are passed as the property-function argument to fuzz-check.\n(= (all-results $property)\n (FuzzPropertyFunction All $property))\n\n(= (any-result $property)\n (FuzzPropertyFunction Any $property))\n\n(= (_fuzz-normalized-add-annotation $annotation $normalized)\n (switch $normalized\n (((NormalizedProperty\n $status\n $tag\n $details\n $labels\n $collected\n $coverage\n $annotations)\n (NormalizedProperty\n $status\n $tag\n $details\n $labels\n $collected\n $coverage\n (append $annotations (cons-atom $annotation ()))))\n ($bad\n (NormalizedProperty\n Invalid\n InvalidPropertyWrapper\n (Value $bad)\n ()\n ()\n ()\n ())))))\n\n(= (_fuzz-normalized-add-label $label $normalized)\n (switch $normalized\n (((NormalizedProperty\n $status\n $tag\n $details\n $labels\n $collected\n $coverage\n $annotations)\n (NormalizedProperty\n $status\n $tag\n $details\n (append $labels (cons-atom $label ()))\n $collected\n $coverage\n $annotations))\n ($bad\n (NormalizedProperty\n Invalid\n InvalidPropertyWrapper\n (Value $bad)\n ()\n ()\n ()\n ())))))\n\n(= (_fuzz-normalized-add-collected $value $normalized)\n (switch $normalized\n (((NormalizedProperty\n $status\n $tag\n $details\n $labels\n $collected\n $coverage\n $annotations)\n (NormalizedProperty\n $status\n $tag\n $details\n $labels\n (append $collected (cons-atom $value ()))\n $coverage\n $annotations))\n ($bad\n (NormalizedProperty\n Invalid\n InvalidPropertyWrapper\n (Value $bad)\n ()\n ()\n ()\n ())))))\n\n(= (_fuzz-normalized-add-coverage\n $minimum-percent\n $label\n $hit\n $normalized)\n (switch $normalized\n (((NormalizedProperty\n $status\n $tag\n $details\n $labels\n $collected\n $coverage\n $annotations)\n (let $observation\n (CoverageObservation $minimum-percent $label $hit)\n (NormalizedProperty\n $status\n $tag\n $details\n $labels\n $collected\n (append $coverage (cons-atom $observation ()))\n $annotations)))\n ($bad\n (NormalizedProperty\n Invalid\n InvalidPropertyWrapper\n (Value $bad)\n ()\n ()\n ()\n ())))))\n\n(= (_fuzz-normalize-property-result $result)\n (switch $result\n (((Pass)\n (NormalizedProperty Pass None () () () () ()))\n (True\n (NormalizedProperty Pass None () () () () ()))\n (False\n (NormalizedProperty Fail BooleanFalse () () () () ()))\n ((Fail $tag $details)\n (NormalizedProperty Fail $tag $details () () () ()))\n ((Discard $reason)\n (NormalizedProperty Discard Discarded $reason () () () ()))\n ((FuzzAnnotated $annotation $outcome)\n (_fuzz-normalized-add-annotation\n $annotation\n (_fuzz-normalize-property-result $outcome)))\n ((FuzzClassified $label $outcome)\n (_fuzz-normalized-add-label\n $label\n (_fuzz-normalize-property-result $outcome)))\n ((FuzzCollected $value $outcome)\n (_fuzz-normalized-add-collected\n $value\n (_fuzz-normalize-property-result $outcome)))\n ((FuzzCovered $minimum-percent $label $hit $outcome)\n (_fuzz-normalized-add-coverage\n $minimum-percent\n $label\n $hit\n (_fuzz-normalize-property-result $outcome)))\n ((FuzzInvalidProperty $code $details)\n (NormalizedProperty Invalid $code $details () () () ()))\n ((Error $subject ResourceLimit)\n (NormalizedProperty\n Cutoff\n ResourceLimit\n (Error $subject ResourceLimit)\n ()\n ()\n ()\n ()))\n ((Error $subject StackOverflow)\n (NormalizedProperty\n Cutoff\n StackOverflow\n (Error $subject StackOverflow)\n ()\n ()\n ()\n ()))\n ((Error $subject TableResourceLimit)\n (NormalizedProperty\n Cutoff\n TableResourceLimit\n (Error $subject TableResourceLimit)\n ()\n ()\n ()\n ()))\n ((Error $subject $reason)\n (NormalizedProperty\n Fail\n LanguageError\n (Error $subject $reason)\n ()\n ()\n ()\n ()))\n ($bad\n (NormalizedProperty\n Invalid\n MalformedPropertyResult\n (Value $bad)\n ()\n ()\n ()\n ())))))\n\n(= (_fuzz-first-result $current $candidate)\n (switch $current\n ((None (Some $candidate))\n ((Some $value) $current)\n ($bad (Some $candidate)))))\n\n(= (_fuzz-classification-add $normalized $state)\n (switch $state\n (((PropertyClassification\n $pass-count\n $first-fail\n $first-discard\n $first-cutoff\n $first-invalid\n $labels\n $collected\n $coverage\n $annotations)\n (switch $normalized\n (((NormalizedProperty\n $status\n $tag\n $details\n $new-labels\n $new-collected\n $new-coverage\n $new-annotations)\n (let* (($next-pass-count\n (if (== $status Pass)\n (+ $pass-count 1)\n $pass-count))\n ($next-fail\n (if (== $status Fail)\n (_fuzz-first-result $first-fail $normalized)\n $first-fail))\n ($next-discard\n (if (== $status Discard)\n (_fuzz-first-result $first-discard $normalized)\n $first-discard))\n ($next-cutoff\n (if (== $status Cutoff)\n (_fuzz-first-result $first-cutoff $normalized)\n $first-cutoff))\n ($next-invalid\n (if (== $status Invalid)\n (_fuzz-first-result $first-invalid $normalized)\n $first-invalid)))\n (PropertyClassification\n $next-pass-count\n $next-fail\n $next-discard\n $next-cutoff\n $next-invalid\n (append $labels $new-labels)\n (append $collected $new-collected)\n (append $coverage $new-coverage)\n (append $annotations $new-annotations))))\n ($bad\n (PropertyClassification\n $pass-count\n $first-fail\n $first-discard\n $first-cutoff\n (Some\n (NormalizedProperty\n Invalid\n InvalidNormalizedProperty\n (Value $bad)\n ()\n ()\n ()\n ()))\n $labels\n $collected\n $coverage\n $annotations)))))\n ($bad-state $bad-state))))\n\n(= (_fuzz-classify-results-loop $remaining $state)\n (if (== $remaining ())\n $state\n (let* ((($result $tail) (decons-atom $remaining))\n ($normalized\n (_fuzz-normalize-property-result $result))\n ($next\n (_fuzz-classification-add $normalized $state)))\n (_fuzz-classify-results-loop $tail $next))))\n\n(= (_fuzz-case-from-normalized\n $normalized\n $state\n $results\n $steps)\n (switch $normalized\n (((NormalizedProperty\n $status\n $tag\n $details\n $ignored-labels\n $ignored-collected\n $ignored-coverage\n $ignored-annotations)\n (switch $state\n (((PropertyClassification\n $pass-count\n $first-fail\n $first-discard\n $first-cutoff\n $first-invalid\n $labels\n $collected\n $coverage\n $annotations)\n (FuzzCaseResult\n $status\n $tag\n (Details $details)\n (Labels $labels)\n (Collected $collected)\n (Coverage $coverage)\n (Annotations $annotations)\n (Results $results)\n (Steps $steps)))\n ($bad-state\n (FuzzCaseResult\n Invalid\n InvalidClassificationState\n (Details (Value $bad-state))\n (Labels ())\n (Collected ())\n (Coverage ())\n (Annotations ())\n (Results $results)\n (Steps $steps))))))\n ($bad\n (FuzzCaseResult\n Invalid\n InvalidNormalizedProperty\n (Details (Value $bad))\n (Labels ())\n (Collected ())\n (Coverage ())\n (Annotations ())\n (Results $results)\n (Steps $steps))))))\n\n(= (_fuzz-synthetic-case $status $tag $details $state $results $steps)\n (_fuzz-case-from-normalized\n (NormalizedProperty $status $tag $details () () () ())\n $state\n $results\n $steps))\n\n(= (_fuzz-case-from-option\n $option\n $fallback-status\n $fallback-tag\n $state\n $results\n $steps)\n (switch $option\n (((Some $normalized)\n (_fuzz-case-from-normalized\n $normalized\n $state\n $results\n $steps))\n (None\n (_fuzz-synthetic-case\n $fallback-status\n $fallback-tag\n ()\n $state\n $results\n $steps))\n ($bad\n (_fuzz-synthetic-case\n Invalid\n InvalidClassificationOption\n (Value $bad)\n $state\n $results\n $steps)))))\n\n(= (_fuzz-finish-default-after-fail $state $results $steps)\n (switch $state\n (((PropertyClassification\n $pass-count\n $first-fail\n $first-discard\n $first-cutoff\n $first-invalid\n $labels\n $collected\n $coverage\n $annotations)\n (switch $first-cutoff\n (((Some $cutoff)\n (_fuzz-case-from-normalized\n $cutoff\n $state\n $results\n $steps))\n (None\n (if (> $pass-count 0)\n (_fuzz-synthetic-case\n Pass\n None\n ()\n $state\n $results\n $steps)\n (_fuzz-case-from-option\n $first-discard\n Invalid\n NoPropertyResult\n $state\n $results\n $steps))))))\n ($bad-state\n (_fuzz-synthetic-case\n Invalid\n InvalidClassificationState\n (Value $bad-state)\n $state\n $results\n $steps)))))\n\n(= (_fuzz-finish-default $state $results $steps)\n (switch $state\n (((PropertyClassification\n $pass-count\n $first-fail\n $first-discard\n $first-cutoff\n $first-invalid\n $labels\n $collected\n $coverage\n $annotations)\n (switch $first-fail\n (((Some $failure)\n (_fuzz-case-from-normalized\n $failure\n $state\n $results\n $steps))\n (None\n (_fuzz-finish-default-after-fail\n $state\n $results\n $steps)))))\n ($bad-state\n (_fuzz-synthetic-case\n Invalid\n InvalidClassificationState\n (Value $bad-state)\n $state\n $results\n $steps)))))\n\n(= (_fuzz-finish-all-after-fail $state $results $steps)\n (switch $state\n (((PropertyClassification\n $pass-count\n $first-fail\n $first-discard\n $first-cutoff\n $first-invalid\n $labels\n $collected\n $coverage\n $annotations)\n (switch $first-cutoff\n (((Some $cutoff)\n (_fuzz-case-from-normalized\n $cutoff\n $state\n $results\n $steps))\n (None\n (switch $first-discard\n (((Some $discard)\n (_fuzz-case-from-normalized\n $discard\n $state\n $results\n $steps))\n (None\n (if (> $pass-count 0)\n (_fuzz-synthetic-case\n Pass\n None\n ()\n $state\n $results\n $steps)\n (_fuzz-synthetic-case\n Invalid\n NoPropertyResult\n ()\n $state\n $results\n $steps)))))))))\n ($bad-state\n (_fuzz-synthetic-case\n Invalid\n InvalidClassificationState\n (Value $bad-state)\n $state\n $results\n $steps)))))\n\n(= (_fuzz-finish-all $state $results $steps)\n (switch $state\n (((PropertyClassification\n $pass-count\n $first-fail\n $first-discard\n $first-cutoff\n $first-invalid\n $labels\n $collected\n $coverage\n $annotations)\n (switch $first-fail\n (((Some $failure)\n (_fuzz-case-from-normalized\n $failure\n $state\n $results\n $steps))\n (None\n (_fuzz-finish-all-after-fail\n $state\n $results\n $steps)))))\n ($bad-state\n (_fuzz-synthetic-case\n Invalid\n InvalidClassificationState\n (Value $bad-state)\n $state\n $results\n $steps)))))\n\n(= (_fuzz-finish-any-after-pass $state $results $steps)\n (switch $state\n (((PropertyClassification\n $pass-count\n $first-fail\n $first-discard\n $first-cutoff\n $first-invalid\n $labels\n $collected\n $coverage\n $annotations)\n (switch $first-fail\n (((Some $failure)\n (_fuzz-case-from-normalized\n $failure\n $state\n $results\n $steps))\n (None\n (switch $first-cutoff\n (((Some $cutoff)\n (_fuzz-case-from-normalized\n $cutoff\n $state\n $results\n $steps))\n (None\n (_fuzz-case-from-option\n $first-discard\n Invalid\n NoPropertyResult\n $state\n $results\n $steps))))))))\n ($bad-state\n (_fuzz-synthetic-case\n Invalid\n InvalidClassificationState\n (Value $bad-state)\n $state\n $results\n $steps)))))\n\n(= (_fuzz-finish-any $state $results $steps)\n (switch $state\n (((PropertyClassification\n $pass-count\n $first-fail\n $first-discard\n $first-cutoff\n $first-invalid\n $labels\n $collected\n $coverage\n $annotations)\n (if (> $pass-count 0)\n (_fuzz-synthetic-case\n Pass\n None\n ()\n $state\n $results\n $steps)\n (_fuzz-finish-any-after-pass\n $state\n $results\n $steps)))\n ($bad-state\n (_fuzz-synthetic-case\n Invalid\n InvalidClassificationState\n (Value $bad-state)\n $state\n $results\n $steps)))))\n\n(= (_fuzz-finish-valid-classification\n $quantifier\n $state\n $results\n $steps)\n (if (== $quantifier Default)\n (_fuzz-finish-default $state $results $steps)\n (if (== $quantifier All)\n (_fuzz-finish-all $state $results $steps)\n (if (== $quantifier Any)\n (_fuzz-finish-any $state $results $steps)\n (_fuzz-synthetic-case\n Invalid\n InvalidQuantifier\n (Quantifier $quantifier)\n $state\n $results\n $steps)))))\n\n(= (_fuzz-finish-property-classification\n $quantifier\n $state\n $results\n $steps)\n (switch $state\n (((PropertyClassification\n $pass-count\n $first-fail\n $first-discard\n $first-cutoff\n $first-invalid\n $labels\n $collected\n $coverage\n $annotations)\n (switch $first-invalid\n (((Some $invalid)\n (_fuzz-case-from-normalized\n $invalid\n $state\n $results\n $steps))\n (None\n (_fuzz-finish-valid-classification\n $quantifier\n $state\n $results\n $steps)))))\n ($bad-state\n (_fuzz-synthetic-case\n Invalid\n InvalidClassificationState\n (Value $bad-state)\n $state\n $results\n $steps)))))\n\n(= (_fuzz-initial-classification $outcome-status)\n (if (== $outcome-status Completed)\n (PropertyClassification\n 0 None None None None () () () ())\n (if (== $outcome-status ResourceLimit)\n (PropertyClassification\n 0\n None\n None\n (Some\n (NormalizedProperty\n Cutoff ResourceLimit () () () () ()))\n None\n ()\n ()\n ()\n ())\n (if (== $outcome-status StackOverflow)\n (PropertyClassification\n 0\n None\n None\n (Some\n (NormalizedProperty\n Cutoff StackOverflow () () () () ()))\n None\n ()\n ()\n ()\n ())\n (PropertyClassification\n 0\n None\n None\n None\n (Some\n (NormalizedProperty\n Invalid\n InvalidEvaluatorStatus\n (Status $outcome-status)\n ()\n ()\n ()\n ()))\n ()\n ()\n ()\n ())))))\n\n(= (_fuzz-classify-property-results\n $quantifier\n $results\n $steps\n $outcome-status)\n (if (== $results ())\n (let $state (_fuzz-initial-classification $outcome-status)\n (_fuzz-synthetic-case\n Invalid\n NoPropertyResult\n ()\n $state\n $results\n $steps))\n (let* (($initial\n (_fuzz-initial-classification $outcome-status))\n ($classified\n (_fuzz-classify-results-loop\n $results\n $initial)))\n (_fuzz-finish-property-classification\n $quantifier\n $classified\n $results\n $steps))))\n\n(= (_fuzz-evaluate-property\n $property\n $quantifier\n $value\n $maximum-steps\n $maximum-depth\n $effect-policy)\n (let $resolved-policy $effect-policy\n (let $outcome\n (_fuzz-eval-case\n ($property $value)\n $maximum-steps\n $maximum-depth\n $resolved-policy)\n (switch $outcome\n (((FuzzCaseOutcome Completed $results $steps)\n (_fuzz-classify-property-results\n $quantifier\n $results\n $steps\n Completed))\n ((FuzzCaseOutcome ResourceLimit $results $steps)\n (_fuzz-classify-property-results\n $quantifier\n $results\n $steps\n ResourceLimit))\n ((FuzzCaseOutcome StackOverflow $results $steps)\n (_fuzz-classify-property-results\n $quantifier\n $results\n $steps\n StackOverflow))\n ((FuzzCaseOutcome\n (EffectDenied $effect $operation)\n $results\n $steps)\n (let $state\n (PropertyClassification\n 0 None None None None () () () ())\n (_fuzz-synthetic-case\n HostFault\n EffectDenied\n ((Effect $effect) (Operation $operation))\n $state\n $results\n $steps)))\n ($bad\n (let $state\n (PropertyClassification\n 0 None None None None () () () ())\n (_fuzz-synthetic-case\n Invalid\n InvalidEvaluatorOutcome\n (Value $bad)\n $state\n ()\n 0))))))))\n\n; SPDX-FileCopyrightText: 2026 MesTTo\n;\n; SPDX-License-Identifier: MIT\n\n(= (_fuzz-default-config-data)\n (FuzzConfig\n (Runs 100)\n (Seed 0)\n (MaxSize 100)\n (MaxDiscards 1000)\n (MaxShrinks 1000)\n (MaxShrinkImprovements 1000)\n (CaseSteps 100000)\n (CaseDepth 1000)\n (EffectPolicy Sandboxed)\n (EdgeCases 16)\n ; A safety bound on exhaustive mode, sized against what a case actually costs. One case is\n ; milliseconds of interpretation here, measured at roughly 7ms for a scalar generator and 18ms for a\n ; list of forty, so a bound of 10000 meant a domain that cannot fit ground for three minutes before\n ; saying so. A thousand keeps that under half a minute. A domain larger than this is still coverable,\n ; by asking for it: the run reports EnumerationLimit rather than pretending to have covered it.\n (MaxEnumerated 1000)\n (FailureMode SameFailureTag)))\n\n(= (fuzz-default-config)\n (_fuzz-default-config-data))\n\n(= (_fuzz-config-option-name $option)\n (switch $option\n (((Runs $value) Runs)\n ((Seed $value) Seed)\n ((MaxSize $value) MaxSize)\n ((MaxDiscards $value) MaxDiscards)\n ((MaxShrinks $value) MaxShrinks)\n ((MaxShrinkImprovements $value) MaxShrinkImprovements)\n ((CaseSteps $value) CaseSteps)\n ((CaseDepth $value) CaseDepth)\n ((EffectPolicy $value) EffectPolicy)\n ((EdgeCases $value) EdgeCases)\n ((MaxEnumerated $value) MaxEnumerated)\n ((FailureMode $value) FailureMode)\n ($bad (InvalidOption $bad)))))\n\n(= (_fuzz-valid-nonnegative-integer $value)\n (and (_fuzz-is-integer $value) (>= $value 0)))\n\n(= (_fuzz-valid-positive-integer $value)\n (and (_fuzz-is-integer $value) (> $value 0)))\n\n(= (_fuzz-config-values $config)\n (switch $config\n (((FuzzConfig\n (Runs $runs)\n (Seed $seed)\n (MaxSize $maximum-size)\n (MaxDiscards $maximum-discards)\n (MaxShrinks $maximum-shrinks)\n (MaxShrinkImprovements $maximum-improvements)\n (CaseSteps $case-steps)\n (CaseDepth $case-depth)\n (EffectPolicy $effect-policy)\n (EdgeCases $edge-cases)\n (MaxEnumerated $maximum-enumerated)\n (FailureMode $failure-mode))\n (FuzzConfigValues\n $runs\n $seed\n $maximum-size\n $maximum-discards\n $maximum-shrinks\n $maximum-improvements\n $case-steps\n $case-depth\n $effect-policy\n $edge-cases\n $maximum-enumerated\n $failure-mode))\n ($bad\n (FuzzInvalid InvalidConfig (MalformedConfig $bad))))))\n\n(= (_fuzz-config-set $option $config)\n (let $values (_fuzz-config-values $config)\n (switch $values\n (((FuzzConfigValues\n $runs\n $seed\n $maximum-size\n $maximum-discards\n $maximum-shrinks\n $maximum-improvements\n $case-steps\n $case-depth\n $effect-policy\n $edge-cases\n $maximum-enumerated\n $failure-mode)\n (switch $option\n (((Runs $value)\n (if (_fuzz-valid-positive-integer $value)\n (FuzzConfig\n (Runs $value)\n (Seed $seed)\n (MaxSize $maximum-size)\n (MaxDiscards $maximum-discards)\n (MaxShrinks $maximum-shrinks)\n (MaxShrinkImprovements $maximum-improvements)\n (CaseSteps $case-steps)\n (CaseDepth $case-depth)\n (EffectPolicy $effect-policy)\n (EdgeCases $edge-cases)\n (MaxEnumerated $maximum-enumerated)\n (FailureMode $failure-mode))\n (FuzzInvalid\n InvalidConfig\n (InvalidRuns (Runs $value)))))\n ((Seed $value)\n (if (_fuzz-is-integer $value)\n (FuzzConfig\n (Runs $runs)\n (Seed $value)\n (MaxSize $maximum-size)\n (MaxDiscards $maximum-discards)\n (MaxShrinks $maximum-shrinks)\n (MaxShrinkImprovements $maximum-improvements)\n (CaseSteps $case-steps)\n (CaseDepth $case-depth)\n (EffectPolicy $effect-policy)\n (EdgeCases $edge-cases)\n (MaxEnumerated $maximum-enumerated)\n (FailureMode $failure-mode))\n (FuzzInvalid\n InvalidConfig\n (InvalidSeed (Seed $value)))))\n ((MaxSize $value)\n (if (_fuzz-valid-nonnegative-integer $value)\n (FuzzConfig\n (Runs $runs)\n (Seed $seed)\n (MaxSize $value)\n (MaxDiscards $maximum-discards)\n (MaxShrinks $maximum-shrinks)\n (MaxShrinkImprovements $maximum-improvements)\n (CaseSteps $case-steps)\n (CaseDepth $case-depth)\n (EffectPolicy $effect-policy)\n (EdgeCases $edge-cases)\n (MaxEnumerated $maximum-enumerated)\n (FailureMode $failure-mode))\n (FuzzInvalid\n InvalidConfig\n (InvalidMaxSize (MaxSize $value)))))\n ((MaxDiscards $value)\n (if (_fuzz-valid-nonnegative-integer $value)\n (FuzzConfig\n (Runs $runs)\n (Seed $seed)\n (MaxSize $maximum-size)\n (MaxDiscards $value)\n (MaxShrinks $maximum-shrinks)\n (MaxShrinkImprovements $maximum-improvements)\n (CaseSteps $case-steps)\n (CaseDepth $case-depth)\n (EffectPolicy $effect-policy)\n (EdgeCases $edge-cases)\n (MaxEnumerated $maximum-enumerated)\n (FailureMode $failure-mode))\n (FuzzInvalid\n InvalidConfig\n (InvalidMaxDiscards (MaxDiscards $value)))))\n ((MaxShrinks $value)\n (if (_fuzz-valid-nonnegative-integer $value)\n (FuzzConfig\n (Runs $runs)\n (Seed $seed)\n (MaxSize $maximum-size)\n (MaxDiscards $maximum-discards)\n (MaxShrinks $value)\n (MaxShrinkImprovements $maximum-improvements)\n (CaseSteps $case-steps)\n (CaseDepth $case-depth)\n (EffectPolicy $effect-policy)\n (EdgeCases $edge-cases)\n (MaxEnumerated $maximum-enumerated)\n (FailureMode $failure-mode))\n (FuzzInvalid\n InvalidConfig\n (InvalidMaxShrinks (MaxShrinks $value)))))\n ((MaxShrinkImprovements $value)\n (if (_fuzz-valid-nonnegative-integer $value)\n (FuzzConfig\n (Runs $runs)\n (Seed $seed)\n (MaxSize $maximum-size)\n (MaxDiscards $maximum-discards)\n (MaxShrinks $maximum-shrinks)\n (MaxShrinkImprovements $value)\n (CaseSteps $case-steps)\n (CaseDepth $case-depth)\n (EffectPolicy $effect-policy)\n (EdgeCases $edge-cases)\n (MaxEnumerated $maximum-enumerated)\n (FailureMode $failure-mode))\n (FuzzInvalid\n InvalidConfig\n (InvalidMaxShrinkImprovements\n (MaxShrinkImprovements $value)))))\n ((CaseSteps $value)\n (if (_fuzz-valid-nonnegative-integer $value)\n (FuzzConfig\n (Runs $runs)\n (Seed $seed)\n (MaxSize $maximum-size)\n (MaxDiscards $maximum-discards)\n (MaxShrinks $maximum-shrinks)\n (MaxShrinkImprovements $maximum-improvements)\n (CaseSteps $value)\n (CaseDepth $case-depth)\n (EffectPolicy $effect-policy)\n (EdgeCases $edge-cases)\n (MaxEnumerated $maximum-enumerated)\n (FailureMode $failure-mode))\n (FuzzInvalid\n InvalidConfig\n (InvalidCaseSteps (CaseSteps $value)))))\n ((CaseDepth $value)\n (if (_fuzz-valid-nonnegative-integer $value)\n (FuzzConfig\n (Runs $runs)\n (Seed $seed)\n (MaxSize $maximum-size)\n (MaxDiscards $maximum-discards)\n (MaxShrinks $maximum-shrinks)\n (MaxShrinkImprovements $maximum-improvements)\n (CaseSteps $case-steps)\n (CaseDepth $value)\n (EffectPolicy $effect-policy)\n (EdgeCases $edge-cases)\n (MaxEnumerated $maximum-enumerated)\n (FailureMode $failure-mode))\n (FuzzInvalid\n InvalidConfig\n (InvalidCaseDepth (CaseDepth $value)))))\n ((EffectPolicy $value)\n (if (or\n (== $value Sandboxed)\n (== $value ExternalEffects))\n (FuzzConfig\n (Runs $runs)\n (Seed $seed)\n (MaxSize $maximum-size)\n (MaxDiscards $maximum-discards)\n (MaxShrinks $maximum-shrinks)\n (MaxShrinkImprovements $maximum-improvements)\n (CaseSteps $case-steps)\n (CaseDepth $case-depth)\n (EffectPolicy $value)\n (EdgeCases $edge-cases)\n (MaxEnumerated $maximum-enumerated)\n (FailureMode $failure-mode))\n (FuzzInvalid\n InvalidConfig\n (InvalidEffectPolicy (EffectPolicy $value)))))\n ((EdgeCases $value)\n (if (_fuzz-valid-nonnegative-integer $value)\n (FuzzConfig\n (Runs $runs)\n (Seed $seed)\n (MaxSize $maximum-size)\n (MaxDiscards $maximum-discards)\n (MaxShrinks $maximum-shrinks)\n (MaxShrinkImprovements $maximum-improvements)\n (CaseSteps $case-steps)\n (CaseDepth $case-depth)\n (EffectPolicy $effect-policy)\n (EdgeCases $value)\n (MaxEnumerated $maximum-enumerated)\n (FailureMode $failure-mode))\n (FuzzInvalid\n InvalidConfig\n (InvalidEdgeCases (EdgeCases $value)))))\n ((MaxEnumerated $value)\n (if (_fuzz-valid-positive-integer $value)\n (FuzzConfig\n (Runs $runs)\n (Seed $seed)\n (MaxSize $maximum-size)\n (MaxDiscards $maximum-discards)\n (MaxShrinks $maximum-shrinks)\n (MaxShrinkImprovements $maximum-improvements)\n (CaseSteps $case-steps)\n (CaseDepth $case-depth)\n (EffectPolicy $effect-policy)\n (EdgeCases $edge-cases)\n (MaxEnumerated $value)\n (FailureMode $failure-mode))\n (FuzzInvalid\n InvalidConfig\n (InvalidMaxEnumerated (MaxEnumerated $value)))))\n ((FailureMode $value)\n (if (or\n (== $value SameFailureTag)\n (== $value AnyFailure))\n (FuzzConfig\n (Runs $runs)\n (Seed $seed)\n (MaxSize $maximum-size)\n (MaxDiscards $maximum-discards)\n (MaxShrinks $maximum-shrinks)\n (MaxShrinkImprovements $maximum-improvements)\n (CaseSteps $case-steps)\n (CaseDepth $case-depth)\n (EffectPolicy $effect-policy)\n (EdgeCases $edge-cases)\n (MaxEnumerated $maximum-enumerated)\n (FailureMode $value))\n (FuzzInvalid\n InvalidConfig\n (InvalidFailureMode (FailureMode $value)))))\n ($bad\n (FuzzInvalid InvalidConfig (UnknownOption $bad))))))\n ((FuzzInvalid $code $details) $values)\n ($bad\n (FuzzInvalid InvalidConfig (MalformedConfigValues $bad)))))))\n\n(= (_fuzz-config-options $options $config $seen)\n (if (== $options ())\n $config\n (let* ((($option $tail) (decons-atom $options))\n ($name (_fuzz-config-option-name $option)))\n (switch $name\n (((InvalidOption $bad)\n (FuzzInvalid InvalidConfig (UnknownOption $bad)))\n ($valid-name\n (if (is-member $valid-name $seen)\n (FuzzInvalid InvalidConfig (DuplicateOption $valid-name))\n (let $next (_fuzz-config-set $option $config)\n (switch $next\n (((FuzzInvalid $code $details) $next)\n ($valid-config\n (_fuzz-config-options\n $tail\n $valid-config\n (append\n $seen\n (cons-atom $valid-name ()))))))))))))))\n\n(= (_fuzz-build-config $options)\n (_fuzz-config-options\n $options\n (_fuzz-default-config-data)\n ()))\n\n(= (fuzz-config)\n (_fuzz-build-config ()))\n\n(= (fuzz-config $a)\n (_fuzz-build-config ($a)))\n\n(= (fuzz-config $a $b)\n (_fuzz-build-config ($a $b)))\n\n(= (fuzz-config $a $b $c)\n (_fuzz-build-config ($a $b $c)))\n\n(= (fuzz-config $a $b $c $d)\n (_fuzz-build-config ($a $b $c $d)))\n\n(= (fuzz-config $a $b $c $d $e)\n (_fuzz-build-config ($a $b $c $d $e)))\n\n(= (fuzz-config $a $b $c $d $e $f)\n (_fuzz-build-config ($a $b $c $d $e $f)))\n\n(= (fuzz-config $a $b $c $d $e $f $g)\n (_fuzz-build-config ($a $b $c $d $e $f $g)))\n\n(= (fuzz-config $a $b $c $d $e $f $g $h)\n (_fuzz-build-config ($a $b $c $d $e $f $g $h)))\n\n(= (fuzz-config $a $b $c $d $e $f $g $h $i)\n (_fuzz-build-config ($a $b $c $d $e $f $g $h $i)))\n\n(= (fuzz-config $a $b $c $d $e $f $g $h $i $j)\n (_fuzz-build-config ($a $b $c $d $e $f $g $h $i $j)))\n\n(= (fuzz-config $a $b $c $d $e $f $g $h $i $j $k)\n (_fuzz-build-config ($a $b $c $d $e $f $g $h $i $j $k)))\n\n(= (fuzz-config $a $b $c $d $e $f $g $h $i $j $k $l)\n (_fuzz-build-config ($a $b $c $d $e $f $g $h $i $j $k $l)))\n\n(= (_fuzz-config-get $name $config)\n (let $values (_fuzz-config-values $config)\n (switch $values\n (((FuzzConfigValues\n $runs\n $seed\n $maximum-size\n $maximum-discards\n $maximum-shrinks\n $maximum-improvements\n $case-steps\n $case-depth\n $effect-policy\n $edge-cases\n $maximum-enumerated\n $failure-mode)\n (switch $name\n ((Runs $runs)\n (Seed $seed)\n (MaxSize $maximum-size)\n (MaxDiscards $maximum-discards)\n (MaxShrinks $maximum-shrinks)\n (MaxShrinkImprovements $maximum-improvements)\n (CaseSteps $case-steps)\n (CaseDepth $case-depth)\n (EffectPolicy $effect-policy)\n (EdgeCases $edge-cases)\n (MaxEnumerated $maximum-enumerated)\n (FailureMode $failure-mode)\n ($bad (FuzzInvalid InvalidConfig (UnknownConfigField $bad))))))\n ((FuzzInvalid $code $details) $values)\n ($bad\n (FuzzInvalid InvalidConfig (MalformedConfigValues $bad)))))))\n\n(= (_fuzz-validate-config $config)\n (let $values (_fuzz-config-values $config)\n (switch $values\n (((FuzzConfigValues\n $runs\n $seed\n $maximum-size\n $maximum-discards\n $maximum-shrinks\n $maximum-improvements\n $case-steps\n $case-depth\n $effect-policy\n $edge-cases\n $maximum-enumerated\n $failure-mode)\n $config)\n ((FuzzInvalid $code $details) $values)\n ($bad\n (FuzzInvalid InvalidConfig (MalformedConfigValues $bad)))))))\n\n(= (_fuzz-resolve-property-function $property)\n (switch $property\n (((FuzzPropertyFunction All $function)\n (ResolvedProperty All $function))\n ((FuzzPropertyFunction Any $function)\n (ResolvedProperty Any $function))\n ((FuzzPropertyFunction Default $function)\n (ResolvedProperty Default $function))\n ($function\n (ResolvedProperty Default $function)))))\n\n(= (_fuzz-validate-property-signature $property)\n (let $type (get-type $property)\n (if (== $type (-> Atom FuzzProperty))\n ValidPropertySignature\n (FuzzInvalid\n MissingPropertySignature\n (Property $property)\n (Expected (-> Atom FuzzProperty))))))\n\n(= (_fuzz-count-one $item $counts)\n (if (== $counts ())\n (cons-atom (FuzzCount $item 1) ())\n (let* ((($entry $tail) (decons-atom $counts)))\n (switch $entry\n (((FuzzCount $seen $count)\n (if (== $item $seen)\n (cons-atom\n (FuzzCount $seen (+ $count 1))\n $tail)\n (cons-atom\n $entry\n (_fuzz-count-one $item $tail))))\n ($bad\n (cons-atom\n $entry\n (_fuzz-count-one $item $tail))))))))\n\n(= (_fuzz-count-all $items $counts)\n (if (== $items ())\n $counts\n (let* ((($item $tail) (decons-atom $items))\n ($next (_fuzz-count-one $item $counts)))\n (_fuzz-count-all $tail $next))))\n\n(= (_fuzz-coverage-one\n $minimum-percent\n $label\n $hit\n $counts)\n (if (== $counts ())\n (let $hits (if $hit 1 0)\n (cons-atom\n (CoverageCount $minimum-percent $label $hits 1)\n ()))\n (let* ((($entry $tail) (decons-atom $counts)))\n (switch $entry\n (((CoverageCount\n $seen-minimum\n $seen-label\n $hits\n $total)\n (if (== $label $seen-label)\n (let* (($next-minimum\n (max $minimum-percent $seen-minimum))\n ($next-hits\n (if $hit (+ $hits 1) $hits)))\n (cons-atom\n (CoverageCount\n $next-minimum\n $seen-label\n $next-hits\n (+ $total 1))\n $tail))\n (cons-atom\n $entry\n (_fuzz-coverage-one\n $minimum-percent\n $label\n $hit\n $tail))))\n ($bad\n (cons-atom\n $entry\n (_fuzz-coverage-one\n $minimum-percent\n $label\n $hit\n $tail))))))))\n\n(= (_fuzz-coverage-all $observations $counts)\n (if (== $observations ())\n $counts\n (let* ((($observation $tail)\n (decons-atom $observations)))\n (switch $observation\n (((CoverageObservation\n $minimum-percent\n $label\n $hit)\n (_fuzz-coverage-all\n $tail\n (_fuzz-coverage-one\n $minimum-percent\n $label\n $hit\n $counts)))\n ($bad\n (_fuzz-coverage-all $tail $counts)))))))\n\n(= (_fuzz-initial-run-state)\n (FuzzRunState\n 0 0 0 0 0 0 0 () () ()))\n\n(= (_fuzz-state-attempt $phase $state)\n (switch $state\n (((FuzzRunState\n $passed\n $property-discards\n $generation-discards\n $regressions\n $examples\n $edges\n $random\n $labels\n $collected\n $coverage)\n (FuzzRunState\n $passed\n $property-discards\n $generation-discards\n (if (== $phase Regression)\n (+ $regressions 1)\n $regressions)\n (if (== $phase Example)\n (+ $examples 1)\n $examples)\n (if (== $phase Edge)\n (+ $edges 1)\n $edges)\n (if (== $phase Random)\n (+ $random 1)\n $random)\n $labels\n $collected\n $coverage))\n ($bad $bad))))\n\n(= (_fuzz-state-pass $case $state)\n (switch $case\n (((FuzzCaseResult\n Pass\n $tag\n $details\n (Labels $new-labels)\n (Collected $new-collected)\n (Coverage $new-coverage)\n $annotations\n $results\n $steps)\n (switch $state\n (((FuzzRunState\n $passed\n $property-discards\n $generation-discards\n $regressions\n $examples\n $edges\n $random\n $labels\n $collected\n $coverage)\n (FuzzRunState\n (+ $passed 1)\n $property-discards\n $generation-discards\n $regressions\n $examples\n $edges\n $random\n (_fuzz-count-all $new-labels $labels)\n (_fuzz-count-all $new-collected $collected)\n (_fuzz-coverage-all $new-coverage $coverage)))\n ($bad-state $bad-state))))\n ($bad-case $state))))\n\n(= (_fuzz-state-property-discard $state)\n (switch $state\n (((FuzzRunState\n $passed\n $property-discards\n $generation-discards\n $regressions\n $examples\n $edges\n $random\n $labels\n $collected\n $coverage)\n (FuzzRunState\n $passed\n (+ $property-discards 1)\n $generation-discards\n $regressions\n $examples\n $edges\n $random\n $labels\n $collected\n $coverage))\n ($bad $bad))))\n\n(= (_fuzz-state-generation-discard $state)\n (switch $state\n (((FuzzRunState\n $passed\n $property-discards\n $generation-discards\n $regressions\n $examples\n $edges\n $random\n $labels\n $collected\n $coverage)\n (FuzzRunState\n $passed\n $property-discards\n (+ $generation-discards 1)\n $regressions\n $examples\n $edges\n $random\n $labels\n $collected\n $coverage))\n ($bad $bad))))\n\n(= (_fuzz-run-statistics $state)\n (switch $state\n (((FuzzRunState\n $passed\n $property-discards\n $generation-discards\n $regressions\n $examples\n $edges\n $random\n $labels\n $collected\n $coverage)\n (FuzzStatistics\n (Counts\n (Passed $passed)\n (PropertyDiscards $property-discards)\n (GenerationDiscards $generation-discards)\n (Regressions $regressions)\n (Examples $examples)\n (Edges $edges)\n (Random $random))\n (Labels $labels)\n (Collected $collected)\n (Coverage $coverage)))\n ($bad\n (FuzzStatistics\n (InvalidRunState $bad)\n (Labels ())\n (Collected ())\n (Coverage ()))))))\n\n(= (_fuzz-discard-limit-exceeded $config $state)\n (switch $state\n (((FuzzRunState\n $passed\n $property-discards\n $generation-discards\n $regressions\n $examples\n $edges\n $random\n $labels\n $collected\n $coverage)\n (let $limit (_fuzz-config-get MaxDiscards $config)\n (> (+ $property-discards $generation-discards) $limit)))\n ($bad True))))\n\n(= (_fuzz-first-insufficient-coverage $coverage)\n (if (== $coverage ())\n None\n (let* ((($entry $tail) (decons-atom $coverage)))\n (switch $entry\n (((CoverageCount\n $minimum-percent\n $label\n $hits\n $total)\n (if (< (* $hits 100) (* $minimum-percent $total))\n (Some $entry)\n (_fuzz-first-insufficient-coverage $tail)))\n ($bad\n (_fuzz-first-insufficient-coverage $tail)))))))\n\n(= (_fuzz-finish-run $property-id $config $state)\n (switch $state\n (((FuzzRunState\n $passed\n $property-discards\n $generation-discards\n $regressions\n $examples\n $edges\n $random\n $labels\n $collected\n $coverage)\n (let $insufficient\n (_fuzz-first-insufficient-coverage $coverage)\n (switch $insufficient\n (((Some\n (CoverageCount\n $minimum-percent\n $label\n $hits\n $total))\n (FuzzInsufficientCoverage\n (Property $property-id)\n (Requirement\n $label\n (MinimumPercent $minimum-percent)\n (Hits $hits)\n (Total $total))\n (_fuzz-run-statistics $state)))\n (None\n (FuzzPassed\n (Property $property-id)\n (Seed (_fuzz-config-get Seed $config))\n (_fuzz-run-statistics $state)))))))\n ($bad\n (FuzzInvalid InvalidRunState (State $bad))))))\n\n(= (_fuzz-failure-signature $tag)\n (_fuzz-atom-key AlphaReplay (PropertyFailure $tag)))\n\n(= (_fuzz-failed\n $property-id\n $generator\n $property\n $quantifier\n $phase\n $case-index\n $origin\n $size\n $value\n $decision\n $case\n $config\n $state)\n (_fuzz-finalize-failure\n $property-id\n $generator\n $property\n $quantifier\n $phase\n $case-index\n $origin\n $size\n $value\n $decision\n $case\n $config\n $state))\n\n(= (_fuzz-invalid-case\n $property-id\n $phase\n $case-index\n $case\n $state)\n (switch $case\n (((FuzzCaseResult\n Invalid\n $tag\n $details\n $labels\n $collected\n $coverage\n $annotations\n $results\n $steps)\n (FuzzInvalid\n $tag\n (Property $property-id)\n (Phase $phase)\n (CaseIndex $case-index)\n $details\n $results\n (_fuzz-run-statistics $state)))\n ($bad\n (FuzzInvalid\n InvalidCase\n (Property $property-id)\n (Case $bad))))))\n\n(= (_fuzz-cutoff\n $property-id\n $phase\n $case-index\n $case\n $state)\n (switch $case\n (((FuzzCaseResult\n Cutoff\n $tag\n $details\n $labels\n $collected\n $coverage\n $annotations\n $results\n $steps)\n (FuzzCutoff\n (Property $property-id)\n (Phase $phase)\n (CaseIndex $case-index)\n (CutoffTag $tag)\n $details\n $results\n (_fuzz-run-statistics $state)))\n ($bad\n (FuzzInvalid\n InvalidCutoffCase\n (Property $property-id)\n (Case $bad))))))\n\n(= (_fuzz-host-fault\n $property-id\n $phase\n $case-index\n $case\n $state)\n (switch $case\n (((FuzzCaseResult\n HostFault\n $tag\n $details\n $labels\n $collected\n $coverage\n $annotations\n $results\n $steps)\n (FuzzHostFault\n (Property $property-id)\n (Phase $phase)\n (CaseIndex $case-index)\n (FaultTag $tag)\n $details\n $results\n (_fuzz-run-statistics $state)))\n ($bad\n (FuzzInvalid\n InvalidHostFaultCase\n (Property $property-id)\n (Case $bad))))))\n\n(= (_fuzz-handle-case\n $property-id\n $generator\n $property\n $quantifier\n $phase\n $case-index\n $origin\n $size\n $value\n $decision\n $case\n $config\n $state\n $discard-policy)\n (switch $case\n (((FuzzCaseResult Pass $tag $details $labels $collected $coverage $annotations $results $steps)\n (FuzzContinue Pass (_fuzz-state-pass $case $state)))\n ((FuzzCaseResult Discard $tag $details $labels $collected $coverage $annotations $results $steps)\n (if (== $discard-policy Reject)\n (FuzzInvalid\n ConcreteCaseDiscarded\n (Property $property-id)\n (Phase $phase)\n (CaseIndex $case-index)\n $details)\n (let $next (_fuzz-state-property-discard $state)\n (if (_fuzz-discard-limit-exceeded $config $next)\n (FuzzGaveUp\n (Property $property-id)\n PropertyDiscards\n (_fuzz-run-statistics $next))\n (FuzzContinue Discard $next)))))\n ((FuzzCaseResult Fail $tag $details $labels $collected $coverage $annotations $results $steps)\n (_fuzz-failed\n $property-id\n $generator\n $property\n $quantifier\n $phase\n $case-index\n $origin\n $size\n $value\n $decision\n $case\n $config\n $state))\n ((FuzzCaseResult Invalid $tag $details $labels $collected $coverage $annotations $results $steps)\n (_fuzz-invalid-case\n $property-id $phase $case-index $case $state))\n ((FuzzCaseResult Cutoff $tag $details $labels $collected $coverage $annotations $results $steps)\n (_fuzz-cutoff\n $property-id $phase $case-index $case $state))\n ((FuzzCaseResult HostFault $tag $details $labels $collected $coverage $annotations $results $steps)\n (_fuzz-host-fault\n $property-id $phase $case-index $case $state))\n ($bad\n (FuzzInvalid\n MalformedCaseResult\n (Property $property-id)\n (Case $bad))))))\n\n(= (_fuzz-map-regressions $entries $index)\n (if (== $entries ())\n ()\n (let* ((($entry $tail) (decons-atom $entries))\n ($rest\n (_fuzz-map-regressions\n $tail\n (+ $index 1))))\n (switch $entry\n (((FuzzRegression $value $replay)\n (cons-atom\n (FuzzConcrete\n Regression\n $index\n $value\n $replay)\n $rest))\n ($bad\n (cons-atom\n (FuzzConcrete\n Regression\n $index\n (MalformedRegression $bad)\n None)\n $rest)))))))\n\n(= (_fuzz-map-examples $entries $index)\n (if (== $entries ())\n ()\n (let* ((($entry $tail) (decons-atom $entries))\n ($rest\n (_fuzz-map-examples\n $tail\n (+ $index 1))))\n (switch $entry\n (((FuzzExample $value)\n (cons-atom\n (FuzzConcrete Example $index $value None)\n $rest))\n ($bad\n (cons-atom\n (FuzzConcrete\n Example\n $index\n (MalformedExample $bad)\n None)\n $rest)))))))\n\n(= (_fuzz-run-concrete\n $remaining\n $property-id\n $generator\n $property\n $quantifier\n $config\n $state)\n (if (== $remaining ())\n (_fuzz-run-edges\n 0\n (_fuzz-config-get EdgeCases $config)\n ()\n $property-id\n $generator\n $property\n $quantifier\n $config\n $state)\n (let* ((($entry $tail) (decons-atom $remaining)))\n (switch $entry\n (((FuzzConcrete\n $phase\n $index\n $value\n $replay)\n (let* (($attempted\n (_fuzz-state-attempt $phase $state))\n ($case\n (_fuzz-evaluate-property\n $property\n $quantifier\n $value\n (_fuzz-config-get CaseSteps $config)\n (_fuzz-config-get CaseDepth $config)\n (_fuzz-config-get\n EffectPolicy\n $config)))\n ($handled\n (_fuzz-handle-case\n $property-id\n $generator\n $property\n $quantifier\n $phase\n $index\n (Concrete (Replay $replay))\n 0\n $value\n None\n $case\n $config\n $attempted\n Reject)))\n (switch $handled\n (((FuzzContinue Pass $next-state)\n (_fuzz-run-concrete\n $tail\n $property-id\n $generator\n $property\n $quantifier\n $config\n $next-state))\n ($result $result)))))\n ($bad\n (FuzzInvalid\n MalformedConcreteCase\n (Property $property-id)\n (Case $bad))))))))\n\n(= (_fuzz-generation-discard\n $property-id\n $config\n $state)\n (let $next (_fuzz-state-generation-discard $state)\n (if (_fuzz-discard-limit-exceeded $config $next)\n (FuzzGaveUp\n (Property $property-id)\n GenerationDiscards\n (_fuzz-run-statistics $next))\n (FuzzContinue GenerationDiscard $next))))\n\n(= (_fuzz-run-edge-with-valid-key\n $key\n $value\n $tree\n $raw-index\n $remaining\n $seen\n $property-id\n $generator\n $property\n $quantifier\n $config\n $state)\n (if (is-member $key $seen)\n (_fuzz-run-edges\n (+ $raw-index 1)\n (- $remaining 1)\n $seen\n $property-id\n $generator\n $property\n $quantifier\n $config\n $state)\n (let* (($attempted\n (_fuzz-state-attempt Edge $state))\n ($case\n (_fuzz-evaluate-property\n $property\n $quantifier\n $value\n (_fuzz-config-get CaseSteps $config)\n (_fuzz-config-get CaseDepth $config)\n (_fuzz-config-get\n EffectPolicy\n $config)))\n ($handled\n (_fuzz-handle-case\n $property-id\n $generator\n $property\n $quantifier\n Edge\n $raw-index\n (Edge (Index $raw-index))\n (_fuzz-config-get MaxSize $config)\n $value\n $tree\n $case\n $config\n $attempted\n Count)))\n (switch $handled\n (((FuzzContinue $status $next-state)\n (_fuzz-run-edges\n (+ $raw-index 1)\n (- $remaining 1)\n (append\n $seen\n (cons-atom $key ()))\n $property-id\n $generator\n $property\n $quantifier\n $config\n $next-state))\n ($result $result))))))\n\n(= (_fuzz-run-edge-with-key\n $key\n $value\n $tree\n $raw-index\n $remaining\n $seen\n $property-id\n $generator\n $property\n $quantifier\n $config\n $state)\n (switch $key\n (((FuzzKernelError $code $details)\n (FuzzInvalid\n NonReplayableEdgeDecision\n (Property $property-id)\n (Phase Edge)\n (ErrorCode $code)\n $details))\n ($valid\n (_fuzz-run-edge-with-valid-key\n $valid\n $value\n $tree\n $raw-index\n $remaining\n $seen\n $property-id\n $generator\n $property\n $quantifier\n $config\n $state)))))\n\n(= (_fuzz-run-edges\n $raw-index\n $remaining\n $seen\n $property-id\n $generator\n $property\n $quantifier\n $config\n $state)\n (if (<= $remaining 0)\n (_fuzz-run-random\n 0\n 0\n $property-id\n $generator\n $property\n $quantifier\n $config\n $state)\n (let $generated\n (fuzz-generate-edge\n $generator\n $raw-index\n (_fuzz-config-get MaxSize $config))\n (switch $generated\n (((FuzzSample $value $driver $tree)\n (let $key (_fuzz-atom-key Replay $tree)\n (_fuzz-run-edge-with-key\n $key\n $value\n $tree\n $raw-index\n $remaining\n $seen\n $property-id\n $generator\n $property\n $quantifier\n $config\n $state)))\n ((FuzzGenerationDiscard $reason $driver $tree)\n (let* (($attempted\n (_fuzz-state-attempt Edge $state))\n ($handled\n (_fuzz-generation-discard\n $property-id\n $config\n $attempted)))\n (switch $handled\n (((FuzzContinue\n GenerationDiscard\n $next-state)\n (_fuzz-run-edges\n (+ $raw-index 1)\n (- $remaining 1)\n $seen\n $property-id\n $generator\n $property\n $quantifier\n $config\n $next-state))\n ($result $result)))))\n ((FuzzGenerationError $code $details)\n (FuzzInvalid\n GenerationError\n (Property $property-id)\n (Phase Edge)\n (ErrorCode $code)\n $details))\n ($bad\n (FuzzInvalid\n MalformedGenerationResult\n (Property $property-id)\n (Phase Edge)\n (Value $bad))))))))\n\n(= (_fuzz-size-for-case $case-index $maximum-size)\n (% $case-index (+ $maximum-size 1)))\n\n(= (_fuzz-run-random\n $attempt-index\n $successful-random\n $property-id\n $generator\n $property\n $quantifier\n $config\n $state)\n (if (>= $successful-random (_fuzz-config-get Runs $config))\n (_fuzz-finish-run $property-id $config $state)\n (let* (($size\n (_fuzz-size-for-case\n $successful-random\n (_fuzz-config-get MaxSize $config)))\n ($seed\n (+ (_fuzz-config-get Seed $config)\n $attempt-index))\n ($generated\n (fuzz-generate-random\n $generator\n $seed\n $size)))\n (switch $generated\n (((FuzzSample $value $driver $tree)\n (let* (($attempted\n (_fuzz-state-attempt Random $state))\n ($case\n (_fuzz-evaluate-property\n $property\n $quantifier\n $value\n (_fuzz-config-get CaseSteps $config)\n (_fuzz-config-get CaseDepth $config)\n (_fuzz-config-get\n EffectPolicy\n $config)))\n ($handled\n (_fuzz-handle-case\n $property-id\n $generator\n $property\n $quantifier\n Random\n $attempt-index\n (Random\n (Rng xorshift128plus-v1)\n (Seed (_fuzz-config-get Seed $config))\n (Case $attempt-index)\n (Size $size))\n $size\n $value\n $tree\n $case\n $config\n $attempted\n Count)))\n (switch $handled\n (((FuzzContinue Pass $next-state)\n (_fuzz-run-random\n (+ $attempt-index 1)\n (+ $successful-random 1)\n $property-id\n $generator\n $property\n $quantifier\n $config\n $next-state))\n ((FuzzContinue Discard $next-state)\n (_fuzz-run-random\n (+ $attempt-index 1)\n $successful-random\n $property-id\n $generator\n $property\n $quantifier\n $config\n $next-state))\n ($result $result)))))\n ((FuzzGenerationDiscard $reason $driver $tree)\n (let* (($attempted\n (_fuzz-state-attempt Random $state))\n ($handled\n (_fuzz-generation-discard\n $property-id\n $config\n $attempted)))\n (switch $handled\n (((FuzzContinue\n GenerationDiscard\n $next-state)\n (_fuzz-run-random\n (+ $attempt-index 1)\n $successful-random\n $property-id\n $generator\n $property\n $quantifier\n $config\n $next-state))\n ($result $result)))))\n ((FuzzGenerationError $code $details)\n (FuzzInvalid\n GenerationError\n (Property $property-id)\n (Phase Random)\n (ErrorCode $code)\n $details))\n ($bad\n (FuzzInvalid\n MalformedGenerationResult\n (Property $property-id)\n (Phase Random)\n (Value $bad))))))))\n\n(= (_fuzz-start-run\n $property-id\n $generator\n $property\n $quantifier\n $config)\n (let* (($regressions\n (collapse\n (match &self\n (FuzzRegression\n $property-id\n $value\n $replay)\n (FuzzRegression $value $replay))))\n ($examples\n (collapse\n (match &self\n (FuzzExample $property-id $value)\n (FuzzExample $value))))\n ($concrete\n (append\n (_fuzz-map-regressions $regressions 0)\n (_fuzz-map-examples $examples 0))))\n (_fuzz-run-concrete\n $concrete\n $property-id\n $generator\n $property\n $quantifier\n $config\n (_fuzz-initial-run-state))))\n\n(= (fuzz-check $property-id $generator $property-function $config)\n (_fuzz-check-with\n $property-id\n $generator\n $property-function\n $config\n RandomPhases))\n\n; Exhaustive mode makes a stronger claim than fuzz-check: every decision tree the generator\n; accepts at size MaxSize passes the property. It walks the whole domain with the exhaustive\n; cursor and skips the regression, example, edge, and random phases; pinned concrete cases\n; belong to fuzz-check.\n(= (fuzz-check-exhaustive $property-id $generator $property-function $config)\n (_fuzz-check-with\n $property-id\n $generator\n $property-function\n $config\n ExhaustiveDomain))\n\n(= (_fuzz-check-with $property-id $generator $property-function $config $mode)\n (switch $generator\n (((FuzzGenerationError $code $details)\n (FuzzInvalid\n InvalidGenerator\n (Property $property-id)\n (ErrorCode $code)\n $details))\n ($valid-generator\n (let $validated-config (_fuzz-validate-config $config)\n (switch $validated-config\n (((FuzzInvalid $code $details) $validated-config)\n ((FuzzInvalid $code $first $second) $validated-config)\n ($valid-config\n (let $resolved\n (_fuzz-resolve-property-function\n $property-function)\n (switch $resolved\n (((ResolvedProperty\n $quantifier\n $property)\n (let $signature\n (_fuzz-validate-property-signature\n $property)\n (switch $signature\n ((ValidPropertySignature\n (if (== $mode ExhaustiveDomain)\n (_fuzz-start-exhaustive\n $property-id\n $valid-generator\n $property\n $quantifier\n $valid-config)\n (_fuzz-start-run\n $property-id\n $valid-generator\n $property\n $quantifier\n $valid-config)))\n ((FuzzInvalid $code $first $second)\n $signature)\n ((FuzzInvalid $code $details)\n $signature)\n ($bad-signature\n (FuzzInvalid\n InvalidPropertySignatureResult\n (Property $property)\n (Value $bad-signature)))))))\n ($bad\n (FuzzInvalid\n InvalidPropertyFunction\n (Property $property-id)\n (Value $bad))))))))))))))\n\n(= (_fuzz-start-exhaustive\n $property-id\n $generator\n $property\n $quantifier\n $config)\n (let $initial (_fuzz-initial-run-state)\n (_fuzz-exhaustive-check-loop\n (FuzzExhaustiveRun\n $property-id\n $generator\n $property\n $quantifier\n $config\n ()\n 0\n 0\n $initial))))\n\n(= (_fuzz-exhaustive-check-loop $state)\n (if (_fuzz-exhaustive-check-finished $state)\n $state\n (_fuzz-exhaustive-check-loop\n (_fuzz-exhaustive-check-step $state))))\n\n(= (_fuzz-exhaustive-check-finished $state)\n (unify $state\n (FuzzExhaustiveRun\n $property-id $generator $property $quantifier $config\n $plan $enumerated $accepted $run-state)\n False\n True))\n\n; One cursor run per step. Generation discards are legitimate domain holes, so MaxDiscards\n; does not apply to them here; MaxEnumerated caps every terminal attempt instead.\n(= (_fuzz-exhaustive-check-step $state)\n (unify $state\n (FuzzExhaustiveRun\n $property-id $generator $property $quantifier $config\n $plan $enumerated $accepted $run-state)\n (if (>= $enumerated (_fuzz-config-get MaxEnumerated $config))\n (FuzzGaveUp\n (Property $property-id)\n EnumerationLimit\n (_fuzz-exhaustive-statistics $enumerated $accepted $run-state))\n (let* (($size (_fuzz-config-get MaxSize $config))\n ($driver (_fuzz-exhaustive-resume-driver $plan))\n ($generated (fuzz-generate $generator $driver $size)))\n (switch $generated\n (((FuzzSample\n $value\n (FuzzDriver Exhaustive (ExhaustiveCursor $choices $cursor $frames))\n $tree)\n (_fuzz-exhaustive-check-case\n $property-id $generator $property $quantifier $config\n $frames $enumerated $accepted $run-state $value $tree $size))\n ((FuzzGenerationDiscard\n $reason\n (FuzzDriver Exhaustive (ExhaustiveCursor $choices $cursor $frames))\n $tree)\n (_fuzz-exhaustive-check-advance\n $property-id $generator $property $quantifier $config\n $frames\n (+ $enumerated 1)\n $accepted\n (_fuzz-state-generation-discard $run-state)))\n ((FuzzGenerationError $code $details)\n (FuzzInvalid\n GenerationError\n (Property $property-id)\n (Phase Exhaustive)\n (ErrorCode $code)\n $details))\n ($bad\n (FuzzInvalid\n MalformedGenerationResult\n (Property $property-id)\n (Phase Exhaustive)\n (Value $bad)))))))\n (FuzzInvalid MalformedExhaustiveRunState (Value $state))))\n\n; Every accepted tree is replayed before its property case counts: the tree must rebuild the\n; same value through the replay driver, which is what licenses the final verified claim.\n(= (_fuzz-exhaustive-check-case\n $property-id $generator $property $quantifier $config\n $frames $enumerated $accepted $run-state $value $tree $size)\n (let $replayed (fuzz-replay $generator $tree $size)\n (switch $replayed\n (((FuzzSample $replay-value $replay-driver $replay-tree)\n (if (_fuzz-replay-equal $value $replay-value)\n (let* (($coordinates\n (_fuzz-exhaustive-plan-prefix $frames ()))\n ($attempted\n (_fuzz-state-attempt Exhaustive $run-state))\n ($case\n (_fuzz-evaluate-property\n $property\n $quantifier\n $value\n (_fuzz-config-get CaseSteps $config)\n (_fuzz-config-get CaseDepth $config)\n (_fuzz-config-get EffectPolicy $config)))\n ($handled\n (_fuzz-handle-case\n $property-id\n $generator\n $property\n $quantifier\n Exhaustive\n $enumerated\n (Exhaustive\n (Choices $coordinates)\n (Case $enumerated)\n (Size $size))\n $size\n $value\n $tree\n $case\n $config\n $attempted\n Count)))\n (switch $handled\n (((FuzzContinue Pass $next-state)\n (_fuzz-exhaustive-check-advance\n $property-id $generator $property $quantifier $config\n $frames\n (+ $enumerated 1)\n (+ $accepted 1)\n $next-state))\n ((FuzzContinue Discard $next-state)\n (_fuzz-exhaustive-check-advance\n $property-id $generator $property $quantifier $config\n $frames\n (+ $enumerated 1)\n (+ $accepted 1)\n $next-state))\n ($result $result))))\n (FuzzInvalid\n ExhaustiveReplayMismatch\n (Property $property-id)\n (Value $value)\n (ReplayedValue $replay-value))))\n ((FuzzGenerationError $code $details)\n (FuzzInvalid\n ExhaustiveReplayFailure\n (Property $property-id)\n (ErrorCode $code)\n $details))\n ((FuzzGenerationDiscard $replay-reason $replay-driver $replay-tree)\n (FuzzInvalid\n ExhaustiveReplayDiscarded\n (Property $property-id)\n (Reason $replay-reason)))\n ($bad\n (FuzzInvalid\n MalformedReplayResult\n (Property $property-id)\n (Value $bad)))))))\n\n(= (_fuzz-exhaustive-check-advance\n $property-id $generator $property $quantifier $config\n $frames $enumerated $accepted $run-state)\n (let $advanced (_fuzz-exhaustive-next-plan $frames)\n (switch $advanced\n (((ExhaustivePlan $plan)\n (FuzzExhaustiveRun\n $property-id $generator $property $quantifier $config\n $plan $enumerated $accepted $run-state))\n (ExhaustiveComplete\n (_fuzz-finish-exhaustive\n $property-id $enumerated $accepted $run-state))\n ($bad\n (FuzzInvalid\n ExhaustiveAdvanceFailure\n (Property $property-id)\n (Value $bad)))))))\n\n; Verified demands the full walk: a non-empty accepted domain, no property discards (those\n; cases were never checked), and satisfied coverage requirements. Anything less is an\n; explicit invalid or gave-up result, never a pass.\n(= (_fuzz-finish-exhaustive $property-id $enumerated $accepted $run-state)\n (if (== $accepted 0)\n (let $statistics\n (_fuzz-exhaustive-statistics $enumerated $accepted $run-state)\n (FuzzInvalid\n EmptyExhaustiveDomain\n (Property $property-id)\n $statistics))\n (unify $run-state\n (FuzzRunState\n $passed\n $property-discards\n $generation-discards\n $regressions\n $examples\n $edges\n $random\n $labels\n $collected\n $coverage)\n (let $statistics\n (_fuzz-exhaustive-statistics $enumerated $accepted $run-state)\n (if (> $property-discards 0)\n (FuzzGaveUp\n (Property $property-id)\n ExhaustivePropertyDiscards\n $statistics)\n (let $insufficient\n (_fuzz-first-insufficient-coverage $coverage)\n (switch $insufficient\n (((Some\n (CoverageCount\n $minimum-percent\n $label\n $hits\n $total))\n (FuzzInsufficientCoverage\n (Property $property-id)\n (Requirement\n $label\n (MinimumPercent $minimum-percent)\n (Hits $hits)\n (Total $total))\n $statistics))\n (None\n (FuzzExhaustivelyVerified\n (Property $property-id)\n (DomainCount $accepted)\n (Enumerated $enumerated)\n $statistics)))))))\n (FuzzInvalid InvalidRunState (State $run-state)))))\n\n(= (_fuzz-exhaustive-statistics $enumerated $accepted $run-state)\n (let $statistics (_fuzz-run-statistics $run-state)\n (ExhaustiveStatistics\n (Enumerated $enumerated)\n (DomainCount $accepted)\n $statistics)))\n\n; SPDX-FileCopyrightText: 2026 MesTTo\n;\n; SPDX-License-Identifier: MIT\n\n; List edits used by collection and child shrink passes.\n(= (_fuzz-list-take-loop $values $remaining $reversed)\n (if (or (<= $remaining 0) (== $values ()))\n (reverse $reversed)\n (let* ((($value $tail) (decons-atom $values)))\n (_fuzz-list-take-loop\n $tail\n (- $remaining 1)\n (cons-atom $value $reversed)))))\n\n(= (_fuzz-list-take $values $count)\n (_fuzz-list-take-loop $values $count ()))\n\n(= (_fuzz-list-drop $values $count)\n (if (or (<= $count 0) (== $values ()))\n $values\n (let* ((($value $tail) (decons-atom $values)))\n (_fuzz-list-drop $tail (- $count 1)))))\n\n(= (_fuzz-list-remove-range $values $start $count)\n (append\n (_fuzz-list-take $values $start)\n (_fuzz-list-drop $values (+ $start $count))))\n\n(= (_fuzz-add-shrink-value $candidate $current $values)\n (if (or\n (== $candidate $current)\n (is-member $candidate $values))\n $values\n (append $values (cons-atom $candidate ()))))\n\n(= (_fuzz-halves $value)\n (if (<= $value 0)\n ()\n (let $next (trunc-math (/ $value 2))\n (cons-atom $value (_fuzz-halves $next)))))\n\n(= (_fuzz-int-midpoint-values\n $current\n $direction\n $halves\n $values)\n (if (== $halves ())\n $values\n (let* ((($half $tail) (decons-atom $halves))\n ($candidate\n (- $current (* $direction $half)))\n ($next\n (_fuzz-add-shrink-value\n $candidate\n $current\n $values)))\n (_fuzz-int-midpoint-values\n $current\n $direction\n $tail\n $next))))\n\n; A bound is a shrink candidate only when it sits strictly closer to the origin than the current\n; value. The far-side bound is an anti-shrink: on the machine length decision it re-inflated an\n; accepted (increment increment increment) counterexample back to six commands, because the lenient\n; shrink replay filled the missing draws from each decision's origin and the longer run still failed.\n(= (_fuzz-int-bound-candidate $bound $current $distance $origin $values)\n (if (< (abs-math (- $bound $origin)) $distance)\n (_fuzz-add-shrink-value $bound $current $values)\n $values))\n\n(= (_fuzz-int-value-candidates $current $lower $upper $origin)\n (if (== $current $origin)\n ()\n (let* (($distance (abs-math (- $current $origin)))\n ($direction (if (> $current $origin) 1 -1))\n ($first-half (trunc-math (/ $distance 2)))\n ($with-origin\n (_fuzz-add-shrink-value\n $origin\n $current\n ()))\n ($with-midpoints\n (_fuzz-int-midpoint-values\n $current\n $direction\n (_fuzz-halves $first-half)\n $with-origin))\n ($with-lower\n (_fuzz-int-bound-candidate\n $lower\n $current\n $distance\n $origin\n $with-midpoints)))\n (_fuzz-int-bound-candidate\n $upper\n $current\n $distance\n $origin\n $with-lower))))\n\n(= (_fuzz-int-decision-candidates-loop\n $values\n $lower\n $upper\n $origin\n $reversed)\n (if (== $values ())\n (reverse $reversed)\n (let* ((($value $tail) (decons-atom $values)))\n (_fuzz-int-decision-candidates-loop\n $tail\n $lower\n $upper\n $origin\n (cons-atom\n (_fuzz-int-decision\n $lower\n $upper\n $origin\n $value)\n $reversed)))))\n\n(= (_fuzz-int-decision-candidates $decision)\n (switch $decision\n (((Decision\n Int\n (Bounds $lower $upper)\n (Origin $origin)\n (Value $current)\n ())\n (_fuzz-int-decision-candidates-loop\n (_fuzz-int-value-candidates\n $current\n $lower\n $upper\n $origin)\n $lower\n $upper\n $origin\n ()))\n ($bad ()))))\n\n(= (_fuzz-wrap-first-child-candidates\n $kind\n $metadata\n $selection\n $candidates\n $tail\n $reversed)\n (if (== $candidates ())\n (reverse $reversed)\n (let* ((($candidate $rest) (decons-atom $candidates))\n ($children (cons-atom $candidate $tail)))\n (_fuzz-wrap-first-child-candidates\n $kind\n $metadata\n $selection\n $rest\n $tail\n (cons-atom\n (Decision\n $kind\n $metadata\n $selection\n $children)\n $reversed)))))\n\n(= (_fuzz-choice-root-candidates $decision)\n (switch $decision\n (((Decision $kind $metadata $selection $children)\n (if (or\n (== $kind Bool)\n (or\n (== $kind Element)\n (or\n (== $kind Frequency)\n (== $kind Option))))\n (if (== $children ())\n ()\n (let* ((($choice $tail) (decons-atom $children)))\n (_fuzz-wrap-first-child-candidates\n $kind\n $metadata\n $selection\n (_fuzz-int-decision-candidates $choice)\n $tail\n ())))\n ()))\n ($bad ()))))\n\n; Lists remove the largest legal chunks first, then smaller chunks.\n(= (_fuzz-list-removal-candidates-at\n $minimum\n $maximum\n $length\n $length-lower\n $length-upper\n $length-origin\n $items\n $chunk\n $start\n $reversed)\n (if (>= $start $length)\n (reverse $reversed)\n (let* (($available (- $length $start))\n ($removed (min $chunk $available))\n ($new-length (- $length $removed))\n ($remaining\n (_fuzz-list-remove-range\n $items\n $start\n $removed))\n ($next-start (+ $start $chunk)))\n (if (< $new-length $minimum)\n (_fuzz-list-removal-candidates-at\n $minimum\n $maximum\n $length\n $length-lower\n $length-upper\n $length-origin\n $items\n $chunk\n $next-start\n $reversed)\n (let* (($length-decision\n (_fuzz-int-decision\n $length-lower\n $length-upper\n $length-origin\n $new-length))\n ($children\n (cons-atom\n $length-decision\n $remaining))\n ($candidate\n (Decision\n List\n (Bounds $minimum $maximum)\n (Length $new-length)\n $children)))\n (_fuzz-list-removal-candidates-at\n $minimum\n $maximum\n $length\n $length-lower\n $length-upper\n $length-origin\n $items\n $chunk\n $next-start\n (cons-atom $candidate $reversed)))))))\n\n(= (_fuzz-list-removal-candidates-sizes\n $minimum\n $maximum\n $length\n $length-lower\n $length-upper\n $length-origin\n $items\n $sizes\n $candidates)\n (if (== $sizes ())\n $candidates\n (let* ((($chunk $tail) (decons-atom $sizes))\n ($for-size\n (_fuzz-list-removal-candidates-at\n $minimum\n $maximum\n $length\n $length-lower\n $length-upper\n $length-origin\n $items\n $chunk\n 0\n ())))\n (_fuzz-list-removal-candidates-sizes\n $minimum\n $maximum\n $length\n $length-lower\n $length-upper\n $length-origin\n $items\n $tail\n (append $candidates $for-size)))))\n\n(= (_fuzz-list-root-candidates $decision)\n (switch $decision\n (((Decision\n List\n (Bounds $minimum $maximum)\n (Length $length)\n $children)\n (if (== $children ())\n ()\n (let* ((($length-decision $items)\n (decons-atom $children)))\n (switch $length-decision\n (((Decision\n Int\n (Bounds $length-lower $length-upper)\n (Origin $length-origin)\n (Value $seen-length)\n ())\n (if (and\n (== $length $seen-length)\n (> $length $minimum))\n (_fuzz-list-removal-candidates-sizes\n $minimum\n $maximum\n $length\n $length-lower\n $length-upper\n $length-origin\n $items\n (_fuzz-halves (- $length $minimum))\n ())\n ()))\n ($bad ()))))))\n ($bad ()))))\n\n(= (_fuzz-generic-removal-candidates-at\n $kind\n $metadata\n $selection\n $children\n $length\n $chunk\n $start\n $reversed)\n (if (>= $start $length)\n (reverse $reversed)\n (let* (($available (- $length $start))\n ($removed (min $chunk $available))\n ($remaining\n (_fuzz-list-remove-range\n $children\n $start\n $removed))\n ($candidate\n (Decision\n $kind\n $metadata\n $selection\n $remaining)))\n (_fuzz-generic-removal-candidates-at\n $kind\n $metadata\n $selection\n $children\n $length\n $chunk\n (+ $start $chunk)\n (cons-atom $candidate $reversed)))))\n\n(= (_fuzz-generic-removal-candidates-sizes\n $kind\n $metadata\n $selection\n $children\n $length\n $sizes\n $candidates)\n (if (== $sizes ())\n $candidates\n (let* ((($chunk $tail) (decons-atom $sizes))\n ($for-size\n (_fuzz-generic-removal-candidates-at\n $kind\n $metadata\n $selection\n $children\n $length\n $chunk\n 0\n ())))\n (_fuzz-generic-removal-candidates-sizes\n $kind\n $metadata\n $selection\n $children\n $length\n $tail\n (append $candidates $for-size)))))\n\n(= (_fuzz-collection-root-candidates $decision)\n (let $lists (_fuzz-list-root-candidates $decision)\n (if (== $lists ())\n (switch $decision\n (((Decision\n Filter\n $metadata\n $selection\n $children)\n (let $count (length $children)\n (if (> $count 0)\n (_fuzz-generic-removal-candidates-sizes\n Filter\n $metadata\n $selection\n $children\n $count\n (_fuzz-halves $count)\n ())\n ())))\n ((Decision\n Recursive\n $metadata\n $selection\n $children)\n (if (> (length $children) 0)\n (cons-atom\n (Decision\n Recursive\n $metadata\n $selection\n ())\n ())\n ()))\n ($bad ())))\n $lists)))\n\n(= (_fuzz-numeric-root-candidates $decision)\n (_fuzz-int-decision-candidates $decision))\n\n(= (_fuzz-wrap-child-candidates\n $kind\n $metadata\n $selection\n $prefix\n $tail\n $candidates\n $reversed)\n (if (== $candidates ())\n (reverse $reversed)\n (let* ((($candidate $rest)\n (decons-atom $candidates))\n ($children\n (append\n $prefix\n (cons-atom $candidate $tail))))\n (_fuzz-wrap-child-candidates\n $kind\n $metadata\n $selection\n $prefix\n $tail\n $rest\n (cons-atom\n (Decision\n $kind\n $metadata\n $selection\n $children)\n $reversed)))))\n\n(= (_fuzz-child-shrink-candidates-loop\n $kind\n $metadata\n $selection\n $remaining\n $prefix\n $candidates)\n (if (== $remaining ())\n $candidates\n (let ($child $tail) (decons-atom $remaining)\n (let $root-candidates\n (_fuzz-built-in-root-candidates $child)\n (let $nested-candidates\n (switch $child\n (((Decision\n $child-kind\n $child-metadata\n $child-selection\n $child-children)\n (_fuzz-child-shrink-candidates-loop\n $child-kind\n $child-metadata\n $child-selection\n $child-children\n ()\n ()))\n ($bad ())))\n (let $custom-candidates\n (_fuzz-custom-root-candidates $child)\n (let $child-candidates\n (_fuzz-deduplicate-trees\n (append\n $root-candidates\n (append\n $custom-candidates\n $nested-candidates)))\n (let $wrapped\n (_fuzz-wrap-child-candidates\n $kind\n $metadata\n $selection\n $prefix\n $tail\n $child-candidates\n ())\n (_fuzz-child-shrink-candidates-loop\n $kind\n $metadata\n $selection\n $tail\n (append\n $prefix\n (cons-atom $child ()))\n (append $candidates $wrapped))))))))))\n\n(= (_fuzz-child-shrink-candidates $decision)\n (switch $decision\n (((Decision $kind $metadata $selection $children)\n (_fuzz-child-shrink-candidates-loop\n $kind\n $metadata\n $selection\n $children\n ()\n ()))\n ($bad ()))))\n\n(= (_fuzz-valid-custom-shrink-candidates\n $results\n $name\n $arguments\n $candidates)\n (if (== $results ())\n $candidates\n (let* ((($result $tail) (decons-atom $results))\n ($next\n (switch $result\n (((Decision\n Custom\n (CustomGenerator\n (Name $name)\n (Arguments $arguments))\n $selection\n $children)\n (append\n $candidates\n (cons-atom $result ())))\n ($bad $candidates)))))\n (_fuzz-valid-custom-shrink-candidates\n $tail\n $name\n $arguments\n $next))))\n\n(= (_fuzz-custom-root-candidates $decision)\n (switch $decision\n (((Decision\n Custom\n (CustomGenerator\n (Name $name)\n (Arguments $arguments))\n $selection\n $children)\n (let $results\n (collapse\n (ShrinkChoices\n $name\n $arguments\n $decision))\n (_fuzz-valid-custom-shrink-candidates\n $results\n $name\n $arguments\n ())))\n ($bad ()))))\n\n(= (_fuzz-deduplicate-trees $trees)\n (_fuzz-deduplicate-replay $trees))\n\n(= (_fuzz-built-in-root-candidates $decision)\n (let $collections\n (_fuzz-collection-root-candidates $decision)\n (let $choices\n (_fuzz-choice-root-candidates $decision)\n (let $numeric\n (_fuzz-numeric-root-candidates $decision)\n (append\n $collections\n (append $choices $numeric))))))\n\n; The output order is the public shrink relation.\n(= (_fuzz-shrink-candidates $decision)\n (switch $decision\n (((Decision\n Int\n (Bounds $lower $upper)\n (Origin $origin)\n (Value $value)\n ())\n (_fuzz-deduplicate-trees\n (_fuzz-int-decision-candidates $decision)))\n ((Decision $kind $metadata $selection $children)\n (let $root-candidates\n (_fuzz-built-in-root-candidates $decision)\n (let $custom-candidates\n (_fuzz-custom-root-candidates $decision)\n (let $child-candidates\n (_fuzz-child-shrink-candidates $decision)\n ; Custom root candidates come before child descent: a custom hook's structural\n ; reductions (removing machine commands, dropping branches) shrink faster than\n ; simplifying values inside a structure that is about to disappear.\n (_fuzz-deduplicate-trees\n (append\n $root-candidates\n (append\n $custom-candidates\n $child-candidates)))))))\n ($bad ()))))\n\n; SPDX-FileCopyrightText: 2026 MesTTo\n;\n; SPDX-License-Identifier: MIT\n\n; A grammar is an ordinary atom in &self:\n; (FuzzGrammar name (Productions ((Production weight target template) ...)))\n\n; `switch` evaluates its subject. Grammar templates are source atoms, so use `unify` to inspect them\n; without firing user rules whose heads happen to occur in generated syntax.\n(= (_fuzz-grammar-template-switch\n $atom\n $cases)\n (if-decons-expr\n $cases\n $case\n $tail\n (unify\n $case\n ($pattern $template)\n (unify\n $atom\n $pattern\n $template\n (_fuzz-grammar-template-switch\n $atom\n $tail))\n (_fuzz-generation-error\n MalformedGrammarTemplateCase\n (Case $case)))\n Empty))\n\n(= (_fuzz-grammar-generator-validation-tasks\n $remaining\n $tasks)\n (if (== $remaining ())\n $tasks\n (let* ((($generator $tail)\n (decons-atom $remaining))\n ($next\n (cons-atom\n (GrammarGeneratorValidationTask\n $generator)\n $tasks)))\n (_fuzz-grammar-generator-validation-tasks\n $tail\n $next))))\n\n(= (_fuzz-grammar-generator-child-task\n $child\n $tasks)\n (cons-atom\n (GrammarGeneratorValidationTask $child)\n $tasks))\n\n(= (_fuzz-grammar-frequency-validation\n $remaining\n $tasks\n $total)\n (if (== $remaining ())\n (ValidatedGrammarFrequency\n $tasks\n $total)\n (let* ((($entry $tail)\n (decons-atom $remaining)))\n (_fuzz-grammar-template-switch $entry\n ((($weight $generator)\n (if (_fuzz-is-integer $weight)\n (if (> $weight 0)\n (_fuzz-grammar-frequency-validation\n $tail\n (_fuzz-grammar-generator-child-task\n $generator\n $tasks)\n (+ $total $weight))\n (_fuzz-generation-error\n InvalidFrequencyWeight\n (Weight $weight)\n (Generator $generator)))\n (_fuzz-expected-integer\n FrequencyWeight\n $weight)))\n ($bad\n (_fuzz-generation-error\n MalformedFrequencyEntry\n (Entry $bad))))))))\n\n(= (_fuzz-grammar-validate-int-generator\n $lower\n $upper\n $origin\n $tasks)\n (let $validated\n (gen-int-origin\n $lower\n $upper\n $origin)\n (switch $validated\n (((GenInt\n $seen-lower\n $seen-upper\n $seen-origin)\n (_fuzz-validate-grammar-field-generator-loop\n $tasks))\n ((FuzzGenerationError $code $details)\n $validated)\n ($bad\n (_fuzz-generation-error\n MalformedGrammarFieldGenerator\n (Generator\n (GenInt\n $lower\n $upper\n $origin))))))))\n\n(= (_fuzz-grammar-validate-float-generator\n $lower\n $upper\n $origin\n $tasks)\n (if (_fuzz-is-integer $lower)\n (if (_fuzz-is-integer $upper)\n (if (_fuzz-is-integer $origin)\n (if (and\n (<= -9218868437227405312 $lower)\n (and\n (<= $lower $origin)\n (and\n (<= $origin $upper)\n (<= $upper\n 9218868437227405311))))\n (_fuzz-validate-grammar-field-generator-loop\n $tasks)\n (_fuzz-generation-error\n InvalidFloatBounds\n (IndexBounds\n $lower\n $upper\n $origin)))\n (_fuzz-expected-integer\n FloatOriginIndex\n $origin))\n (_fuzz-expected-integer\n FloatUpperIndex\n $upper))\n (_fuzz-expected-integer\n FloatLowerIndex\n $lower)))\n\n(= (_fuzz-grammar-validate-list-generator\n $child\n $minimum\n $maximum\n $tasks)\n (let $validated\n (gen-list\n $child\n $minimum\n $maximum)\n (switch $validated\n (((GenList\n $seen-child\n $seen-minimum\n $seen-maximum)\n (_fuzz-validate-grammar-field-generator-loop\n (_fuzz-grammar-generator-child-task\n $child\n $tasks)))\n ((FuzzGenerationError $code $details)\n $validated)\n ($bad\n (_fuzz-generation-error\n MalformedGrammarFieldGenerator\n (Generator\n (GenList\n $child\n $minimum\n $maximum))))))))\n\n(= (_fuzz-grammar-validate-filter-generator\n $child\n $predicate\n $maximum-attempts\n $tasks)\n (let $validated\n (gen-filter\n $child\n $predicate\n $maximum-attempts)\n (switch $validated\n (((GenFilter\n $seen-child\n $seen-predicate\n $seen-maximum-attempts)\n (if (_fuzz-atom-ground $predicate)\n (_fuzz-validate-grammar-field-generator-loop\n (_fuzz-grammar-generator-child-task\n $child\n $tasks))\n (_fuzz-generation-error\n NonGroundGrammarFieldGenerator\n (Generator\n (GenFilter\n $child\n $predicate\n $maximum-attempts)))))\n ((FuzzGenerationError $code $details)\n $validated)\n ($bad\n (_fuzz-generation-error\n MalformedGrammarFieldGenerator\n (Generator\n (GenFilter\n $child\n $predicate\n $maximum-attempts))))))))\n\n(= (_fuzz-grammar-validate-resize-generator\n $size\n $child\n $tasks)\n (let $validated\n (gen-resize $size $child)\n (switch $validated\n (((GenResize $seen-size $seen-child)\n (_fuzz-validate-grammar-field-generator-loop\n (_fuzz-grammar-generator-child-task\n $child\n $tasks)))\n ((FuzzGenerationError $code $details)\n $validated)\n ($bad\n (_fuzz-generation-error\n MalformedGrammarFieldGenerator\n (Generator\n (GenResize $size $child))))))))\n\n(= (_fuzz-validate-grammar-field-generator-loop\n $tasks)\n (if (== $tasks ())\n (ValidGrammarFieldGenerator)\n (let* ((($task $tail)\n (decons-atom $tasks)))\n (switch $task\n (((GrammarGeneratorValidationTask\n $generator)\n (switch $generator\n (((FuzzGenerationError\n $code\n $details)\n $generator)\n ((GenConst $value)\n (if (_fuzz-atom-ground $value)\n (_fuzz-validate-grammar-field-generator-loop\n $tail)\n (_fuzz-generation-error\n NonGroundGrammarFieldGenerator\n (Generator $generator))))\n ((GenBool)\n (_fuzz-validate-grammar-field-generator-loop\n $tail))\n ((GenInt $lower $upper $origin)\n (_fuzz-grammar-validate-int-generator\n $lower\n $upper\n $origin\n $tail))\n ((GenFloatRange\n $lower-index\n $upper-index\n $origin-index)\n (_fuzz-grammar-validate-float-generator\n $lower-index\n $upper-index\n $origin-index\n $tail))\n ((GenFloatBits)\n (_fuzz-validate-grammar-field-generator-loop\n $tail))\n ((GenElement $values)\n (if (and\n (== (get-metatype $values)\n Expression)\n (> (length $values) 0))\n (if (_fuzz-atom-ground $values)\n (_fuzz-validate-grammar-field-generator-loop\n $tail)\n (_fuzz-generation-error\n NonGroundGrammarFieldGenerator\n (Generator $generator)))\n (_fuzz-generation-error\n EmptyElementSet\n (Values $values))))\n ((GenFrequency $entries $total)\n (let $validated\n (_fuzz-grammar-frequency-validation\n $entries\n $tail\n 0)\n (switch $validated\n (((ValidatedGrammarFrequency\n $next-tasks\n $calculated-total)\n (if (== $total $calculated-total)\n (_fuzz-validate-grammar-field-generator-loop\n $next-tasks)\n (_fuzz-generation-error\n InvalidFrequencyTotal\n (Expected $calculated-total)\n (Actual $total))))\n ((FuzzGenerationError $code $details)\n $validated)\n ($bad\n (_fuzz-generation-error\n MalformedGrammarFieldGenerator\n (Generator $generator)))))))\n ((GenTuple $generators)\n (if (== (get-metatype $generators)\n Expression)\n (_fuzz-validate-grammar-field-generator-loop\n (_fuzz-grammar-generator-validation-tasks\n $generators\n $tail))\n (_fuzz-generation-error\n MalformedGrammarFieldGenerator\n (Generator $generator))))\n ((GenList $child $minimum $maximum)\n (_fuzz-grammar-validate-list-generator\n $child\n $minimum\n $maximum\n $tail))\n ((GenOption $child)\n (_fuzz-validate-grammar-field-generator-loop\n (_fuzz-grammar-generator-child-task\n $child\n $tail)))\n ((GenMap $function $child)\n (if (_fuzz-atom-ground $function)\n (_fuzz-validate-grammar-field-generator-loop\n (_fuzz-grammar-generator-child-task\n $child\n $tail))\n (_fuzz-generation-error\n NonGroundGrammarFieldGenerator\n (Generator $generator))))\n ((GenBind $child $function)\n (if (_fuzz-atom-ground $function)\n (_fuzz-validate-grammar-field-generator-loop\n (_fuzz-grammar-generator-child-task\n $child\n $tail))\n (_fuzz-generation-error\n NonGroundGrammarFieldGenerator\n (Generator $generator))))\n ((GenFilter\n $child\n $predicate\n $maximum-attempts)\n (_fuzz-grammar-validate-filter-generator\n $child\n $predicate\n $maximum-attempts\n $tail))\n ((GenSized $function)\n (if (_fuzz-atom-ground $function)\n (_fuzz-validate-grammar-field-generator-loop\n $tail)\n (_fuzz-generation-error\n NonGroundGrammarFieldGenerator\n (Generator $generator))))\n ((GenResize $size $child)\n (_fuzz-grammar-validate-resize-generator\n $size\n $child\n $tail))\n ((GenRecursive $base $step)\n (if (_fuzz-atom-ground $step)\n (_fuzz-validate-grammar-field-generator-loop\n (_fuzz-grammar-generator-child-task\n $base\n $tail))\n (_fuzz-generation-error\n NonGroundGrammarFieldGenerator\n (Generator $generator))))\n ((GenCustom $name $arguments)\n (if (and\n (_fuzz-atom-ground $name)\n (_fuzz-atom-ground $arguments))\n (_fuzz-validate-grammar-field-generator-loop\n $tail)\n (_fuzz-generation-error\n NonGroundGrammarFieldGenerator\n (Generator $generator))))\n ($bad-generator\n (_fuzz-generation-error\n MalformedGrammarFieldGenerator\n (Generator $bad-generator))))))\n ($bad-task\n (_fuzz-generation-error\n MalformedGrammarGeneratorValidationTask\n (Value $bad-task))))))))\n\n(= (_fuzz-validate-grammar-field-generator\n $generator)\n (_fuzz-validate-grammar-field-generator-loop\n ((GrammarGeneratorValidationTask\n $generator))))\n\n(= (_fuzz-grammar-field-from-results\n $quoted-expression\n $results)\n (switch $results\n ((()\n (_fuzz-generation-error\n MissingGrammarFieldGenerator\n (Expression $quoted-expression)))\n (($generator)\n (let $validated\n (_fuzz-validate-grammar-field-generator\n $generator)\n (switch $validated\n (((ValidGrammarFieldGenerator)\n (ResolvedGrammarField $generator))\n ((FuzzGenerationError $code $details)\n $validated)\n ($bad\n (_fuzz-generation-error\n MalformedGrammarFieldValidation\n (Value $bad)))))))\n ($many\n (_fuzz-generation-error\n AmbiguousGrammarFieldGenerator\n (Expression $quoted-expression)\n (Results $many))))))\n\n(= (_fuzz-resolve-grammar-field\n $expression)\n (_fuzz-grammar-field-from-results\n (quote $expression)\n (collapse $expression)))\n\n(= (_fuzz-resolve-grammar-fields-loop\n $remaining\n $resolved)\n (if (== $remaining ())\n (ResolvedGrammarFields $resolved)\n (let* ((($quoted-expression $tail)\n (decons-atom $remaining)))\n (_fuzz-grammar-template-switch $quoted-expression\n (((quote $expression)\n (let $field\n (_fuzz-resolve-grammar-field\n $expression)\n (switch $field\n (((ResolvedGrammarField $generator)\n (let $next\n (_fuzz-expression-append\n $resolved\n $generator)\n (_fuzz-resolve-grammar-fields-loop\n $tail\n $next)))\n ((FuzzGenerationError $code $details)\n $field)\n ($bad\n (_fuzz-generation-error\n MalformedResolvedGrammarField\n (Value $bad)))))))\n ($bad\n (_fuzz-generation-error\n MalformedGrammarFieldExpression\n (Value $bad))))))))\n\n(= (_fuzz-normalize-grammar-template-fields\n $template)\n (let $fields\n (_fuzz-grammar-field-expressions\n $template)\n (switch $fields\n (((GrammarFieldExpressions $expressions)\n (let $resolved\n (_fuzz-resolve-grammar-fields-loop\n $expressions\n ())\n (switch $resolved\n (((ResolvedGrammarFields $generators)\n (let $normalized-template\n (_fuzz-grammar-replace-fields\n $template\n $generators)\n (NormalizedGrammarTemplate\n (quote $normalized-template))))\n ((FuzzGenerationError $code $details)\n $resolved)\n ($bad\n (_fuzz-generation-error\n MalformedResolvedGrammarFields\n (Value $bad)))))))\n ((FuzzKernelError $code $details)\n (_fuzz-generation-error\n KernelError\n (OperationResult $fields)))\n ($bad\n (_fuzz-generation-error\n MalformedGrammarFieldExpressions\n (Value $bad)))))))\n\n(= (_fuzz-prepare-grammar-template\n $grammar\n $template)\n (let $profile\n (_fuzz-grammar-template-profile\n $template)\n (switch $profile\n (((GrammarTemplateProfile\n (Ground True)\n (References $references)\n (MinimumNextId $minimum-next-id)\n (Nodes $nodes)\n (Depth $depth))\n (let $normalized\n (_fuzz-normalize-grammar-template-fields\n $template)\n (switch $normalized\n (((NormalizedGrammarTemplate\n (quote $normalized-template))\n (let $validated\n (_fuzz-validate-grammar-template\n $grammar\n $normalized-template)\n (switch $validated\n (((ValidGrammarTemplate)\n (let $indexed-template\n (_fuzz-grammar-index-references\n $normalized-template)\n (PreparedGrammarTemplate\n (quote $indexed-template)\n $references\n $minimum-next-id\n $nodes\n $depth)))\n ((FuzzGenerationError $code $details)\n $validated)\n ($bad\n (_fuzz-generation-error\n MalformedGrammarTemplateValidation\n (Grammar $grammar)\n (Value $bad)))))))\n ((FuzzGenerationError $code $details)\n $normalized)\n ($bad\n (_fuzz-generation-error\n MalformedGrammarTemplateNormalization\n (Grammar $grammar)\n (Value $bad)))))))\n ((GrammarTemplateProfile\n (Ground False)\n (References $references)\n (MinimumNextId $minimum-next-id)\n (Nodes $nodes)\n (Depth $depth))\n (_fuzz-generation-error\n NonGroundGrammarTemplate\n (Grammar $grammar)\n (Template $template)))\n ((FuzzKernelError $code $details)\n (_fuzz-generation-error\n KernelError\n (OperationResult $profile)))\n ($bad\n (_fuzz-generation-error\n MalformedGrammarTemplateProfile\n (Grammar $grammar)\n (Value $bad)))))))\n\n(= (_fuzz-validate-grammar-binding-step\n $state\n $binding)\n (switch $state\n (((FuzzGenerationError $code $details)\n $state)\n ((GrammarBindingValidationState\n $seen\n $normalized\n $next-id)\n (_fuzz-grammar-template-switch $binding\n (((Binding $sort $id)\n (if (_fuzz-is-integer $id)\n (if (>= $id 0)\n (let $present\n (_fuzz-exact-member\n $id\n $seen)\n (switch $present\n ((True\n (_fuzz-generation-error\n DuplicateGrammarBindingId\n (BindingId $id)))\n (False\n (let $next-seen\n (_fuzz-expression-append\n $seen\n $id)\n (let $next-normalized\n (_fuzz-expression-append\n $normalized\n (GrammarBinding\n (quote $sort)\n $id))\n (GrammarBindingValidationState\n $next-seen\n $next-normalized\n (max $next-id (+ $id 1))))))\n ((FuzzKernelError $code $details)\n (_fuzz-generation-error\n KernelError\n (OperationResult $present)))\n ($bad\n (_fuzz-generation-error\n MalformedGrammarBindingMembership\n (Value $bad))))))\n (_fuzz-generation-error\n InvalidGrammarBindingId\n (BindingId $id)))\n (_fuzz-expected-integer\n GrammarBindingId\n $id)))\n ($bad\n (_fuzz-generation-error\n MalformedGrammarBinding\n (Binding $bad))))))\n ($bad\n (_fuzz-generation-error\n MalformedGrammarBindingValidationState\n (Value $bad))))))\n\n(= (_fuzz-validate-grammar-bindings $bindings)\n (let $view\n (_fuzz-expression-view $bindings)\n (switch $view\n (((FuzzExpressionView\n $arity\n $forward\n $reversed)\n (let $folded\n (foldl-atom\n $bindings\n (GrammarBindingValidationState\n ()\n ()\n 0)\n $state\n $binding\n (_fuzz-validate-grammar-binding-step\n $state\n $binding))\n (switch $folded\n (((GrammarBindingValidationState\n $seen\n $normalized\n $next-id)\n (ValidGrammarBindings\n $normalized\n $next-id))\n ((FuzzGenerationError $code $details)\n $folded)\n ($bad\n (_fuzz-generation-error\n MalformedGrammarBindingValidationState\n (Value $bad)))))))\n ((FuzzAtomLeaf)\n (_fuzz-generation-error\n MalformedGrammarBindings\n (Bindings $bindings)))\n ((FuzzKernelError $code $details)\n (_fuzz-generation-error\n KernelError\n (OperationResult $view)))\n ($bad\n (_fuzz-generation-error\n MalformedGrammarBindingView\n (Value $bad)))))))\n\n(= (_fuzz-grammar-validation-enter-scope\n $grammar\n $bindings\n $scopes\n $used)\n (if-decons-expr\n $scopes\n $scope\n $parents\n (let $validated\n (_fuzz-validate-grammar-bindings\n $bindings)\n (switch $validated\n (((ValidGrammarBindings\n $normalized\n $next-id)\n (if (_fuzz-grammar-scopes-disjoint\n $normalized\n $used)\n (let $bound-scope\n (_fuzz-expression-concat\n $normalized\n $scope)\n (let $next-scopes\n (cons-atom\n $bound-scope\n $scopes)\n (let $next-used\n (_fuzz-expression-concat\n $normalized\n $used)\n (GrammarValidationState\n $next-scopes\n $next-used))))\n (_fuzz-generation-error\n DuplicateGrammarBindingId\n (Bindings $bindings))))\n ((FuzzGenerationError $code $details)\n $validated)\n ($bad\n (_fuzz-generation-error\n MalformedGrammarBindingValidation\n (Grammar $grammar)\n (Value $bad))))))\n (_fuzz-generation-error\n MalformedGrammarValidationScopes\n (Scopes $scopes))))\n\n(= (_fuzz-grammar-validation-exit-scope\n $scopes\n $used)\n (if-decons-expr\n $scopes\n $scope\n $parents\n (if-decons-expr\n $parents\n $parent\n $rest\n (GrammarValidationState\n $parents\n $used)\n (_fuzz-generation-error\n UnbalancedGrammarValidationScope\n (Scopes $scopes)))\n (_fuzz-generation-error\n UnbalancedGrammarValidationScope\n (Scopes $scopes))))\n\n(= (_fuzz-grammar-validation-event\n $state\n $event\n $grammar)\n (switch $state\n (((GrammarValidationState\n $scopes\n $used)\n (_fuzz-grammar-template-switch $event\n (((GrammarValidationField\n (quote $generator))\n (let $validated\n (_fuzz-validate-grammar-field-generator\n $generator)\n (switch $validated\n (((ValidGrammarFieldGenerator)\n $state)\n ((FuzzGenerationError $code $details)\n $validated)\n ($bad\n (_fuzz-generation-error\n MalformedGrammarFieldValidation\n (Grammar $grammar)\n (Value $bad)))))))\n ((GrammarValidationScopedEnter\n (quote $bindings))\n (_fuzz-grammar-validation-enter-scope\n $grammar\n $bindings\n $scopes\n $used))\n ((GrammarValidationScopedExit)\n (_fuzz-grammar-validation-exit-scope\n $scopes\n $used))\n ((GrammarValidationMalformed\n (quote $template))\n (_fuzz-generation-error\n MalformedGrammarTemplate\n (Grammar $grammar)\n (Template (quote $template))))\n ($bad\n (_fuzz-generation-error\n MalformedGrammarValidationEvent\n (Grammar $grammar)\n (Value $bad))))))\n ((FuzzGenerationError $code $details)\n $state)\n ($bad\n (_fuzz-generation-error\n MalformedGrammarValidationState\n (Grammar $grammar)\n (Value $bad))))))\n\n(= (_fuzz-grammar-validation-from-fold\n $grammar\n $folded)\n (switch $folded\n (((GrammarValidationState\n (())\n $used)\n (ValidGrammarTemplate))\n ((GrammarValidationState\n $scopes\n $used)\n (_fuzz-generation-error\n UnbalancedGrammarValidationScope\n (Grammar $grammar)\n (Scopes $scopes)))\n ((FuzzGenerationError $code $details)\n $folded)\n ($bad\n (_fuzz-generation-error\n MalformedGrammarValidationState\n (Grammar $grammar)\n (Value $bad))))))\n\n(= (_fuzz-validate-grammar-template\n $grammar\n $template)\n (let $planned\n (_fuzz-grammar-validation-plan\n $template)\n (switch $planned\n (((GrammarValidationPlan $events)\n (_fuzz-grammar-validation-from-fold\n $grammar\n (foldl-atom\n $events\n (GrammarValidationState\n (())\n ())\n $state\n $event\n (_fuzz-grammar-validation-event\n $state\n $event\n $grammar))))\n ((FuzzKernelError $code $details)\n (_fuzz-generation-error\n KernelError\n (OperationResult $planned)))\n ($bad\n (_fuzz-generation-error\n MalformedGrammarValidationPlan\n (Grammar $grammar)\n (Value $bad)))))))\n\n; Normalization walks productions as a bare-tail machine: field resolution inside\n; `_fuzz-prepare-grammar-template` evaluates user Field expressions, so the per-production\n; work stays MeTTa; the walk itself must not pay stack depth or quadratic accumulation, so\n; the accumulator is a nested stack flattened once at the end.\n(= (_fuzz-normalize-walk-done $state)\n (unify $state\n (FuzzNormalizeWalk $grammar $remaining $index $accumulated $minimum-next-id)\n (unify $remaining () True False)\n True))\n\n(= (_fuzz-normalize-walk-prepared\n $grammar\n $tail\n $index\n $accumulated\n $minimum-next-id\n $weight\n $target\n $prepared)\n (unify $prepared\n (PreparedGrammarTemplate\n (quote $normalized-template)\n $references\n $template-minimum-next-id\n $nodes\n $depth)\n (FuzzNormalizeWalk\n $grammar\n $tail\n (+ $index 1)\n (FuzzStack\n (GrammarProduction\n $index\n $weight\n (quote $target)\n (quote $normalized-template))\n $accumulated)\n (max $minimum-next-id $template-minimum-next-id))\n (unify $prepared\n (FuzzGenerationError $code $details)\n $prepared\n (unify $prepared\n $bad\n (_fuzz-generation-error\n MalformedPreparedGrammarTemplate\n (Grammar $grammar)\n (Value $bad))\n Empty))))\n\n(= (_fuzz-normalize-walk-step $state)\n (unify $state\n (FuzzNormalizeWalk $grammar $remaining $index $accumulated $minimum-next-id)\n (if-decons-expr\n $remaining\n $production\n $tail\n (_fuzz-grammar-template-switch $production\n (((Production $weight $target $template)\n (if (_fuzz-is-integer $weight)\n (if (> $weight 0)\n (if (_fuzz-atom-ground $target)\n (let $prepared\n (_fuzz-prepare-grammar-template\n $grammar\n $template)\n (_fuzz-normalize-walk-prepared\n $grammar\n $tail\n $index\n $accumulated\n $minimum-next-id\n $weight\n $target\n $prepared))\n (_fuzz-generation-error\n NonGroundGrammarProductionTarget\n (Grammar $grammar)\n (ProductionIndex $index)\n (Target (quote $target))))\n (_fuzz-generation-error\n InvalidGrammarProductionWeight\n (Grammar $grammar)\n (ProductionIndex $index)\n (Weight $weight)))\n (_fuzz-expected-integer\n GrammarProductionWeight\n $weight)))\n ($bad\n (_fuzz-generation-error\n MalformedGrammarProduction\n (Grammar $grammar)\n (ProductionIndex $index)\n (Production $bad)))))\n (_fuzz-generation-error\n MalformedGrammarProductions\n (Grammar $grammar)\n (Productions $remaining)))\n $state))\n\n(= (_fuzz-normalize-walk-loop $state)\n (if (_fuzz-normalize-walk-done $state)\n $state\n (_fuzz-normalize-walk-loop\n (_fuzz-normalize-walk-step $state))))\n\n(= (_fuzz-normalize-grammar-productions\n $grammar\n $productions)\n (if-decons-expr\n $productions\n $first\n $tail\n (let $settled\n (_fuzz-normalize-walk-loop\n (FuzzNormalizeWalk\n $grammar\n $productions\n 0\n FuzzStackBottom\n 0))\n (unify $settled\n (FuzzNormalizeWalk $seen-grammar $remaining $count $accumulated $minimum-next-id)\n (let $flattened (_fuzz-stack-to-expression $accumulated)\n (unify $flattened\n (FuzzKernelError $code $details)\n (_fuzz-generation-error\n KernelError\n (OperationResult $flattened))\n (unify $flattened\n $normalized\n (ValidatedGrammarProductions\n $normalized\n $minimum-next-id)\n Empty)))\n (unify $settled\n (FuzzGenerationError $code $details)\n $settled\n (unify $settled\n $bad\n (_fuzz-generation-error\n MalformedGrammarNormalization\n (Grammar $grammar)\n (Value $bad))\n Empty))))\n (unify\n $productions\n ()\n (_fuzz-generation-error\n EmptyGrammar\n (Grammar $grammar))\n (_fuzz-generation-error\n MalformedGrammarProductions\n (Grammar $grammar)\n (Productions $productions)))))\n\n(= (_fuzz-grammar-target-member\n $target\n $targets)\n (if-decons-expr\n $targets\n $quoted\n $tail\n (_fuzz-grammar-template-switch $quoted\n (((quote $candidate)\n (if (noreduce-eq $target $candidate)\n True\n (_fuzz-grammar-target-member\n $target\n $tail)))\n ($bad\n (_fuzz-generation-error\n MalformedGrammarTarget\n (Value $bad)))))\n False))\n\n(= (_fuzz-grammar-add-target\n $target\n $targets)\n (if (_fuzz-grammar-target-member\n $target\n $targets)\n $targets\n (_fuzz-expression-append\n $targets\n (quote $target))))\n\n(= (_fuzz-template-reference-target-step\n $targets\n $quoted)\n (_fuzz-grammar-template-switch $quoted\n (((quote $target)\n (_fuzz-grammar-add-target\n $target\n $targets))\n ($bad\n (_fuzz-generation-error\n MalformedGrammarTarget\n (Value $bad))))))\n\n(= (_fuzz-template-reference-targets\n $template\n $targets)\n (let $planned\n (_fuzz-grammar-template-reference-plan\n $template)\n (switch $planned\n (((GrammarReferenceTargets $references)\n (foldl-atom\n $references\n $targets\n $seen\n $quoted\n (_fuzz-template-reference-target-step\n $seen\n $quoted)))\n ((FuzzKernelError $code $details)\n (_fuzz-generation-error\n KernelError\n (OperationResult $planned)))\n ($bad\n (_fuzz-generation-error\n MalformedGrammarReferencePlan\n (Value $bad)))))))\n\n(= (_fuzz-grammar-reference-targets-loop\n $productions\n $targets)\n (if-decons-expr\n $productions\n $production\n $tail\n (_fuzz-grammar-template-switch $production\n (((GrammarProduction\n $index\n $weight\n (quote $target)\n (quote $template))\n (_fuzz-grammar-reference-targets-loop\n $tail\n (_fuzz-template-reference-targets\n $template\n $targets)))\n ($bad\n (_fuzz-generation-error\n MalformedNormalizedGrammarProduction\n (Production $bad)))))\n $targets))\n\n(= (_fuzz-grammar-reference-targets\n $productions)\n (_fuzz-grammar-reference-targets-loop\n $productions\n ()))\n\n(= (_fuzz-grammar-summary-merge-candidate\n $changed\n $candidate\n $current-alternatives\n $summary\n $target)\n (let $added\n (_fuzz-grammar-alternatives-add\n $current-alternatives\n $candidate)\n (unify $added\n (GrammarAlternativesAdd False $same)\n (GrammarSummaryMergeState\n $changed\n $summary)\n (unify $added\n (GrammarAlternativesAdd True $next)\n (let $replaced\n (_fuzz-grammar-summary-replace\n $summary\n $target\n $next)\n (unify $replaced\n (FuzzKernelError $code $details)\n (_fuzz-generation-error\n KernelError\n (OperationResult $replaced))\n (unify $replaced\n $next-summary\n (GrammarSummaryMergeState\n True\n $next-summary)\n Empty)))\n (unify $added\n (FuzzKernelError $code $details)\n (_fuzz-generation-error\n KernelError\n (OperationResult $added))\n (unify $added\n $bad\n (_fuzz-generation-error\n MalformedGrammarRequirementDominance\n (Value $bad))\n Empty))))))\n\n(= (_fuzz-grammar-summary-merge-alternative\n $changed\n $alternative\n $summary\n $target)\n (_fuzz-grammar-template-switch $alternative\n (((GrammarRequirementAlternative $candidate)\n (let $current\n (_fuzz-grammar-summary-alternatives\n $summary\n $target)\n (switch $current\n (((GrammarRequirementAlternatives\n $current-alternatives)\n (_fuzz-grammar-summary-merge-candidate\n $changed\n $candidate\n $current-alternatives\n $summary\n $target))\n ((FuzzGenerationError $code $details)\n $current)\n ((FuzzKernelError $code $details)\n (_fuzz-generation-error\n KernelError\n (OperationResult $current)))\n ($bad\n (_fuzz-generation-error\n MalformedGrammarRequirementAlternatives\n (Value $bad)))))))\n ($bad\n (_fuzz-generation-error\n MalformedGrammarRequirementAlternative\n (Value $bad))))))\n\n(= (_fuzz-grammar-summary-merge-step\n $state\n $alternative\n $target)\n (switch $state\n (((FuzzGenerationError $code $details)\n $state)\n ((GrammarSummaryMergeState\n $changed\n $summary)\n (_fuzz-grammar-summary-merge-alternative\n $changed\n $alternative\n $summary\n $target))\n ($bad\n (_fuzz-generation-error\n MalformedGrammarSummaryMergeState\n (Value $bad))))))\n\n(= (_fuzz-grammar-summary-merge\n $target\n $new-alternatives\n $summary)\n (foldl-atom\n $new-alternatives\n (GrammarSummaryMergeState\n False\n $summary)\n $state\n $alternative\n (_fuzz-grammar-summary-merge-step\n $state\n $alternative\n $target)))\n\n(= (_fuzz-grammar-template-requirements\n $template\n $summary)\n (let $analyzed\n (_fuzz-grammar-template-requirements-op\n $template\n $summary)\n (unify $analyzed\n (GrammarRequirementAlternatives $alternatives)\n $analyzed\n (unify $analyzed\n (FuzzKernelError $code $details)\n (_fuzz-generation-error\n KernelError\n (OperationResult $analyzed))\n (unify $analyzed\n $bad\n (_fuzz-generation-error\n MalformedGrammarRequirementAlternatives\n (Value $bad))\n Empty)))))\n\n; The fixed point runs as a worklist: analyzing a production whose target's alternatives\n; changed enqueues exactly the productions that reference that target, so a chain of N\n; targets settles in O(N + references) analyses instead of O(N) full restarts. Merge is\n; monotone, so any fair processing order reaches the same least fixed point, and the\n; summary is validation-internal, so queue order is unobservable downstream.\n(= (_fuzz-productivity-done $state)\n (unify $state\n (FuzzProductivityQueue $productions (FuzzStack $index $rest) $summary)\n False\n True))\n\n(= (_fuzz-productivity-changed\n $productions\n $rest\n $target\n $next-summary)\n (let $dependents\n (_fuzz-grammar-dependents-of\n $productions\n (quote $target))\n (unify $dependents\n (GrammarDependents $indices)\n (let $next-queue (_fuzz-stack-push-all $rest $indices)\n (FuzzProductivityQueue\n $productions\n $next-queue\n $next-summary))\n (unify $dependents\n (FuzzKernelError $code $details)\n (_fuzz-generation-error\n KernelError\n (OperationResult $dependents))\n (unify $dependents\n $bad\n (_fuzz-generation-error\n MalformedGrammarDependents\n (Value $bad))\n Empty)))))\n\n(= (_fuzz-productivity-analyze\n $productions\n $rest\n $summary\n $target\n $template)\n (let $requirements\n (_fuzz-grammar-template-requirements\n $template\n $summary)\n (unify $requirements\n (GrammarRequirementAlternatives $alternatives)\n (let $merged\n (_fuzz-grammar-summary-merge\n $target\n $alternatives\n $summary)\n (unify $merged\n (GrammarSummaryMergeState True $next-summary)\n (_fuzz-productivity-changed\n $productions\n $rest\n $target\n $next-summary)\n (unify $merged\n (GrammarSummaryMergeState False $next-summary)\n (FuzzProductivityQueue\n $productions\n $rest\n $next-summary)\n (unify $merged\n (FuzzGenerationError $code $details)\n $merged\n (unify $merged\n $bad\n (_fuzz-generation-error\n MalformedGrammarSummaryMergeState\n (Value $bad))\n Empty)))))\n (unify $requirements\n (FuzzGenerationError $code $details)\n $requirements\n (unify $requirements\n $bad\n (_fuzz-generation-error\n MalformedGrammarRequirementAlternatives\n (Value $bad))\n Empty)))))\n\n(= (_fuzz-productivity-step $state)\n (unify $state\n (FuzzProductivityQueue $productions (FuzzStack $index $rest) $summary)\n (let $production (index-atom $productions $index)\n (_fuzz-grammar-template-switch $production\n (((GrammarProduction\n $production-index\n $weight\n (quote $target)\n (quote $template))\n (_fuzz-productivity-analyze\n $productions\n $rest\n $summary\n $target\n $template))\n ($bad\n (_fuzz-generation-error\n MalformedNormalizedGrammarProduction\n (Production $bad))))))\n $state))\n\n(= (_fuzz-productivity-loop $state)\n (if (_fuzz-productivity-done $state)\n $state\n (_fuzz-productivity-loop\n (_fuzz-productivity-step $state))))\n\n(= (_fuzz-grammar-summary-has-target\n $target\n $summary)\n (let $found\n (_fuzz-grammar-summary-alternatives\n $summary\n $target)\n (switch $found\n (((GrammarRequirementAlternatives\n $alternatives)\n (> (length $alternatives) 0))\n ((FuzzKernelError $code $details)\n (_fuzz-generation-error\n KernelError\n (OperationResult $found)))\n ($bad\n (_fuzz-generation-error\n MalformedGrammarRequirementAlternatives\n (Value $bad)))))))\n\n(= (_fuzz-grammar-summary-has-closed-target\n $target\n $summary)\n (let $found\n (_fuzz-grammar-summary-alternatives\n $summary\n $target)\n (switch $found\n (((GrammarRequirementAlternatives\n $alternatives)\n (let $present\n (_fuzz-exact-member\n (GrammarRequirementAlternative ())\n $alternatives)\n (switch $present\n (((FuzzKernelError $code $details)\n (_fuzz-generation-error\n KernelError\n (OperationResult $present)))\n ($valid $valid)))))\n ((FuzzKernelError $code $details)\n (_fuzz-generation-error\n KernelError\n (OperationResult $found)))\n ($bad\n (_fuzz-generation-error\n MalformedGrammarRequirementAlternatives\n (Value $bad)))))))\n\n(= (_fuzz-first-unsummarized-target-step\n $state\n $quoted\n $summary)\n (switch $state\n (((FuzzGenerationError $code $details)\n $state)\n ((GrammarMissingTarget (quote $missing))\n $state)\n ((GrammarMissingTarget None)\n (_fuzz-grammar-template-switch $quoted\n (((quote $target)\n (if (_fuzz-grammar-summary-has-target\n $target\n $summary)\n $state\n (GrammarMissingTarget\n (quote $target))))\n ($bad\n (_fuzz-generation-error\n MalformedGrammarTarget\n (Value $bad))))))\n ($bad\n (_fuzz-generation-error\n MalformedGrammarMissingTargetState\n (Value $bad))))))\n\n(= (_fuzz-first-unsummarized-target\n $targets\n $summary)\n (let $folded\n (foldl-atom\n $targets\n (GrammarMissingTarget None)\n $state\n $quoted\n (_fuzz-first-unsummarized-target-step\n $state\n $quoted\n $summary))\n (switch $folded\n (((GrammarMissingTarget (quote $missing))\n (quote $missing))\n ((GrammarMissingTarget None)\n (_fuzz-generation-error\n MissingGrammarTarget\n (Targets $targets)))\n ((FuzzGenerationError $code $details)\n $folded)\n ($bad\n (_fuzz-generation-error\n MalformedGrammarMissingTargetState\n (Value $bad)))))))\n\n(= (_fuzz-grammar-all-targets-summarized-step\n $state\n $quoted\n $summary)\n (switch $state\n (((FuzzGenerationError $code $details)\n $state)\n (False False)\n (True\n (_fuzz-grammar-template-switch $quoted\n (((quote $target)\n (_fuzz-grammar-summary-has-target\n $target\n $summary))\n ($bad\n (_fuzz-generation-error\n MalformedGrammarTarget\n (Value $bad))))))\n ($bad\n (_fuzz-generation-error\n MalformedGrammarRequirementMembership\n (Value $bad))))))\n\n(= (_fuzz-grammar-all-targets-summarized\n $targets\n $summary)\n (foldl-atom\n $targets\n True\n $state\n $quoted\n (_fuzz-grammar-all-targets-summarized-step\n $state\n $quoted\n $summary)))\n\n(= (_fuzz-grammar-productivity-result\n $grammar\n $root\n $targets\n $summary)\n (let $all\n (_fuzz-grammar-all-targets-summarized\n $targets\n $summary)\n (switch $all\n ((True\n (let $closed\n (_fuzz-grammar-summary-has-closed-target\n $root\n $summary)\n (switch $closed\n ((True\n (ValidGrammarProductivity))\n (False\n (_fuzz-generation-error\n UnproductiveGrammarNonterminal\n (Grammar $grammar)\n (Nonterminal (quote $root))))\n ((FuzzGenerationError $code $details)\n $closed)\n ($bad\n (_fuzz-generation-error\n MalformedGrammarRequirementMembership\n (Value $bad)))))))\n (False\n (let $missing\n (_fuzz-first-unsummarized-target\n $targets\n $summary)\n (_fuzz-generation-error\n UnproductiveGrammarNonterminal\n (Grammar $grammar)\n (Nonterminal $missing))))\n ((FuzzGenerationError $code $details)\n $all)\n ($bad\n (_fuzz-generation-error\n MalformedGrammarRequirementMembership\n (Value $bad)))))))\n\n(= (_fuzz-grammar-productivity-fixedpoint\n $grammar\n $root\n $productions\n $targets\n $summary)\n (let $seed-queue (_fuzz-index-stack (length $productions))\n (let $settled\n (_fuzz-productivity-loop\n (FuzzProductivityQueue\n $productions\n $seed-queue\n $summary))\n (unify $settled\n (FuzzProductivityQueue\n $seen-productions\n $queue\n $next-summary)\n (_fuzz-grammar-productivity-result\n $grammar\n $root\n $targets\n $next-summary)\n (unify $settled\n (FuzzGenerationError $code $details)\n $settled\n (unify $settled\n $bad\n (_fuzz-generation-error\n MalformedGrammarProductivity\n (Grammar $grammar)\n (Value $bad))\n Empty))))))\n\n; The default validation path: the whole fixed point runs kernel-side; the exact error\n; shape stays here. The specification fixed point remains callable through\n; `_fuzz-validate-grammar-productivity-reference`.\n(= (_fuzz-validate-grammar-productivity\n $grammar\n $root\n $productions\n $targets)\n (let $verdict\n (_fuzz-grammar-productivity-op\n $productions\n (quote $root)\n $targets)\n (unify $verdict\n (ValidGrammarProductivity)\n (ValidGrammarProductivity)\n (unify $verdict\n (GrammarUnproductive (quote $nonterminal))\n (_fuzz-generation-error\n UnproductiveGrammarNonterminal\n (Grammar $grammar)\n (Nonterminal (quote $nonterminal)))\n (unify $verdict\n (FuzzKernelError $code $details)\n (_fuzz-generation-error\n KernelError\n (OperationResult $verdict))\n (unify $verdict\n $bad\n (_fuzz-generation-error\n MalformedGrammarProductivity\n (Grammar $grammar)\n (Value $bad))\n Empty))))))\n\n(= (_fuzz-validate-grammar-productivity-reference\n $grammar\n $root\n $productions\n $targets)\n (_fuzz-grammar-productivity-fixedpoint\n $grammar\n $root\n $productions\n $targets\n ()))\n\n(= (_fuzz-validated-references\n $grammar\n $root\n $productions\n $minimum-next-id\n $targets)\n (let $checked\n (_fuzz-grammar-validate-references-op\n $productions\n $targets)\n (unify $checked\n (ValidGrammarReferences)\n (let $productivity\n (_fuzz-validate-grammar-productivity\n $grammar\n $root\n $productions\n $targets)\n (unify $productivity\n (ValidGrammarProductivity)\n (ValidatedGrammar\n (quote $grammar)\n (quote $root)\n $productions\n $minimum-next-id)\n (unify $productivity\n (FuzzGenerationError $code $details)\n $productivity\n (unify $productivity\n $bad\n (_fuzz-generation-error\n MalformedGrammarProductivity\n (Grammar $grammar)\n (Value $bad))\n Empty))))\n (unify $checked\n (GrammarMissingReference (quote $nonterminal))\n (_fuzz-generation-error\n MissingGrammarNonterminal\n (Grammar $grammar)\n (Nonterminal (quote $nonterminal)))\n (unify $checked\n (FuzzKernelError $code $details)\n (_fuzz-generation-error\n KernelError\n (OperationResult $checked))\n (unify $checked\n $bad\n (_fuzz-generation-error\n MalformedGrammarReferenceValidation\n (Grammar $grammar)\n (Value $bad))\n Empty))))))\n\n(= (_fuzz-validate-normalized-grammar\n $grammar\n $root\n $productions\n $minimum-next-id)\n (let $targets-result\n (_fuzz-grammar-targets-op $productions)\n (unify $targets-result\n (GrammarTargets $targets)\n (if (_fuzz-grammar-target-member\n $root\n $targets)\n (_fuzz-validated-references\n $grammar\n $root\n $productions\n $minimum-next-id\n $targets)\n (_fuzz-generation-error\n MissingGrammarRoot\n (Grammar $grammar)\n (Root (quote $root))))\n (unify $targets-result\n (FuzzKernelError $code $details)\n (_fuzz-generation-error\n KernelError\n (OperationResult $targets-result))\n (unify $targets-result\n $bad\n (_fuzz-generation-error\n MalformedGrammarTargets\n (Grammar $grammar)\n (Value $bad))\n Empty)))))\n\n(= (_fuzz-build-grammar\n $grammar\n $root\n $productions)\n (let $normalized\n (_fuzz-normalize-grammar-productions\n $grammar\n $productions)\n (switch $normalized\n (((ValidatedGrammarProductions\n $valid\n $minimum-next-id)\n (_fuzz-validate-normalized-grammar\n $grammar\n $root\n $valid\n $minimum-next-id))\n ((FuzzGenerationError $code $details)\n $normalized)\n ($bad\n (_fuzz-generation-error\n MalformedGrammarNormalization\n (Grammar $grammar)\n (Value $bad)))))))\n\n(= (_fuzz-grammar-from-results\n $grammar\n $root\n $results)\n (switch $results\n ((()\n (_fuzz-generation-error\n MissingGrammar\n (Grammar $grammar)))\n (((quote $productions))\n (_fuzz-build-grammar\n $grammar\n $root\n $productions))\n ($many\n (_fuzz-generation-error\n AmbiguousGrammar\n (Grammar $grammar)\n (Results $many))))))\n\n(= (_fuzz-gen-grammar-root-ground\n (quote $grammar)\n (quote $root))\n (let $results\n (collapse\n (match &self\n (FuzzGrammar\n $grammar\n (Productions $productions))\n (quote $productions)))\n (let $validated\n (_fuzz-grammar-from-results\n $grammar\n $root\n $results)\n (switch $validated\n (((ValidatedGrammar\n (quote $name)\n (quote $target)\n $productions\n $minimum-next-id)\n (GenCustom\n _fuzz-grammar\n (GrammarRequest\n (StaticGrammar\n (quote $name)\n $productions)\n (quote $target)\n ()\n $minimum-next-id)))\n ((FuzzGenerationError $code $details)\n $validated)\n ($bad\n (_fuzz-generation-error\n MalformedValidatedGrammar\n (Grammar $grammar)\n (Value $bad))))))))\n\n(= (gen-grammar-root $grammar $root)\n (if (_fuzz-atom-ground (quote $grammar))\n (if (_fuzz-atom-ground (quote $root))\n (_fuzz-gen-grammar-root-ground\n (quote $grammar)\n (quote $root))\n (_fuzz-generation-error\n NonGroundGrammarRoot\n (Grammar $grammar)\n (Root (quote $root))))\n (_fuzz-generation-error\n NonGroundGrammarName\n (Grammar (quote $grammar)))))\n\n(= (gen-grammar $grammar)\n (gen-grammar-root\n $grammar\n $grammar))\n\n; Scope bindings are ordered from nearest to farthest.\n(= (_fuzz-grammar-scope-has-id-step\n $state\n $binding\n $id)\n (switch $state\n ((True True)\n (False\n (_fuzz-grammar-template-switch $binding\n (((GrammarBinding (quote $sort) $candidate)\n (== $id $candidate))\n ($bad False))))\n ($bad False))))\n\n(= (_fuzz-grammar-scope-has-id\n $scope\n $id)\n (foldl-atom\n $scope\n False\n $state\n $binding\n (_fuzz-grammar-scope-has-id-step\n $state\n $binding\n $id)))\n\n(= (_fuzz-grammar-scopes-disjoint-step\n $state\n $binding\n $existing)\n (switch $state\n ((False False)\n (True\n (_fuzz-grammar-template-switch $binding\n (((GrammarBinding (quote $sort) $id)\n (== (_fuzz-grammar-scope-has-id\n $existing\n $id)\n False))\n ($bad False))))\n ($bad False))))\n\n(= (_fuzz-grammar-scopes-disjoint\n $added\n $existing)\n (foldl-atom\n $added\n True\n $state\n $binding\n (_fuzz-grammar-scopes-disjoint-step\n $state\n $binding\n $existing)))\n\n(= (_fuzz-static-productions-for-target-loop\n $remaining\n (quote $target)\n $selected)\n (if-decons-expr\n $remaining\n $production\n $tail\n (_fuzz-grammar-template-switch $production\n (((GrammarProduction\n $index\n $weight\n (quote $candidate)\n (quote $template))\n (let $next\n (if (noreduce-eq $target $candidate)\n (_fuzz-expression-append\n $selected\n $production)\n $selected)\n (_fuzz-static-productions-for-target-loop\n $tail\n (quote $target)\n $next)))\n ($bad\n (_fuzz-generation-error\n MalformedNormalizedGrammarProduction\n (Production $bad)))))\n (GrammarProductions $selected)))\n\n(= (_fuzz-source-productions\n (StaticGrammar (quote $grammar) $productions)\n (quote $target))\n (_fuzz-static-productions-for-target-loop\n $productions\n (quote $target)\n ()))\n\n(= (_fuzz-normalize-type-constructors-loop\n $schema\n $type\n $remaining\n $index\n $normalized\n $minimum-next-id)\n (if-decons-expr\n $remaining\n $constructor\n $tail\n (_fuzz-grammar-template-switch $constructor\n (((Constructor $weight $result-type $template)\n (if (_fuzz-atom-ground $result-type)\n (if (noreduce-eq $type $result-type)\n (if (_fuzz-is-integer $weight)\n (if (> $weight 0)\n (let $prepared\n (_fuzz-prepare-grammar-template\n $schema\n $template)\n (switch $prepared\n (((PreparedGrammarTemplate\n (quote $normalized-template)\n $references\n $template-minimum-next-id\n $nodes\n $depth)\n (let $next\n (_fuzz-expression-append\n $normalized\n (GrammarProduction\n $index\n $weight\n (quote $type)\n (quote\n $normalized-template)))\n (_fuzz-normalize-type-constructors-loop\n $schema\n $type\n $tail\n (+ $index 1)\n $next\n (max\n $minimum-next-id\n $template-minimum-next-id))))\n ((FuzzGenerationError $code $details)\n $prepared)\n ($bad\n (_fuzz-generation-error\n MalformedPreparedGrammarTemplate\n (Schema $schema)\n (Value $bad))))))\n (_fuzz-generation-error\n InvalidTypeConstructorWeight\n (Schema $schema)\n (Type (quote $type))\n (ConstructorIndex $index)\n (Weight $weight)))\n (_fuzz-expected-integer\n TypeConstructorWeight\n $weight))\n (_fuzz-generation-error\n TypeConstructorResultMismatch\n (Schema $schema)\n (RequestedType (quote $type))\n (ConstructorType (quote $result-type))\n (ConstructorIndex $index)))\n (_fuzz-generation-error\n NonGroundTypeConstructorResult\n (Schema $schema)\n (RequestedType (quote $type))\n (ConstructorType (quote $result-type))\n (ConstructorIndex $index))))\n ($bad\n (_fuzz-generation-error\n MalformedTypeConstructor\n (Schema $schema)\n (Type (quote $type))\n (ConstructorIndex $index)\n (Constructor (quote $bad))))))\n (unify\n $remaining\n ()\n (PreparedTypeConstructors\n $normalized\n $minimum-next-id)\n (_fuzz-generation-error\n MalformedTypeConstructors\n (Schema $schema)\n (Type (quote $type))\n (Constructors $remaining)))))\n\n(= (_fuzz-normalize-type-constructors\n $schema\n $type\n $constructors)\n (if-decons-expr\n $constructors\n $first\n $tail\n (_fuzz-normalize-type-constructors-loop\n $schema\n $type\n $constructors\n 0\n ()\n 0)\n (unify\n $constructors\n ()\n (_fuzz-generation-error\n EmptyTypeSchema\n (Schema $schema)\n (Type (quote $type)))\n (_fuzz-generation-error\n MalformedTypeConstructors\n (Schema $schema)\n (Type (quote $type))\n (Constructors $constructors)))))\n\n(= (_fuzz-type-schema-from-results\n $schema\n $type\n $results)\n (switch $results\n ((()\n (_fuzz-generation-error\n MissingTypeSchema\n (Schema $schema)\n (Type (quote $type))))\n (((quote $single))\n (_fuzz-grammar-template-switch $single\n (((FuzzTypeConstructors $constructors)\n (_fuzz-normalize-type-constructors\n $schema\n $type\n $constructors))\n ($bad\n (_fuzz-generation-error\n MalformedTypeSchema\n (Schema $schema)\n (Type (quote $type))\n (Value (quote $bad)))))))\n ($many\n (_fuzz-generation-error\n AmbiguousTypeSchema\n (Schema $schema)\n (Type (quote $type))\n (Results $many))))))\n\n(= (_fuzz-source-productions\n (DynamicTypeGrammar (quote $schema))\n (quote $type))\n (let $results\n (collapse\n (match &self\n (= (FuzzTypeSchema\n $schema\n $type)\n $constructors)\n (quote $constructors)))\n (_fuzz-type-schema-from-results\n $schema\n $type\n $results)))\n\n(= (_fuzz-source-productions\n (StaticTypeGrammar (quote $schema) $productions)\n (quote $type))\n (_fuzz-static-productions-for-target-loop\n $productions\n (quote $type)\n ()))\n\n(= (_fuzz-finalize-type-grammar\n $schema\n $root\n $productions\n $minimum-next-id)\n (let $validated\n (_fuzz-validate-normalized-grammar\n $schema\n $root\n $productions\n $minimum-next-id)\n (switch $validated\n (((ValidatedGrammar\n (quote $seen-schema)\n (quote $seen-root)\n $validated-productions\n $validated-minimum-next-id)\n (ValidatedTypeGrammar\n (quote $schema)\n (quote $root)\n $validated-productions\n $validated-minimum-next-id))\n ((FuzzGenerationError\n UnproductiveGrammarNonterminal\n (Details\n (Grammar $seen-schema)\n (Nonterminal (quote $type))))\n (_fuzz-generation-error\n UnproductiveTypeSchema\n (Schema $schema)\n (Type (quote $type))))\n ((FuzzGenerationError $code $details)\n $validated)\n ($bad\n (_fuzz-generation-error\n MalformedTypeSchemaValidation\n (Schema $schema)\n (Type (quote $root))\n (Value $bad)))))))\n\n(= (_fuzz-build-type-grammar-prepared\n $schema\n $root\n $type\n $tail\n $seen\n $productions\n $minimum-next-id\n $remaining\n $constructors\n $constructor-minimum-next-id)\n (let $references\n (_fuzz-grammar-reference-targets\n $constructors)\n (switch $references\n (((FuzzGenerationError $code $details)\n $references)\n ($valid-references\n (let $next-pending\n (_fuzz-expression-concat\n $tail\n $valid-references)\n (let $next-seen\n (_fuzz-expression-append\n $seen\n (quote $type))\n (let $next-productions\n (_fuzz-expression-concat\n $productions\n $constructors)\n (_fuzz-build-type-grammar-loop\n $schema\n $root\n $next-pending\n $next-seen\n $next-productions\n (max\n $minimum-next-id\n $constructor-minimum-next-id)\n (- $remaining 1))))))))))\n\n(= (_fuzz-build-type-grammar-available\n $schema\n $root\n $type\n $tail\n $seen\n $productions\n $minimum-next-id\n $remaining\n $available)\n (switch $available\n (((PreparedTypeConstructors\n $constructors\n $constructor-minimum-next-id)\n (_fuzz-build-type-grammar-prepared\n $schema\n $root\n $type\n $tail\n $seen\n $productions\n $minimum-next-id\n $remaining\n $constructors\n $constructor-minimum-next-id))\n ((FuzzGenerationError $code $details)\n $available)\n ($bad\n (_fuzz-generation-error\n MalformedTypeSchemaValidation\n (Schema $schema)\n (Type (quote $type))\n (Value $bad))))))\n\n(= (_fuzz-build-type-grammar-type\n $schema\n $root\n $type\n $tail\n $seen\n $productions\n $minimum-next-id\n $remaining)\n (let $present\n (_fuzz-grammar-target-member\n $type\n $seen)\n (switch $present\n ((True\n (_fuzz-build-type-grammar-loop\n $schema\n $root\n $tail\n $seen\n $productions\n $minimum-next-id\n $remaining))\n (False\n (if (<= $remaining 0)\n (_fuzz-generation-error\n TypeSchemaExpansionLimitExceeded\n (Schema $schema)\n (Root (quote $root))\n (Limit 256))\n (_fuzz-build-type-grammar-available\n $schema\n $root\n $type\n $tail\n $seen\n $productions\n $minimum-next-id\n $remaining\n (_fuzz-source-productions\n (DynamicTypeGrammar\n (quote $schema))\n (quote $type)))))\n ((FuzzGenerationError $code $details)\n $present)\n ($bad\n (_fuzz-generation-error\n MalformedGrammarTargetMembership\n (Type (quote $type))\n (Value $bad)))))))\n\n(= (_fuzz-build-type-grammar-loop\n $schema\n $root\n $pending\n $seen\n $productions\n $minimum-next-id\n $remaining)\n (if-decons-expr\n $pending\n $quoted\n $tail\n (_fuzz-grammar-template-switch $quoted\n (((quote $type)\n (_fuzz-build-type-grammar-type\n $schema\n $root\n $type\n $tail\n $seen\n $productions\n $minimum-next-id\n $remaining))\n ($bad\n (_fuzz-generation-error\n MalformedGrammarTarget\n (Value $bad)))))\n (_fuzz-finalize-type-grammar\n $schema\n $root\n $productions\n $minimum-next-id)))\n\n(= (_fuzz-build-type-grammar\n $schema\n $type)\n (_fuzz-build-type-grammar-loop\n $schema\n $type\n ((quote $type))\n ()\n ()\n 0\n 256))\n\n(= (_fuzz-gen-well-typed-ground\n (quote $schema)\n (quote $type))\n (let $validated\n (_fuzz-build-type-grammar\n $schema\n $type)\n (switch $validated\n (((ValidatedTypeGrammar\n (quote $seen-schema)\n (quote $seen-type)\n $constructors\n $minimum-next-id)\n (GenCustom\n _fuzz-grammar\n (GrammarRequest\n (StaticTypeGrammar\n (quote $schema)\n $constructors)\n (quote $type)\n ()\n $minimum-next-id)))\n ((FuzzGenerationError $code $details)\n $validated)\n ($bad\n (_fuzz-generation-error\n MalformedTypeSchemaValidation\n (Schema $schema)\n (Type (quote $type))\n (Value $bad)))))))\n\n(= (gen-well-typed $schema $type)\n (if (_fuzz-atom-ground (quote $schema))\n (if (_fuzz-atom-ground (quote $type))\n (_fuzz-gen-well-typed-ground\n (quote $schema)\n (quote $type))\n (_fuzz-generation-error\n NonGroundTypeSchemaRequest\n (Schema $schema)\n (Type (quote $type))))\n (_fuzz-generation-error\n NonGroundTypeSchemaName\n (Schema (quote $schema)))))\n\n; Eligibility is one grounded call: the fit semantics (Use needs its sort in scope, a\n; reference needs size > 0 and an eligible target at the split size, Scoped checks binding-id\n; disjointness) run kernel-side over raw template syntax, memoised per grammar. The MeTTa\n; side keeps the driver policy: which production a driver picks, and every wrapper shape.\n(= (_fuzz-eligible-productions\n $source\n (quote $target)\n $scope\n $size)\n (unify $source\n (StaticGrammar (quote $grammar) $productions)\n (_fuzz-eligible-productions-checked\n $productions\n (quote $target)\n $scope\n $size)\n (unify $source\n (StaticTypeGrammar (quote $schema) $productions)\n (_fuzz-eligible-productions-checked\n $productions\n (quote $target)\n $scope\n $size)\n (_fuzz-generation-error\n MalformedGrammarSource\n (Value $source)))))\n\n(= (_fuzz-eligible-productions-checked\n $productions\n (quote $target)\n $scope\n $size)\n (let $eligible\n (_fuzz-grammar-eligible-productions-op\n $productions\n (quote $target)\n $scope\n $size)\n (unify $eligible\n (EligibleGrammarProductions $selected)\n $eligible\n (unify $eligible\n (FitDuplicateGrammarBindingId (quote $bindings))\n (_fuzz-generation-error\n DuplicateGrammarBindingId\n (Bindings $bindings))\n (unify $eligible\n (FuzzKernelError $code $details)\n (_fuzz-generation-error\n KernelError\n (OperationResult $eligible))\n (unify $eligible\n $bad\n (_fuzz-generation-error\n MalformedEligibleGrammarProductions\n (Target (quote $target))\n (Value $bad))\n Empty))))))\n\n(= (_fuzz-grammar-weight-total\n $productions\n $total)\n (if (== $productions ())\n $total\n (let* ((($production $tail)\n (decons-atom $productions)))\n (switch $production\n (((GrammarProduction\n $index\n $weight\n (quote $target)\n (quote $template))\n (_fuzz-grammar-weight-total\n $tail\n (+ $total $weight)))\n ($bad $total))))))\n\n(= (_fuzz-grammar-ticket-index\n $productions\n $ticket\n $index)\n (let* ((($production $tail)\n (decons-atom $productions)))\n (switch $production\n (((GrammarProduction\n $production-index\n $weight\n (quote $target)\n (quote $template))\n (if (<= $ticket $weight)\n $index\n (_fuzz-grammar-ticket-index\n $tail\n (- $ticket $weight)\n (+ $index 1))))\n ($bad $index)))))\n\n(= (_fuzz-grammar-random-production-choice\n $rng\n $productions)\n (let* (($count (length $productions))\n ($total\n (_fuzz-grammar-weight-total\n $productions\n 0))\n ($draw\n (_fuzz-draw-int\n $rng\n 1\n $total)))\n (switch $draw\n (((FuzzDraw $ticket $next-rng)\n (let $index\n (_fuzz-grammar-ticket-index\n $productions\n $ticket\n 0)\n (DriverChoice\n $index\n (FuzzDriver Random $next-rng)\n (_fuzz-int-decision\n 0\n (- $count 1)\n 0\n $index))))\n ($bad\n (_fuzz-generation-error\n KernelError\n (OperationResult $bad)))))))\n\n(= (_fuzz-grammar-production-choice\n $driver\n $productions)\n (switch $driver\n (((FuzzDriver Random $rng)\n (_fuzz-grammar-random-production-choice\n $rng\n $productions))\n ((FuzzDriver Edge $index)\n (let* (($count\n (length $productions))\n ($position\n (% $index $count)))\n (DriverChoice\n $position\n (FuzzDriver Edge (+ $index 1))\n (_fuzz-int-decision\n 0\n (- $count 1)\n 0\n $position))))\n ($other\n (_fuzz-driver-int\n $other\n 0\n (- (length $productions) 1)\n 0)))))\n\n(= (_fuzz-grammar-reference-size\n $size\n $ordinal\n $total)\n (if (and\n (> $total 0)\n (and\n (<= 0 $ordinal)\n (< $ordinal $total)))\n (let* (($budget (max 0 (- $size 1)))\n ($base (/ $budget $total))\n ($remainder (% $budget $total)))\n (+ $base\n (if (< $ordinal $remainder)\n 1\n 0)))\n (_fuzz-generation-error\n MalformedIndexedGrammarReference\n (Ordinal $ordinal)\n (Total $total))))\n\n(= (_fuzz-grammar-scope-values\n $scope\n $sort\n $values)\n (if-decons-expr\n $scope\n $binding\n $tail\n (_fuzz-grammar-template-switch $binding\n (((GrammarBinding (quote $candidate) $id)\n (let $next-values\n (if (noreduce-eq $sort $candidate)\n (let $marker\n (_fuzz-variable-marker $id)\n (_fuzz-expression-append\n $values\n $marker))\n $values)\n (_fuzz-grammar-scope-values\n $tail\n $sort\n $next-values)))\n ($bad\n (_fuzz-grammar-scope-values\n $tail\n $sort\n $values))))\n $values))\n\n; ---- the generation machine ----\n; One bare-tail machine generates a nonterminal: flat instruction plans compiled per template\n; (kernel, memoised) execute against a frame chain and nested value/tree stacks, so neither\n; template depth nor width costs engine stack, and no frame holds a growing value. Frames:\n; (FPlan instrs len cursor size) one template's instructions in execution order\n; (FExpr arity vdepth tdepth) an open expression node (snapshot depths for discards)\n; (FRef (quote t)) wrap a completed reference\n; (FProd (quote t) index pos ctree) wrap a completed production\n; (FBind (quote s) id var) wrap a completed binder body\n; (FScoped added) wrap a completed scoped body\n; (FScope saved) restore the lexical scope\n; The running state is (FuzzGenRun source frames values vdepth trees tdepth scope next-id driver);\n; a discard unwinds as (FuzzGenCut source frames values vdepth trees tdepth reason tree driver),\n; wrapping the partial tree through each frame exactly as the recursive interpreter did; both\n; settle to (FuzzGenDone result).\n\n(= (_fuzz-gen-loop $state)\n (if (_fuzz-gen-finished $state)\n $state\n (_fuzz-gen-loop (_fuzz-gen-step $state))))\n\n(= (_fuzz-gen-finished $state)\n (unify $state\n (FuzzGenDone $result)\n True\n (unify $state\n (FuzzGenRun $source $frames $values $vd $trees $td $scope $next-id $driver)\n False\n (unify $state\n (FuzzGenCut $source $frames $values $vd $trees $td $reason $tree $driver)\n False\n True))))\n\n(= (_fuzz-gen-step $state)\n (unify $state\n (FuzzGenRun $source $frames $values $vd $trees $td $scope $next-id $driver)\n (_fuzz-gen-run-step\n $source $frames $values $vd $trees $td $scope $next-id $driver)\n (unify $state\n (FuzzGenCut $source $frames $values $vd $trees $td $reason $tree $driver)\n (_fuzz-gen-cut-step\n $source $frames $values $vd $trees $td $reason $tree $driver)\n $state)))\n\n; Push one generated value + decision tree.\n(= (_fuzz-gen-push\n $source $frames $values $vd $trees $td $scope $next-id $driver\n $value\n $tree)\n (FuzzGenRun\n $source\n $frames\n (FuzzStack $value $values)\n (+ $vd 1)\n (FuzzStack $tree $trees)\n (+ $td 1)\n $scope\n $next-id\n $driver))\n\n(= (_fuzz-gen-run-step\n $source $frames $values $vd $trees $td $scope $next-id $driver)\n (unify $frames\n (GF (FPlan $instrs $len $cursor $size) $parent)\n (if (== $cursor $len)\n (FuzzGenRun $source $parent $values $vd $trees $td $scope $next-id $driver)\n (let $instr (index-atom $instrs $cursor)\n (_fuzz-gen-instr\n $source\n (GF (FPlan $instrs $len (+ $cursor 1) $size) $parent)\n $values $vd $trees $td $scope $next-id $driver\n $instr\n $size)))\n (unify $frames\n (GF (FRef (quote $target)) $parent)\n (unify $values\n (FuzzStack $value $rest-values)\n (unify $trees\n (FuzzStack $tree $rest-trees)\n (_fuzz-gen-push\n $source $parent $rest-values (- $vd 1) $rest-trees (- $td 1) $scope $next-id $driver\n $value\n (Decision GrammarRef (Target (quote $target)) () ($tree)))\n (FuzzGenDone (_fuzz-generation-error MalformedGrammarMachineState (State trees))))\n (FuzzGenDone (_fuzz-generation-error MalformedGrammarMachineState (State values))))\n (unify $frames\n (GF (FProd (quote $target) $production-index $position $choice-tree) $parent)\n (unify $values\n (FuzzStack $value $rest-values)\n (unify $trees\n (FuzzStack $tree $rest-trees)\n (let $children (_fuzz-two-children $choice-tree $tree)\n (_fuzz-gen-push\n $source $parent $rest-values (- $vd 1) $rest-trees (- $td 1) $scope $next-id $driver\n $value\n (Decision\n GrammarProduction\n (Target (quote $target))\n (ProductionIndex $production-index $position)\n $children)))\n (FuzzGenDone (_fuzz-generation-error MalformedGrammarMachineState (State trees))))\n (FuzzGenDone (_fuzz-generation-error MalformedGrammarMachineState (State values))))\n (unify $frames\n (GF (FBind (quote $sort) $binding-id $variable) $parent)\n (unify $values\n (FuzzStack $body $rest-values)\n (unify $trees\n (FuzzStack $tree $rest-trees)\n (let $bound (_fuzz-expression-append ($variable) $body)\n (_fuzz-gen-push\n $source $parent $rest-values (- $vd 1) $rest-trees (- $td 1) $scope $next-id $driver\n $bound\n (Decision\n GrammarBind\n (Sort (quote $sort))\n (BindingId $binding-id)\n ($tree))))\n (FuzzGenDone (_fuzz-generation-error MalformedGrammarMachineState (State trees))))\n (FuzzGenDone (_fuzz-generation-error MalformedGrammarMachineState (State values))))\n (unify $frames\n (GF (FScoped $added) $parent)\n (unify $values\n (FuzzStack $value $rest-values)\n (unify $trees\n (FuzzStack $tree $rest-trees)\n (_fuzz-gen-push\n $source $parent $rest-values (- $vd 1) $rest-trees (- $td 1) $scope $next-id $driver\n $value\n (Decision GrammarScoped (Bindings $added) () ($tree)))\n (FuzzGenDone (_fuzz-generation-error MalformedGrammarMachineState (State trees))))\n (FuzzGenDone (_fuzz-generation-error MalformedGrammarMachineState (State values))))\n (unify $frames\n (GF (FScope $saved) $parent)\n (FuzzGenRun $source $parent $values $vd $trees $td $saved $next-id $driver)\n (unify $frames\n GFB\n (unify $values\n (FuzzStack $value FuzzStackBottom)\n (unify $trees\n (FuzzStack $tree FuzzStackBottom)\n (FuzzGenDone (GrammarResult $value $driver $next-id $tree))\n (FuzzGenDone (_fuzz-generation-error MalformedGrammarMachineState (State trees))))\n (FuzzGenDone (_fuzz-generation-error MalformedGrammarMachineState (State values))))\n (FuzzGenDone\n (_fuzz-generation-error\n MalformedGrammarMachineState\n (Frames $frames)))))))))))\n\n(= (_fuzz-gen-instr\n $source $frames $values $vd $trees $td $scope $next-id $driver\n $instr\n $size)\n (_fuzz-grammar-template-switch $instr\n (((GILit (quote $value))\n (_fuzz-gen-push\n $source $frames $values $vd $trees $td $scope $next-id $driver\n $value\n (Decision GrammarLiteral () (Value (quote $value)) ())))\n ((GIField $generator)\n (let $sample (fuzz-generate $generator $driver $size)\n (_fuzz-gen-field\n $source $frames $values $vd $trees $td $scope $next-id $driver\n $generator\n $sample)))\n ((GIRef (quote $target) $ordinal $total)\n (if (> $size 0)\n (let $child-size\n (_fuzz-grammar-reference-size $size $ordinal $total)\n (unify $child-size\n (FuzzGenerationError $code $details)\n (FuzzGenDone $child-size)\n (_fuzz-gen-nonterminal\n $source\n (GF (FRef (quote $target)) $frames)\n $values $vd $trees $td $scope $next-id $driver\n (quote $target)\n $child-size)))\n (FuzzGenDone\n (_fuzz-generation-error\n GrammarDepthExhausted\n (Target (quote $target))\n (Size $size)))))\n ((GIFresh (quote $sort))\n (let $variable (_fuzz-variable-marker $next-id)\n (_fuzz-gen-push\n $source $frames $values $vd $trees $td $scope (+ $next-id 1) $driver\n $variable\n (Decision GrammarFresh (Sort (quote $sort)) (BindingId $next-id) ()))))\n ((GIUse (quote $sort))\n (let $choices (_fuzz-grammar-scope-values $scope $sort ())\n (if (> (length $choices) 0)\n (let $sample (fuzz-generate (gen-element $choices) $driver $size)\n (_fuzz-gen-use\n $source $frames $values $vd $trees $td $scope $next-id\n (quote $sort)\n $sample))\n (FuzzGenDone\n (_fuzz-generation-error\n UnboundGrammarUse\n (Sort (quote $sort)))))))\n ((GIBind (quote $sort) $body)\n (let $variable (_fuzz-variable-marker $next-id)\n (let $body-length (length $body)\n (let $bound-scope (cons-atom (GrammarBinding (quote $sort) $next-id) $scope)\n (FuzzGenRun\n $source\n (GF (FPlan $body $body-length 0 $size)\n (GF (FBind (quote $sort) $next-id $variable)\n (GF (FScope $scope) $frames)))\n $values $vd $trees $td\n $bound-scope\n (+ $next-id 1)\n $driver)))))\n ((GIScoped $added $minimum-next-id (quote $raw) $body)\n (if (_fuzz-grammar-scopes-disjoint $added $scope)\n (let $body-length (length $body)\n (let $bound-scope (_fuzz-expression-concat $added $scope)\n (FuzzGenRun\n $source\n (GF (FPlan $body $body-length 0 $size)\n (GF (FScoped $added)\n (GF (FScope $scope) $frames)))\n $values $vd $trees $td\n $bound-scope\n (max $next-id $minimum-next-id)\n $driver)))\n (FuzzGenDone\n (_fuzz-generation-error\n DuplicateGrammarBindingId\n (Bindings $raw)))))\n ((GIExprEnter $arity)\n (let $entered (_fuzz-gen-insert-expr $frames $arity $vd $td)\n (FuzzGenRun\n $source\n $entered\n $values $vd $trees $td $scope $next-id $driver)))\n ((GIExprBuild)\n (unify $frames\n (GF (FPlan $instrs $len $cursor $size2) (GF (FExpr $arity $svd $std) $parent))\n (let $taken-values (_fuzz-stack-take $values $arity)\n (unify $taken-values\n (FuzzStackTake $value-list $rest-values)\n (let $taken-trees (_fuzz-stack-take $trees $arity)\n (unify $taken-trees\n (FuzzStackTake $tree-list $rest-trees)\n (_fuzz-gen-push\n $source\n (GF (FPlan $instrs $len $cursor $size2) $parent)\n $rest-values (- $vd $arity) $rest-trees (- $td $arity) $scope $next-id $driver\n $value-list\n (Decision GrammarExpression (Arity $arity) () $tree-list))\n (FuzzGenDone\n (_fuzz-generation-error\n KernelError\n (OperationResult $taken-trees)))))\n (FuzzGenDone\n (_fuzz-generation-error\n KernelError\n (OperationResult $taken-values)))))\n (FuzzGenDone\n (_fuzz-generation-error\n MalformedGrammarMachineState\n (Frames $frames)))))\n ($bad\n (FuzzGenDone\n (_fuzz-generation-error\n MalformedGrammarInstruction\n (Value $bad)))))))\n\n; GIExprEnter runs from inside the plan frame, so the expression frame is inserted below it.\n(= (_fuzz-gen-insert-expr $frames $arity $vd $td)\n (unify $frames\n (GF $top $parent)\n (GF $top (GF (FExpr $arity $vd $td) $parent))\n $frames))\n\n(= (_fuzz-gen-field\n $source $frames $values $vd $trees $td $scope $next-id $driver\n $generator\n $sample)\n (unify $sample\n (FuzzSample $value $next-driver $tree)\n (if (_fuzz-contains-variable-marker $value)\n (FuzzGenDone\n (_fuzz-generation-error\n ForgedGrammarVariableMarker\n (Generator $generator)\n (Value $value)))\n (_fuzz-gen-push\n $source $frames $values $vd $trees $td $scope $next-id $next-driver\n $value\n (Decision GrammarField (Generator $generator) () ($tree))))\n (unify $sample\n (FuzzGenerationDiscard $reason $next-driver $tree)\n (FuzzGenCut\n $source $frames $values $vd $trees $td\n $reason\n (Decision GrammarField (Generator $generator) () ($tree))\n $next-driver)\n (unify $sample\n (FuzzGenerationError $code $details)\n (FuzzGenDone $sample)\n (unify $sample\n $bad\n (FuzzGenDone\n (_fuzz-generation-error\n MalformedGrammarFieldResult\n (Generator $generator)\n (Value $bad)))\n Empty)))))\n\n(= (_fuzz-gen-use\n $source $frames $values $vd $trees $td $scope $next-id\n (quote $sort)\n $sample)\n (unify $sample\n (FuzzSample $value $next-driver $tree)\n (_fuzz-gen-push\n $source $frames $values $vd $trees $td $scope $next-id $next-driver\n $value\n (Decision GrammarUse (Sort (quote $sort)) () ($tree)))\n (unify $sample\n (FuzzGenerationError $code $details)\n (FuzzGenDone $sample)\n (unify $sample\n $bad\n (FuzzGenDone\n (_fuzz-generation-error\n MalformedGrammarUseResult\n (Sort (quote $sort))\n (Value $bad)))\n Empty))))\n\n(= (_fuzz-gen-nonterminal\n $source $frames $values $vd $trees $td $scope $next-id $driver\n (quote $target)\n $size)\n (let $eligible\n (_fuzz-eligible-productions\n $source\n (quote $target)\n $scope\n $size)\n (unify $eligible\n (EligibleGrammarProductions $productions)\n (if (> (length $productions) 0)\n (let $choice (_fuzz-grammar-production-choice $driver $productions)\n (_fuzz-gen-choose\n $source $frames $values $vd $trees $td $scope $next-id\n (quote $target)\n $size\n $productions\n $choice))\n (FuzzGenCut\n $source $frames $values $vd $trees $td\n (NoEligibleGrammarProduction\n (Target (quote $target))\n (Size $size))\n (Decision\n GrammarUnavailable\n (Target (quote $target))\n (Size $size)\n ())\n $driver))\n (unify $eligible\n (FuzzGenerationError $code $details)\n (FuzzGenDone $eligible)\n (FuzzGenDone\n (_fuzz-generation-error\n MalformedEligibleGrammarProductions\n (Target (quote $target))\n (Value $eligible)))))))\n\n(= (_fuzz-gen-choose\n $source $frames $values $vd $trees $td $scope $next-id\n (quote $target)\n $size\n $productions\n $choice)\n (unify $choice\n (DriverChoice $position $next-driver $choice-tree)\n (if (and (<= 0 $position) (< $position (length $productions)))\n (let $production (index-atom $productions $position)\n (_fuzz-grammar-template-switch $production\n (((GrammarProduction\n $production-index\n $weight\n (quote $seen-target)\n (quote $template))\n (let $planned (_fuzz-grammar-template-plan $template)\n (unify $planned\n (GrammarTemplatePlan $instrs)\n (let $plan-length (length $instrs)\n (FuzzGenRun\n $source\n (GF (FPlan $instrs $plan-length 0 $size)\n (GF (FProd (quote $target) $production-index $position $choice-tree)\n $frames))\n $values $vd $trees $td $scope $next-id $next-driver))\n (unify $planned\n (FuzzKernelError $code $details)\n (FuzzGenDone\n (_fuzz-generation-error\n KernelError\n (OperationResult $planned)))\n (FuzzGenDone\n (_fuzz-generation-error\n MalformedGrammarTemplatePlan\n (Value $planned)))))))\n ($bad\n (FuzzGenDone\n (_fuzz-generation-error\n MalformedSelectedGrammarProduction\n (Target (quote $target))\n (Production $bad)))))))\n (FuzzGenDone\n (_fuzz-generation-error\n GrammarProductionIndexOutOfBounds\n (Target (quote $target))\n (Position $position))))\n (unify $choice\n (FuzzGenerationError $code $details)\n (FuzzGenDone $choice)\n (FuzzGenDone\n (_fuzz-generation-error\n MalformedGrammarProductionChoice\n (Target (quote $target))\n (Value $choice))))))\n\n(= (_fuzz-gen-cut-step\n $source $frames $values $vd $trees $td $reason $tree $driver)\n (unify $frames\n (GF (FPlan $instrs $len $cursor $size) $parent)\n (FuzzGenCut $source $parent $values $vd $trees $td $reason $tree $driver)\n (unify $frames\n (GF (FExpr $arity $svd $std) $parent)\n (let $generated (- $td $std)\n (let $taken-trees (_fuzz-stack-take $trees $generated)\n (unify $taken-trees\n (FuzzStackTake $tree-list $rest-trees)\n (let $taken-values (_fuzz-stack-take $values $generated)\n (unify $taken-values\n (FuzzStackTake $value-list $rest-values)\n (let $partial (_fuzz-expression-append $tree-list $tree)\n (FuzzGenCut\n $source $parent $rest-values $svd $rest-trees $std\n $reason\n (Decision\n GrammarExpression\n (Arity $arity)\n (Generated (+ $generated 1))\n $partial)\n $driver))\n (FuzzGenDone\n (_fuzz-generation-error\n KernelError\n (OperationResult $taken-values)))))\n (FuzzGenDone\n (_fuzz-generation-error\n KernelError\n (OperationResult $taken-trees))))))\n (unify $frames\n (GF (FRef (quote $target)) $parent)\n (FuzzGenCut\n $source $parent $values $vd $trees $td\n $reason\n (Decision GrammarRef (Target (quote $target)) () ($tree))\n $driver)\n (unify $frames\n (GF (FProd (quote $target) $production-index $position $choice-tree) $parent)\n (let $children (_fuzz-two-children $choice-tree $tree)\n (FuzzGenCut\n $source $parent $values $vd $trees $td\n $reason\n (Decision\n GrammarProduction\n (Target (quote $target))\n (ProductionIndex $production-index $position)\n $children)\n $driver))\n (unify $frames\n (GF (FBind (quote $sort) $binding-id $variable) $parent)\n (FuzzGenCut\n $source $parent $values $vd $trees $td\n $reason\n (Decision GrammarBind (Sort (quote $sort)) (BindingId $binding-id) ($tree))\n $driver)\n (unify $frames\n (GF (FScoped $added) $parent)\n (FuzzGenCut\n $source $parent $values $vd $trees $td\n $reason\n (Decision GrammarScoped (Bindings $added) () ($tree))\n $driver)\n (unify $frames\n (GF (FScope $saved) $parent)\n (FuzzGenCut $source $parent $values $vd $trees $td $reason $tree $driver)\n (unify $frames\n GFB\n (FuzzGenDone (FuzzGenerationDiscard $reason $driver $tree))\n (FuzzGenDone\n (_fuzz-generation-error\n MalformedGrammarMachineState\n (Frames $frames))))))))))))\n\n; The default generation path: start the kernel machine, and serve each of its effect\n; requests with `fuzz-generate`, so user Field callbacks, custom generators, and the whole\n; generator algebra stay ordinary MeTTa. The specification machine above remains callable\n; through `_fuzz-generate-grammar-nonterminal-reference`, and a differential test drives\n; both against identical drivers.\n(= (_fuzz-gen-trampoline $outcome)\n (unify $outcome\n (GrammarMachineDone $result)\n $result\n (unify $outcome\n (GrammarMachineNeed $suspended (EvaluateGenerator $generator $driver $sub-size))\n (let $descriptor $generator\n (let $sample (fuzz-generate $descriptor $driver $sub-size)\n (_fuzz-gen-trampoline\n (_fuzz-grammar-machine-op\n (GrammarMachineResume $suspended $sample)))))\n (unify $outcome\n $bad\n (_fuzz-generation-error\n MalformedGrammarMachineOutcome\n (Value $bad))\n Empty))))\n\n(= (_fuzz-generate-grammar-nonterminal\n $source\n (quote $target)\n $scope\n $next-id\n $driver\n $size)\n (_fuzz-gen-trampoline\n (_fuzz-grammar-machine-op\n (GrammarMachineStart\n $source\n (quote $target)\n $scope\n $next-id\n (WithDriver $driver $size)))))\n\n(= (_fuzz-generate-grammar-nonterminal-reference\n $source\n (quote $target)\n $scope\n $next-id\n $driver\n $size)\n (let $settled\n (_fuzz-gen-loop\n (_fuzz-gen-nonterminal\n $source\n GFB\n FuzzStackBottom\n 0\n FuzzStackBottom\n 0\n $scope\n $next-id\n $driver\n (quote $target)\n $size))\n (unify $settled\n (FuzzGenDone $result)\n $result\n (_fuzz-generation-error\n MalformedGrammarMachineState\n (Value $settled)))))\n\n(= (_fuzz-drive-grammar-result\n $result)\n (unify $result\n (GrammarResult $value $next-driver $next-id $tree)\n (FuzzSample $value $next-driver $tree)\n (unify $result\n (FuzzGenerationDiscard $reason $next-driver $tree)\n $result\n (unify $result\n (FuzzGenerationError $code $details)\n $result\n (unify $result\n $bad\n (_fuzz-generation-error\n MalformedGrammarGenerationResult\n (Value $bad))\n Empty)))))\n\n(= (CustomCapabilities\n _fuzz-grammar\n (GrammarRequest\n $source\n (quote $target)\n $scope\n $next-id))\n (FuzzCustomCapabilities\n (Modes\n (Random\n Edge\n Replay\n ShrinkReplay\n Exhaustive\n Bytes))))\n\n(= (DriveCustom\n _fuzz-grammar\n (GrammarRequest\n $source\n (quote $target)\n $scope\n $next-id)\n $driver\n $size)\n (_fuzz-drive-grammar-result\n (_fuzz-generate-grammar-nonterminal\n $source\n (quote $target)\n $scope\n $next-id\n $driver\n $size)))\n\n; SPDX-FileCopyrightText: 2026 MesTTo\n;\n; SPDX-License-Identifier: MIT\n\n(= (_fuzz-case-observation $case)\n (switch $case\n (((FuzzCaseResult\n $status\n $tag\n $details\n $labels\n $collected\n $coverage\n $annotations\n (Results $results)\n $steps)\n (FuzzCaseObservation $status $tag $results))\n ($bad\n (FuzzCaseObservation\n Malformed\n MalformedCaseResult\n ($bad))))))\n\n(= (_fuzz-strict-replay-case\n $probe\n $generator\n $property\n $quantifier\n $decision\n $size\n $config)\n (let $replayed (fuzz-replay $generator $decision $size)\n (switch $replayed\n (((FuzzSample $value $driver $actual-tree)\n (let $case\n (_fuzz-evaluate-property\n $property\n $quantifier\n $value\n (_fuzz-config-get CaseSteps $config)\n (_fuzz-config-get CaseDepth $config)\n (_fuzz-config-get EffectPolicy $config))\n (FuzzReplayEvaluation\n $probe\n $value\n $actual-tree\n $case)))\n ((FuzzGenerationDiscard $reason $driver $actual-tree)\n (FuzzReplayProblem\n $probe\n GenerationDiscard\n (Reason $reason)\n (DecisionTree $actual-tree)))\n ((FuzzGenerationError $code $details)\n (FuzzReplayProblem\n $probe\n GenerationError\n (ErrorCode $code)\n $details))\n ($bad\n (FuzzReplayProblem\n $probe\n MalformedReplayResult\n (Value $bad)))))))\n\n(= (_fuzz-replay-matches\n $expected-value\n $expected-tree\n $expected-case\n $replayed)\n (switch $replayed\n (((FuzzReplayEvaluation\n $probe\n $actual-value\n $actual-tree\n $actual-case)\n (and\n (_fuzz-replay-equal $expected-value $actual-value)\n (and\n (_fuzz-replay-equal $expected-tree $actual-tree)\n (_fuzz-replay-equal\n (_fuzz-case-observation $expected-case)\n (_fuzz-case-observation $actual-case)))))\n ($bad False))))\n\n(= (_fuzz-stability-check\n $stage\n $generator\n $property\n $quantifier\n $value\n $decision\n $case\n $size\n $config)\n (let $first\n (_fuzz-strict-replay-case\n (Probe $stage 1)\n $generator\n $property\n $quantifier\n $decision\n $size\n $config)\n (let $second\n (_fuzz-strict-replay-case\n (Probe $stage 2)\n $generator\n $property\n $quantifier\n $decision\n $size\n $config)\n (if (and\n (_fuzz-replay-matches\n $value\n $decision\n $case\n $first)\n (_fuzz-replay-matches\n $value\n $decision\n $case\n $second))\n (FuzzStable $first $second)\n (FuzzUnstable\n (Stage $stage)\n (ExpectedValue $value)\n (ExpectedDecision $decision)\n (ExpectedCase\n (_fuzz-case-observation $case))\n (First $first)\n (Second $second))))))\n\n(= (_fuzz-shrink-case-acceptable\n $expected-signature\n $failure-mode\n $case)\n (switch $case\n (((FuzzCaseResult\n Fail\n $tag\n $details\n $labels\n $collected\n $coverage\n $annotations\n $results\n $steps)\n (if (== $failure-mode AnyFailure)\n True\n (if (== $failure-mode SameFailureTag)\n (==\n $expected-signature\n (_fuzz-failure-signature $tag))\n False)))\n ($bad False))))\n\n(= (_fuzz-shrink-add-visited $tree $visited)\n (let $combined\n (append $visited (cons-atom $tree ()))\n (_fuzz-deduplicate-replay $combined)))\n\n; The shrink order (mettascript-shrink-v1): shortlex over the flattened decision leaves \u2014 fewer\n; decisions first, then lexicographically smaller origin-distances. The runner accepts a reproducing\n; candidate only when its canonical tree is strictly smaller under this order, so no candidate\n; source (a built-in shrinker or a custom ShrinkChoices relation) can re-inflate an accepted\n; counterexample through the lenient shrink replay.\n(= (_fuzz-leaf-distance $leaf)\n (unify $leaf\n (Decision Int (Bounds $lower $upper) (Origin $origin) (Value $value) ())\n (abs-math (- $value $origin))\n 0))\n\n; Flat accumulator: a decision tree carries one leaf per drawn decision, so a large machine run\n; would nest an evaluator frame per leaf under recurse-then-cons.\n(= (_fuzz-leaf-distances $leaves)\n (_fuzz-leaf-distances-loop (FuzzLeafDistanceFold $leaves ())))\n\n(= (_fuzz-leaf-distances-loop $state)\n (if (_fuzz-leaf-distances-finished $state)\n $state\n (_fuzz-leaf-distances-loop (_fuzz-leaf-distances-step $state))))\n\n(= (_fuzz-leaf-distances-finished $state)\n (unify $state (FuzzLeafDistanceFold $leaves $reversed) False True))\n\n(= (_fuzz-leaf-distances-step $state)\n (unify $state\n (FuzzLeafDistanceFold $leaves $reversed)\n (if (== $leaves ())\n (reverse $reversed)\n (let ($head $tail) (decons-atom $leaves)\n (let $distance (_fuzz-leaf-distance $head)\n (let $next (cons-atom $distance $reversed)\n (FuzzLeafDistanceFold $tail $next)))))\n $state))\n\n(= (_fuzz-distances-less $first $second)\n (if (== $first ())\n False\n (let ($first-head $first-tail) (decons-atom $first)\n (let ($second-head $second-tail) (decons-atom $second)\n (if (< $first-head $second-head)\n True\n (if (> $first-head $second-head)\n False\n (_fuzz-distances-less $first-tail $second-tail)))))))\n\n(= (_fuzz-tree-strictly-smaller $candidate-tree $target-tree)\n (let $candidate-leaves (_fuzz-decision-leaves-op $candidate-tree)\n (let $target-leaves (_fuzz-decision-leaves-op $target-tree)\n (unify $candidate-leaves\n (FuzzDecisionLeaves $candidate-flat)\n (unify $target-leaves\n (FuzzDecisionLeaves $target-flat)\n (let $candidate-count (length $candidate-flat)\n (let $target-count (length $target-flat)\n (if (< $candidate-count $target-count)\n True\n (if (> $candidate-count $target-count)\n False\n (_fuzz-distances-less\n (_fuzz-leaf-distances $candidate-flat)\n (_fuzz-leaf-distances $target-flat))))))\n False)\n False))))\n\n(= (_fuzz-shrink-finish\n $status\n (FuzzShrinkTarget $value $tree $case)\n (FuzzShrinkProgress\n $attempts\n $improvements\n $visited))\n (FuzzShrinkResult\n $status\n $attempts\n $improvements\n $value\n $tree\n $case))\n\n(= (_fuzz-shrink-start\n $context\n (FuzzShrinkTarget $value $tree $case)\n $progress)\n (let $candidates (_fuzz-shrink-candidates $tree)\n (switch $candidates\n (((FuzzKernelError $code $details)\n (FuzzShrinkError\n CandidateGenerationFailed\n (ErrorCode $code)\n $details\n $progress))\n ($valid\n (_fuzz-shrink-search\n (Candidates $valid)\n $context\n (FuzzShrinkTarget $value $tree $case)\n $progress))))))\n\n(= (_fuzz-shrink-search\n (Candidates $remaining)\n (FuzzShrinkContext\n $generator\n $property\n $quantifier\n $size\n $config\n $expected-signature)\n $target\n (FuzzShrinkProgress\n $attempts\n $improvements\n $visited))\n (if (== $remaining ())\n (_fuzz-shrink-finish\n LocallyMinimal\n $target\n (FuzzShrinkProgress\n $attempts\n $improvements\n $visited))\n (if (>=\n $attempts\n (_fuzz-config-get MaxShrinks $config))\n (_fuzz-shrink-finish\n MaxShrinksReached\n $target\n (FuzzShrinkProgress\n $attempts\n $improvements\n $visited))\n (if (>=\n $improvements\n (_fuzz-config-get\n MaxShrinkImprovements\n $config))\n (_fuzz-shrink-finish\n MaxShrinkImprovementsReached\n $target\n (FuzzShrinkProgress\n $attempts\n $improvements\n $visited))\n (let ($candidate $tail)\n (decons-atom $remaining)\n (_fuzz-shrink-consider\n $candidate\n $tail\n (FuzzShrinkContext\n $generator\n $property\n $quantifier\n $size\n $config\n $expected-signature)\n $target\n (FuzzShrinkProgress\n $attempts\n $improvements\n $visited)))))))\n\n(= (_fuzz-shrink-consider\n $candidate\n $remaining\n $context\n $target\n (FuzzShrinkProgress\n $attempts\n $improvements\n $visited))\n (let $seen (_fuzz-replay-member $candidate $visited)\n (_fuzz-shrink-consider-seen\n $seen\n $candidate\n $remaining\n $context\n $target\n (FuzzShrinkProgress\n $attempts\n $improvements\n $visited))))\n\n(= (_fuzz-shrink-consider-seen\n True\n $candidate\n $remaining\n $context\n $target\n $progress)\n (_fuzz-shrink-search\n (Candidates $remaining)\n $context\n $target\n $progress))\n\n(= (_fuzz-shrink-consider-seen\n False\n $candidate\n $remaining\n (FuzzShrinkContext\n $generator\n $property\n $quantifier\n $size\n $config\n $expected-signature)\n $target\n (FuzzShrinkProgress\n $attempts\n $improvements\n $visited))\n (let $candidate-visited\n (_fuzz-shrink-add-visited $candidate $visited)\n (let $replayed\n (_fuzz-shrink-replay\n $generator\n $candidate\n $size)\n (_fuzz-shrink-consider-replay\n $replayed\n $remaining\n (FuzzShrinkContext\n $generator\n $property\n $quantifier\n $size\n $config\n $expected-signature)\n $target\n (FuzzShrinkProgress\n $attempts\n $improvements\n $candidate-visited)\n $visited))))\n\n(= (_fuzz-shrink-consider-seen\n (FuzzKernelError $code $details)\n $candidate\n $remaining\n $context\n $target\n $progress)\n (FuzzShrinkError\n VisitedTreeLookupFailed\n (ErrorCode $code)\n $details\n $progress))\n\n(= (_fuzz-shrink-consider-replay\n (FuzzShrinkReplay $value $actual-tree)\n $remaining\n $context\n $target\n $progress\n $previously-visited)\n (_fuzz-shrink-consider-actual\n $value\n $actual-tree\n $remaining\n $context\n $target\n $progress\n $previously-visited))\n\n(= (_fuzz-shrink-consider-replay\n (FuzzShrinkDiscard $reason $actual-tree)\n $remaining\n $context\n $target\n $progress\n $previously-visited)\n (_fuzz-shrink-search\n (Candidates $remaining)\n $context\n $target\n $progress))\n\n(= (_fuzz-shrink-consider-replay\n (FuzzGenerationError $code $details)\n $remaining\n $context\n $target\n $progress\n $previously-visited)\n (_fuzz-shrink-search\n (Candidates $remaining)\n $context\n $target\n $progress))\n\n(= (_fuzz-shrink-consider-actual\n $value\n $actual-tree\n $remaining\n $context\n $target\n $progress\n $previously-visited)\n (let $seen\n (_fuzz-replay-member\n $actual-tree\n $previously-visited)\n (_fuzz-shrink-consider-actual-seen\n $seen\n $value\n $actual-tree\n $remaining\n $context\n $target\n $progress)))\n\n(= (_fuzz-shrink-consider-actual-seen\n True\n $value\n $actual-tree\n $remaining\n $context\n $target\n $progress)\n (_fuzz-shrink-search\n (Candidates $remaining)\n $context\n $target\n $progress))\n\n(= (_fuzz-shrink-consider-actual-seen\n False\n $value\n $actual-tree\n $remaining\n (FuzzShrinkContext\n $generator\n $property\n $quantifier\n $size\n $config\n $expected-signature)\n $target\n (FuzzShrinkProgress\n $attempts\n $improvements\n $visited))\n (let $actual-visited\n (_fuzz-shrink-add-visited\n $actual-tree\n $visited)\n (let $case\n (_fuzz-evaluate-property\n $property\n $quantifier\n $value\n (_fuzz-config-get CaseSteps $config)\n (_fuzz-config-get CaseDepth $config)\n (_fuzz-config-get EffectPolicy $config))\n (let $next-progress\n (FuzzShrinkProgress\n (+ $attempts 1)\n $improvements\n $actual-visited)\n (if (and\n (_fuzz-shrink-case-acceptable\n $expected-signature\n (_fuzz-config-get FailureMode $config)\n $case)\n (unify $target\n (FuzzShrinkTarget $target-value $target-tree $target-case)\n (_fuzz-tree-strictly-smaller $actual-tree $target-tree)\n False))\n (_fuzz-shrink-start\n (FuzzShrinkContext\n $generator\n $property\n $quantifier\n $size\n $config\n $expected-signature)\n (FuzzShrinkTarget\n $value\n $actual-tree\n $case)\n (FuzzShrinkProgress\n (+ $attempts 1)\n (+ $improvements 1)\n $actual-visited))\n (_fuzz-shrink-search\n (Candidates $remaining)\n (FuzzShrinkContext\n $generator\n $property\n $quantifier\n $size\n $config\n $expected-signature)\n $target\n $next-progress))))))\n\n(= (_fuzz-shrink-consider-actual-seen\n (FuzzKernelError $code $details)\n $value\n $actual-tree\n $remaining\n $context\n $target\n $progress)\n (FuzzShrinkError\n VisitedTreeLookupFailed\n (ErrorCode $code)\n $details\n $progress))\n\n(= (_fuzz-run-shrinker\n $generator\n $property\n $quantifier\n $value\n $decision\n $case\n $size\n $config\n $signature)\n (_fuzz-shrink-start\n (FuzzShrinkContext\n $generator\n $property\n $quantifier\n $size\n $config\n $signature)\n (FuzzShrinkTarget $value $decision $case)\n (FuzzShrinkProgress\n 0\n 0\n (cons-atom $decision ()))))\n\n(= (_fuzz-shrink-claim $status $reason)\n (switch $status\n ((LocallyMinimal\n (LocallyMinimalUnder\n (Order mettascript-shrink-v1)))\n (Disabled\n (NotShrunk (Reason $reason)))\n ($stopped\n (SmallestFoundUnder\n (Order mettascript-shrink-v1)\n (StoppedBy $stopped))))))\n\n(= (_fuzz-replay-record\n $generator\n $origin\n $decision\n $value)\n (let $generator-key\n (_fuzz-atom-key Replay $generator)\n (switch $generator-key\n (((FuzzKernelError $code $details)\n (FuzzReplayUnavailable\n (Stage Generator)\n (Error $code $details)))\n ($key\n (let $encoded-decision\n (_fuzz-encode-atom $decision)\n (switch $encoded-decision\n (((FuzzKernelError $code $details)\n (FuzzReplayUnavailable\n (Stage DecisionTree)\n (Error $code $details)))\n ($decision-codec\n (let $encoded-value\n (_fuzz-encode-atom $value)\n (switch $encoded-value\n (((FuzzKernelError $code $details)\n (FuzzReplayUnavailable\n (Stage ConcreteValue)\n (Error $code $details)))\n ($value-codec\n (FuzzReplay\n (Format 2)\n (Origin $origin)\n (GeneratorKey $key)\n (DecisionTree $decision)\n (EncodedDecisionTree $decision-codec)\n (ConcreteValue $value)\n (EncodedValue $value-codec)))))))))))))))\n\n(= (_fuzz-build-failure\n (FuzzFailureContext\n $property-id\n $generator\n $property\n $quantifier\n $phase\n $case-index\n $origin\n $size\n $original-value\n $original-decision\n (FuzzCaseResult\n Fail\n $original-tag\n $original-details\n $original-labels\n $original-collected\n $original-coverage\n $original-annotations\n (Results $original-results)\n $original-steps)\n $config\n $state\n $original-signature)\n (FuzzShrinkTarget\n $smallest-value\n $smallest-decision\n (FuzzCaseResult\n Fail\n $smallest-tag\n $smallest-details\n $smallest-labels\n $smallest-collected\n $smallest-coverage\n $smallest-annotations\n (Results $smallest-results)\n $smallest-steps))\n (FuzzShrinkSummary\n $status\n $reason\n $attempts\n $accepted))\n (FuzzFailed\n (Property $property-id)\n (Phase $phase)\n (CaseIndex $case-index)\n (FailureTag $smallest-tag)\n (FailureSignature\n (_fuzz-failure-signature $smallest-tag))\n (OriginalFailureTag $original-tag)\n (OriginalFailureSignature $original-signature)\n (OriginalValue $original-value)\n (OriginalDecision $original-decision)\n (OriginalDetails $original-details)\n (OriginalLabels $original-labels)\n (OriginalCollected $original-collected)\n (OriginalCoverage $original-coverage)\n (OriginalAnnotations $original-annotations)\n (OriginalPropertyResults $original-results)\n (SmallestValue $smallest-value)\n (SmallestDecision $smallest-decision)\n (SmallestDetails $smallest-details)\n (SmallestLabels $smallest-labels)\n (SmallestCollected $smallest-collected)\n (SmallestCoverage $smallest-coverage)\n (SmallestAnnotations $smallest-annotations)\n (PropertyResults $smallest-results)\n (Replay\n (_fuzz-failure-replay-record\n $generator\n $origin\n $smallest-decision\n $smallest-value\n (FuzzCaseResult\n Fail\n $smallest-tag\n $smallest-details\n $smallest-labels\n $smallest-collected\n $smallest-coverage\n $smallest-annotations\n (Results $smallest-results)\n $smallest-steps)))\n (Shrink\n (Order mettascript-shrink-v1)\n (Status $status)\n (Reason $reason)\n (Attempts $attempts)\n (Accepted $accepted)\n (_fuzz-shrink-claim $status $reason))\n (_fuzz-run-statistics $state)))\n\n(= (_fuzz-build-flaky\n (FuzzFailureContext\n $property-id\n $generator\n $property\n $quantifier\n $phase\n $case-index\n $origin\n $size\n $original-value\n $original-decision\n $original-case\n $config\n $state\n $signature)\n $unstable\n (FuzzShrinkSummary\n $status\n $reason\n $attempts\n $accepted))\n (FuzzFlaky\n (Property $property-id)\n (Phase $phase)\n (CaseIndex $case-index)\n (Origin $origin)\n (OriginalValue $original-value)\n (OriginalDecision $original-decision)\n (OriginalCase\n (_fuzz-case-observation $original-case))\n $unstable\n (Shrink\n (Order mettascript-shrink-v1)\n (Status $status)\n (Reason $reason)\n (Attempts $attempts)\n (Accepted $accepted))\n (_fuzz-run-statistics $state)))\n\n(= (_fuzz-failure-replay-record\n $generator\n $origin\n $decision\n $value\n $case)\n (let $record\n (_fuzz-replay-record\n $generator\n $origin\n $decision\n $value)\n (switch $record\n (((FuzzReplayUnavailable $stage $error) $record)\n ($available\n (let $encoded-observation\n (_fuzz-encode-atom\n (_fuzz-case-observation $case))\n (switch $encoded-observation\n (((FuzzKernelError $code $details)\n (FuzzReplayUnavailable\n (Stage PropertyObservation)\n (Error $code $details)))\n ($encoded $record)))))))))\n\n(= (_fuzz-failure-replayability\n $generator\n $origin\n $decision\n $value\n $case)\n (let $record\n (_fuzz-failure-replay-record\n $generator\n $origin\n $decision\n $value\n $case)\n (switch $record\n (((FuzzReplayUnavailable $stage $error) $record)\n ($available (FuzzReplayReady))))))\n\n(= (_fuzz-failure-target\n (FuzzFailureContext\n $property-id\n $generator\n $property\n $quantifier\n $phase\n $case-index\n $origin\n $size\n $value\n $decision\n $case\n $config\n $state\n $signature))\n (FuzzShrinkTarget $value $decision $case))\n\n(= (_fuzz-start-stability-check\n (FuzzFailureContext\n $property-id\n $generator\n $property\n $quantifier\n $phase\n $case-index\n $origin\n $size\n $value\n $decision\n $case\n $config\n $state\n $signature))\n (let $stability\n (_fuzz-stability-check\n PreShrink\n $generator\n $property\n $quantifier\n $value\n $decision\n $case\n $size\n $config)\n (_fuzz-after-pre-stability\n $stability\n (FuzzFailureContext\n $property-id\n $generator\n $property\n $quantifier\n $phase\n $case-index\n $origin\n $size\n $value\n $decision\n $case\n $config\n $state\n $signature))))\n\n(= (_fuzz-start-replayability\n (FuzzReplayUnavailable $stage $error)\n $context)\n (_fuzz-build-failure\n $context\n (_fuzz-failure-target $context)\n (FuzzShrinkSummary\n Disabled\n (ReplayUnavailable $stage $error)\n 0\n 0)))\n\n(= (_fuzz-start-replayability\n (FuzzReplayReady)\n $context)\n (_fuzz-start-stability-check $context))\n\n(= (_fuzz-start-failure-processing\n (FuzzFailureContext\n $property-id\n $generator\n $property\n $quantifier\n $phase\n $case-index\n $origin\n $size\n $value\n $decision\n $case\n $config\n $state\n $signature))\n (if (== (_fuzz-config-get EffectPolicy $config)\n ExternalEffects)\n (_fuzz-build-failure\n (FuzzFailureContext\n $property-id\n $generator\n $property\n $quantifier\n $phase\n $case-index\n $origin\n $size\n $value\n $decision\n $case\n $config\n $state\n $signature)\n (FuzzShrinkTarget $value $decision $case)\n (FuzzShrinkSummary\n Disabled\n ExternalEffectsWithoutReset\n 0\n 0))\n (if (== $decision None)\n (_fuzz-build-failure\n (FuzzFailureContext\n $property-id\n $generator\n $property\n $quantifier\n $phase\n $case-index\n $origin\n $size\n $value\n $decision\n $case\n $config\n $state\n $signature)\n (FuzzShrinkTarget $value $decision $case)\n (FuzzShrinkSummary\n Disabled\n NoDecisionTree\n 0\n 0))\n (if (<= (_fuzz-config-get MaxShrinks $config) 0)\n (_fuzz-build-failure\n (FuzzFailureContext\n $property-id\n $generator\n $property\n $quantifier\n $phase\n $case-index\n $origin\n $size\n $value\n $decision\n $case\n $config\n $state\n $signature)\n (FuzzShrinkTarget $value $decision $case)\n (FuzzShrinkSummary\n Disabled\n MaxShrinksZero\n 0\n 0))\n (_fuzz-start-replayability\n (_fuzz-failure-replayability\n $generator\n $origin\n $decision\n $value\n $case)\n (FuzzFailureContext\n $property-id\n $generator\n $property\n $quantifier\n $phase\n $case-index\n $origin\n $size\n $value\n $decision\n $case\n $config\n $state\n $signature))))))\n\n(= (_fuzz-after-pre-stability\n (FuzzStable $first $second)\n (FuzzFailureContext\n $property-id\n $generator\n $property\n $quantifier\n $phase\n $case-index\n $origin\n $size\n $value\n $decision\n $case\n $config\n $state\n $signature))\n (let $shrunk\n (_fuzz-run-shrinker\n $generator\n $property\n $quantifier\n $value\n $decision\n $case\n $size\n $config\n $signature)\n (_fuzz-after-shrink\n $shrunk\n (FuzzFailureContext\n $property-id\n $generator\n $property\n $quantifier\n $phase\n $case-index\n $origin\n $size\n $value\n $decision\n $case\n $config\n $state\n $signature))))\n\n(= (_fuzz-after-pre-stability\n (FuzzUnstable\n $stage\n $expected-value\n $expected-decision\n $expected-case\n $first\n $second)\n $context)\n (_fuzz-build-flaky\n $context\n (FuzzUnstable\n $stage\n $expected-value\n $expected-decision\n $expected-case\n $first\n $second)\n (FuzzShrinkSummary\n NotStarted\n PreShrinkReplayMismatch\n 0\n 0)))\n\n(= (_fuzz-after-shrink\n (FuzzShrinkResult\n $status\n $attempts\n $accepted\n $value\n $decision\n $case)\n (FuzzFailureContext\n $property-id\n $generator\n $property\n $quantifier\n $phase\n $case-index\n $origin\n $size\n $original-value\n $original-decision\n $original-case\n $config\n $state\n $signature))\n (let $stability\n (_fuzz-stability-check\n PostShrink\n $generator\n $property\n $quantifier\n $value\n $decision\n $case\n $size\n $config)\n (_fuzz-after-post-stability\n $stability\n (FuzzFailureContext\n $property-id\n $generator\n $property\n $quantifier\n $phase\n $case-index\n $origin\n $size\n $original-value\n $original-decision\n $original-case\n $config\n $state\n $signature)\n (FuzzShrinkTarget $value $decision $case)\n (FuzzShrinkSummary\n $status\n None\n $attempts\n $accepted))))\n\n(= (_fuzz-after-shrink\n (FuzzShrinkError\n $code\n $first\n $second\n (FuzzShrinkProgress\n $attempts\n $accepted\n $visited))\n (FuzzFailureContext\n $property-id\n $generator\n $property\n $quantifier\n $phase\n $case-index\n $origin\n $size\n $original-value\n $original-decision\n $original-case\n $config\n $state\n $signature))\n (_fuzz-build-failure\n (FuzzFailureContext\n $property-id\n $generator\n $property\n $quantifier\n $phase\n $case-index\n $origin\n $size\n $original-value\n $original-decision\n $original-case\n $config\n $state\n $signature)\n (FuzzShrinkTarget\n $original-value\n $original-decision\n $original-case)\n (FuzzShrinkSummary\n Error\n (ShrinkError $code $first $second)\n $attempts\n $accepted)))\n\n(= (_fuzz-after-post-stability\n (FuzzStable $first $second)\n $context\n $target\n $summary)\n (_fuzz-build-failure\n $context\n $target\n $summary))\n\n(= (_fuzz-after-post-stability\n (FuzzUnstable\n $stage\n $expected-value\n $expected-decision\n $expected-case\n $first\n $second)\n $context\n $target\n (FuzzShrinkSummary\n $status\n $reason\n $attempts\n $accepted))\n (_fuzz-build-flaky\n $context\n (FuzzUnstable\n $stage\n $expected-value\n $expected-decision\n $expected-case\n $first\n $second)\n (FuzzShrinkSummary\n $status\n PostShrinkReplayMismatch\n $attempts\n $accepted)))\n\n(= (_fuzz-finalize-failure\n $property-id\n $generator\n $property\n $quantifier\n $phase\n $case-index\n $origin\n $size\n $value\n $decision\n (FuzzCaseResult\n Fail\n $tag\n $details\n $labels\n $collected\n $coverage\n $annotations\n $results\n $steps)\n $config\n $state)\n (let $signature (_fuzz-failure-signature $tag)\n (_fuzz-start-failure-processing\n (FuzzFailureContext\n $property-id\n $generator\n $property\n $quantifier\n $phase\n $case-index\n $origin\n $size\n $value\n $decision\n (FuzzCaseResult\n Fail\n $tag\n $details\n $labels\n $collected\n $coverage\n $annotations\n $results\n $steps)\n $config\n $state\n $signature))))\n\n; SPDX-FileCopyrightText: 2026 MesTTo\n;\n; SPDX-License-Identifier: MIT\n\n; Model-based state machines. A machine is declared as ordinary MeTTa data:\n;\n; (FuzzMachine Counter\n; (InitialModel (Count 0))\n; (InitializeReal counter-initialize)\n; (CommandGenerator counter-command-generator)\n; (Precondition counter-precondition)\n; (Execute counter-execute)\n; (NextModel counter-next-model)\n; (Postcondition counter-postcondition)\n; (Invariant counter-invariant)\n; (Cleanup counter-cleanup))\n;\n; Generation walks the abstract model only: `(CommandGenerator model)` returns a command\n; generator, each drawn command must satisfy `(Precondition model command)`, and\n; `(NextModel model command)` threads the model forward without touching the real system.\n; Execution happens in the `fuzz-machine-run` property: it builds the real system with\n; `(InitializeReal)`, checks `(Invariant model)` before the first command and after every\n; model update, rechecks each precondition, runs `(Execute real command)`, judges\n; `(Postcondition model command result)` against the pre-command model, and always calls\n; `(Cleanup real)`. `NextModel` stays a pure symbolic transition, so the model can never\n; absorb behavior from the system it is meant to predict. Cleanup's world effects roll back\n; with the rest of the run (the case sandbox restores the pre-run world), so cleanup matters\n; for genuinely external resources: host-effectful operations under the ExternalEffects\n; policy, whose effects live outside the world. A MeTTa cleanup relation cannot run after a\n; host-level abort either; an external system needs a host try/finally reset adapter around\n; the whole check.\n\n(= (_fuzz-machine-spec-results $name $results)\n (switch $results\n ((()\n (_fuzz-generation-error\n MissingFuzzMachine\n (Name $name)))\n (($spec)\n (ValidMachineSpec $spec))\n ($many\n (_fuzz-generation-error\n AmbiguousFuzzMachine\n (Name $name)\n (Results $many))))))\n\n(= (_fuzz-machine-spec $name)\n (let $results\n (collapse\n (match &self\n (FuzzMachine $name\n (InitialModel $initial)\n (InitializeReal $initialize)\n (CommandGenerator $command-generator)\n (Precondition $precondition)\n (Execute $execute)\n (NextModel $next-model)\n (Postcondition $postcondition)\n (Invariant $invariant)\n (Cleanup $cleanup))\n (MachineSpec\n (InitialModel (quote $initial))\n (InitializeReal $initialize)\n (CommandGenerator $command-generator)\n (Precondition $precondition)\n (Execute $execute)\n (NextModel $next-model)\n (Postcondition $postcondition)\n (Invariant $invariant)\n (Cleanup $cleanup))))\n (_fuzz-machine-spec-results $name $results)))\n\n; Cardinality-checked applications for the machine's user relations, sharing\n; `_fuzz-call-results-bind` and `_fuzz-bool-result` with the unary helper. Each collapse-bind\n; sits inside a function/chain context so the call reaches it raw; an evaluated argument would\n; branch first and a nondeterministic relation would slip through as parallel single results.\n(= (_fuzz-machine-call-zero $function $context)\n (function\n (chain (context-space) $space\n (chain (collapse-bind (metta ($function) %Undefined% $space)) $pairs\n (chain (eval (_fuzz-call-results-bind $pairs $context)) $out\n (return $out))))))\n\n(= (_fuzz-machine-call-two $function $first $second $context)\n (function\n (chain (context-space) $space\n (chain (collapse-bind (metta ($function $first $second) %Undefined% $space)) $pairs\n (chain (eval (_fuzz-call-results-bind $pairs $context)) $out\n (return $out))))))\n\n(= (_fuzz-machine-call-three $function $first $second $third $context)\n (function\n (chain (context-space) $space\n (chain (collapse-bind (metta ($function $first $second $third) %Undefined% $space)) $pairs\n (chain (eval (_fuzz-call-results-bind $pairs $context)) $out\n (return $out))))))\n\n(= (_fuzz-machine-bool-two $function $first $second $context)\n (_fuzz-bool-result\n (_fuzz-machine-call-two $function $first $second $context)\n $context))\n\n; One command for the current model: draw from the user generator and retry, up to a fixed\n; budget, until the precondition holds. Every attempt's decision tree is recorded in the\n; command's MachineCommand node (the same shape gen-filter uses), so replay repeats the\n; rejected draws deterministically and the whole sequence stays a pure function of its tree.\n(= (_fuzz-machine-command-descriptor $command-generator $model)\n (let $called\n (_fuzz-call-one\n $command-generator\n $model\n (MachineCommandGenerator (Model (quote $model))))\n (switch $called\n (((CallOne $descriptor) (CallOne $descriptor))\n ((FuzzGenerationError $code $details) $called)\n ($bad\n (_fuzz-generation-error\n MalformedMachineCommandGenerator\n (Value $bad)))))))\n\n(= (_fuzz-machine-draw-command\n $descriptor $precondition $model $driver $size $attempt $attempt-trees-reversed)\n (_fuzz-machine-draw-loop\n (MachineDraw\n $descriptor $precondition $model $driver $size\n $attempt $attempt-trees-reversed)))\n\n(= (_fuzz-machine-draw-loop $state)\n (if (_fuzz-machine-draw-finished $state)\n $state\n (_fuzz-machine-draw-loop (_fuzz-machine-draw-step $state))))\n\n(= (_fuzz-machine-draw-finished $state)\n (unify $state\n (MachineDraw\n $descriptor $precondition $model $driver $size\n $attempt $attempt-trees-reversed)\n False\n True))\n\n(= (_fuzz-machine-draw-step $state)\n (unify $state\n (MachineDraw\n $descriptor $precondition $model $driver $size\n $attempt $attempt-trees-reversed)\n (if (> $attempt 16)\n (let* (($children (reverse $attempt-trees-reversed))\n ($tree\n (Decision\n MachineCommand\n (MaximumAttempts 16)\n (Attempts 16)\n $children)))\n (FuzzGenerationDiscard\n (MachineCommandRetriesExhausted (Attempts 16))\n $driver\n $tree))\n (let $sample (fuzz-generate $descriptor $driver $size)\n (switch $sample\n (((FuzzSample $command $next-driver $draw-tree)\n (let $checked\n (_fuzz-machine-bool-two\n $precondition\n $model\n $command\n (MachinePrecondition\n (Attempt $attempt)\n (Command (quote $command))))\n (switch $checked\n (((CallBool True)\n (let* (($children\n (reverse\n (cons-atom $draw-tree $attempt-trees-reversed)))\n ($tree\n (Decision\n MachineCommand\n (MaximumAttempts 16)\n (Attempts $attempt)\n $children)))\n (MachineCommandDrawn $command $next-driver $tree)))\n ((CallBool False)\n (let $next-trees\n (cons-atom $draw-tree $attempt-trees-reversed)\n (MachineDraw\n $descriptor\n $precondition\n $model\n $next-driver\n $size\n (+ $attempt 1)\n $next-trees)))\n ((FuzzGenerationError $code $details) $checked)\n ($bad\n (_fuzz-generation-error\n MalformedMachinePrecondition\n (Value $bad)))))))\n ((FuzzGenerationDiscard $reason $next-driver $draw-tree)\n (let* (($children\n (reverse (cons-atom $draw-tree $attempt-trees-reversed)))\n ($tree\n (Decision\n MachineCommand\n (MaximumAttempts 16)\n (Attempts $attempt)\n $children)))\n (FuzzGenerationDiscard $reason $next-driver $tree)))\n ((FuzzGenerationError $code $details) $sample)\n ($bad\n (_fuzz-generation-error\n MalformedGenerationResult\n (Value $bad)))))))\n $state))\n\n(= (CustomCapabilities _fuzz-machine (MachineSequence $quoted-name $spec))\n (FuzzCustomCapabilities\n (Modes\n (Random\n Edge\n Replay\n ShrinkReplay\n Exhaustive\n Bytes))))\n\n; Sequence generation: one integer decision for the length in [0, size], then one\n; model-aware command per step. The value embeds the machine name and spec so the\n; executor property needs no space read.\n(= (DriveCustom _fuzz-machine (MachineSequence $quoted-name $spec) $driver $size)\n (unify $spec\n (MachineSpec\n (InitialModel (quote $initial))\n (InitializeReal $initialize)\n (CommandGenerator $command-generator)\n (Precondition $precondition)\n (Execute $execute)\n (NextModel $next-model)\n (Postcondition $postcondition)\n (Invariant $invariant)\n (Cleanup $cleanup))\n (let $length-choice (_fuzz-driver-int $driver 0 $size 0)\n (switch $length-choice\n (((DriverChoice $count $next-driver $length-decision)\n (let $seed-trees (cons-atom $length-decision ())\n (_fuzz-machine-gen-loop\n (MachineGenRun\n $quoted-name\n $spec\n $initial\n $count\n $next-driver\n $size\n $seed-trees\n ()))))\n ((FuzzGenerationError $code $details) $length-choice)\n ($bad\n (_fuzz-generation-error\n MalformedDriverChoice\n (Value $bad))))))\n (_fuzz-generation-error MalformedMachineSpec (Value $spec))))\n\n(= (_fuzz-machine-gen-loop $state)\n (if (_fuzz-machine-gen-finished $state)\n $state\n (_fuzz-machine-gen-loop (_fuzz-machine-gen-step $state))))\n\n(= (_fuzz-machine-gen-finished $state)\n (unify $state\n (MachineGenRun\n $quoted-name $spec $model $remaining $driver $size\n $trees-reversed $commands-reversed)\n False\n True))\n\n(= (_fuzz-machine-gen-step $state)\n (unify $state\n (MachineGenRun\n $quoted-name $spec $model $remaining $driver $size\n $trees-reversed $commands-reversed)\n (if (== $remaining 0)\n (let* (($commands (reverse $commands-reversed))\n ($children (reverse $trees-reversed))\n ($count (length $commands))\n ($value (FuzzMachineRun $quoted-name $spec $commands))\n ($tree (Decision MachineSequence (Count $count) () $children)))\n (FuzzSample $value $driver $tree))\n (unify $spec\n (MachineSpec\n (InitialModel (quote $initial))\n (InitializeReal $initialize)\n (CommandGenerator $command-generator)\n (Precondition $precondition)\n (Execute $execute)\n (NextModel $next-model)\n (Postcondition $postcondition)\n (Invariant $invariant)\n (Cleanup $cleanup))\n (let $described\n (_fuzz-machine-command-descriptor\n $command-generator\n $model)\n (switch $described\n (((FuzzGenerationError $code $details) $described)\n ((CallOne $descriptor)\n (let $sample\n (_fuzz-machine-draw-command\n $descriptor\n $precondition\n $model\n $driver\n $size\n 1\n ())\n (switch $sample\n (((MachineCommandDrawn $command $next-driver $tree)\n (let $stepped\n (_fuzz-machine-call-two\n $next-model\n $model\n $command\n (MachineNextModel\n (Model (quote $model))\n (Command (quote $command))))\n (switch $stepped\n (((CallOne $next-model-value)\n (let* (($next-trees\n (cons-atom $tree $trees-reversed))\n ($next-commands\n (cons-atom $command $commands-reversed)))\n (MachineGenRun\n $quoted-name\n $spec\n $next-model-value\n (- $remaining 1)\n $next-driver\n $size\n $next-trees\n $next-commands)))\n ((FuzzGenerationError $code $details) $stepped)\n ($bad\n (_fuzz-generation-error\n MalformedMachineModel\n (Value $bad)))))))\n ((FuzzGenerationDiscard $reason $next-driver $tree)\n (let* (($children\n (reverse (cons-atom $tree $trees-reversed)))\n ($count (length $commands-reversed))\n ($wrapped\n (Decision\n MachineSequence\n (Count $count)\n ()\n $children)))\n (FuzzGenerationDiscard\n $reason\n $next-driver\n $wrapped)))\n ((FuzzGenerationError $code $details) $sample)\n ($bad\n (_fuzz-generation-error\n MalformedGenerationResult\n (Value $bad))))))))))\n (_fuzz-generation-error MalformedMachineSpec (Value $spec))))\n $state))\n\n; Structural shrink candidates in the handoff's stable order: remove large command chunks\n; first, then smaller chunks by ascending start index. Individual command trees shrink\n; afterwards through the generic child descent. Every candidate replays from the initial\n; model, so a chunk whose suffix no longer satisfies its preconditions is discarded by the\n; filter during shrink replay and rejected.\n(= (ShrinkChoices _fuzz-machine (MachineSequence $quoted-name $spec) $decision)\n (let $candidates (_fuzz-machine-chunk-candidates $decision)\n (superpose $candidates)))\n\n(= (_fuzz-machine-chunk-candidates $decision)\n (switch $decision\n (((Decision Custom $metadata $selection ($sequence))\n (switch $sequence\n (((Decision MachineSequence $count-metadata $sequence-selection $children)\n (if-decons-expr\n $children\n $length-decision\n $command-trees\n (_fuzz-machine-chunk-sizes\n $decision\n $length-decision\n $command-trees\n (length $command-trees))\n ()))\n ($bad ()))))\n ($bad ()))))\n\n(= (_fuzz-machine-chunk-sizes $decision $length-decision $command-trees $chunk)\n (if (< $chunk 1)\n ()\n (let* (($here\n (_fuzz-machine-chunk-starts\n $decision\n $length-decision\n $command-trees\n $chunk\n 0))\n ($half (if (== $chunk 1) 0 (trunc-math (/ $chunk 2))))\n ($rest\n (_fuzz-machine-chunk-sizes\n $decision\n $length-decision\n $command-trees\n $half)))\n (append $here $rest))))\n\n(= (_fuzz-machine-chunk-starts $decision $length-decision $command-trees $chunk $start)\n (if (> (+ $start $chunk) (length $command-trees))\n ()\n (let* (($candidate\n (_fuzz-machine-remove-chunk\n $decision\n $length-decision\n $command-trees\n $chunk\n $start))\n ($rest\n (_fuzz-machine-chunk-starts\n $decision\n $length-decision\n $command-trees\n $chunk\n (+ $start 1))))\n (cons-atom $candidate $rest))))\n\n(= (_fuzz-machine-remove-chunk $decision $length-decision $command-trees $chunk $start)\n (switch $decision\n (((Decision Custom $metadata $selection ($sequence))\n (let* (($prefix (_fuzz-list-take $command-trees $start))\n ($suffix (_fuzz-list-drop $command-trees (+ $start $chunk)))\n ($kept (append $prefix $suffix))\n ($count (length $kept))\n ($shortened\n (_fuzz-machine-shorten-length $length-decision $count))\n ($rebuilt-children (cons-atom $shortened $kept))\n ($rebuilt\n (Decision\n MachineSequence\n (Count $count)\n ()\n $rebuilt-children))\n ($rebuilt-child (cons-atom $rebuilt ())))\n (Decision Custom $metadata $selection $rebuilt-child)))\n ($bad $bad))))\n\n(= (_fuzz-machine-shorten-length $length-decision $count)\n (switch $length-decision\n (((Decision Int (Bounds $lower $upper) (Origin $origin) (Value $value) ())\n (_fuzz-int-decision $lower $upper $origin $count))\n ($bad $bad))))\n\n; Public surface: `(gen-machine Name)` generates `(FuzzMachineRun (quote Name) spec\n; commands)` values, and `fuzz-machine-run` is the ordinary arity-one property that\n; executes them, so machines run under fuzz-check, fuzz-check-exhaustive, replay, and\n; shrinking without special cases.\n(= (gen-machine $name)\n (if (_fuzz-atom-ground $name)\n (let $validated (_fuzz-machine-spec $name)\n (switch $validated\n (((ValidMachineSpec $spec)\n (GenCustom _fuzz-machine (MachineSequence (quote $name) $spec)))\n ((FuzzGenerationError $code $details) $validated)\n ($bad\n (_fuzz-generation-error\n MalformedMachineSpec\n (Value $bad))))))\n (_fuzz-generation-error NonGroundMachineName (Name $name))))\n\n(: fuzz-machine-run (-> Atom FuzzProperty))\n(= (fuzz-machine-run $value)\n (unify $value\n (FuzzMachineRun $quoted-name $spec $commands)\n (unify $spec\n (MachineSpec\n (InitialModel (quote $initial))\n (InitializeReal $initialize)\n (CommandGenerator $command-generator)\n (Precondition $precondition)\n (Execute $execute)\n (NextModel $next-model)\n (Postcondition $postcondition)\n (Invariant $invariant)\n (Cleanup $cleanup))\n (let $started\n (_fuzz-machine-call-zero\n $initialize\n (MachineInitializeReal $quoted-name))\n (switch $started\n (((CallOne $real)\n (let $verdict\n (_fuzz-machine-exec-start\n $spec\n $initial\n $real\n $commands)\n (_fuzz-machine-cleanup $cleanup $real $verdict)))\n ((FuzzGenerationError $code $details)\n (fuzz-fail MachineInitializeFailed (CausedBy $started)))\n ($bad\n (fuzz-fail MachineInitializeFailed (Value $bad))))))\n (fuzz-fail MalformedMachineSpec (Value (quote $spec))))\n (fuzz-fail MalformedMachineRun (Value (quote $value)))))\n\n(= (_fuzz-machine-exec-start $spec $initial $real $commands)\n (unify $spec\n (MachineSpec\n (InitialModel (quote $unused-initial))\n (InitializeReal $initialize)\n (CommandGenerator $command-generator)\n (Precondition $precondition)\n (Execute $execute)\n (NextModel $next-model)\n (Postcondition $postcondition)\n (Invariant $invariant)\n (Cleanup $cleanup))\n (let $checked\n (_fuzz-call-bool\n $invariant\n $initial\n (MachineInvariant (Step 0) (Model (quote $initial))))\n (switch $checked\n (((CallBool True)\n (_fuzz-machine-exec-loop\n (MachineExecRun $spec $initial $real $commands 0)))\n ((CallBool False)\n (let $failed\n (fuzz-fail\n MachineInvariantViolated\n ((Step 0) (Model (quote $initial))))\n (MachineVerdict $failed)))\n ((FuzzGenerationError $code $details)\n (let $failed\n (fuzz-fail MachineInvariantError (CausedBy $checked))\n (MachineVerdict $failed)))\n ($bad\n (let $failed\n (fuzz-fail MachineInvariantError (Value $bad))\n (MachineVerdict $failed))))))\n (let $failed\n (fuzz-fail MalformedMachineSpec (Value (quote $spec)))\n (MachineVerdict $failed))))\n\n(= (_fuzz-machine-exec-loop $state)\n (if (_fuzz-machine-exec-finished $state)\n $state\n (_fuzz-machine-exec-loop (_fuzz-machine-exec-step $state))))\n\n(= (_fuzz-machine-exec-finished $state)\n (unify $state\n (MachineExecRun $spec $model $real $commands $index)\n False\n True))\n\n(= (_fuzz-machine-exec-step $state)\n (unify $state\n (MachineExecRun $spec $model $real $commands $index)\n (if (== $commands ())\n (let $pass (fuzz-pass)\n (MachineVerdict $pass))\n (unify $spec\n (MachineSpec\n (InitialModel (quote $unused-initial))\n (InitializeReal $initialize)\n (CommandGenerator $command-generator)\n (Precondition $precondition)\n (Execute $execute)\n (NextModel $next-model)\n (Postcondition $postcondition)\n (Invariant $invariant)\n (Cleanup $cleanup))\n (let* ((($command $rest) (decons-atom $commands))\n ($pre\n (_fuzz-machine-bool-two\n $precondition\n $model\n $command\n (MachinePrecondition\n (Step $index)\n (Command (quote $command))))))\n (switch $pre\n (((CallBool False)\n (let $verdict\n (fuzz-discard\n (MachinePreconditionViolated\n (Step $index)\n (Command (quote $command))))\n (MachineVerdict $verdict)))\n ((CallBool True)\n (_fuzz-machine-exec-command\n $spec $model $real $command $rest $index))\n ((FuzzGenerationError $code $details)\n (let $failed\n (fuzz-fail MachinePreconditionError (CausedBy $pre))\n (MachineVerdict $failed)))\n ($bad\n (let $failed\n (fuzz-fail MachinePreconditionError (Value $bad))\n (MachineVerdict $failed))))))\n (let $failed\n (fuzz-fail MalformedMachineSpec (Value (quote $spec)))\n (MachineVerdict $failed))))\n $state))\n\n(= (_fuzz-machine-exec-command $spec $model $real $command $rest $index)\n (unify $spec\n (MachineSpec\n (InitialModel (quote $unused-initial))\n (InitializeReal $initialize)\n (CommandGenerator $command-generator)\n (Precondition $precondition)\n (Execute $execute)\n (NextModel $next-model)\n (Postcondition $postcondition)\n (Invariant $invariant)\n (Cleanup $cleanup))\n (let $ran\n (_fuzz-machine-call-two\n $execute\n $real\n $command\n (MachineExecute (Step $index) (Command (quote $command))))\n (switch $ran\n (((CallOne $result)\n (let $post\n (_fuzz-bool-result\n (_fuzz-machine-call-three\n $postcondition\n $model\n $command\n $result\n (MachinePostcondition (Step $index)))\n (MachinePostcondition (Step $index)))\n (switch $post\n (((CallBool False)\n (let $failed\n (fuzz-fail\n MachinePostconditionFailed\n ((Step $index)\n (Command (quote $command))\n (Result (quote $result))\n (Model (quote $model))))\n (MachineVerdict $failed)))\n ((CallBool True)\n (_fuzz-machine-exec-advance\n $spec $model $real $command $result $rest $index))\n ((FuzzGenerationError $code $details)\n (let $failed\n (fuzz-fail MachinePostconditionError (CausedBy $post))\n (MachineVerdict $failed)))\n ($bad\n (let $failed\n (fuzz-fail MachinePostconditionError (Value $bad))\n (MachineVerdict $failed)))))))\n ((FuzzGenerationError $code $details)\n (let $failed\n (fuzz-fail MachineExecuteFailed (CausedBy $ran))\n (MachineVerdict $failed)))\n ($bad\n (let $failed\n (fuzz-fail MachineExecuteFailed (Value $bad))\n (MachineVerdict $failed))))))\n (let $failed\n (fuzz-fail MalformedMachineSpec (Value (quote $spec)))\n (MachineVerdict $failed))))\n\n(= (_fuzz-machine-exec-advance $spec $model $real $command $result $rest $index)\n (unify $spec\n (MachineSpec\n (InitialModel (quote $unused-initial))\n (InitializeReal $initialize)\n (CommandGenerator $command-generator)\n (Precondition $precondition)\n (Execute $execute)\n (NextModel $next-model)\n (Postcondition $postcondition)\n (Invariant $invariant)\n (Cleanup $cleanup))\n (let $stepped\n (_fuzz-machine-call-two\n $next-model\n $model\n $command\n (MachineNextModel\n (Model (quote $model))\n (Command (quote $command))))\n (switch $stepped\n (((CallOne $next)\n (let $checked\n (_fuzz-call-bool\n $invariant\n $next\n (MachineInvariant\n (Step (+ $index 1))\n (Model (quote $next))))\n (switch $checked\n (((CallBool True)\n (MachineExecRun $spec $next $real $rest (+ $index 1)))\n ((CallBool False)\n (let $failed\n (fuzz-fail\n MachineInvariantViolated\n ((Step (+ $index 1)) (Model (quote $next))))\n (MachineVerdict $failed)))\n ((FuzzGenerationError $code $details)\n (let $failed\n (fuzz-fail MachineInvariantError (CausedBy $checked))\n (MachineVerdict $failed)))\n ($bad\n (let $failed\n (fuzz-fail MachineInvariantError (Value $bad))\n (MachineVerdict $failed)))))))\n ((FuzzGenerationError $code $details)\n (let $failed\n (fuzz-fail MachineNextModelFailed (CausedBy $stepped))\n (MachineVerdict $failed)))\n ($bad\n (let $failed\n (fuzz-fail MachineNextModelFailed (Value $bad))\n (MachineVerdict $failed))))))\n (let $failed\n (fuzz-fail MalformedMachineSpec (Value (quote $spec)))\n (MachineVerdict $failed))))\n\n(= (_fuzz-machine-cleanup $cleanup $real $verdict)\n (let $cleaned\n (_fuzz-call-one\n $cleanup\n $real\n (MachineCleanup))\n (switch $cleaned\n (((CallOne $ignored)\n (unify $verdict\n (MachineVerdict $property)\n $property\n (fuzz-fail MalformedMachineVerdict (Value (quote $verdict)))))\n ((FuzzGenerationError $code $details)\n (unify $verdict\n (MachineVerdict $property)\n (_fuzz-machine-cleanup-verdict $property $cleaned)\n (fuzz-fail MalformedMachineVerdict (Value (quote $verdict)))))\n ($bad\n (fuzz-fail MachineCleanupFailed (Value $bad)))))))\n\n; A cleanup error surfaces only when the run itself passed; a real counterexample keeps\n; its own failure.\n(= (_fuzz-machine-cleanup-verdict $property $cleanup-error)\n (unify $property\n (Pass)\n (fuzz-fail MachineCleanupFailed (CausedBy $cleanup-error))\n $property))\n\n(= (fuzz-check-machine $name $config)\n (fuzz-check $name (gen-machine $name) fuzz-machine-run $config))\n\n; SPDX-FileCopyrightText: 2026 MesTTo\n;\n; SPDX-License-Identifier: MIT\n\n; Bounded state reachability over a model transition relation, as deterministic level-order\n; breadth-first search:\n;\n; !(fuzz-reachable Counter (Count 0)\n; counter-enumerate counter-transition counter-target?\n; (reach-config (MaxDepth 20) (MaxStates 5000) (MaxTransitions 200000)))\n;\n; The command enumerator returns `(FiniteCommands c1 c2 ...)` or `(IncompleteCommands reason)`.\n; The transition relation may return several next states; the whole ordered result bag becomes\n; outgoing edges and each branch's index is recorded, so a witness names exactly one branch.\n; Breadth-first order makes the first witness shortest in transition count.\n;\n; `MaxDepth` bounds the depth of every state the search considers, so a reported witness is never\n; longer than `MaxDepth` commands. The boundary level is still enumerated, because a state with no\n; command at all ends the model while a state with commands continues past the bound, and that is what\n; separates exhaustion from a depth answer; no transition runs there, so no deeper state is built.\n;\n; The outcomes are kept apart on purpose. `FuzzReachable` carries a witness that was replayed from\n; the initial model before being reported. `FuzzUnreachableWithinDepth` says only that no target\n; occurred at or below the depth actually completed. `FuzzReachabilityExhausted` is reported only\n; when the frontier ran dry with every command enumeration complete and no limit fired: it means\n; unreachable in the declared finite model, never unreachable in an external system. Every limit,\n; incomplete enumeration, relation failure, or replay mismatch is a `FuzzReachabilityCutoff` and\n; never becomes exhaustion.\n;\n; State identity is exact structural equality by default. `(StateIdentity Alpha)` merges\n; alpha-variant states and is valid only when the transition and target relations are equivariant\n; under variable renaming, which the user states with `(FuzzReachEquivariant Name)`.\n;\n; Identity runs through `_fuzz-atom-key`, whose key is a length-prefixed structural serialization\n; (typed prefixes, explicit arities, canonically renumbered variables under Alpha), not a hash.\n; Distinct states cannot share a key, so key equality IS state identity under the selected mode and\n; no second confirmation pass is needed; `reachability.test.ts` pins that property from both sides.\n; A state whose grounded payload has no serialization is an explicit `UnkeyableState` invalid\n; result rather than a silently missed state.\n;\n; Visited states are held as a key list scanned by the grounded `_fuzz-exact-member`, so the search\n; is quadratic in visited states while each user relation call costs a full MeTTa interpretation.\n; `MaxStates` defaults to 5000, where the scan stays far below the relation cost.\n\n; ---------------------------------------------------------------------------\n; Configuration\n\n(= (_fuzz-reach-default-values)\n (ReachConfigValues\n (MaxDepth 20)\n (MaxStates 5000)\n (MaxTransitions 200000)\n (StateIdentity Exact)))\n\n(= (reach-config-defaults)\n (_fuzz-reach-default-values))\n\n; A bound is a nonnegative integer; zero selects the unlimited policy, as elsewhere in the library.\n(= (_fuzz-reach-bound-value $value)\n (if (== (get-metatype $value) Grounded)\n (and (>= $value 0) (== $value (trunc-math $value)))\n False))\n\n(= (_fuzz-reach-config-set $values $option)\n (unify $values\n (ReachConfigValues\n (MaxDepth $depth)\n (MaxStates $states)\n (MaxTransitions $transitions)\n (StateIdentity $identity))\n (switch $option\n (((MaxDepth $value)\n (if (_fuzz-reach-bound-value $value)\n (ReachConfigValues\n (MaxDepth $value)\n (MaxStates $states)\n (MaxTransitions $transitions)\n (StateIdentity $identity))\n (FuzzInvalid InvalidReachConfig (InvalidMaxDepth (MaxDepth $value)))))\n ((MaxStates $value)\n (if (_fuzz-reach-bound-value $value)\n (ReachConfigValues\n (MaxDepth $depth)\n (MaxStates $value)\n (MaxTransitions $transitions)\n (StateIdentity $identity))\n (FuzzInvalid InvalidReachConfig (InvalidMaxStates (MaxStates $value)))))\n ((MaxTransitions $value)\n (if (_fuzz-reach-bound-value $value)\n (ReachConfigValues\n (MaxDepth $depth)\n (MaxStates $states)\n (MaxTransitions $value)\n (StateIdentity $identity))\n (FuzzInvalid\n InvalidReachConfig\n (InvalidMaxTransitions (MaxTransitions $value)))))\n ((StateIdentity $value)\n (if (or (== $value Exact) (== $value Alpha))\n (ReachConfigValues\n (MaxDepth $depth)\n (MaxStates $states)\n (MaxTransitions $transitions)\n (StateIdentity $value))\n (FuzzInvalid\n InvalidReachConfig\n (InvalidStateIdentity (StateIdentity $value)))))\n ($unknown\n (FuzzInvalid InvalidReachConfig (UnknownReachOption $unknown)))))\n (FuzzInvalid InvalidReachConfig (MalformedReachConfigValues $values))))\n\n(= (_fuzz-reach-config-loop $state)\n (if (_fuzz-reach-config-finished $state)\n $state\n (_fuzz-reach-config-loop (_fuzz-reach-config-step $state))))\n\n(= (_fuzz-reach-config-finished $state)\n (unify $state (ReachConfigFold $values $options) False True))\n\n(= (_fuzz-reach-config-step $state)\n (unify $state\n (ReachConfigFold $values $options)\n (if (== $options ())\n $values\n (let ($option $rest) (decons-atom $options)\n (let $applied (_fuzz-reach-config-set $values $option)\n (switch $applied\n (((FuzzInvalid $code $details) $applied)\n ($updated (ReachConfigFold $updated $rest)))))))\n $state))\n\n(= (_fuzz-reach-config-values $config)\n (let $head (_fuzz-expression-head $config)\n (if (== $head reach-config)\n (let $options (cdr-atom $config)\n (let $defaults (_fuzz-reach-default-values)\n (_fuzz-reach-config-loop (ReachConfigFold $defaults $options))))\n (FuzzInvalid InvalidReachConfig (MalformedReachConfig (Value (quote $config)))))))\n\n; The head symbol of an expression, or Empty for anything else, so a malformed argument reports\n; itself instead of erroring inside car-atom.\n(= (_fuzz-expression-head $atom)\n (if (== (get-metatype $atom) Expression)\n (if-decons-expr $atom $head $tail $head Empty)\n Empty))\n\n(= (_fuzz-reach-config-get $name $values)\n (unify $values\n (ReachConfigValues\n (MaxDepth $depth)\n (MaxStates $states)\n (MaxTransitions $transitions)\n (StateIdentity $identity))\n (switch $name\n ((MaxDepth $depth)\n (MaxStates $states)\n (MaxTransitions $transitions)\n (StateIdentity $identity)))\n Empty))\n\n; ---------------------------------------------------------------------------\n; User relation calls\n;\n; The collapse-bind sits inside a function/chain context so its call reaches it raw; an evaluated\n; argument would branch first and a nondeterministic relation would slip through as parallel single\n; results. Unlike the single-result helpers this one keeps the whole ordered bag: a transition\n; relation is nondeterministic by design.\n\n(= (_fuzz-call-all-two $function $first $second $context)\n (function\n (chain (context-space) $space\n (chain (collapse-bind (metta ($function $first $second) %Undefined% $space)) $pairs\n (chain (eval (_fuzz-call-all-results $pairs $context)) $out\n (return $out))))))\n\n(= (_fuzz-call-all-results $pairs $context)\n (if (== $pairs ())\n (_fuzz-generation-error FunctionReturnedNoResults $context)\n (let $values (_fuzz-pair-values $pairs)\n (CallAll $values))))\n\n; ---------------------------------------------------------------------------\n; State identity\n\n(= (_fuzz-reach-state-key $identity $state)\n (let $key (_fuzz-atom-key $identity $state)\n (switch $key\n (((FuzzKernelError $code $details)\n (ReachUnkeyable (ErrorCode $code) $details))\n ($valid (ReachKey $valid))))))\n\n; ---------------------------------------------------------------------------\n; Command lists\n\n(= (_fuzz-reach-command-items $commands)\n (switch $commands\n (((IncompleteCommands $reason) (ReachIncomplete $reason))\n ($listed\n (let $head (_fuzz-expression-head $listed)\n (if (== $head FiniteCommands)\n (let $items (cdr-atom $listed) (ReachFinite $items))\n (ReachMalformed (Value $listed))))))))\n\n(= (_fuzz-reach-nth $values $index)\n (let $dropped (_fuzz-list-drop $values $index)\n (if-decons-expr $dropped $head $tail (ReachItem $head) ReachMissing)))\n\n; ---------------------------------------------------------------------------\n; Search\n;\n; One frontier node carries its own path from the initial model, so a witness needs no predecessor\n; table: `(ReachNode state path)` with path `((Step command-index command branch) ...)` in\n; transition order.\n\n(= (_fuzz-reach-loop $state)\n (if (_fuzz-reach-finished $state)\n $state\n (_fuzz-reach-loop (_fuzz-reach-step $state))))\n\n(= (_fuzz-reach-finished $state)\n (unify $state\n (ReachRun $spec $frontier $next $visited $counts $depth $values Searching)\n False\n True))\n\n; MaxDepth bounds the depth of every state the search considers, so a witness is never longer than\n; MaxDepth commands and a depth answer means exactly \"every state at or below MaxDepth was generated\n; and judged against the target\". Zero is the unlimited policy, as with the other bounds.\n(= (_fuzz-reach-at-depth-limit $depth $values)\n (let $limit (_fuzz-reach-config-get MaxDepth $values)\n (and (> $limit 0) (>= $depth $limit))))\n\n; A step either advances the level or expands the first node of the current level. Advancing with an\n; empty next level is exhaustion; refusing to advance past MaxDepth is the depth answer, not a\n; cutoff, because every level at or below it was searched completely.\n(= (_fuzz-reach-step $state)\n (unify $state\n (ReachRun $spec $frontier $next $visited $counts $depth $values Searching)\n (if (== $frontier ())\n (if (== $next ())\n (ReachRun $spec () () $visited $counts $depth $values (ReachExhausted $depth))\n (if (_fuzz-reach-at-depth-limit $depth $values)\n (ReachRun\n $spec () () $visited $counts $depth $values\n (ReachUnreachableWithinDepth $depth))\n (let $level (reverse $next)\n (ReachRun\n $spec $level () $visited $counts (+ $depth 1) $values Searching))))\n (let ($node $rest) (decons-atom $frontier)\n (_fuzz-reach-expand\n (ReachRun $spec $rest $next $visited $counts $depth $values Searching)\n $node)))\n $state))\n\n(= (_fuzz-reach-cutoff $run $reason)\n (unify $run\n (ReachRun $spec $frontier $next $visited $counts $depth $values $outcome)\n (ReachRun $spec $frontier $next $visited $counts $depth $values (ReachCutoff $reason))\n $run))\n\n(= (_fuzz-reach-expand $run $node)\n (unify $node\n (ReachNode $state-atom $path)\n (unify $run\n (ReachRun $spec $frontier $next $visited $counts $depth $values Searching)\n (unify $spec\n (ReachSpec $name $initial $enumerate $transition $target $identity)\n (let $enumerated\n (_fuzz-call-one $enumerate $state-atom (ReachEnumerate (Depth $depth)))\n (switch $enumerated\n (((CallOne $commands)\n (let $items (_fuzz-reach-command-items $commands)\n (switch $items\n (((ReachFinite $listed)\n (if (_fuzz-reach-at-depth-limit $depth $values)\n (_fuzz-reach-note-beyond-depth $run $listed)\n (_fuzz-reach-commands-loop (ReachCommands $run $node $listed 0))))\n ((ReachIncomplete $reason)\n (_fuzz-reach-cutoff $run (IncompleteCommandEnumeration $reason)))\n ((ReachMalformed $value)\n (_fuzz-reach-cutoff $run (MalformedCommandEnumeration $value)))))))\n ((FuzzGenerationError $code $details)\n (_fuzz-reach-cutoff $run (CommandEnumerationFailed (CausedBy $enumerated))))\n ($bad\n (_fuzz-reach-cutoff $run (MalformedCommandEnumeration (Value $bad)))))))\n (_fuzz-reach-cutoff $run (MalformedReachSpec (Value $spec))))\n $run)\n $run))\n\n; At the boundary the enumerator still runs, because whether a state has any command at all is what\n; separates a model that ended from one that continues past the bound, and that distinction is the\n; difference between exhaustion and a depth answer. No transition runs there, so no state deeper than\n; MaxDepth is ever built, keyed, or judged. A state that does have commands leaves a marker in the\n; next level: the level is not empty, which is all the loop needs to know, and since the loop refuses\n; to advance into a level past the bound the marker is never expanded or reported.\n(= (_fuzz-reach-note-beyond-depth $run $listed)\n (if (== $listed ())\n $run\n (unify $run\n (ReachRun $spec $frontier $next $visited $counts $depth $values Searching)\n (let $marked (cons-atom ReachBeyondDepth $next)\n (ReachRun $spec $frontier $marked $visited $counts $depth $values Searching))\n $run)))\n\n(= (_fuzz-reach-commands-loop $state)\n (if (_fuzz-reach-commands-finished $state)\n $state\n (_fuzz-reach-commands-loop (_fuzz-reach-commands-step $state))))\n\n(= (_fuzz-reach-commands-finished $state)\n (unify $state (ReachCommands $run $node $commands $index) False True))\n\n(= (_fuzz-reach-commands-step $state)\n (unify $state\n (ReachCommands $run $node $commands $index)\n (if (== $commands ())\n $run\n (let ($command $rest) (decons-atom $commands)\n (let $applied (_fuzz-reach-apply $run $node $command $index)\n (if (_fuzz-reach-searching $applied)\n (ReachCommands $applied $node $rest (+ $index 1))\n $applied))))\n $state))\n\n(= (_fuzz-reach-searching $run)\n (unify $run\n (ReachRun $spec $frontier $next $visited $counts $depth $values Searching)\n True\n False))\n\n; Applying one command: the whole ordered result bag becomes outgoing edges.\n(= (_fuzz-reach-apply $run $node $command $command-index)\n (unify $node\n (ReachNode $state-atom $path)\n (unify $run\n (ReachRun $spec $frontier $next $visited $counts $depth $values Searching)\n (unify $spec\n (ReachSpec $name $initial $enumerate $transition $target $identity)\n (let $stepped\n (_fuzz-call-all-two\n $transition\n $state-atom\n $command\n (ReachTransition (Depth $depth) (Command (quote $command))))\n (switch $stepped\n (((CallAll $produced)\n (_fuzz-reach-branches-loop\n (ReachBranches $run $node $command $command-index $produced 0)))\n ((FuzzGenerationError $code $details)\n (_fuzz-reach-cutoff $run (TransitionFailed (CausedBy $stepped))))\n ($bad\n (_fuzz-reach-cutoff $run (MalformedTransition (Value $bad)))))))\n (_fuzz-reach-cutoff $run (MalformedReachSpec (Value $spec))))\n $run)\n $run))\n\n(= (_fuzz-reach-branches-loop $state)\n (if (_fuzz-reach-branches-finished $state)\n $state\n (_fuzz-reach-branches-loop (_fuzz-reach-branches-step $state))))\n\n(= (_fuzz-reach-branches-finished $state)\n (unify $state\n (ReachBranches $run $node $command $command-index $produced $branch)\n False\n True))\n\n(= (_fuzz-reach-branches-step $state)\n (unify $state\n (ReachBranches $run $node $command $command-index $produced $branch)\n (if (== $produced ())\n $run\n (let ($state-atom $rest) (decons-atom $produced)\n (let $visited-run\n (_fuzz-reach-visit $run $node $command $command-index $branch $state-atom)\n (if (_fuzz-reach-searching $visited-run)\n (ReachBranches\n $visited-run $node $command $command-index $rest (+ $branch 1))\n $visited-run))))\n $state))\n\n; One produced state. The order here is the contract: the transition branch is counted before any\n; deduplication, the target is judged before MaxStates can cut, and MaxStates is checked against the\n; state this step would actually add.\n(= (_fuzz-reach-visit $run $node $command $command-index $branch $produced)\n (unify $run\n (ReachRun $spec $frontier $next $visited $counts $depth $values Searching)\n (unify $counts\n (ReachCounts $states $transitions)\n (let* (($next-transitions (+ $transitions 1))\n ($limit (_fuzz-reach-config-get MaxTransitions $values))\n ($counted (ReachCounts $states $next-transitions))\n ($advanced\n (ReachRun $spec $frontier $next $visited $counted $depth $values Searching)))\n (if (and (> $limit 0) (> $next-transitions $limit))\n (_fuzz-reach-cutoff\n $advanced\n (MaxTransitionsReached (MaxTransitions $limit)))\n (_fuzz-reach-judge\n $advanced\n $node\n (Step $command-index $command $branch)\n $produced)))\n $run)\n $run))\n\n(= (_fuzz-reach-judge $run $node $step $produced)\n (unify $node\n (ReachNode $parent $path)\n (unify $run\n (ReachRun $spec $frontier $next $visited $counts $depth $values Searching)\n (unify $spec\n (ReachSpec $name $initial $enumerate $transition $target $identity)\n (let $keyed (_fuzz-reach-state-key $identity $produced)\n (switch $keyed\n (((ReachUnkeyable $code $details)\n (_fuzz-reach-cutoff\n $run\n (UnkeyableState (State (quote $produced)) $code $details)))\n ((ReachKey $key)\n (_fuzz-reach-target $run $key $step $path $produced)))))\n (_fuzz-reach-cutoff $run (MalformedReachSpec (Value $spec))))\n $run)\n $run))\n\n; The target is judged on the produced state before any deduplication or MaxStates check, so a\n; target that is only reachable as an already-visited state is still reported.\n(= (_fuzz-reach-target $run $key $step $path $produced)\n (unify $run\n (ReachRun $spec $frontier $next $visited $counts $depth $values Searching)\n (unify $spec\n (ReachSpec $name $initial $enumerate $transition $target $identity)\n (let $hit\n (_fuzz-call-bool\n $target\n $produced\n (ReachTarget (Depth $depth) (State (quote $produced))))\n (switch $hit\n (((CallBool True)\n (let $witness (append $path (cons-atom $step ()))\n (_fuzz-reach-confirm $run $witness $produced)))\n ((CallBool False)\n (_fuzz-reach-enqueue $run $key $step $path $produced))\n ((FuzzGenerationError $code $details)\n (_fuzz-reach-cutoff $run (TargetFailed (CausedBy $hit))))\n ($bad\n (_fuzz-reach-cutoff $run (MalformedTarget (Value $bad)))))))\n (_fuzz-reach-cutoff $run (MalformedReachSpec (Value $spec))))\n $run))\n\n(= (_fuzz-reach-enqueue $run $key $step $path $produced)\n (unify $run\n (ReachRun $spec $frontier $next $visited $counts $depth $values Searching)\n (if (== (_fuzz-exact-member $key $visited) True)\n $run\n (unify $counts\n (ReachCounts $states $transitions)\n (let* (($next-states (+ $states 1))\n ($limit (_fuzz-reach-config-get MaxStates $values)))\n (if (and (> $limit 0) (> $next-states $limit))\n (_fuzz-reach-cutoff $run (MaxStatesReached (MaxStates $limit)))\n (let* (($seen (append $visited (cons-atom $key ())))\n ($witness (append $path (cons-atom $step ())))\n ($node (ReachNode $produced $witness))\n ($queued (cons-atom $node $next)))\n (ReachRun\n $spec\n $frontier\n $queued\n $seen\n (ReachCounts $next-states $transitions)\n $depth\n $values\n Searching))))\n $run))\n $run))\n\n; ---------------------------------------------------------------------------\n; Witness replay\n;\n; A found target is replayed from the initial model before it is reported: every step re-enumerates\n; the commands, requires the recorded command at its recorded index, takes the recorded branch\n; without deduplication, and the final state must satisfy the target. A mismatch means the\n; transition relation, the enumerator, or the target is not a function of the model state, so the\n; witness is not evidence and the result is a cutoff rather than a reachable claim.\n\n(= (_fuzz-reach-confirm $run $witness $produced)\n (unify $run\n (ReachRun $spec $frontier $next $visited $counts $depth $values Searching)\n (unify $spec\n (ReachSpec $name $initial $enumerate $transition $target $identity)\n (let $replayed (_fuzz-reach-replay $spec $witness)\n (switch $replayed\n (((ReachReplayed $final)\n (if (== (_fuzz-reach-same-state $identity $final $produced) True)\n (ReachRun\n $spec $frontier $next $visited $counts $depth $values\n (ReachFound $witness $produced))\n (_fuzz-reach-cutoff\n $run\n (WitnessReplayMismatch\n (Expected (quote $produced))\n (Actual (quote $final))))))\n ((ReachReplayFailed $reason)\n (_fuzz-reach-cutoff $run (WitnessReplayMismatch $reason)))\n ($bad\n (_fuzz-reach-cutoff $run (WitnessReplayMismatch (Value $bad)))))))\n (_fuzz-reach-cutoff $run (MalformedReachSpec (Value $spec))))\n $run))\n\n(= (_fuzz-reach-same-state $identity $left $right)\n (let $left-key (_fuzz-reach-state-key $identity $left)\n (let $right-key (_fuzz-reach-state-key $identity $right)\n (unify $left-key\n (ReachKey $lk)\n (unify $right-key (ReachKey $rk) (== $lk $rk) False)\n False))))\n\n(= (_fuzz-reach-replay $spec $witness)\n (unify $spec\n (ReachSpec $name $initial $enumerate $transition $target $identity)\n (let $walked (_fuzz-reach-replay-loop (ReachReplay $spec $initial $witness 0))\n (switch $walked\n (((ReachReplayed $final)\n (let $hit\n (_fuzz-call-bool\n $target\n $final\n (ReachReplayTarget (State (quote $final))))\n (switch $hit\n (((CallBool True) (ReachReplayed $final))\n ((CallBool False)\n (ReachReplayFailed (TargetFalseOnReplay (State (quote $final)))))\n ($bad (ReachReplayFailed (TargetUnreadableOnReplay (Value $bad))))))))\n ($failed $failed))))\n (ReachReplayFailed (MalformedReachSpec (Value $spec)))))\n\n(= (_fuzz-reach-replay-loop $state)\n (if (_fuzz-reach-replay-finished $state)\n $state\n (_fuzz-reach-replay-loop (_fuzz-reach-replay-step $state))))\n\n(= (_fuzz-reach-replay-finished $state)\n (unify $state (ReachReplay $spec $current $steps $index) False True))\n\n(= (_fuzz-reach-replay-step $state)\n (unify $state\n (ReachReplay $spec $current $steps $index)\n (if (== $steps ())\n (ReachReplayed $current)\n (let ($step $rest) (decons-atom $steps)\n (let $applied (_fuzz-reach-replay-apply $spec $current $step $index)\n (switch $applied\n (((ReachReplayState $produced)\n (ReachReplay $spec $produced $rest (+ $index 1)))\n ($failed $failed))))))\n $state))\n\n(= (_fuzz-reach-replay-apply $spec $current $step $index)\n (unify $spec\n (ReachSpec $name $initial $enumerate $transition $target $identity)\n (unify $step\n (Step $command-index $command $branch)\n (let $enumerated\n (_fuzz-call-one $enumerate $current (ReachReplayEnumerate (Step $index)))\n (switch $enumerated\n (((CallOne $commands)\n (let $items (_fuzz-reach-command-items $commands)\n (switch $items\n (((ReachFinite $listed)\n (let $found (_fuzz-reach-nth $listed $command-index)\n (switch $found\n (((ReachItem $seen)\n (if (== (_fuzz-replay-equal $seen $command) True)\n (_fuzz-reach-replay-transition\n $spec $current $command $branch $index)\n (ReachReplayFailed\n (CommandChangedOnReplay\n (Step $index)\n (Expected (quote $command))\n (Actual (quote $seen))))))\n ($missing\n (ReachReplayFailed\n (CommandMissingOnReplay\n (Step $index)\n (CommandIndex $command-index))))))))\n ((ReachIncomplete $reason)\n (ReachReplayFailed\n (IncompleteCommandsOnReplay (Step $index) (Reason $reason))))\n ((ReachMalformed $value)\n (ReachReplayFailed\n (MalformedCommandsOnReplay (Step $index) $value)))))))\n ($bad\n (ReachReplayFailed (EnumerationFailedOnReplay (Step $index) (Value $bad)))))))\n (ReachReplayFailed (MalformedWitnessStep (Step $index) (Value (quote $step)))))\n (ReachReplayFailed (MalformedReachSpec (Value $spec)))))\n\n(= (_fuzz-reach-replay-transition $spec $current $command $branch $index)\n (unify $spec\n (ReachSpec $name $initial $enumerate $transition $target $identity)\n (let $stepped\n (_fuzz-call-all-two\n $transition\n $current\n $command\n (ReachReplayTransition (Step $index)))\n (switch $stepped\n (((CallAll $produced)\n (let $selected (_fuzz-reach-nth $produced $branch)\n (switch $selected\n (((ReachItem $chosen) (ReachReplayState $chosen))\n ($missing\n (ReachReplayFailed\n (BranchMissingOnReplay (Step $index) (Branch $branch))))))))\n ($bad\n (ReachReplayFailed (TransitionFailedOnReplay (Step $index) (Value $bad)))))))\n (ReachReplayFailed (MalformedReachSpec (Value $spec)))))\n\n; ---------------------------------------------------------------------------\n; Public surface\n\n(= (fuzz-reachable $name $initial $enumerate $transition $target $config)\n (let $values (_fuzz-reach-config-values $config)\n (switch $values\n (((FuzzInvalid $code $details) $values)\n ($valid (_fuzz-reach-start $name $initial $enumerate $transition $target $valid))))))\n\n(= (_fuzz-reach-start $name $initial $enumerate $transition $target $values)\n (let $identity (_fuzz-reach-config-get StateIdentity $values)\n (if (== (_fuzz-reach-identity-permitted $name $identity) True)\n (let $keyed (_fuzz-reach-state-key $identity $initial)\n (switch $keyed\n (((ReachUnkeyable $code $details)\n (FuzzInvalid\n UnkeyableState\n (Property $name)\n (State (quote $initial))\n $code\n $details))\n ((ReachKey $key)\n (let $spec (ReachSpec $name $initial $enumerate $transition $target $identity)\n (_fuzz-reach-run $spec $key $values))))))\n (FuzzInvalid\n MissingEquivarianceDeclaration\n (Property $name)\n (StateIdentity $identity)))))\n\n; Alpha identity merges states that differ only by variable names, which is sound only when the\n; user's relations cannot tell those states apart. That is a claim about the model, so the user\n; states it explicitly and the search refuses the mode otherwise.\n(= (_fuzz-reach-identity-permitted $name $identity)\n (if (== $identity Alpha)\n (let $declared (collapse (match &self (FuzzReachEquivariant $name) Declared))\n (if (== $declared ()) False True))\n True))\n\n(= (_fuzz-reach-run $spec $key $values)\n (unify $spec\n (ReachSpec $name $initial $enumerate $transition $target $identity)\n (let $hit\n (_fuzz-call-bool $target $initial (ReachTarget (Depth 0) (State (quote $initial))))\n (switch $hit\n (((CallBool True)\n (let* (($seen (cons-atom $key ()))\n ($counts (ReachCounts 1 0))\n ($found (ReachFound () $initial)))\n (_fuzz-reach-report\n (ReachRun $spec () () $seen $counts 0 $values $found))))\n ((CallBool False)\n (let* (($seen (cons-atom $key ()))\n ($counts (ReachCounts 1 0))\n ($root (ReachNode $initial ()))\n ($frontier (cons-atom $root ()))\n ($start (ReachRun $spec $frontier () $seen $counts 0 $values Searching))\n ($finished (_fuzz-reach-loop $start)))\n (_fuzz-reach-report $finished)))\n ((FuzzGenerationError $code $details)\n (FuzzInvalid TargetFailed (Property $name) (CausedBy $hit)))\n ($bad\n (FuzzInvalid MalformedTarget (Property $name) (Value $bad))))))\n (FuzzInvalid MalformedReachSpec (Value $spec))))\n\n(= (_fuzz-reach-report $run)\n (unify $run\n (ReachRun $spec $frontier $next $visited $counts $depth $values $outcome)\n (unify $spec\n (ReachSpec $name $initial $enumerate $transition $target $identity)\n (unify $counts\n (ReachCounts $states $transitions)\n (let $statistics\n (ReachStatistics\n (States $states)\n (Transitions $transitions)\n (Depth $depth))\n (switch $outcome\n (((ReachFound $witness $state)\n (let $commands (_fuzz-reach-witness-commands $witness)\n (FuzzReachable\n (Property $name)\n (Depth (length $witness))\n (Commands $commands)\n (Witness $witness)\n (Target (quote $state))\n $statistics)))\n ((ReachUnreachableWithinDepth $searched)\n (FuzzUnreachableWithinDepth (Property $name) (Depth $searched) $statistics))\n ((ReachExhausted $searched)\n (FuzzReachabilityExhausted\n (Property $name)\n (States $states)\n (Depth $searched)\n $statistics))\n ((ReachCutoff $reason)\n (FuzzReachabilityCutoff (Property $name) (Reason $reason) $statistics))\n ($bad\n (FuzzInvalid MalformedReachOutcome (Property $name) (Value $bad))))))\n (FuzzInvalid MalformedReachCounts (Value $counts)))\n (FuzzInvalid MalformedReachSpec (Value $spec)))\n (FuzzInvalid MalformedReachRun (Value $run))))\n\n; Flat accumulator, not recurse-then-cons: a witness is one step per transition and a long chain\n; would otherwise nest one evaluator frame per step.\n(= (_fuzz-reach-witness-commands $witness)\n (_fuzz-reach-witness-loop (ReachWitnessFold $witness ())))\n\n(= (_fuzz-reach-witness-loop $state)\n (if (_fuzz-reach-witness-finished $state)\n $state\n (_fuzz-reach-witness-loop (_fuzz-reach-witness-step $state))))\n\n(= (_fuzz-reach-witness-finished $state)\n (unify $state (ReachWitnessFold $steps $reversed) False True))\n\n(= (_fuzz-reach-witness-step $state)\n (unify $state\n (ReachWitnessFold $steps $reversed)\n (if (== $steps ())\n (reverse $reversed)\n (let ($step $rest) (decons-atom $steps)\n (unify $step\n (Step $command-index $command $branch)\n (let $next (cons-atom $command $reversed)\n (ReachWitnessFold $rest $next))\n (ReachWitnessFold $rest $reversed))))\n $state))\n\n; SPDX-FileCopyrightText: 2026 MesTTo\n;\n; SPDX-License-Identifier: MIT\n\n; Suite discovery. A file declares its tests as ordinary data rather than through a second host-side\n; test DSL:\n;\n; (: reverse-involution (-> Atom FuzzProperty))\n; (= (reverse-involution $xs) (expect-equal (reverse (reverse $xs)) $xs))\n; (FuzzTest reverse-involution (gen-list (gen-int -100 100) 0 40) reverse-involution\n; (fuzz-config (Runs 200)))\n;\n; `(fuzz-run-suite)` finds every `FuzzTest` fact and runs it through the ordinary `fuzz-check`, so a\n; suite is exactly what a hand-written `!(fuzz-check ...)` query would have been. The generator is\n; stored as syntax by the declaration and evaluated once per test when `fuzz-check` receives it,\n; which is what lets one declaration be replayed, shrunk, and enumerated like any other.\n;\n; The host may override configuration from the command line. Options are merged by REPLACEMENT rather\n; than appended, because a config carrying the same option twice is an explicit `DuplicateOption`\n; error; a test's own choices survive except where an override names the same option.\n\n(: FuzzTest (-> Atom Atom Atom Atom Atom))\n(: FuzzTestCase (-> Atom Atom Atom Atom Atom))\n(: FuzzSuiteRun (-> Atom Atom Atom Atom Atom))\n(: fuzz-run-suite (-> %Undefined%))\n(: fuzz-run-suite-with (-> Atom %Undefined%))\n(: fuzz-run-suite-exhaustive (-> Atom %Undefined%))\n(: fuzz-suite-tests (-> %Undefined%))\n(: _fuzz-suite-cases (-> %Undefined%))\n(: _fuzz-options-merged (-> Atom Atom Atom Atom %Undefined%))\n(: _fuzz-config-with-overrides (-> Atom Atom %Undefined%))\n(: _fuzz-reach-config-with-overrides (-> Atom Atom %Undefined%))\n(: _fuzz-override-names (-> Atom %Undefined%))\n(: _fuzz-options-without (-> Atom Atom %Undefined%))\n; The loop trio is deliberately UNDECLARED. An `Atom` parameter freezes its argument, and\n; `(_fuzz-suite-loop (_fuzz-suite-step $state))` passes a computed call: declaring it would freeze\n; the step, run exactly one iteration, and return the unevaluated call as the result.\n(: FuzzOverrideNames (-> Atom Atom Atom))\n(: FuzzOptionFilter (-> Atom Atom Atom Atom))\n\n; ---------------------------------------------------------------------------\n; Declared tests\n\n(= (_fuzz-suite-cases)\n (collapse\n (match &self\n (FuzzTest $id $generator $property $config)\n (FuzzTestCase $id $generator $property $config))))\n\n; The declared tests, for a host that wants to list a suite without running it.\n(= (fuzz-suite-tests)\n (let $cases (_fuzz-suite-cases) $cases))\n\n; ---------------------------------------------------------------------------\n; Configuration overrides\n;\n; Flat accumulator loops throughout: a suite may carry many options and a recurse-then-cons builder\n; costs an evaluator frame per element.\n;\n; An option is named by its head symbol rather than by `_fuzz-config-option-name`, whose switch is a\n; whitelist of the `fuzz-config` options and reports anything else as `InvalidOption`. Merging is\n; head-structural so it serves `reach-config` too; an option the target record does not accept is\n; still refused, by that record's own validation.\n\n(= (_fuzz-override-names $overrides)\n (_fuzz-override-names-loop (FuzzOverrideNames $overrides ())))\n\n(= (_fuzz-override-names-loop $state)\n (if (_fuzz-override-names-finished $state)\n $state\n (_fuzz-override-names-loop (_fuzz-override-names-step $state))))\n\n(= (_fuzz-override-names-finished $state)\n (unify $state (FuzzOverrideNames $options $reversed) False True))\n\n(= (_fuzz-override-names-step $state)\n (unify $state\n (FuzzOverrideNames $options $reversed)\n (if (== $options ())\n (reverse $reversed)\n (let ($option $rest) (decons-atom $options)\n (let $name (_fuzz-expression-head $option)\n (let $next (cons-atom $name $reversed)\n (FuzzOverrideNames $rest $next)))))\n $state))\n\n(= (_fuzz-options-without $options $names)\n (_fuzz-options-without-loop (FuzzOptionFilter $options $names ())))\n\n(= (_fuzz-options-without-loop $state)\n (if (_fuzz-options-without-finished $state)\n $state\n (_fuzz-options-without-loop (_fuzz-options-without-step $state))))\n\n(= (_fuzz-options-without-finished $state)\n (unify $state (FuzzOptionFilter $options $names $reversed) False True))\n\n(= (_fuzz-options-without-step $state)\n (unify $state\n (FuzzOptionFilter $options $names $reversed)\n (if (== $options ())\n (reverse $reversed)\n (let ($option $rest) (decons-atom $options)\n (let $name (_fuzz-expression-head $option)\n (if (is-member $name $names)\n (FuzzOptionFilter $rest $names $reversed)\n (let $next (cons-atom $option $reversed)\n (FuzzOptionFilter $rest $names $next))))))\n $state))\n\n; Merge overrides into an option record by replacement. An empty override list returns the record\n; unchanged, so the ordinary path allocates nothing. The expected head is a parameter because the two\n; record kinds differ only in that symbol: `fuzz-config` rejects a repeated option outright, while\n; `reach-config` folds last-wins, and replacement is right for both.\n(= (_fuzz-options-merged $head $record $overrides $code)\n (if (== $overrides ())\n $record\n (let $found (_fuzz-expression-head $record)\n (if (== $found $head)\n (let* (($options (cdr-atom $record))\n ($names (_fuzz-override-names $overrides))\n ($kept (_fuzz-options-without $options $names))\n ($merged (append $kept $overrides)))\n (cons-atom $head $merged))\n (FuzzInvalid $code (MalformedConfig (Value (quote $record))))))))\n\n(= (_fuzz-config-with-overrides $config $overrides)\n (_fuzz-options-merged fuzz-config $config $overrides InvalidConfig))\n\n(= (_fuzz-reach-config-with-overrides $config $overrides)\n (_fuzz-options-merged reach-config $config $overrides InvalidReachConfig))\n\n; ---------------------------------------------------------------------------\n; Running a suite\n;\n; Each result is paired with its test id so a host can report per-test without re-deriving identity\n; from the result atom.\n\n(= (fuzz-run-suite)\n (fuzz-run-suite-with ()))\n\n(= (fuzz-run-suite-with $overrides)\n (let $cases (_fuzz-suite-cases)\n (_fuzz-suite-loop (FuzzSuiteRun $cases $overrides Random ()))))\n\n(= (fuzz-run-suite-exhaustive $overrides)\n (let $cases (_fuzz-suite-cases)\n (_fuzz-suite-loop (FuzzSuiteRun $cases $overrides Exhaustive ()))))\n\n(= (_fuzz-suite-loop $state)\n (if (_fuzz-suite-finished $state)\n $state\n (_fuzz-suite-loop (_fuzz-suite-step $state))))\n\n(= (_fuzz-suite-finished $state)\n (unify $state (FuzzSuiteRun $cases $overrides $mode $reversed) False True))\n\n(= (_fuzz-suite-step $state)\n (unify $state\n (FuzzSuiteRun $cases $overrides $mode $reversed)\n (if (== $cases ())\n (reverse $reversed)\n (let ($case $rest) (decons-atom $cases)\n (let $result (_fuzz-suite-run-case $case $overrides $mode)\n (let $next (cons-atom $result $reversed)\n (FuzzSuiteRun $rest $overrides $mode $next)))))\n $state))\n\n(: _fuzz-suite-run-case (-> Atom Atom Atom %Undefined%))\n; The merged config is inspected with `unify`, not `switch`: switch evaluates its scrutinee, which\n; normalizes a `fuzz-config` expression into either a config record or a validation error, and an arm\n; matching that error would then report the pre-evaluation syntax instead of the error itself. unify\n; leaves the subject alone, so a merge that genuinely failed is caught here and an ordinary config\n; travels on to fuzz-check as syntax, which is what lets fuzz-check normalize and validate it.\n(= (_fuzz-suite-run-case $case $overrides $mode)\n (unify $case\n (FuzzTestCase $id $generator $property $config)\n (let $merged (_fuzz-config-with-overrides $config $overrides)\n (unify $merged\n (FuzzInvalid $code $details)\n (FuzzSuiteResult $id $merged)\n (let $result (_fuzz-suite-check $id $generator $property $merged $mode)\n (FuzzSuiteResult $id $result))))\n (FuzzSuiteResult Unknown (FuzzInvalid MalformedFuzzTest (Value (quote $case))))))\n\n; The generator reaches fuzz-check as syntax and is evaluated there, exactly as in a hand-written\n; query. Exhaustive mode swaps in fuzz-check-exhaustive and nothing else changes.\n(: _fuzz-suite-check (-> Atom Atom Atom Atom Atom %Undefined%))\n(= (_fuzz-suite-check $id $generator $property $config Random)\n (fuzz-check $id $generator $property $config))\n(= (_fuzz-suite-check $id $generator $property $config Exhaustive)\n (fuzz-check-exhaustive $id $generator $property $config))\n\n(: FuzzSuiteResult (-> Atom Atom Atom))\n\n; ---------------------------------------------------------------------------\n; Declared reachability searches\n;\n; The same data-declaration idea for bounded reachability:\n;\n; (FuzzReachTest counter (Count 0) counter-enumerate counter-transition counter-target\n; (reach-config (MaxDepth 20)))\n;\n; A search needs its own relations rather than a machine spec, because a transition that returns\n; several next states is the point of the search; a FuzzMachine's NextModel is single-valued.\n\n(: FuzzReachTest (-> Atom Atom Atom Atom Atom Atom Atom))\n(: FuzzReachCase (-> Atom Atom Atom Atom Atom Atom Atom))\n(: FuzzReachSuiteRun (-> Atom Atom Atom Atom))\n(: fuzz-run-reach-suite (-> %Undefined%))\n(: fuzz-run-reach-suite-with (-> Atom %Undefined%))\n(: fuzz-reach-suite-tests (-> %Undefined%))\n(: _fuzz-reach-suite-cases (-> %Undefined%))\n\n(= (_fuzz-reach-suite-cases)\n (collapse\n (match &self\n (FuzzReachTest $id $initial $enumerate $transition $target $config)\n (FuzzReachCase $id $initial $enumerate $transition $target $config))))\n\n(= (fuzz-reach-suite-tests)\n (let $cases (_fuzz-reach-suite-cases) $cases))\n\n(= (fuzz-run-reach-suite)\n (fuzz-run-reach-suite-with ()))\n\n(= (fuzz-run-reach-suite-with $overrides)\n (let $cases (_fuzz-reach-suite-cases)\n (_fuzz-reach-suite-loop (FuzzReachSuiteRun $cases $overrides ()))))\n\n(= (_fuzz-reach-suite-loop $state)\n (if (_fuzz-reach-suite-finished $state)\n $state\n (_fuzz-reach-suite-loop (_fuzz-reach-suite-step $state))))\n\n(= (_fuzz-reach-suite-finished $state)\n (unify $state (FuzzReachSuiteRun $cases $overrides $reversed) False True))\n\n(= (_fuzz-reach-suite-step $state)\n (unify $state\n (FuzzReachSuiteRun $cases $overrides $reversed)\n (if (== $cases ())\n (reverse $reversed)\n (let ($case $rest) (decons-atom $cases)\n (let $result (_fuzz-reach-suite-run-case $case $overrides)\n (let $next (cons-atom $result $reversed)\n (FuzzReachSuiteRun $rest $overrides $next)))))\n $state))\n\n; As in `_fuzz-suite-run-case`, the merged config is inspected with `unify` rather than `switch` so a\n; merge that failed is reported instead of being evaluated into something else.\n(: _fuzz-reach-suite-run-case (-> Atom Atom %Undefined%))\n(= (_fuzz-reach-suite-run-case $case $overrides)\n (unify $case\n (FuzzReachCase $id $initial $enumerate $transition $target $config)\n (let $merged (_fuzz-reach-config-with-overrides $config $overrides)\n (unify $merged\n (FuzzInvalid $code $details)\n (FuzzSuiteResult $id $merged)\n (let $result (fuzz-reachable $id $initial $enumerate $transition $target $merged)\n (FuzzSuiteResult $id $result))))\n (FuzzSuiteResult Unknown (FuzzInvalid MalformedFuzzReachTest (Value (quote $case))))))\n";
6
+
7
+ // src/kernel.ts
8
+ import {
9
+ atomEq,
10
+ expr,
11
+ gbool,
12
+ gfloat,
13
+ gint,
14
+ gnd,
15
+ groundType,
16
+ gstr,
17
+ gunit,
18
+ registerBuiltinGroundedOperation,
19
+ sym,
20
+ variable
21
+ } from "@mettascript/core";
22
+ import { uniformBigInt } from "pure-rand/distribution/uniformBigInt";
23
+ import { xorshift128plus, xorshift128plusFromState } from "pure-rand/generator/xorshift128plus";
24
+ var FUZZ_RNG_ALGORITHM = "xorshift128plus-v1";
25
+ var FUZZ_ATOM_KEY_ALGORITHM = "mettascript-atom-key-v1";
26
+ var FUZZ_REPLAY_KEY_ALGORITHM = "mettascript-replay-key-v1";
27
+ var FUZZ_ALPHA_REPLAY_KEY_ALGORITHM = "mettascript-alpha-replay-key-v1";
28
+ var FUZZ_ATOM_CODEC_VERSION = 1;
29
+ var RNG_HEAD = sym("FuzzRng");
30
+ var RNG_ALGORITHM = sym(FUZZ_RNG_ALGORITHM);
31
+ var DRAW_HEAD = sym("FuzzDraw");
32
+ var ERROR_HEAD = sym("FuzzKernelError");
33
+ var FLOAT_BITS_HEAD = sym("Float64Bits");
34
+ var FLOAT_INDEX_HEAD = sym("Float64Index");
35
+ var ENCODED_ATOM_HEAD = sym("FuzzEncodedAtom");
36
+ var ENCODED_SYMBOL = sym("Symbol");
37
+ var ENCODED_VARIABLE = sym("Variable");
38
+ var ENCODED_EXPRESSION = sym("Expression");
39
+ var ENCODED_INTEGER = sym("Integer");
40
+ var ENCODED_FLOAT = sym("Float64Bits");
41
+ var ENCODED_STRING = sym("String");
42
+ var ENCODED_BOOLEAN = sym("Boolean");
43
+ var ENCODED_UNIT = sym("Unit");
44
+ var ENCODED_ERROR = sym("Error");
45
+ var FUZZ_SAMPLE_HEAD = sym("FuzzSample");
46
+ var FUZZ_GENERATION_DISCARD_HEAD = sym("FuzzGenerationDiscard");
47
+ var FUZZ_GENERATION_ERROR_HEAD = sym("FuzzGenerationError");
48
+ var FUZZ_DRIVER_HEAD = sym("FuzzDriver");
49
+ var CUSTOM_REPLAY_TREE_HEAD = sym("CustomReplayTree");
50
+ var CUSTOM_REPLAY_SKIP_HEAD = sym("CustomReplaySkip");
51
+ var CUSTOM_REPLAY_PROTOCOL_ERROR_HEAD = sym("CustomReplayProtocolError");
52
+ var GRAMMAR_FIELD_EXPRESSIONS_HEAD = sym("GrammarFieldExpressions");
53
+ var GRAMMAR_TEMPLATE_PROFILE_HEAD = sym("GrammarTemplateProfile");
54
+ var GRAMMAR_REQUIREMENT_ALTERNATIVES_HEAD = sym("GrammarRequirementAlternatives");
55
+ var GRAMMAR_REQUIREMENT_ALTERNATIVE_HEAD = sym("GrammarRequirementAlternative");
56
+ var GRAMMAR_REQUIREMENT_SUMMARY_ENTRY_HEAD = sym("GrammarRequirementSummaryEntry");
57
+ var GRAMMAR_VALIDATION_PLAN_HEAD = sym("GrammarValidationPlan");
58
+ var GRAMMAR_VALIDATION_FIELD_HEAD = sym("GrammarValidationField");
59
+ var GRAMMAR_VALIDATION_SCOPED_ENTER_HEAD = sym("GrammarValidationScopedEnter");
60
+ var GRAMMAR_VALIDATION_SCOPED_EXIT_HEAD = sym("GrammarValidationScopedExit");
61
+ var GRAMMAR_VALIDATION_MALFORMED_HEAD = sym("GrammarValidationMalformed");
62
+ var GRAMMAR_REFERENCE_TARGETS_HEAD = sym("GrammarReferenceTargets");
63
+ var GRAMMAR_INDEXED_REFERENCE_HEAD = sym("_FuzzGrammarRef");
64
+ var GRAMMAR_ALTERNATIVES_ADD_HEAD = sym("GrammarAlternativesAdd");
65
+ var GRAMMAR_PRODUCTIONS_HEAD = sym("GrammarProductions");
66
+ var GRAMMAR_TEMPLATE_PLAN_HEAD = sym("GrammarTemplatePlan");
67
+ var GI_LIT_HEAD = sym("GILit");
68
+ var GI_FIELD_HEAD = sym("GIField");
69
+ var GI_REF_HEAD = sym("GIRef");
70
+ var GI_FRESH_HEAD = sym("GIFresh");
71
+ var GI_USE_HEAD = sym("GIUse");
72
+ var GI_BIND_HEAD = sym("GIBind");
73
+ var GI_SCOPED_HEAD = sym("GIScoped");
74
+ var GI_EXPR_ENTER_HEAD = sym("GIExprEnter");
75
+ var GI_EXPR_BUILD_HEAD = sym("GIExprBuild");
76
+ var FUZZ_STACK_HEAD = sym("FuzzStack");
77
+ var FUZZ_STACK_TAKE_HEAD = sym("FuzzStackTake");
78
+ var FUZZ_EXPRESSION_VIEW_HEAD = sym("FuzzExpressionView");
79
+ var FUZZ_ATOM_LEAF_HEAD = sym("FuzzAtomLeaf");
80
+ var QUOTE_HEAD = sym("quote");
81
+ var FUZZ_VARIABLE_MARKER_TYPE = sym("FuzzVariableMarker");
82
+ var FUZZ_VARIABLE_MARKER_KIND = "mettascript-fuzz-variable-marker";
83
+ var UNICODE_SCALAR_COUNT = 1112062n;
84
+ var UNICODE_FIRST_GAP_INDEX = 55296n;
85
+ var UNICODE_SECOND_GAP_INDEX = 63486n;
86
+ var GRAMMAR_RESERVED_TEMPLATE_HEADS = /* @__PURE__ */ new Set([
87
+ "Literal",
88
+ "Field",
89
+ "Ref",
90
+ "Fresh",
91
+ "Use",
92
+ "Bind",
93
+ "Scoped"
94
+ ]);
95
+ var MIN_I32 = -2147483648;
96
+ var MAX_I32 = 2147483647;
97
+ var F64_SIGN_BIT = 1n << 63n;
98
+ var F64_MAGNITUDE_MASK = F64_SIGN_BIT - 1n;
99
+ var F64_POSITIVE_INFINITY_BITS = 0x7ff0000000000000n;
100
+ var F64_MIN_INDEX = -F64_POSITIVE_INFINITY_BITS - 1n;
101
+ var F64_MAX_INDEX = F64_POSITIVE_INFINITY_BITS;
102
+ var floatBuffer = new ArrayBuffer(8);
103
+ var floatView = new DataView(floatBuffer);
104
+ var ok = (result) => ({ tag: "ok", results: [result] });
105
+ function isErrorAtom(value) {
106
+ return !Array.isArray(value);
107
+ }
108
+ function kernelError(code, ...details) {
109
+ return expr([ERROR_HEAD, sym(code), ...details]);
110
+ }
111
+ function operationError(code, operation, detail) {
112
+ return ok(kernelError(code, expr([sym("Operation"), sym(operation)]), sym(detail)));
113
+ }
114
+ function arityError(operation, expected, actual) {
115
+ return ok(
116
+ kernelError(
117
+ "InvalidArity",
118
+ expr([sym("Operation"), sym(operation)]),
119
+ expr([sym("Expected"), gint(expected)]),
120
+ expr([sym("Actual"), gint(actual)])
121
+ )
122
+ );
123
+ }
124
+ function exactIntegerValue(atom) {
125
+ return atom.kind === "gnd" && atom.value.g === "int" ? BigInt(atom.value.n) : void 0;
126
+ }
127
+ function integralNumberValue(atom) {
128
+ const exact = exactIntegerValue(atom);
129
+ if (exact !== void 0) return exact;
130
+ if (atom.kind !== "gnd" || atom.value.g !== "float" || !Number.isFinite(atom.value.n) || !Number.isInteger(atom.value.n))
131
+ return void 0;
132
+ return BigInt(atom.value.n);
133
+ }
134
+ function floatValue(atom) {
135
+ return atom.kind === "gnd" && atom.value.g === "float" ? atom.value.n : void 0;
136
+ }
137
+ function float64Bits(value) {
138
+ floatView.setFloat64(0, value, false);
139
+ return BigInt(floatView.getUint32(0, false)) << 32n | BigInt(floatView.getUint32(4, false));
140
+ }
141
+ function float64FromBits(bits) {
142
+ floatView.setUint32(0, Number(bits >> 32n), false);
143
+ floatView.setUint32(4, Number(bits & 0xffffffffn), false);
144
+ return floatView.getFloat64(0, false);
145
+ }
146
+ function float64Words(value) {
147
+ const bits = float64Bits(value);
148
+ return [bits >> 32n, bits & 0xffffffffn];
149
+ }
150
+ function unsigned32Value(atom) {
151
+ const value = exactIntegerValue(atom);
152
+ return value !== void 0 && value >= 0n && value <= 0xffffffffn ? value : void 0;
153
+ }
154
+ function float64FromWords(high, low) {
155
+ return float64FromBits(high << 32n | low);
156
+ }
157
+ function float64Index(value) {
158
+ if (Number.isNaN(value)) return void 0;
159
+ const bits = float64Bits(value);
160
+ const magnitude = bits & F64_MAGNITUDE_MASK;
161
+ return (bits & F64_SIGN_BIT) === 0n ? magnitude : -magnitude - 1n;
162
+ }
163
+ function float64FromIndex(index) {
164
+ if (index < F64_MIN_INDEX || index > F64_MAX_INDEX) return void 0;
165
+ const bits = index < 0n ? F64_SIGN_BIT | -index - 1n : index;
166
+ return float64FromBits(bits);
167
+ }
168
+ function rngStateAtom(state) {
169
+ return expr([RNG_HEAD, RNG_ALGORITHM, ...state.map(gint)]);
170
+ }
171
+ function parseRngState(atom) {
172
+ if (atom.kind !== "expr" || atom.items.length !== 6 || !atomEq(atom.items[0], RNG_HEAD) || !atomEq(atom.items[1], RNG_ALGORITHM)) {
173
+ return void 0;
174
+ }
175
+ const state = [];
176
+ for (const part of atom.items.slice(2)) {
177
+ const value = exactIntegerValue(part);
178
+ if (value === void 0 || value < BigInt(MIN_I32) || value > BigInt(MAX_I32)) return void 0;
179
+ state.push(Number(value));
180
+ }
181
+ if (state.every((value) => value === 0)) return void 0;
182
+ return [state[0], state[1], state[2], state[3]];
183
+ }
184
+ var rngInit = (args) => {
185
+ if (args.length !== 1) return arityError("_fuzz-rng-init", 1, args.length);
186
+ const seed = integralNumberValue(args[0]);
187
+ if (seed === void 0) return operationError("InvalidSeed", "_fuzz-rng-init", "ExpectedInteger");
188
+ const seed32 = Number(BigInt.asIntN(32, seed));
189
+ return ok(rngStateAtom(xorshift128plus(seed32).getState()));
190
+ };
191
+ var drawInt = (args) => {
192
+ if (args.length !== 3) return arityError("_fuzz-draw-int", 3, args.length);
193
+ const state = parseRngState(args[0]);
194
+ if (state === void 0)
195
+ return operationError("InvalidRngState", "_fuzz-draw-int", "ExpectedFuzzRng");
196
+ const lower = integralNumberValue(args[1]);
197
+ const upper = integralNumberValue(args[2]);
198
+ if (lower === void 0 || upper === void 0)
199
+ return operationError("InvalidBounds", "_fuzz-draw-int", "ExpectedIntegers");
200
+ if (lower > upper) return operationError("InvalidBounds", "_fuzz-draw-int", "LowerExceedsUpper");
201
+ const rng = xorshift128plusFromState(state);
202
+ const value = uniformBigInt(rng, lower, upper);
203
+ return ok(expr([DRAW_HEAD, gint(value), rngStateAtom(rng.getState())]));
204
+ };
205
+ function lengthPrefixed(tag, value) {
206
+ return `${tag}${value.length}:${value};`;
207
+ }
208
+ function nonReplayable(reason) {
209
+ return {
210
+ ok: false,
211
+ reason: kernelError("NonReplayableGroundedValue", sym(reason))
212
+ };
213
+ }
214
+ function groundedKey(atom, mode) {
215
+ if (atom.value.g === "ext") return nonReplayable("ExternalGrounded");
216
+ if (atom.exec !== void 0) return nonReplayable("ExecutableGrounded");
217
+ if (atom.match !== void 0) return nonReplayable("CustomMatcher");
218
+ if (!atomEq(atom.typ, groundType(atom.value))) return nonReplayable("CustomGroundedType");
219
+ if (mode === "Replay" || mode === "AlphaReplay") {
220
+ switch (atom.value.g) {
221
+ case "int":
222
+ return { ok: true, key: `I${atom.value.n};` };
223
+ case "float":
224
+ return { ok: true, key: `F${float64Bits(atom.value.n).toString(16).padStart(16, "0")};` };
225
+ case "str":
226
+ return { ok: true, key: lengthPrefixed("T", atom.value.s) };
227
+ case "bool":
228
+ return { ok: true, key: atom.value.b ? "B1;" : "B0;" };
229
+ case "unit":
230
+ return { ok: true, key: "U;" };
231
+ case "error":
232
+ return { ok: true, key: lengthPrefixed("R", atom.value.msg) };
233
+ }
234
+ }
235
+ switch (atom.value.g) {
236
+ case "int":
237
+ case "float":
238
+ return { ok: true, key: lengthPrefixed("N", String(Number(atom.value.n))) };
239
+ case "str":
240
+ return { ok: true, key: lengthPrefixed("T", atom.value.s) };
241
+ case "bool":
242
+ return { ok: true, key: atom.value.b ? "B1;" : "B0;" };
243
+ case "unit":
244
+ return { ok: true, key: "U;" };
245
+ case "error":
246
+ return { ok: true, key: lengthPrefixed("R", atom.value.msg) };
247
+ }
248
+ }
249
+ function structuralAtomKey(atom, mode) {
250
+ const algorithm = mode === "Replay" ? FUZZ_REPLAY_KEY_ALGORITHM : mode === "AlphaReplay" ? FUZZ_ALPHA_REPLAY_KEY_ALGORITHM : FUZZ_ATOM_KEY_ALGORITHM;
251
+ const output = [`${algorithm};`];
252
+ const variables = /* @__PURE__ */ new Map();
253
+ const pending = [atom];
254
+ while (pending.length > 0) {
255
+ const current = pending.pop();
256
+ switch (current.kind) {
257
+ case "sym":
258
+ output.push(lengthPrefixed("S", current.name));
259
+ break;
260
+ case "var": {
261
+ let name = current.name;
262
+ if (mode === "Alpha" || mode === "AlphaReplay") {
263
+ const known = variables.get(name);
264
+ if (known === void 0) {
265
+ name = `%${variables.size}`;
266
+ variables.set(current.name, name);
267
+ } else {
268
+ name = known;
269
+ }
270
+ }
271
+ output.push(lengthPrefixed("V", name));
272
+ break;
273
+ }
274
+ case "expr":
275
+ output.push(`E${current.items.length}:`);
276
+ for (let index = current.items.length - 1; index >= 0; index -= 1) {
277
+ pending.push(current.items[index]);
278
+ }
279
+ break;
280
+ case "gnd": {
281
+ const encoded = groundedKey(current, mode);
282
+ if (!encoded.ok) return encoded;
283
+ output.push(encoded.key);
284
+ break;
285
+ }
286
+ }
287
+ }
288
+ return { ok: true, key: output.join("") };
289
+ }
290
+ var atomKey = (args) => {
291
+ if (args.length !== 2) return arityError("_fuzz-atom-key", 2, args.length);
292
+ const mode = args[0];
293
+ if (mode.kind !== "sym" || mode.name !== "Exact" && mode.name !== "Alpha" && mode.name !== "Replay" && mode.name !== "AlphaReplay")
294
+ return operationError("InvalidKeyMode", "_fuzz-atom-key", "ExpectedKeyMode");
295
+ const result = structuralAtomKey(args[1], mode.name);
296
+ return ok(result.ok ? gstr(result.key) : result.reason);
297
+ };
298
+ function atomsEqualForKeyMode(left, right, mode) {
299
+ return mode === "Replay" ? replayAtomEqual(left, right) : atomEq(left, right);
300
+ }
301
+ function deduplicateAtoms(args, operation, mode) {
302
+ if (args.length !== 1) return arityError(operation, 1, args.length);
303
+ const values = args[0];
304
+ if (values.kind !== "expr")
305
+ return operationError("InvalidDeduplicationInput", operation, "ExpectedExpression");
306
+ const buckets = /* @__PURE__ */ new Map();
307
+ const unique = [];
308
+ for (const value of values.items) {
309
+ const encoded = structuralAtomKey(value, mode);
310
+ if (!encoded.ok) return ok(encoded.reason);
311
+ const bucket = buckets.get(encoded.key);
312
+ if (bucket?.some((seen) => atomsEqualForKeyMode(seen, value, mode)) === true) continue;
313
+ if (bucket === void 0) buckets.set(encoded.key, [value]);
314
+ else bucket.push(value);
315
+ unique.push(value);
316
+ }
317
+ return ok(expr(unique));
318
+ }
319
+ var deduplicateExact = (args) => deduplicateAtoms(args, "_fuzz-deduplicate-exact", "Exact");
320
+ var deduplicateReplay = (args) => deduplicateAtoms(args, "_fuzz-deduplicate-replay", "Replay");
321
+ function memberAtom(args, operation, mode) {
322
+ if (args.length !== 2) return arityError(operation, 2, args.length);
323
+ const values = args[1];
324
+ if (values.kind !== "expr")
325
+ return operationError("InvalidMembershipInput", operation, "ExpectedExpression");
326
+ const needle = args[0];
327
+ const needleKey = structuralAtomKey(needle, mode);
328
+ if (!needleKey.ok) return ok(needleKey.reason);
329
+ for (const value of values.items) {
330
+ const valueKey = structuralAtomKey(value, mode);
331
+ if (!valueKey.ok) return ok(valueKey.reason);
332
+ if (valueKey.key === needleKey.key && atomsEqualForKeyMode(value, needle, mode))
333
+ return ok(gbool(true));
334
+ }
335
+ return ok(gbool(false));
336
+ }
337
+ var exactMember = (args) => memberAtom(args, "_fuzz-exact-member", "Exact");
338
+ var replayMember = (args) => memberAtom(args, "_fuzz-replay-member", "Replay");
339
+ var makeVariable = (args) => {
340
+ if (args.length !== 1) return arityError("_fuzz-make-variable", 1, args.length);
341
+ const index = integralNumberValue(args[0]);
342
+ if (index === void 0 || index < 0n)
343
+ return operationError(
344
+ "InvalidVariableIndex",
345
+ "_fuzz-make-variable",
346
+ "ExpectedNonNegativeInteger"
347
+ );
348
+ return ok(variable(`fuzz-${index}`));
349
+ };
350
+ var variableMarker = (args) => {
351
+ if (args.length !== 1) return arityError("_fuzz-variable-marker", 1, args.length);
352
+ const index = integralNumberValue(args[0]);
353
+ if (index === void 0 || index < 0n)
354
+ return operationError(
355
+ "InvalidVariableIndex",
356
+ "_fuzz-variable-marker",
357
+ "ExpectedNonNegativeInteger"
358
+ );
359
+ return ok(
360
+ gnd(
361
+ { g: "ext", kind: FUZZ_VARIABLE_MARKER_KIND, id: index.toString() },
362
+ FUZZ_VARIABLE_MARKER_TYPE
363
+ )
364
+ );
365
+ };
366
+ var containsVariableMarker = (args) => {
367
+ if (args.length !== 1) return arityError("_fuzz-contains-variable-marker", 1, args.length);
368
+ const pending = [args[0]];
369
+ while (pending.length > 0) {
370
+ const atom = pending.pop();
371
+ if (atom.kind === "gnd" && atom.value.g === "ext" && atom.value.kind === FUZZ_VARIABLE_MARKER_KIND) {
372
+ return ok(gbool(true));
373
+ }
374
+ if (atom.kind !== "expr") continue;
375
+ for (let index = atom.items.length - 1; index >= 0; index -= 1)
376
+ pending.push(atom.items[index]);
377
+ }
378
+ return ok(gbool(false));
379
+ };
380
+ function materializeGeneratedVariables(root) {
381
+ const frames = [];
382
+ let current = root;
383
+ let completed;
384
+ for (; ; ) {
385
+ if (current.kind === "gnd" && current.value.g === "ext" && current.value.kind === FUZZ_VARIABLE_MARKER_KIND) {
386
+ let index;
387
+ try {
388
+ index = BigInt(current.value.id);
389
+ } catch {
390
+ index = -1n;
391
+ }
392
+ if (index < 0n || index.toString() !== current.value.id)
393
+ return {
394
+ ok: false,
395
+ error: kernelError(
396
+ "InvalidVariableMarker",
397
+ expr([sym("Operation"), sym("_fuzz-materialize-grammar-sample")]),
398
+ sym("ExpectedCanonicalNonNegativeInteger")
399
+ )
400
+ };
401
+ completed = variable(`fuzz-${index}`);
402
+ } else if (current.kind === "expr") {
403
+ if (current.items.length > 0) {
404
+ frames.push({ children: current.items, index: 1, materialized: [] });
405
+ current = current.items[0];
406
+ continue;
407
+ } else {
408
+ completed = current;
409
+ }
410
+ } else {
411
+ completed = current;
412
+ }
413
+ for (; ; ) {
414
+ const frame = frames.at(-1);
415
+ if (frame === void 0) return { ok: true, atom: completed };
416
+ frame.materialized.push(completed);
417
+ if (frame.index < frame.children.length) {
418
+ current = frame.children[frame.index];
419
+ frame.index += 1;
420
+ break;
421
+ }
422
+ frames.pop();
423
+ completed = expr(frame.materialized);
424
+ }
425
+ }
426
+ }
427
+ var materializeGrammarSample = (args) => {
428
+ if (args.length !== 3) return arityError("_fuzz-materialize-grammar-sample", 3, args.length);
429
+ const materialized = materializeGeneratedVariables(args[0]);
430
+ if (!materialized.ok) return ok(materialized.error);
431
+ return ok(expr([FUZZ_SAMPLE_HEAD, materialized.atom, args[1], args[2]]));
432
+ };
433
+ var appendExpressionItem = (args) => {
434
+ if (args.length !== 2) return arityError("_fuzz-expression-append", 2, args.length);
435
+ const values = args[0];
436
+ if (values.kind !== "expr")
437
+ return operationError(
438
+ "InvalidExpressionAppendInput",
439
+ "_fuzz-expression-append",
440
+ "ExpectedExpression"
441
+ );
442
+ return ok(expr([...values.items, args[1]]));
443
+ };
444
+ var concatenateExpressions = (args) => {
445
+ if (args.length !== 2) return arityError("_fuzz-expression-concat", 2, args.length);
446
+ const [left, right] = args;
447
+ if (left.kind !== "expr" || right.kind !== "expr")
448
+ return operationError(
449
+ "InvalidExpressionConcatInput",
450
+ "_fuzz-expression-concat",
451
+ "ExpectedExpressions"
452
+ );
453
+ return ok(expr([...left.items, ...right.items]));
454
+ };
455
+ function grammarSummaryEntries(summary, operation) {
456
+ if (summary.kind !== "expr")
457
+ return kernelError(
458
+ "InvalidGrammarRequirementSummary",
459
+ expr([sym("Operation"), sym(operation)]),
460
+ sym("ExpectedExpression")
461
+ );
462
+ const entries = [];
463
+ for (const encoded of summary.items) {
464
+ if (encoded.kind !== "expr" || encoded.items.length !== 3 || encoded.items[0].kind !== "sym" || encoded.items[0].name !== GRAMMAR_REQUIREMENT_SUMMARY_ENTRY_HEAD.name) {
465
+ return kernelError(
466
+ "InvalidGrammarRequirementSummary",
467
+ expr([sym("Operation"), sym(operation)]),
468
+ sym("MalformedEntry")
469
+ );
470
+ }
471
+ const quotedTarget = encoded.items[1];
472
+ const alternatives = encoded.items[2];
473
+ if (quotedTarget.kind !== "expr" || quotedTarget.items.length !== 2 || quotedTarget.items[0].kind !== "sym" || quotedTarget.items[0].name !== QUOTE_HEAD.name || alternatives.kind !== "expr") {
474
+ return kernelError(
475
+ "InvalidGrammarRequirementSummary",
476
+ expr([sym("Operation"), sym(operation)]),
477
+ sym("MalformedEntry")
478
+ );
479
+ }
480
+ for (const alternative of alternatives.items) {
481
+ if (alternative.kind !== "expr" || alternative.items.length !== 2 || alternative.items[0].kind !== "sym" || alternative.items[0].name !== GRAMMAR_REQUIREMENT_ALTERNATIVE_HEAD.name || alternative.items[1].kind !== "expr") {
482
+ return kernelError(
483
+ "InvalidGrammarRequirementSummary",
484
+ expr([sym("Operation"), sym(operation)]),
485
+ sym("MalformedAlternative")
486
+ );
487
+ }
488
+ }
489
+ entries.push({
490
+ target: quotedTarget.items[1],
491
+ alternatives,
492
+ encoded
493
+ });
494
+ }
495
+ return entries;
496
+ }
497
+ var grammarSummaryAlternatives = (args) => {
498
+ if (args.length !== 2) return arityError("_fuzz-grammar-summary-alternatives", 2, args.length);
499
+ const entries = grammarSummaryEntries(args[0], "_fuzz-grammar-summary-alternatives");
500
+ if (isErrorAtom(entries)) return ok(entries);
501
+ const found = entries.find((entry) => atomEq(entry.target, args[1]));
502
+ return ok(expr([GRAMMAR_REQUIREMENT_ALTERNATIVES_HEAD, found?.alternatives ?? expr([])]));
503
+ };
504
+ var grammarSummaryReplace = (args) => {
505
+ if (args.length !== 3) return arityError("_fuzz-grammar-summary-replace", 3, args.length);
506
+ const entries = grammarSummaryEntries(args[0], "_fuzz-grammar-summary-replace");
507
+ if (isErrorAtom(entries)) return ok(entries);
508
+ const alternatives = args[2];
509
+ if (alternatives.kind !== "expr")
510
+ return operationError(
511
+ "InvalidGrammarRequirementSummary",
512
+ "_fuzz-grammar-summary-replace",
513
+ "ExpectedAlternativesExpression"
514
+ );
515
+ for (const alternative of alternatives.items) {
516
+ if (alternative.kind !== "expr" || alternative.items.length !== 2 || alternative.items[0].kind !== "sym" || alternative.items[0].name !== GRAMMAR_REQUIREMENT_ALTERNATIVE_HEAD.name || alternative.items[1].kind !== "expr") {
517
+ return operationError(
518
+ "InvalidGrammarRequirementSummary",
519
+ "_fuzz-grammar-summary-replace",
520
+ "MalformedAlternative"
521
+ );
522
+ }
523
+ }
524
+ const replacement = expr([
525
+ GRAMMAR_REQUIREMENT_SUMMARY_ENTRY_HEAD,
526
+ expr([QUOTE_HEAD, args[1]]),
527
+ alternatives
528
+ ]);
529
+ const updated = [];
530
+ let replaced = false;
531
+ for (const entry of entries) {
532
+ if (atomEq(entry.target, args[1])) {
533
+ if (!replaced) updated.push(replacement);
534
+ replaced = true;
535
+ } else {
536
+ updated.push(entry.encoded);
537
+ }
538
+ }
539
+ if (!replaced) updated.push(replacement);
540
+ return ok(expr(updated));
541
+ };
542
+ var expressionView = (args) => {
543
+ if (args.length !== 1) return arityError("_fuzz-expression-view", 1, args.length);
544
+ const atom = args[0];
545
+ if (atom.kind !== "expr") return ok(expr([FUZZ_ATOM_LEAF_HEAD]));
546
+ const quoted = atom.items.map((item) => expr([QUOTE_HEAD, item]));
547
+ return ok(
548
+ expr([
549
+ FUZZ_EXPRESSION_VIEW_HEAD,
550
+ expr([sym("Arity"), gint(atom.items.length)]),
551
+ expr([sym("Forward"), expr(quoted)]),
552
+ expr([sym("Reversed"), expr([...quoted].reverse())])
553
+ ])
554
+ );
555
+ };
556
+ function grammarTemplateChildIndices(atom) {
557
+ if (atom.kind !== "expr" || atom.items.length === 0 || atom.items[0].kind !== "sym") return [];
558
+ const head = atom.items[0].name;
559
+ if (head === "Literal" || head === "Field" || head === "Ref" || head === "Fresh" || head === "Use")
560
+ return [];
561
+ if (head === "Bind" && atom.items.length === 3) return [2];
562
+ if (head === "Scoped" && atom.items.length === 3) return [2];
563
+ return atom.items.map((_, index) => index);
564
+ }
565
+ function scanTemplateLeaves(root, leafHead, visit) {
566
+ const pending = [root];
567
+ while (pending.length > 0) {
568
+ const atom = pending.pop();
569
+ if (atom.kind === "expr" && atom.items.length === 2 && atom.items[0].kind === "sym" && atom.items[0].name === leafHead) {
570
+ visit(atom);
571
+ continue;
572
+ }
573
+ const indices = grammarTemplateChildIndices(atom);
574
+ for (let index = indices.length - 1; index >= 0; index -= 1)
575
+ pending.push(atom.items[indices[index]]);
576
+ }
577
+ }
578
+ function rewriteTemplateLeaves(root, leafHead, rewrite) {
579
+ const pending = [{ tag: "visit", atom: root }];
580
+ const completed = [];
581
+ while (pending.length > 0) {
582
+ const task = pending.pop();
583
+ if (task.tag === "build") {
584
+ const built = completed.splice(completed.length - task.indices.length, task.indices.length);
585
+ const items = [...task.atom.items];
586
+ for (let index = 0; index < task.indices.length; index += 1)
587
+ items[task.indices[index]] = built[index];
588
+ completed.push(expr(items));
589
+ continue;
590
+ }
591
+ const atom = task.atom;
592
+ if (atom.kind === "expr" && atom.items.length === 2 && atom.items[0].kind === "sym" && atom.items[0].name === leafHead) {
593
+ const replaced = rewrite(atom);
594
+ if (replaced === null) return null;
595
+ completed.push(replaced);
596
+ continue;
597
+ }
598
+ const indices = grammarTemplateChildIndices(atom);
599
+ if (indices.length === 0 || atom.kind !== "expr") {
600
+ completed.push(atom);
601
+ continue;
602
+ }
603
+ pending.push({ tag: "build", atom, indices });
604
+ for (let index = indices.length - 1; index >= 0; index -= 1)
605
+ pending.push({ tag: "visit", atom: atom.items[indices[index]] });
606
+ }
607
+ return completed[0];
608
+ }
609
+ var grammarFieldExpressions = (args) => {
610
+ if (args.length !== 1) return arityError("_fuzz-grammar-field-expressions", 1, args.length);
611
+ const fields = [];
612
+ scanTemplateLeaves(args[0], "Field", (field2) => {
613
+ fields.push(expr([QUOTE_HEAD, field2.items[1]]));
614
+ });
615
+ return ok(expr([GRAMMAR_FIELD_EXPRESSIONS_HEAD, expr(fields)]));
616
+ };
617
+ var replaceGrammarFields = (args) => {
618
+ if (args.length !== 2) return arityError("_fuzz-grammar-replace-fields", 2, args.length);
619
+ const replacements = args[1];
620
+ if (replacements.kind !== "expr")
621
+ return operationError(
622
+ "InvalidGrammarFieldReplacements",
623
+ "_fuzz-grammar-replace-fields",
624
+ "ExpectedExpression"
625
+ );
626
+ let replacementIndex = 0;
627
+ const rebuilt = rewriteTemplateLeaves(args[0], "Field", (field2) => {
628
+ const replacement = replacements.items[replacementIndex];
629
+ if (replacement === void 0) return null;
630
+ replacementIndex += 1;
631
+ return expr([field2.items[0], replacement]);
632
+ });
633
+ if (rebuilt === null)
634
+ return operationError(
635
+ "InvalidGrammarFieldReplacements",
636
+ "_fuzz-grammar-replace-fields",
637
+ "MissingReplacement"
638
+ );
639
+ if (replacementIndex !== replacements.items.length)
640
+ return operationError(
641
+ "InvalidGrammarFieldReplacements",
642
+ "_fuzz-grammar-replace-fields",
643
+ "TrailingReplacement"
644
+ );
645
+ return ok(rebuilt);
646
+ };
647
+ var indexGrammarReferences = (args) => {
648
+ if (args.length !== 1) return arityError("_fuzz-grammar-index-references", 1, args.length);
649
+ let total = 0;
650
+ scanTemplateLeaves(args[0], "Ref", () => {
651
+ total += 1;
652
+ });
653
+ let ordinal = 0;
654
+ const rebuilt = rewriteTemplateLeaves(args[0], "Ref", (reference) => {
655
+ const indexed = expr([
656
+ GRAMMAR_INDEXED_REFERENCE_HEAD,
657
+ reference.items[1],
658
+ gint(ordinal),
659
+ gint(total)
660
+ ]);
661
+ ordinal += 1;
662
+ return indexed;
663
+ });
664
+ return ok(rebuilt);
665
+ };
666
+ var grammarTemplateProfile = (args) => {
667
+ if (args.length !== 1) return arityError("_fuzz-grammar-template-profile", 1, args.length);
668
+ const root = args[0];
669
+ const pending = [[root, 1]];
670
+ let references = 0;
671
+ let minimumNextId = 0n;
672
+ let nodes = 0;
673
+ let maximumDepth = 0;
674
+ while (pending.length > 0) {
675
+ const [atom, depth] = pending.pop();
676
+ nodes += 1;
677
+ maximumDepth = Math.max(maximumDepth, depth);
678
+ if (atom.kind === "expr" && atom.items.length > 0 && atom.items[0].kind === "sym") {
679
+ const head = atom.items[0].name;
680
+ if (head === "Ref" && atom.items.length === 2) references += 1;
681
+ if (head === "Scoped" && atom.items.length === 3) {
682
+ const bindings = atom.items[1];
683
+ if (bindings.kind === "expr") {
684
+ for (const binding of bindings.items) {
685
+ if (binding.kind === "expr" && binding.items.length === 3 && binding.items[0].kind === "sym" && binding.items[0].name === "Binding") {
686
+ const id = integralNumberValue(binding.items[2]);
687
+ if (id !== void 0 && id >= 0n)
688
+ minimumNextId = minimumNextId > id ? minimumNextId : id + 1n;
689
+ }
690
+ }
691
+ }
692
+ }
693
+ }
694
+ const indices = grammarTemplateChildIndices(atom);
695
+ for (let index = indices.length - 1; index >= 0; index -= 1) {
696
+ pending.push([
697
+ atom.items[indices[index]],
698
+ depth + 1
699
+ ]);
700
+ }
701
+ }
702
+ return ok(
703
+ expr([
704
+ GRAMMAR_TEMPLATE_PROFILE_HEAD,
705
+ expr([sym("Ground"), gbool(root.ground)]),
706
+ expr([sym("References"), gint(references)]),
707
+ expr([sym("MinimumNextId"), gint(minimumNextId)]),
708
+ expr([sym("Nodes"), gint(nodes)]),
709
+ expr([sym("Depth"), gint(maximumDepth)])
710
+ ])
711
+ );
712
+ };
713
+ function parseRequirementList(atom, operation) {
714
+ if (atom.kind !== "expr")
715
+ return kernelError(
716
+ "InvalidGrammarRequirement",
717
+ expr([sym("Operation"), sym(operation)]),
718
+ sym("ExpectedExpression")
719
+ );
720
+ const sorts = [];
721
+ for (const quoted of atom.items) {
722
+ if (quoted.kind !== "expr" || quoted.items.length !== 2 || quoted.items[0].kind !== "sym" || quoted.items[0].name !== QUOTE_HEAD.name)
723
+ return kernelError(
724
+ "InvalidGrammarRequirement",
725
+ expr([sym("Operation"), sym(operation)]),
726
+ sym("MalformedRequirement")
727
+ );
728
+ sorts.push(quoted.items[1]);
729
+ }
730
+ return sorts;
731
+ }
732
+ function parseAlternativeList(atom, operation) {
733
+ if (atom.kind !== "expr")
734
+ return kernelError(
735
+ "InvalidGrammarRequirementAlternatives",
736
+ expr([sym("Operation"), sym(operation)]),
737
+ sym("ExpectedExpression")
738
+ );
739
+ const parsed = [];
740
+ for (const alternative of atom.items) {
741
+ if (alternative.kind !== "expr" || alternative.items.length !== 2 || alternative.items[0].kind !== "sym" || alternative.items[0].name !== GRAMMAR_REQUIREMENT_ALTERNATIVE_HEAD.name)
742
+ return kernelError(
743
+ "InvalidGrammarRequirementAlternatives",
744
+ expr([sym("Operation"), sym(operation)]),
745
+ sym("MalformedAlternative")
746
+ );
747
+ const requirements = parseRequirementList(alternative.items[1], operation);
748
+ if (isErrorAtom(requirements)) return requirements;
749
+ parsed.push({ encoded: alternative, requirements });
750
+ }
751
+ return parsed;
752
+ }
753
+ function requirementMember(sort, requirements) {
754
+ return requirements.some((candidate) => atomEq(candidate, sort));
755
+ }
756
+ function requirementSubset(left, right) {
757
+ return left.every((sort) => requirementMember(sort, right));
758
+ }
759
+ function encodeRequirements(sorts) {
760
+ return expr(sorts.map((sort) => expr([QUOTE_HEAD, sort])));
761
+ }
762
+ function encodeAlternative(sorts) {
763
+ return expr([GRAMMAR_REQUIREMENT_ALTERNATIVE_HEAD, encodeRequirements(sorts)]);
764
+ }
765
+ function alternativesAddCore(alternatives, candidate) {
766
+ for (const existing of alternatives)
767
+ if (requirementSubset(existing.requirements, candidate)) return false;
768
+ const kept = alternatives.filter(
769
+ (existing) => !requirementSubset(candidate, existing.requirements)
770
+ );
771
+ kept.push({ encoded: encodeAlternative(candidate), requirements: candidate });
772
+ alternatives.length = 0;
773
+ alternatives.push(...kept);
774
+ return true;
775
+ }
776
+ function encodeAlternatives(alternatives) {
777
+ return expr(alternatives.map((alternative) => alternative.encoded));
778
+ }
779
+ var grammarAlternativesAdd = (args) => {
780
+ if (args.length !== 2) return arityError("_fuzz-grammar-alternatives-add", 2, args.length);
781
+ const alternatives = parseAlternativeList(args[0], "_fuzz-grammar-alternatives-add");
782
+ if (isErrorAtom(alternatives)) return ok(alternatives);
783
+ const candidate = parseRequirementList(args[1], "_fuzz-grammar-alternatives-add");
784
+ if (isErrorAtom(candidate)) return ok(candidate);
785
+ const mutable = [...alternatives];
786
+ const changed = alternativesAddCore(mutable, candidate);
787
+ return ok(
788
+ expr([
789
+ GRAMMAR_ALTERNATIVES_ADD_HEAD,
790
+ gbool(changed),
791
+ changed ? encodeAlternatives(mutable) : args[0]
792
+ ])
793
+ );
794
+ };
795
+ function removeSortFromAlternatives(alternatives, sort) {
796
+ const reduced = [];
797
+ for (const alternative of alternatives) {
798
+ const kept = alternative.requirements.filter((candidate) => !atomEq(candidate, sort));
799
+ alternativesAddCore(reduced, kept);
800
+ }
801
+ return reduced;
802
+ }
803
+ function parseProductionsTargetArgs(args, code, operation) {
804
+ if (args.length !== 2) return arityError(operation, 2, args.length);
805
+ const productions = args[0];
806
+ const quotedTarget = args[1];
807
+ if (productions.kind !== "expr" || quotedTarget.kind !== "expr" || quotedTarget.items.length !== 2 || quotedTarget.items[0].kind !== "sym" || quotedTarget.items[0].name !== QUOTE_HEAD.name)
808
+ return operationError(code, operation, "ExpectedProductionsAndQuotedTarget");
809
+ return { productions, target: quotedTarget.items[1] };
810
+ }
811
+ var productionsForTargetCache = /* @__PURE__ */ new WeakMap();
812
+ var grammarProductionsForTarget = (args) => {
813
+ const parsed = parseProductionsTargetArgs(
814
+ args,
815
+ "InvalidGrammarProductionLookup",
816
+ "_fuzz-grammar-productions-for-target"
817
+ );
818
+ if ("tag" in parsed) return parsed;
819
+ const { productions, target } = parsed;
820
+ const targetKey = structuralAtomKey(target, "Exact");
821
+ if (!targetKey.ok) return ok(targetKey.reason);
822
+ let byTarget = productionsForTargetCache.get(productions);
823
+ if (byTarget === void 0) {
824
+ byTarget = /* @__PURE__ */ new Map();
825
+ for (const production of productions.items) {
826
+ if (production.kind !== "expr" || production.items.length !== 5 || production.items[0].kind !== "sym" || production.items[0].name !== "GrammarProduction" || production.items[3].kind !== "expr" || production.items[3].items.length !== 2 || production.items[3].items[0].kind !== "sym" || production.items[3].items[0].name !== QUOTE_HEAD.name)
827
+ return operationError(
828
+ "InvalidGrammarProductionLookup",
829
+ "_fuzz-grammar-productions-for-target",
830
+ "MalformedProduction"
831
+ );
832
+ const candidateKey = structuralAtomKey(production.items[3].items[1], "Exact");
833
+ if (!candidateKey.ok) return ok(candidateKey.reason);
834
+ const bucket = byTarget.get(candidateKey.key);
835
+ if (bucket === void 0) byTarget.set(candidateKey.key, expr([production]));
836
+ else
837
+ byTarget.set(
838
+ candidateKey.key,
839
+ expr([...bucket.items, production])
840
+ );
841
+ }
842
+ productionsForTargetCache.set(productions, byTarget);
843
+ }
844
+ return ok(expr([GRAMMAR_PRODUCTIONS_HEAD, byTarget.get(targetKey.key) ?? expr([])]));
845
+ };
846
+ function summaryAlternativesFor(entries, target) {
847
+ const found = entries.find((entry) => atomEq(entry.target, target));
848
+ if (found === void 0) return [];
849
+ return parseAlternativeList(found.alternatives, "_fuzz-grammar-template-requirements");
850
+ }
851
+ function combineAlternatives(left, right) {
852
+ const combined = [];
853
+ for (const leftEntry of left) {
854
+ for (const rightEntry of right) {
855
+ const union = [...leftEntry.requirements];
856
+ for (const sort of rightEntry.requirements)
857
+ if (!requirementMember(sort, union)) union.push(sort);
858
+ alternativesAddCore(combined, union);
859
+ }
860
+ }
861
+ return combined;
862
+ }
863
+ var parsedSummaryCache = /* @__PURE__ */ new WeakMap();
864
+ function parsedSummaryFor(summary) {
865
+ const cached = parsedSummaryCache.get(summary);
866
+ if (cached !== void 0) return cached;
867
+ const entries = grammarSummaryEntries(summary, "_fuzz-grammar-template-requirements-op");
868
+ const result = isErrorAtom(entries) ? entries : { entries, byTarget: /* @__PURE__ */ new Map() };
869
+ parsedSummaryCache.set(summary, result);
870
+ return result;
871
+ }
872
+ function summaryAlternativesCached(parsed, target) {
873
+ const key = structuralAtomKey(target, "Exact");
874
+ if (!key.ok) return key.reason;
875
+ const cached = parsed.byTarget.get(key.key);
876
+ if (cached !== void 0) return cached;
877
+ const computed = summaryAlternativesFor(parsed.entries, target);
878
+ parsed.byTarget.set(key.key, computed);
879
+ return computed;
880
+ }
881
+ var grammarTemplateRequirements = (args) => {
882
+ if (args.length !== 2)
883
+ return arityError("_fuzz-grammar-template-requirements-op", 2, args.length);
884
+ const parsedSummary = parsedSummaryFor(args[1]);
885
+ if (!("entries" in parsedSummary)) return ok(parsedSummary);
886
+ const summaryIndex = parsedSummary;
887
+ const analyzed = analyzeTemplateRequirements(
888
+ args[0],
889
+ (target) => summaryAlternativesCached(summaryIndex, target)
890
+ );
891
+ if (isErrorAtom(analyzed)) return ok(analyzed);
892
+ return ok(expr([GRAMMAR_REQUIREMENT_ALTERNATIVES_HEAD, encodeAlternatives(analyzed)]));
893
+ };
894
+ function analyzeTemplateRequirements(template, lookup) {
895
+ const pending = [{ tag: "visit", atom: template }];
896
+ const results = [];
897
+ const staticNode = { dynamic: false, alternatives: [] };
898
+ while (pending.length > 0) {
899
+ const task = pending.pop();
900
+ if (task.tag === "discharge") {
901
+ const child = results.pop();
902
+ if (!child.dynamic) {
903
+ results.push(child);
904
+ continue;
905
+ }
906
+ let reduced = [...child.alternatives];
907
+ for (const sort of task.sorts) reduced = removeSortFromAlternatives(reduced, sort);
908
+ results.push({ dynamic: true, alternatives: reduced });
909
+ continue;
910
+ }
911
+ if (task.tag === "combine") {
912
+ const children = results.splice(results.length - task.childCount, task.childCount);
913
+ const dynamicChildren = children.filter((child) => child.dynamic);
914
+ if (dynamicChildren.length === 0) {
915
+ results.push(staticNode);
916
+ continue;
917
+ }
918
+ let alternatives = dynamicChildren[0].alternatives;
919
+ for (let index = 1; index < dynamicChildren.length; index += 1)
920
+ alternatives = combineAlternatives(alternatives, dynamicChildren[index].alternatives);
921
+ results.push({ dynamic: true, alternatives });
922
+ continue;
923
+ }
924
+ const atom = task.atom;
925
+ if (atom.kind === "expr" && atom.items.length > 0 && atom.items[0].kind === "sym") {
926
+ const head = atom.items[0].name;
927
+ if ((head === "Literal" || head === "Field" || head === "Fresh") && atom.items.length === 2) {
928
+ results.push(staticNode);
929
+ continue;
930
+ }
931
+ if (head === "Use" && atom.items.length === 2) {
932
+ results.push({
933
+ dynamic: true,
934
+ alternatives: [
935
+ {
936
+ encoded: encodeAlternative([atom.items[1]]),
937
+ requirements: [atom.items[1]]
938
+ }
939
+ ]
940
+ });
941
+ continue;
942
+ }
943
+ if (head === "Ref" && atom.items.length === 2 || head === GRAMMAR_INDEXED_REFERENCE_HEAD.name && atom.items.length === 4) {
944
+ const referenced = lookup(atom.items[1]);
945
+ if (isErrorAtom(referenced)) return referenced;
946
+ results.push({ dynamic: true, alternatives: referenced });
947
+ continue;
948
+ }
949
+ if (head === "Bind" && atom.items.length === 3) {
950
+ pending.push({ tag: "discharge", sorts: [atom.items[1]] });
951
+ pending.push({ tag: "visit", atom: atom.items[2] });
952
+ continue;
953
+ }
954
+ if (head === "Scoped" && atom.items.length === 3) {
955
+ const bindings = atom.items[1];
956
+ if (bindings.kind !== "expr")
957
+ return kernelError(
958
+ "InvalidGrammarTemplate",
959
+ expr([sym("Operation"), sym("_fuzz-grammar-template-requirements-op")]),
960
+ sym("MalformedScopedBindings")
961
+ );
962
+ const sorts = [];
963
+ for (const binding of bindings.items) {
964
+ if (binding.kind !== "expr" || binding.items.length !== 3 || binding.items[0].kind !== "sym" || binding.items[0].name !== "Binding")
965
+ return kernelError(
966
+ "InvalidGrammarTemplate",
967
+ expr([sym("Operation"), sym("_fuzz-grammar-template-requirements-op")]),
968
+ sym("MalformedScopedBindings")
969
+ );
970
+ sorts.push(binding.items[1]);
971
+ }
972
+ pending.push({ tag: "discharge", sorts });
973
+ pending.push({ tag: "visit", atom: atom.items[2] });
974
+ continue;
975
+ }
976
+ }
977
+ if (atom.kind === "expr" && atom.items.length > 0) {
978
+ pending.push({ tag: "combine", childCount: atom.items.length });
979
+ for (let index = atom.items.length - 1; index >= 0; index -= 1)
980
+ pending.push({ tag: "visit", atom: atom.items[index] });
981
+ continue;
982
+ }
983
+ results.push(staticNode);
984
+ }
985
+ if (results.length !== 1)
986
+ return kernelError(
987
+ "InvalidGrammarTemplate",
988
+ expr([sym("Operation"), sym("_fuzz-grammar-template-requirements-op")]),
989
+ sym("InvalidTraversalResult")
990
+ );
991
+ const root = results[0];
992
+ return root.dynamic ? [...root.alternatives] : [{ encoded: encodeAlternative([]), requirements: [] }];
993
+ }
994
+ var grammarProductivityOp = (args) => {
995
+ if (args.length !== 3) return arityError("_fuzz-grammar-productivity-op", 3, args.length);
996
+ const [productionsAtom, quotedRoot, targetsAtom] = args;
997
+ const root = quotedRoot === void 0 ? void 0 : unquote(quotedRoot);
998
+ if (productionsAtom.kind !== "expr" || root === void 0 || targetsAtom.kind !== "expr")
999
+ return operationError(
1000
+ "InvalidGrammarProductivity",
1001
+ "_fuzz-grammar-productivity-op",
1002
+ "ExpectedProductionsRootTargets"
1003
+ );
1004
+ const productions = productionsAtom.items;
1005
+ const analyses = [];
1006
+ for (const production of productions) {
1007
+ if (production.kind !== "expr" || production.items.length !== 5 || production.items[3].kind !== "expr" || production.items[3].items.length !== 2 || production.items[4].kind !== "expr" || production.items[4].items.length !== 2)
1008
+ return operationError(
1009
+ "InvalidGrammarProductivity",
1010
+ "_fuzz-grammar-productivity-op",
1011
+ "MalformedProduction"
1012
+ );
1013
+ const target = production.items[3].items[1];
1014
+ const key = structuralAtomKey(target, "Exact");
1015
+ if (!key.ok) return ok(key.reason);
1016
+ analyses.push({ targetKey: key.key, target, template: production.items[4].items[1] });
1017
+ }
1018
+ const dependents = /* @__PURE__ */ new Map();
1019
+ for (let index = 0; index < analyses.length; index += 1) {
1020
+ for (const referenced of templateReferenceTargetAtoms(analyses[index].template)) {
1021
+ const key = structuralAtomKey(referenced, "Exact");
1022
+ if (!key.ok) return ok(key.reason);
1023
+ const bucket = dependents.get(key.key);
1024
+ if (bucket === void 0) dependents.set(key.key, [index]);
1025
+ else if (bucket[bucket.length - 1] !== index) bucket.push(index);
1026
+ }
1027
+ }
1028
+ const summary = /* @__PURE__ */ new Map();
1029
+ const lookup = (target) => {
1030
+ const key = structuralAtomKey(target, "Exact");
1031
+ if (!key.ok) return key.reason;
1032
+ return summary.get(key.key) ?? [];
1033
+ };
1034
+ const queue = [];
1035
+ for (let index = analyses.length - 1; index >= 0; index -= 1) queue.push(index);
1036
+ while (queue.length > 0) {
1037
+ const index = queue.pop();
1038
+ const analysis = analyses[index];
1039
+ const alternatives = analyzeTemplateRequirements(analysis.template, lookup);
1040
+ if (isErrorAtom(alternatives)) return ok(alternatives);
1041
+ const current = summary.get(analysis.targetKey) ?? [];
1042
+ let changed = false;
1043
+ for (const alternative of alternatives)
1044
+ if (alternativesAddCore(current, alternative.requirements)) changed = true;
1045
+ if (!changed) continue;
1046
+ summary.set(analysis.targetKey, current);
1047
+ const affected = dependents.get(analysis.targetKey);
1048
+ if (affected !== void 0)
1049
+ for (let position = affected.length - 1; position >= 0; position -= 1)
1050
+ queue.push(affected[position]);
1051
+ }
1052
+ for (const quotedTarget of targetsAtom.items) {
1053
+ const target = unquote(quotedTarget);
1054
+ if (target === void 0)
1055
+ return operationError(
1056
+ "InvalidGrammarProductivity",
1057
+ "_fuzz-grammar-productivity-op",
1058
+ "MalformedTarget"
1059
+ );
1060
+ const key = structuralAtomKey(target, "Exact");
1061
+ if (!key.ok) return ok(key.reason);
1062
+ if ((summary.get(key.key) ?? []).length === 0)
1063
+ return ok(expr([sym("GrammarUnproductive"), quoteAtom(target)]));
1064
+ }
1065
+ const rootKey = structuralAtomKey(root, "Exact");
1066
+ if (!rootKey.ok) return ok(rootKey.reason);
1067
+ const rootClosed = (summary.get(rootKey.key) ?? []).some(
1068
+ (alternative) => alternative.requirements.length === 0
1069
+ );
1070
+ if (!rootClosed) return ok(expr([sym("GrammarUnproductive"), quoteAtom(root)]));
1071
+ return ok(expr([sym("ValidGrammarProductivity")]));
1072
+ };
1073
+ var eligibilityCache = /* @__PURE__ */ new WeakMap();
1074
+ function scopeEntriesFrom(scope, operation) {
1075
+ if (scope.kind !== "expr")
1076
+ return kernelError(
1077
+ "InvalidGrammarScope",
1078
+ expr([sym("Operation"), sym(operation)]),
1079
+ sym("ExpectedExpression")
1080
+ );
1081
+ const out = [];
1082
+ for (const binding of scope.items) {
1083
+ if (binding.kind !== "expr" || binding.items.length !== 3 || binding.items[0].kind !== "sym" || binding.items[0].name !== "GrammarBinding" || binding.items[1].kind !== "expr" || binding.items[1].items.length !== 2 || binding.items[1].items[0].kind !== "sym" || binding.items[1].items[0].name !== QUOTE_HEAD.name)
1084
+ return kernelError(
1085
+ "InvalidGrammarScope",
1086
+ expr([sym("Operation"), sym(operation)]),
1087
+ sym("MalformedBinding")
1088
+ );
1089
+ out.push({ sort: binding.items[1].items[1], id: binding.items[2] });
1090
+ }
1091
+ return out;
1092
+ }
1093
+ function scopeCacheKey(entries) {
1094
+ const parts = [];
1095
+ for (const entry of entries) {
1096
+ const sortKey = structuralAtomKey(entry.sort, "Exact");
1097
+ if (!sortKey.ok) return sortKey.reason;
1098
+ const idKey = entry.id === void 0 ? "" : structuralAtomKey(entry.id, "Exact");
1099
+ if (typeof idKey !== "string" && !idKey.ok) return idKey.reason;
1100
+ parts.push(`${sortKey.key}=${typeof idKey === "string" ? idKey : idKey.key}`);
1101
+ }
1102
+ return [...new Set(parts)].sort().join(" ");
1103
+ }
1104
+ function referenceChildSize(size, ordinal, total) {
1105
+ const budget = size - 1n < 0n ? 0n : size - 1n;
1106
+ const base = budget / total;
1107
+ const remainder = budget % total;
1108
+ return base + (ordinal < remainder ? 1n : 0n);
1109
+ }
1110
+ var grammarEligibleProductions = (args) => {
1111
+ if (args.length !== 4) return arityError("_fuzz-grammar-eligible-productions-op", 4, args.length);
1112
+ const [productionsAtom, quotedTarget, scopeAtom, sizeAtom] = args;
1113
+ const size = integralNumberValue(sizeAtom);
1114
+ if (size === void 0)
1115
+ return operationError(
1116
+ "InvalidGrammarEligibility",
1117
+ "_fuzz-grammar-eligible-productions-op",
1118
+ "ExpectedIntegerSize"
1119
+ );
1120
+ if (productionsAtom.kind !== "expr" || quotedTarget.kind !== "expr" || quotedTarget.items.length !== 2 || quotedTarget.items[0].kind !== "sym" || quotedTarget.items[0].name !== QUOTE_HEAD.name)
1121
+ return operationError(
1122
+ "InvalidGrammarEligibility",
1123
+ "_fuzz-grammar-eligible-productions-op",
1124
+ "ExpectedProductionsAndQuotedTarget"
1125
+ );
1126
+ const scopeEntries = scopeEntriesFrom(scopeAtom, "_fuzz-grammar-eligible-productions-op");
1127
+ if (!Array.isArray(scopeEntries)) return ok(scopeEntries);
1128
+ let cache = eligibilityCache.get(productionsAtom);
1129
+ if (cache === void 0) {
1130
+ cache = /* @__PURE__ */ new Map();
1131
+ eligibilityCache.set(productionsAtom, cache);
1132
+ }
1133
+ const productionsFor = (target) => {
1134
+ const looked = grammarProductionsForTarget([productionsAtom, expr([QUOTE_HEAD, target])]);
1135
+ if (looked.tag !== "ok" || looked.results.length !== 1)
1136
+ return kernelError(
1137
+ "InvalidGrammarEligibility",
1138
+ expr([sym("Operation"), sym("_fuzz-grammar-eligible-productions-op")]),
1139
+ sym("ProductionLookupFailed")
1140
+ );
1141
+ const result = looked.results[0];
1142
+ if (result.kind !== "expr" || result.items.length !== 2 || result.items[0].kind !== "sym" || result.items[0].name !== GRAMMAR_PRODUCTIONS_HEAD.name || result.items[1].kind !== "expr")
1143
+ return result;
1144
+ return result.items[1].items;
1145
+ };
1146
+ function fitsTemplate(template, scope, templateSize) {
1147
+ const tasks = [{ atom: template, scope }];
1148
+ while (tasks.length > 0) {
1149
+ const task = tasks.pop();
1150
+ const atom = task.atom;
1151
+ if (atom.kind !== "expr" || atom.items.length === 0) continue;
1152
+ const h = atom.items[0];
1153
+ if (h.kind === "sym") {
1154
+ const head = h.name;
1155
+ if ((head === "Literal" || head === "Field" || head === "Fresh") && atom.items.length === 2)
1156
+ continue;
1157
+ if (head === "Use" && atom.items.length === 2) {
1158
+ const sort = atom.items[1];
1159
+ if (!task.scope.some((entry) => atomEq(entry.sort, sort))) return false;
1160
+ continue;
1161
+ }
1162
+ if (head === "Ref" && atom.items.length === 2 || head === GRAMMAR_INDEXED_REFERENCE_HEAD.name && atom.items.length === 4) {
1163
+ if (templateSize <= 0n) return false;
1164
+ let ordinal = 0n;
1165
+ let total = 1n;
1166
+ if (atom.items.length === 4) {
1167
+ const seenOrdinal = integralNumberValue(atom.items[2]);
1168
+ const seenTotal = integralNumberValue(atom.items[3]);
1169
+ if (seenOrdinal === void 0 || seenTotal === void 0 || seenTotal <= 0n || seenOrdinal < 0n || seenOrdinal >= seenTotal)
1170
+ return {
1171
+ error: kernelError(
1172
+ "InvalidGrammarEligibility",
1173
+ expr([sym("Operation"), sym("_fuzz-grammar-eligible-productions-op")]),
1174
+ sym("MalformedIndexedReference")
1175
+ )
1176
+ };
1177
+ ordinal = seenOrdinal;
1178
+ total = seenTotal;
1179
+ }
1180
+ const childSize = referenceChildSize(templateSize, ordinal, total);
1181
+ const eligible = eligibleFor(atom.items[1], task.scope, childSize);
1182
+ if (typeof eligible !== "boolean") return eligible;
1183
+ if (!eligible) return false;
1184
+ continue;
1185
+ }
1186
+ if (head === "Bind" && atom.items.length === 3) {
1187
+ tasks.push({
1188
+ atom: atom.items[2],
1189
+ scope: [{ sort: atom.items[1], id: void 0 }, ...task.scope]
1190
+ });
1191
+ continue;
1192
+ }
1193
+ if (head === "Scoped" && atom.items.length === 3) {
1194
+ const bindings = atom.items[1];
1195
+ if (bindings.kind !== "expr")
1196
+ return {
1197
+ error: kernelError(
1198
+ "InvalidGrammarEligibility",
1199
+ expr([sym("Operation"), sym("_fuzz-grammar-eligible-productions-op")]),
1200
+ sym("MalformedScopedBindings")
1201
+ )
1202
+ };
1203
+ const added = [];
1204
+ for (const binding of bindings.items) {
1205
+ if (binding.kind !== "expr" || binding.items.length !== 3 || binding.items[0].kind !== "sym" || binding.items[0].name !== "Binding")
1206
+ return {
1207
+ error: kernelError(
1208
+ "InvalidGrammarEligibility",
1209
+ expr([sym("Operation"), sym("_fuzz-grammar-eligible-productions-op")]),
1210
+ sym("MalformedScopedBindings")
1211
+ )
1212
+ };
1213
+ added.push({ sort: binding.items[1], id: binding.items[2] });
1214
+ }
1215
+ for (const entry of added)
1216
+ if (entry.id !== void 0 && task.scope.some(
1217
+ (existing) => existing.id !== void 0 && atomEq(existing.id, entry.id)
1218
+ ))
1219
+ return {
1220
+ error: expr([sym("FitDuplicateGrammarBindingId"), expr([QUOTE_HEAD, bindings])])
1221
+ };
1222
+ tasks.push({ atom: atom.items[2], scope: [...added, ...task.scope] });
1223
+ continue;
1224
+ }
1225
+ }
1226
+ for (let index = atom.items.length - 1; index >= 0; index -= 1)
1227
+ tasks.push({ atom: atom.items[index], scope: task.scope });
1228
+ }
1229
+ return true;
1230
+ }
1231
+ function eligibleFor(target, scope, targetSize) {
1232
+ const list = eligibleListFor(target, scope, targetSize);
1233
+ if (list.kind !== "expr") return { error: list };
1234
+ return list.items.length > 0;
1235
+ }
1236
+ function eligibleListFor(target, scope, targetSize) {
1237
+ const targetKey = structuralAtomKey(target, "Exact");
1238
+ if (!targetKey.ok) return targetKey.reason;
1239
+ const scopeKey = scopeCacheKey(scope);
1240
+ if (typeof scopeKey !== "string") return scopeKey;
1241
+ const key = `${targetKey.key}#${targetSize}#${scopeKey}`;
1242
+ const cached = cache.get(key);
1243
+ if (cached !== void 0) return cached;
1244
+ const candidates = productionsFor(target);
1245
+ if (isErrorAtom(candidates)) return candidates;
1246
+ const eligible = [];
1247
+ for (const production of candidates) {
1248
+ if (production.kind !== "expr" || production.items.length !== 5 || production.items[4].kind !== "expr" || production.items[4].items.length !== 2)
1249
+ return kernelError(
1250
+ "InvalidGrammarEligibility",
1251
+ expr([sym("Operation"), sym("_fuzz-grammar-eligible-productions-op")]),
1252
+ sym("MalformedProduction")
1253
+ );
1254
+ const outcome = fitsTemplate(production.items[4].items[1], scope, targetSize);
1255
+ if (typeof outcome !== "boolean") return outcome.error;
1256
+ if (outcome) eligible.push(production);
1257
+ }
1258
+ const result = expr([sym("EligibleGrammarProductions"), expr(eligible)]);
1259
+ cache.set(key, result);
1260
+ return result;
1261
+ }
1262
+ return ok(eligibleListFor(quotedTarget.items[1], scopeEntries, size));
1263
+ };
1264
+ function rngStateOf(atom) {
1265
+ return parseRngState(atom);
1266
+ }
1267
+ function rngAtomOf(state) {
1268
+ return rngStateAtom(state);
1269
+ }
1270
+ function drawIntFromState(state, lower, upper) {
1271
+ const rng = xorshift128plusFromState(state);
1272
+ const value = uniformBigInt(rng, lower, upper);
1273
+ return [value, rng.getState()];
1274
+ }
1275
+ var decisionLeaves = (args) => {
1276
+ if (args.length !== 1) return arityError("_fuzz-decision-leaves-op", 1, args.length);
1277
+ const leaves = [];
1278
+ const pending = [args[0]];
1279
+ while (pending.length > 0) {
1280
+ const decision = pending.pop();
1281
+ if (decision.kind === "expr" && decision.items.length === 6 && decision.items[0].kind === "sym" && decision.items[0].name === DECISION_HEAD.name && decision.items[1].kind === "sym" && decision.items[1].name === "Int" && decision.items[5].kind === "expr" && decision.items[5].items.length === 0) {
1282
+ leaves.push(decision);
1283
+ continue;
1284
+ }
1285
+ if (decision.kind === "expr" && decision.items.length === 5 && decision.items[0].kind === "sym" && decision.items[0].name === DECISION_HEAD.name && decision.items[4].kind === "expr") {
1286
+ const children = decision.items[4].items;
1287
+ for (let index = children.length - 1; index >= 0; index -= 1) pending.push(children[index]);
1288
+ continue;
1289
+ }
1290
+ return ok(
1291
+ expr([
1292
+ FUZZ_GENERATION_ERROR_HEAD,
1293
+ sym("MalformedDecisionTree"),
1294
+ expr([sym("Details"), expr([sym("Decision"), decision])])
1295
+ ])
1296
+ );
1297
+ }
1298
+ return ok(expr([sym("FuzzDecisionLeaves"), expr(leaves)]));
1299
+ };
1300
+ var GEN_RUN_HEAD = sym("FuzzGenRun");
1301
+ var GEN_CUT_HEAD = sym("FuzzGenCut");
1302
+ var GF_HEAD = sym("GF");
1303
+ var GFB_SYM = sym("GFB");
1304
+ var FUZZ_STACK_BOTTOM_SYM = sym("FuzzStackBottom");
1305
+ var MACHINE_DONE_HEAD = sym("GrammarMachineDone");
1306
+ var MACHINE_NEED_HEAD = sym("GrammarMachineNeed");
1307
+ var MACHINE_START_HEAD = sym("GrammarMachineStart");
1308
+ var MACHINE_RESUME_HEAD = sym("GrammarMachineResume");
1309
+ var EVALUATE_GENERATOR_HEAD = sym("EvaluateGenerator");
1310
+ var DECISION_HEAD = sym("Decision");
1311
+ function machineError(code, ...details) {
1312
+ return expr([FUZZ_GENERATION_ERROR_HEAD, sym(code), expr([sym("Details"), ...details])]);
1313
+ }
1314
+ function quoteAtom(a) {
1315
+ return expr([QUOTE_HEAD, a]);
1316
+ }
1317
+ function intDecisionAtom(lower, upper, origin, value) {
1318
+ return expr([
1319
+ DECISION_HEAD,
1320
+ sym("Int"),
1321
+ expr([sym("Bounds"), gint(lower), gint(upper)]),
1322
+ expr([sym("Origin"), gint(origin)]),
1323
+ expr([sym("Value"), gint(value)]),
1324
+ expr([])
1325
+ ]);
1326
+ }
1327
+ function decodeDriver(atom) {
1328
+ if (atom.kind !== "expr" || atom.items.length !== 3 || atom.items[0].kind !== "sym" || atom.items[0].name !== FUZZ_DRIVER_HEAD.name || atom.items[1].kind !== "sym")
1329
+ return machineError("MalformedDriver", expr([sym("Driver"), atom]));
1330
+ const mode = atom.items[1].name;
1331
+ const payload = atom.items[2];
1332
+ if (mode === "Random") {
1333
+ const rng = rngStateOf(payload);
1334
+ if (rng === void 0) return machineError("MalformedDriver", expr([sym("Driver"), atom]));
1335
+ return { mode: "Random", rng };
1336
+ }
1337
+ if (mode === "Edge") {
1338
+ const index = integralNumberValue(payload);
1339
+ if (index === void 0 || index < 0n)
1340
+ return machineError("MalformedDriver", expr([sym("Driver"), atom]));
1341
+ return { mode: "Edge", index };
1342
+ }
1343
+ if (mode === "Replay" || mode === "ShrinkReplay") {
1344
+ const stateHead = mode === "Replay" ? "ReplayState" : "ShrinkReplayState";
1345
+ if (payload.kind !== "expr" || payload.items.length !== 3 || payload.items[0].kind !== "sym" || payload.items[0].name !== stateHead || payload.items[1].kind !== "expr")
1346
+ return machineError("MalformedDriver", expr([sym("Driver"), atom]));
1347
+ const cursor = integralNumberValue(payload.items[2]);
1348
+ if (cursor === void 0) return machineError("MalformedDriver", expr([sym("Driver"), atom]));
1349
+ return mode === "Replay" ? { mode: "Replay", leaves: payload.items[1].items, cursor } : { mode: "ShrinkReplay", leaves: payload.items[1].items, cursor };
1350
+ }
1351
+ if (mode === "Exhaustive") {
1352
+ if (payload.kind !== "expr" || payload.items.length !== 4 || payload.items[0].kind !== "sym" || payload.items[0].name !== "ExhaustiveCursor" || payload.items[1].kind !== "expr" || payload.items[3].kind !== "expr")
1353
+ return machineError("MalformedExhaustiveState", expr([sym("State"), payload]));
1354
+ const choices = [];
1355
+ for (const item of payload.items[1].items) {
1356
+ const choice = integralNumberValue(item);
1357
+ if (choice === void 0)
1358
+ return machineError("MalformedExhaustiveState", expr([sym("State"), payload]));
1359
+ choices.push(choice);
1360
+ }
1361
+ const cursor = integralNumberValue(payload.items[2]);
1362
+ if (cursor === void 0 || cursor < 0n)
1363
+ return machineError("MalformedExhaustiveState", expr([sym("State"), payload]));
1364
+ return { mode: "Exhaustive", choices, cursor, frames: payload.items[3].items };
1365
+ }
1366
+ if (mode === "Bytes") {
1367
+ if (payload.kind !== "expr" || payload.items.length !== 3 || payload.items[0].kind !== "sym" || payload.items[0].name !== "BytesState" || payload.items[1].kind !== "expr")
1368
+ return machineError("MalformedByteState", expr([sym("State"), payload]));
1369
+ const cursor = integralNumberValue(payload.items[2]);
1370
+ if (cursor === void 0)
1371
+ return machineError("MalformedByteState", expr([sym("State"), payload]));
1372
+ return { mode: "Bytes", bytes: payload.items[1].items, cursor };
1373
+ }
1374
+ return machineError("MalformedDriver", expr([sym("Driver"), atom]));
1375
+ }
1376
+ function encodeDriver(driver) {
1377
+ switch (driver.mode) {
1378
+ case "Random":
1379
+ return expr([FUZZ_DRIVER_HEAD, sym("Random"), rngAtomOf(driver.rng)]);
1380
+ case "Edge":
1381
+ return expr([FUZZ_DRIVER_HEAD, sym("Edge"), gint(driver.index)]);
1382
+ case "Replay":
1383
+ return expr([
1384
+ FUZZ_DRIVER_HEAD,
1385
+ sym("Replay"),
1386
+ expr([sym("ReplayState"), expr([...driver.leaves]), gint(driver.cursor)])
1387
+ ]);
1388
+ case "ShrinkReplay":
1389
+ return expr([
1390
+ FUZZ_DRIVER_HEAD,
1391
+ sym("ShrinkReplay"),
1392
+ expr([sym("ShrinkReplayState"), expr([...driver.leaves]), gint(driver.cursor)])
1393
+ ]);
1394
+ case "Exhaustive":
1395
+ return expr([
1396
+ FUZZ_DRIVER_HEAD,
1397
+ sym("Exhaustive"),
1398
+ expr([
1399
+ sym("ExhaustiveCursor"),
1400
+ expr(driver.choices.map((choice) => gint(choice))),
1401
+ gint(driver.cursor),
1402
+ expr([...driver.frames])
1403
+ ])
1404
+ ]);
1405
+ case "Bytes":
1406
+ return expr([
1407
+ FUZZ_DRIVER_HEAD,
1408
+ sym("Bytes"),
1409
+ expr([sym("BytesState"), expr([...driver.bytes]), gint(driver.cursor)])
1410
+ ]);
1411
+ }
1412
+ }
1413
+ function inspectIntLeaf(leaf, lower, upper, origin) {
1414
+ if (leaf.kind !== "expr" || leaf.items.length !== 6 || leaf.items[0].kind !== "sym" || leaf.items[0].name !== DECISION_HEAD.name || leaf.items[1].kind !== "sym" || leaf.items[1].name !== "Int" || leaf.items[5].kind !== "expr" || leaf.items[5].items.length !== 0)
1415
+ return { tag: "malformed" };
1416
+ const bounds = leaf.items[2];
1417
+ const originAtom = leaf.items[3];
1418
+ const valueAtom = leaf.items[4];
1419
+ if (bounds.kind !== "expr" || bounds.items.length !== 3 || originAtom.kind !== "expr" || originAtom.items.length !== 2 || valueAtom.kind !== "expr" || valueAtom.items.length !== 2)
1420
+ return { tag: "malformed" };
1421
+ const seenLower = integralNumberValue(bounds.items[1]);
1422
+ const seenUpper = integralNumberValue(bounds.items[2]);
1423
+ const seenOrigin = integralNumberValue(originAtom.items[1]);
1424
+ const value = integralNumberValue(valueAtom.items[1]);
1425
+ if (seenLower === void 0 || seenUpper === void 0 || seenOrigin === void 0 || value === void 0)
1426
+ return { tag: "malformed" };
1427
+ if (seenLower !== lower || seenUpper !== upper || seenOrigin !== origin)
1428
+ return {
1429
+ tag: "metadata",
1430
+ bounds: [bounds.items[1], bounds.items[2]],
1431
+ origin: originAtom.items[1]
1432
+ };
1433
+ if (value < lower || value > upper) return { tag: "out-of-bounds", value };
1434
+ return { tag: "compatible", value };
1435
+ }
1436
+ function driverInt(driver, lower, upper, origin) {
1437
+ if (lower > upper)
1438
+ return {
1439
+ tag: "error",
1440
+ error: machineError("InvalidIntegerBounds", expr([sym("Bounds"), gint(lower), gint(upper)]))
1441
+ };
1442
+ switch (driver.mode) {
1443
+ case "Random": {
1444
+ const [value, next] = drawIntFromState(driver.rng, lower, upper);
1445
+ return {
1446
+ tag: "one",
1447
+ value,
1448
+ driver: { mode: "Random", rng: next },
1449
+ decision: intDecisionAtom(lower, upper, origin, value)
1450
+ };
1451
+ }
1452
+ case "Edge": {
1453
+ const candidates = [];
1454
+ const add = (candidate) => {
1455
+ if (candidate < lower || candidate > upper) return;
1456
+ if (!candidates.includes(candidate)) candidates.push(candidate);
1457
+ };
1458
+ add(origin);
1459
+ add(lower);
1460
+ add(upper);
1461
+ add(0n);
1462
+ add(-1n);
1463
+ add(1n);
1464
+ add((lower + upper) / 2n);
1465
+ const count = BigInt(candidates.length);
1466
+ const position = driver.index % count;
1467
+ const value = candidates[Number(position)];
1468
+ return {
1469
+ tag: "one",
1470
+ value,
1471
+ driver: { mode: "Edge", index: driver.index + 1n },
1472
+ decision: intDecisionAtom(lower, upper, origin, value)
1473
+ };
1474
+ }
1475
+ case "Replay": {
1476
+ if (driver.leaves.length === 0)
1477
+ return {
1478
+ tag: "error",
1479
+ error: machineError(
1480
+ "ReplayMismatch",
1481
+ expr([sym("Path"), gint(driver.cursor)]),
1482
+ expr([
1483
+ sym("Expected"),
1484
+ expr([
1485
+ DECISION_HEAD,
1486
+ sym("Int"),
1487
+ expr([sym("Bounds"), gint(lower), gint(upper)]),
1488
+ expr([sym("Origin"), gint(origin)]),
1489
+ expr([sym("Value"), sym("Any")]),
1490
+ expr([])
1491
+ ])
1492
+ ]),
1493
+ expr([sym("Actual"), sym("EndOfTrace")])
1494
+ )
1495
+ };
1496
+ const leaf = driver.leaves[0];
1497
+ const inspected = inspectIntLeaf(leaf, lower, upper, origin);
1498
+ if (inspected.tag === "compatible")
1499
+ return {
1500
+ tag: "one",
1501
+ value: inspected.value,
1502
+ driver: { mode: "Replay", leaves: driver.leaves.slice(1), cursor: driver.cursor + 1n },
1503
+ decision: leaf
1504
+ };
1505
+ if (inspected.tag === "out-of-bounds")
1506
+ return {
1507
+ tag: "error",
1508
+ error: machineError(
1509
+ "ReplayValueOutOfBounds",
1510
+ expr([sym("Path"), gint(driver.cursor)]),
1511
+ expr([sym("Bounds"), gint(lower), gint(upper)]),
1512
+ expr([sym("Value"), gint(inspected.value)])
1513
+ )
1514
+ };
1515
+ if (inspected.tag === "metadata")
1516
+ return {
1517
+ tag: "error",
1518
+ error: machineError(
1519
+ "ReplayMismatch",
1520
+ expr([sym("Path"), gint(driver.cursor)]),
1521
+ expr([sym("ExpectedBounds"), gint(lower), gint(upper)]),
1522
+ expr([sym("ActualBounds"), inspected.bounds[0], inspected.bounds[1]]),
1523
+ expr([sym("Origins"), gint(origin), inspected.origin])
1524
+ )
1525
+ };
1526
+ return {
1527
+ tag: "error",
1528
+ error: machineError(
1529
+ "ReplayMismatch",
1530
+ expr([sym("Path"), gint(driver.cursor)]),
1531
+ expr([sym("Expected"), sym("IntDecision")]),
1532
+ expr([sym("Actual"), leaf])
1533
+ )
1534
+ };
1535
+ }
1536
+ case "ShrinkReplay": {
1537
+ let leaves = driver.leaves;
1538
+ let cursor = driver.cursor;
1539
+ while (leaves.length > 0) {
1540
+ const leaf = leaves[0];
1541
+ const rest = leaves.slice(1);
1542
+ const nextCursor = cursor + 1n;
1543
+ const inspected = inspectIntLeaf(leaf, lower, upper, origin);
1544
+ if (inspected.tag === "compatible")
1545
+ return {
1546
+ tag: "one",
1547
+ value: inspected.value,
1548
+ driver: { mode: "ShrinkReplay", leaves: rest, cursor: nextCursor },
1549
+ decision: leaf
1550
+ };
1551
+ leaves = rest;
1552
+ cursor = nextCursor;
1553
+ }
1554
+ const value = origin < lower ? lower : origin > upper ? upper : origin;
1555
+ return {
1556
+ tag: "one",
1557
+ value,
1558
+ driver: { mode: "ShrinkReplay", leaves: [], cursor },
1559
+ decision: intDecisionAtom(lower, upper, origin, value)
1560
+ };
1561
+ }
1562
+ case "Exhaustive": {
1563
+ const span = upper - lower + 1n;
1564
+ const offset = driver.cursor < BigInt(driver.choices.length) ? driver.choices[Number(driver.cursor)] : 0n;
1565
+ if (offset < 0n || offset >= span)
1566
+ return {
1567
+ tag: "error",
1568
+ error: machineError(
1569
+ "ExhaustiveResumeMismatch",
1570
+ expr([sym("Offset"), gint(offset)]),
1571
+ expr([sym("Bounds"), gint(lower), gint(upper)])
1572
+ )
1573
+ };
1574
+ const value = lower + offset;
1575
+ return {
1576
+ tag: "one",
1577
+ value,
1578
+ driver: {
1579
+ mode: "Exhaustive",
1580
+ choices: driver.choices,
1581
+ cursor: driver.cursor + 1n,
1582
+ frames: [expr([sym("ExhaustiveFrame"), gint(offset), gint(span)]), ...driver.frames]
1583
+ },
1584
+ decision: intDecisionAtom(lower, upper, origin, value)
1585
+ };
1586
+ }
1587
+ case "Bytes": {
1588
+ const span = upper - lower + 1n;
1589
+ let width = 1n;
1590
+ let capacity = 256n;
1591
+ while (capacity < span) {
1592
+ capacity *= 256n;
1593
+ width += 1n;
1594
+ }
1595
+ let raw = 0n;
1596
+ let cursor = driver.cursor;
1597
+ for (let remaining = width; remaining > 0n; remaining -= 1n) {
1598
+ if (cursor >= BigInt(driver.bytes.length))
1599
+ return {
1600
+ tag: "error",
1601
+ error: machineError(
1602
+ "BytesExhausted",
1603
+ expr([sym("Cursor"), gint(cursor)]),
1604
+ expr([sym("Remaining"), gint(remaining)])
1605
+ )
1606
+ };
1607
+ const byte = integralNumberValue(driver.bytes[Number(cursor)]);
1608
+ if (byte === void 0)
1609
+ return {
1610
+ tag: "error",
1611
+ error: machineError(
1612
+ "MalformedByteRead",
1613
+ expr([sym("OperationResult"), driver.bytes[Number(cursor)]])
1614
+ )
1615
+ };
1616
+ raw = raw * 256n + byte;
1617
+ cursor += 1n;
1618
+ }
1619
+ const value = lower + raw % span;
1620
+ return {
1621
+ tag: "one",
1622
+ value,
1623
+ driver: { mode: "Bytes", bytes: driver.bytes, cursor },
1624
+ decision: intDecisionAtom(lower, upper, origin, value)
1625
+ };
1626
+ }
1627
+ }
1628
+ }
1629
+ function decodeFrames(atom) {
1630
+ const frames = [];
1631
+ let cursor = atom;
1632
+ for (; ; ) {
1633
+ if (cursor.kind === "sym" && cursor.name === GFB_SYM.name) break;
1634
+ if (cursor.kind !== "expr" || cursor.items.length !== 3 || cursor.items[0].kind !== "sym" || cursor.items[0].name !== GF_HEAD.name)
1635
+ return machineError("MalformedGrammarMachineState", expr([sym("Frames"), atom]));
1636
+ const frame = cursor.items[1];
1637
+ cursor = cursor.items[2];
1638
+ if (frame.kind !== "expr" || frame.items.length === 0 || frame.items[0].kind !== "sym")
1639
+ return machineError("MalformedGrammarMachineState", expr([sym("Frames"), atom]));
1640
+ const head = frame.items[0].name;
1641
+ if (head === "FPlan" && frame.items.length === 5 && frame.items[1].kind === "expr") {
1642
+ const cursorValue = integralNumberValue(frame.items[3]);
1643
+ const size = integralNumberValue(frame.items[4]);
1644
+ if (cursorValue === void 0 || size === void 0)
1645
+ return machineError("MalformedGrammarMachineState", expr([sym("Frames"), atom]));
1646
+ frames.push({
1647
+ tag: "plan",
1648
+ instrs: frame.items[1].items,
1649
+ cursor: Number(cursorValue),
1650
+ size
1651
+ });
1652
+ continue;
1653
+ }
1654
+ if (head === "FExpr" && frame.items.length === 4) {
1655
+ const arity = integralNumberValue(frame.items[1]);
1656
+ const depth = integralNumberValue(frame.items[3]);
1657
+ if (arity === void 0 || depth === void 0)
1658
+ return machineError("MalformedGrammarMachineState", expr([sym("Frames"), atom]));
1659
+ frames.push({ tag: "expr", arity: Number(arity), depth: Number(depth) });
1660
+ continue;
1661
+ }
1662
+ if (head === "FRef" && frame.items.length === 2) {
1663
+ const target = unquote(frame.items[1]);
1664
+ if (target === void 0)
1665
+ return machineError("MalformedGrammarMachineState", expr([sym("Frames"), atom]));
1666
+ frames.push({ tag: "ref", target });
1667
+ continue;
1668
+ }
1669
+ if (head === "FProd" && frame.items.length === 5) {
1670
+ const target = unquote(frame.items[1]);
1671
+ const position = integralNumberValue(frame.items[3]);
1672
+ if (target === void 0 || position === void 0)
1673
+ return machineError("MalformedGrammarMachineState", expr([sym("Frames"), atom]));
1674
+ frames.push({
1675
+ tag: "prod",
1676
+ target,
1677
+ productionIndex: frame.items[2],
1678
+ position: Number(position),
1679
+ choiceTree: frame.items[4]
1680
+ });
1681
+ continue;
1682
+ }
1683
+ if (head === "FBind" && frame.items.length === 4) {
1684
+ const sort = unquote(frame.items[1]);
1685
+ const bindingId = integralNumberValue(frame.items[2]);
1686
+ if (sort === void 0 || bindingId === void 0)
1687
+ return machineError("MalformedGrammarMachineState", expr([sym("Frames"), atom]));
1688
+ frames.push({ tag: "bind", sort, bindingId, variable: frame.items[3] });
1689
+ continue;
1690
+ }
1691
+ if (head === "FScoped" && frame.items.length === 2) {
1692
+ frames.push({ tag: "scoped", added: frame.items[1] });
1693
+ continue;
1694
+ }
1695
+ if (head === "FScope" && frame.items.length === 2 && frame.items[1].kind === "expr") {
1696
+ frames.push({ tag: "scope", saved: frame.items[1].items });
1697
+ continue;
1698
+ }
1699
+ return machineError("MalformedGrammarMachineState", expr([sym("Frames"), atom]));
1700
+ }
1701
+ return frames;
1702
+ }
1703
+ function unquote(atom) {
1704
+ if (atom.kind === "expr" && atom.items.length === 2 && atom.items[0].kind === "sym" && atom.items[0].name === QUOTE_HEAD.name)
1705
+ return atom.items[1];
1706
+ return void 0;
1707
+ }
1708
+ function encodeFrames(frames) {
1709
+ let out = GFB_SYM;
1710
+ for (let index = frames.length - 1; index >= 0; index -= 1) {
1711
+ const frame = frames[index];
1712
+ let encoded;
1713
+ switch (frame.tag) {
1714
+ case "plan":
1715
+ encoded = expr([
1716
+ sym("FPlan"),
1717
+ expr([...frame.instrs]),
1718
+ gint(BigInt(frame.instrs.length)),
1719
+ gint(BigInt(frame.cursor)),
1720
+ gint(frame.size)
1721
+ ]);
1722
+ break;
1723
+ case "expr":
1724
+ encoded = expr([
1725
+ sym("FExpr"),
1726
+ gint(BigInt(frame.arity)),
1727
+ gint(BigInt(frame.depth)),
1728
+ gint(BigInt(frame.depth))
1729
+ ]);
1730
+ break;
1731
+ case "ref":
1732
+ encoded = expr([sym("FRef"), quoteAtom(frame.target)]);
1733
+ break;
1734
+ case "prod":
1735
+ encoded = expr([
1736
+ sym("FProd"),
1737
+ quoteAtom(frame.target),
1738
+ frame.productionIndex,
1739
+ gint(BigInt(frame.position)),
1740
+ frame.choiceTree
1741
+ ]);
1742
+ break;
1743
+ case "bind":
1744
+ encoded = expr([
1745
+ sym("FBind"),
1746
+ quoteAtom(frame.sort),
1747
+ gint(frame.bindingId),
1748
+ frame.variable
1749
+ ]);
1750
+ break;
1751
+ case "scoped":
1752
+ encoded = expr([sym("FScoped"), frame.added]);
1753
+ break;
1754
+ case "scope":
1755
+ encoded = expr([sym("FScope"), expr([...frame.saved])]);
1756
+ break;
1757
+ }
1758
+ out = expr([GF_HEAD, encoded, out]);
1759
+ }
1760
+ return out;
1761
+ }
1762
+ function decodeStack(atom) {
1763
+ const out = [];
1764
+ let cursor = atom;
1765
+ for (; ; ) {
1766
+ if (cursor.kind === "sym" && cursor.name === FUZZ_STACK_BOTTOM_SYM.name) break;
1767
+ if (cursor.kind !== "expr" || cursor.items.length !== 3 || cursor.items[0].kind !== "sym" || cursor.items[0].name !== FUZZ_STACK_HEAD.name)
1768
+ return machineError("MalformedGrammarMachineState", expr([sym("Stack"), atom]));
1769
+ out.push(cursor.items[1]);
1770
+ cursor = cursor.items[2];
1771
+ }
1772
+ out.reverse();
1773
+ return out;
1774
+ }
1775
+ function encodeStack(items) {
1776
+ let out = FUZZ_STACK_BOTTOM_SYM;
1777
+ for (const item of items) out = expr([FUZZ_STACK_HEAD, item, out]);
1778
+ return out;
1779
+ }
1780
+ function productionsOfSource(source) {
1781
+ if (source.kind === "expr" && source.items.length === 3 && source.items[0].kind === "sym" && (source.items[0].name === "StaticGrammar" || source.items[0].name === "StaticTypeGrammar") && source.items[2].kind === "expr")
1782
+ return source.items[2];
1783
+ return void 0;
1784
+ }
1785
+ function encodeMachineState(state) {
1786
+ const shared = [
1787
+ state.source,
1788
+ encodeFrames(state.frames),
1789
+ encodeStack(state.values),
1790
+ gint(BigInt(state.values.length)),
1791
+ encodeStack(state.trees),
1792
+ gint(BigInt(state.trees.length))
1793
+ ];
1794
+ if (state.cut === void 0)
1795
+ return expr([
1796
+ GEN_RUN_HEAD,
1797
+ ...shared,
1798
+ expr([...state.scope]),
1799
+ gint(state.nextId),
1800
+ encodeDriver(state.driver)
1801
+ ]);
1802
+ return expr([
1803
+ GEN_CUT_HEAD,
1804
+ ...shared,
1805
+ state.cut.reason,
1806
+ state.cut.tree,
1807
+ encodeDriver(state.driver)
1808
+ ]);
1809
+ }
1810
+ function decodeMachineState(atom) {
1811
+ if (atom.kind !== "expr" || atom.items.length === 0 || atom.items[0].kind !== "sym")
1812
+ return machineError("MalformedGrammarMachineState", expr([sym("Value"), atom]));
1813
+ const head = atom.items[0].name;
1814
+ const running = head === GEN_RUN_HEAD.name;
1815
+ if (running && atom.items.length !== 10 || !running && head !== GEN_CUT_HEAD.name)
1816
+ return machineError("MalformedGrammarMachineState", expr([sym("Value"), atom]));
1817
+ if (!running && atom.items.length !== 10)
1818
+ return machineError("MalformedGrammarMachineState", expr([sym("Value"), atom]));
1819
+ const source = atom.items[1];
1820
+ const productions = productionsOfSource(source);
1821
+ if (productions === void 0)
1822
+ return machineError("MalformedGrammarSource", expr([sym("Value"), source]));
1823
+ const frames = decodeFrames(atom.items[2]);
1824
+ if (!Array.isArray(frames)) return frames;
1825
+ const values = decodeStack(atom.items[3]);
1826
+ if (!Array.isArray(values)) return values;
1827
+ const trees = decodeStack(atom.items[5]);
1828
+ if (!Array.isArray(trees)) return trees;
1829
+ const driver = decodeDriver(atom.items[9]);
1830
+ if (!("mode" in driver)) return driver;
1831
+ if (running) {
1832
+ const scopeAtom = atom.items[7];
1833
+ const nextId = integralNumberValue(atom.items[8]);
1834
+ if (scopeAtom.kind !== "expr" || nextId === void 0)
1835
+ return machineError("MalformedGrammarMachineState", expr([sym("Value"), atom]));
1836
+ return {
1837
+ source,
1838
+ productions,
1839
+ frames,
1840
+ values,
1841
+ trees,
1842
+ scope: [...scopeAtom.items],
1843
+ nextId,
1844
+ driver,
1845
+ cut: void 0
1846
+ };
1847
+ }
1848
+ return {
1849
+ source,
1850
+ productions,
1851
+ frames,
1852
+ values,
1853
+ trees,
1854
+ scope: [],
1855
+ nextId: 0n,
1856
+ driver,
1857
+ cut: { reason: atom.items[7], tree: atom.items[8] }
1858
+ };
1859
+ }
1860
+ function doneOutcome(result) {
1861
+ return { tag: "outcome", outcome: { tag: "done", result } };
1862
+ }
1863
+ function pushResult(state, value, tree) {
1864
+ state.values.push(value);
1865
+ state.trees.push(tree);
1866
+ }
1867
+ function scopeValueMarkers(scope, sort) {
1868
+ const out = [];
1869
+ for (const binding of scope) {
1870
+ if (binding.kind !== "expr" || binding.items.length !== 3 || binding.items[0].kind !== "sym" || binding.items[0].name !== "GrammarBinding")
1871
+ continue;
1872
+ const boundSort = unquote(binding.items[1]);
1873
+ if (boundSort === void 0 || !atomEq(boundSort, sort)) continue;
1874
+ const id = integralNumberValue(binding.items[2]);
1875
+ if (id === void 0 || id < 0n)
1876
+ return machineError("MalformedGrammarMachineState", expr([sym("Scope"), binding]));
1877
+ out.push(
1878
+ gnd(
1879
+ { g: "ext", kind: FUZZ_VARIABLE_MARKER_KIND, id: id.toString() },
1880
+ FUZZ_VARIABLE_MARKER_TYPE
1881
+ )
1882
+ );
1883
+ }
1884
+ return out;
1885
+ }
1886
+ function containsMarkerValue(root) {
1887
+ const pending = [root];
1888
+ while (pending.length > 0) {
1889
+ const atom = pending.pop();
1890
+ if (atom.kind === "gnd" && atom.value.g === "ext" && atom.value.kind === FUZZ_VARIABLE_MARKER_KIND)
1891
+ return true;
1892
+ if (atom.kind === "expr")
1893
+ for (let index = atom.items.length - 1; index >= 0; index -= 1)
1894
+ pending.push(atom.items[index]);
1895
+ }
1896
+ return false;
1897
+ }
1898
+ function fieldDecision(generator, child) {
1899
+ return expr([
1900
+ DECISION_HEAD,
1901
+ sym("GrammarField"),
1902
+ expr([sym("Generator"), generator]),
1903
+ expr([]),
1904
+ expr([child])
1905
+ ]);
1906
+ }
1907
+ function suspend(state, generator, size) {
1908
+ const request = expr([
1909
+ EVALUATE_GENERATOR_HEAD,
1910
+ generator,
1911
+ encodeDriver(state.driver),
1912
+ gint(size)
1913
+ ]);
1914
+ return {
1915
+ tag: "outcome",
1916
+ outcome: { tag: "need", state: encodeMachineState(state), request }
1917
+ };
1918
+ }
1919
+ function stepMachine(state) {
1920
+ if (state.cut !== void 0) {
1921
+ const frame2 = state.frames.pop();
1922
+ if (frame2 === void 0)
1923
+ return doneOutcome(
1924
+ expr([
1925
+ FUZZ_GENERATION_DISCARD_HEAD,
1926
+ state.cut.reason,
1927
+ encodeDriver(state.driver),
1928
+ state.cut.tree
1929
+ ])
1930
+ );
1931
+ switch (frame2.tag) {
1932
+ case "plan":
1933
+ return { tag: "continue" };
1934
+ case "expr": {
1935
+ const generated = state.trees.length - frame2.depth;
1936
+ const taken = state.trees.splice(frame2.depth, generated);
1937
+ state.values.splice(frame2.depth, generated);
1938
+ state.cut = {
1939
+ reason: state.cut.reason,
1940
+ tree: expr([
1941
+ DECISION_HEAD,
1942
+ sym("GrammarExpression"),
1943
+ expr([sym("Arity"), gint(BigInt(frame2.arity))]),
1944
+ expr([sym("Generated"), gint(BigInt(generated + 1))]),
1945
+ expr([...taken, state.cut.tree])
1946
+ ])
1947
+ };
1948
+ return { tag: "continue" };
1949
+ }
1950
+ case "ref":
1951
+ state.cut = {
1952
+ reason: state.cut.reason,
1953
+ tree: expr([
1954
+ DECISION_HEAD,
1955
+ sym("GrammarRef"),
1956
+ expr([sym("Target"), quoteAtom(frame2.target)]),
1957
+ expr([]),
1958
+ expr([state.cut.tree])
1959
+ ])
1960
+ };
1961
+ return { tag: "continue" };
1962
+ case "prod":
1963
+ state.cut = {
1964
+ reason: state.cut.reason,
1965
+ tree: expr([
1966
+ DECISION_HEAD,
1967
+ sym("GrammarProduction"),
1968
+ expr([sym("Target"), quoteAtom(frame2.target)]),
1969
+ expr([sym("ProductionIndex"), frame2.productionIndex, gint(BigInt(frame2.position))]),
1970
+ expr([frame2.choiceTree, state.cut.tree])
1971
+ ])
1972
+ };
1973
+ return { tag: "continue" };
1974
+ case "bind":
1975
+ state.cut = {
1976
+ reason: state.cut.reason,
1977
+ tree: expr([
1978
+ DECISION_HEAD,
1979
+ sym("GrammarBind"),
1980
+ expr([sym("Sort"), quoteAtom(frame2.sort)]),
1981
+ expr([sym("BindingId"), gint(frame2.bindingId)]),
1982
+ expr([state.cut.tree])
1983
+ ])
1984
+ };
1985
+ return { tag: "continue" };
1986
+ case "scoped":
1987
+ state.cut = {
1988
+ reason: state.cut.reason,
1989
+ tree: expr([
1990
+ DECISION_HEAD,
1991
+ sym("GrammarScoped"),
1992
+ expr([sym("Bindings"), frame2.added]),
1993
+ expr([]),
1994
+ expr([state.cut.tree])
1995
+ ])
1996
+ };
1997
+ return { tag: "continue" };
1998
+ case "scope":
1999
+ return { tag: "continue" };
2000
+ }
2001
+ }
2002
+ const frame = state.frames[state.frames.length - 1];
2003
+ if (frame === void 0) {
2004
+ if (state.values.length !== 1 || state.trees.length !== 1)
2005
+ return doneOutcome(
2006
+ machineError("MalformedGrammarMachineState", expr([sym("State"), sym("stacks")]))
2007
+ );
2008
+ return doneOutcome(
2009
+ expr([
2010
+ sym("GrammarResult"),
2011
+ state.values[0],
2012
+ encodeDriver(state.driver),
2013
+ gint(state.nextId),
2014
+ state.trees[0]
2015
+ ])
2016
+ );
2017
+ }
2018
+ if (frame.tag !== "plan") {
2019
+ state.frames.pop();
2020
+ switch (frame.tag) {
2021
+ case "scope":
2022
+ state.scope = [...frame.saved];
2023
+ return { tag: "continue" };
2024
+ case "ref": {
2025
+ const tree = state.trees.pop();
2026
+ state.trees.push(
2027
+ expr([
2028
+ DECISION_HEAD,
2029
+ sym("GrammarRef"),
2030
+ expr([sym("Target"), quoteAtom(frame.target)]),
2031
+ expr([]),
2032
+ expr([tree])
2033
+ ])
2034
+ );
2035
+ return { tag: "continue" };
2036
+ }
2037
+ case "prod": {
2038
+ const tree = state.trees.pop();
2039
+ state.trees.push(
2040
+ expr([
2041
+ DECISION_HEAD,
2042
+ sym("GrammarProduction"),
2043
+ expr([sym("Target"), quoteAtom(frame.target)]),
2044
+ expr([sym("ProductionIndex"), frame.productionIndex, gint(BigInt(frame.position))]),
2045
+ expr([frame.choiceTree, tree])
2046
+ ])
2047
+ );
2048
+ return { tag: "continue" };
2049
+ }
2050
+ case "bind": {
2051
+ const body = state.values.pop();
2052
+ const tree = state.trees.pop();
2053
+ state.values.push(expr([frame.variable, body]));
2054
+ state.trees.push(
2055
+ expr([
2056
+ DECISION_HEAD,
2057
+ sym("GrammarBind"),
2058
+ expr([sym("Sort"), quoteAtom(frame.sort)]),
2059
+ expr([sym("BindingId"), gint(frame.bindingId)]),
2060
+ expr([tree])
2061
+ ])
2062
+ );
2063
+ return { tag: "continue" };
2064
+ }
2065
+ case "scoped": {
2066
+ const tree = state.trees.pop();
2067
+ state.trees.push(
2068
+ expr([
2069
+ DECISION_HEAD,
2070
+ sym("GrammarScoped"),
2071
+ expr([sym("Bindings"), frame.added]),
2072
+ expr([]),
2073
+ expr([tree])
2074
+ ])
2075
+ );
2076
+ return { tag: "continue" };
2077
+ }
2078
+ case "expr":
2079
+ return doneOutcome(
2080
+ machineError("MalformedGrammarMachineState", expr([sym("Frames"), sym("FExpr")]))
2081
+ );
2082
+ }
2083
+ }
2084
+ if (frame.cursor >= frame.instrs.length) {
2085
+ state.frames.pop();
2086
+ return { tag: "continue" };
2087
+ }
2088
+ const instr = frame.instrs[frame.cursor];
2089
+ frame.cursor += 1;
2090
+ const size = frame.size;
2091
+ if (instr.kind !== "expr" || instr.items.length === 0 || instr.items[0].kind !== "sym")
2092
+ return doneOutcome(machineError("MalformedGrammarInstruction", expr([sym("Value"), instr])));
2093
+ const op = instr.items[0].name;
2094
+ if (op === "GILit" && instr.items.length === 2) {
2095
+ const value = unquote(instr.items[1]);
2096
+ if (value === void 0)
2097
+ return doneOutcome(machineError("MalformedGrammarInstruction", expr([sym("Value"), instr])));
2098
+ pushResult(
2099
+ state,
2100
+ value,
2101
+ expr([
2102
+ DECISION_HEAD,
2103
+ sym("GrammarLiteral"),
2104
+ expr([]),
2105
+ expr([sym("Value"), quoteAtom(value)]),
2106
+ expr([])
2107
+ ])
2108
+ );
2109
+ return { tag: "continue" };
2110
+ }
2111
+ if (op === "GIField" && instr.items.length === 2) return suspend(state, instr.items[1], size);
2112
+ if (op === "GIRef" && instr.items.length === 4) {
2113
+ const target = unquote(instr.items[1]);
2114
+ const ordinal = integralNumberValue(instr.items[2]);
2115
+ const total = integralNumberValue(instr.items[3]);
2116
+ if (target === void 0 || ordinal === void 0 || total === void 0)
2117
+ return doneOutcome(machineError("MalformedGrammarInstruction", expr([sym("Value"), instr])));
2118
+ if (size <= 0n)
2119
+ return doneOutcome(
2120
+ machineError(
2121
+ "GrammarDepthExhausted",
2122
+ expr([sym("Target"), quoteAtom(target)]),
2123
+ expr([sym("Size"), gint(size)])
2124
+ )
2125
+ );
2126
+ if (total <= 0n || ordinal < 0n || ordinal >= total)
2127
+ return doneOutcome(
2128
+ machineError(
2129
+ "MalformedIndexedGrammarReference",
2130
+ expr([sym("Ordinal"), gint(ordinal)]),
2131
+ expr([sym("Total"), gint(total)])
2132
+ )
2133
+ );
2134
+ const childSize = referenceChildSize(size, ordinal, total);
2135
+ state.frames.push({ tag: "ref", target });
2136
+ return enterNonterminal(state, target, childSize);
2137
+ }
2138
+ if (op === "GIFresh" && instr.items.length === 2) {
2139
+ const sort = unquote(instr.items[1]);
2140
+ if (sort === void 0)
2141
+ return doneOutcome(machineError("MalformedGrammarInstruction", expr([sym("Value"), instr])));
2142
+ const marker = gnd(
2143
+ { g: "ext", kind: FUZZ_VARIABLE_MARKER_KIND, id: state.nextId.toString() },
2144
+ FUZZ_VARIABLE_MARKER_TYPE
2145
+ );
2146
+ pushResult(
2147
+ state,
2148
+ marker,
2149
+ expr([
2150
+ DECISION_HEAD,
2151
+ sym("GrammarFresh"),
2152
+ expr([sym("Sort"), quoteAtom(sort)]),
2153
+ expr([sym("BindingId"), gint(state.nextId)]),
2154
+ expr([])
2155
+ ])
2156
+ );
2157
+ state.nextId += 1n;
2158
+ return { tag: "continue" };
2159
+ }
2160
+ if (op === "GIUse" && instr.items.length === 2) {
2161
+ const sort = unquote(instr.items[1]);
2162
+ if (sort === void 0)
2163
+ return doneOutcome(machineError("MalformedGrammarInstruction", expr([sym("Value"), instr])));
2164
+ const markers = scopeValueMarkers(state.scope, sort);
2165
+ if (!Array.isArray(markers)) return doneOutcome(markers);
2166
+ if (markers.length === 0)
2167
+ return doneOutcome(machineError("UnboundGrammarUse", expr([sym("Sort"), quoteAtom(sort)])));
2168
+ return suspend(state, expr([sym("GenElement"), expr(markers)]), size);
2169
+ }
2170
+ if (op === "GIBind" && instr.items.length === 3 && instr.items[2].kind === "expr") {
2171
+ const sort = unquote(instr.items[1]);
2172
+ if (sort === void 0)
2173
+ return doneOutcome(machineError("MalformedGrammarInstruction", expr([sym("Value"), instr])));
2174
+ const variable2 = gnd(
2175
+ { g: "ext", kind: FUZZ_VARIABLE_MARKER_KIND, id: state.nextId.toString() },
2176
+ FUZZ_VARIABLE_MARKER_TYPE
2177
+ );
2178
+ state.frames.push({ tag: "scope", saved: [...state.scope] });
2179
+ state.frames.push({ tag: "bind", sort, bindingId: state.nextId, variable: variable2 });
2180
+ state.frames.push({ tag: "plan", instrs: instr.items[2].items, cursor: 0, size });
2181
+ state.scope = [
2182
+ expr([sym("GrammarBinding"), quoteAtom(sort), gint(state.nextId)]),
2183
+ ...state.scope
2184
+ ];
2185
+ state.nextId += 1n;
2186
+ return { tag: "continue" };
2187
+ }
2188
+ if (op === "GIScoped" && instr.items.length === 5 && instr.items[1].kind === "expr" && instr.items[4].kind === "expr") {
2189
+ const added = instr.items[1];
2190
+ const minimumNextId = integralNumberValue(instr.items[2]);
2191
+ const raw = unquote(instr.items[3]);
2192
+ if (minimumNextId === void 0 || raw === void 0)
2193
+ return doneOutcome(machineError("MalformedGrammarInstruction", expr([sym("Value"), instr])));
2194
+ for (const binding of added.items) {
2195
+ if (binding.kind !== "expr" || binding.items.length !== 3) continue;
2196
+ const id = binding.items[2];
2197
+ for (const existing of state.scope)
2198
+ if (existing.kind === "expr" && existing.items.length === 3 && atomEq(existing.items[2], id))
2199
+ return doneOutcome(
2200
+ machineError("DuplicateGrammarBindingId", expr([sym("Bindings"), raw]))
2201
+ );
2202
+ }
2203
+ state.frames.push({ tag: "scope", saved: [...state.scope] });
2204
+ state.frames.push({ tag: "scoped", added });
2205
+ state.frames.push({ tag: "plan", instrs: instr.items[4].items, cursor: 0, size });
2206
+ state.scope = [...added.items, ...state.scope];
2207
+ if (minimumNextId > state.nextId) state.nextId = minimumNextId;
2208
+ return { tag: "continue" };
2209
+ }
2210
+ if (op === "GIExprEnter" && instr.items.length === 2) {
2211
+ const arity = integralNumberValue(instr.items[1]);
2212
+ if (arity === void 0)
2213
+ return doneOutcome(machineError("MalformedGrammarInstruction", expr([sym("Value"), instr])));
2214
+ const plan = state.frames.pop();
2215
+ state.frames.push({ tag: "expr", arity: Number(arity), depth: state.trees.length });
2216
+ state.frames.push(plan);
2217
+ return { tag: "continue" };
2218
+ }
2219
+ if (op === "GIExprBuild" && instr.items.length === 1) {
2220
+ const plan = state.frames.pop();
2221
+ const exprFrame = state.frames.pop();
2222
+ if (exprFrame === void 0 || exprFrame.tag !== "expr")
2223
+ return doneOutcome(
2224
+ machineError("MalformedGrammarMachineState", expr([sym("Frames"), sym("GIExprBuild")]))
2225
+ );
2226
+ state.frames.push(plan);
2227
+ const values = state.values.splice(state.values.length - exprFrame.arity, exprFrame.arity);
2228
+ const trees = state.trees.splice(state.trees.length - exprFrame.arity, exprFrame.arity);
2229
+ pushResult(
2230
+ state,
2231
+ expr(values),
2232
+ expr([
2233
+ DECISION_HEAD,
2234
+ sym("GrammarExpression"),
2235
+ expr([sym("Arity"), gint(BigInt(exprFrame.arity))]),
2236
+ expr([]),
2237
+ expr(trees)
2238
+ ])
2239
+ );
2240
+ return { tag: "continue" };
2241
+ }
2242
+ return doneOutcome(machineError("MalformedGrammarInstruction", expr([sym("Value"), instr])));
2243
+ }
2244
+ function enterNonterminal(state, target, size) {
2245
+ const eligibleAtom = eligibleListForMachine(state.productions, target, state.scope, size);
2246
+ if (eligibleAtom.kind !== "expr" || eligibleAtom.items.length !== 2 || eligibleAtom.items[0].kind !== "sym" || eligibleAtom.items[0].name !== "EligibleGrammarProductions" || eligibleAtom.items[1].kind !== "expr") {
2247
+ if (eligibleAtom.kind === "expr" && eligibleAtom.items.length === 2 && eligibleAtom.items[0].kind === "sym" && eligibleAtom.items[0].name === "FitDuplicateGrammarBindingId") {
2248
+ const raw = unquote(eligibleAtom.items[1]);
2249
+ return doneOutcome(
2250
+ machineError(
2251
+ "DuplicateGrammarBindingId",
2252
+ expr([sym("Bindings"), raw ?? eligibleAtom.items[1]])
2253
+ )
2254
+ );
2255
+ }
2256
+ return doneOutcome(machineError("KernelError", expr([sym("OperationResult"), eligibleAtom])));
2257
+ }
2258
+ const eligible = eligibleAtom.items[1].items;
2259
+ if (eligible.length === 0) {
2260
+ state.cut = {
2261
+ reason: expr([
2262
+ sym("NoEligibleGrammarProduction"),
2263
+ expr([sym("Target"), quoteAtom(target)]),
2264
+ expr([sym("Size"), gint(size)])
2265
+ ]),
2266
+ tree: expr([
2267
+ DECISION_HEAD,
2268
+ sym("GrammarUnavailable"),
2269
+ expr([sym("Target"), quoteAtom(target)]),
2270
+ expr([sym("Size"), gint(size)]),
2271
+ expr([])
2272
+ ])
2273
+ };
2274
+ return { tag: "continue" };
2275
+ }
2276
+ const count = BigInt(eligible.length);
2277
+ let choice;
2278
+ if (state.driver.mode === "Random") {
2279
+ let total = 0n;
2280
+ for (const production of eligible) {
2281
+ const weight = integralNumberValue(
2282
+ production.items[2]
2283
+ );
2284
+ total += weight ?? 0n;
2285
+ }
2286
+ const [ticket, nextRng] = drawIntFromState(state.driver.rng, 1n, total);
2287
+ let remaining = ticket;
2288
+ let position = 0n;
2289
+ for (const production of eligible) {
2290
+ const weight = integralNumberValue(production.items[2]) ?? 0n;
2291
+ if (remaining <= weight) break;
2292
+ remaining -= weight;
2293
+ position += 1n;
2294
+ }
2295
+ choice = {
2296
+ tag: "one",
2297
+ value: position,
2298
+ driver: { mode: "Random", rng: nextRng },
2299
+ decision: intDecisionAtom(0n, count - 1n, 0n, position)
2300
+ };
2301
+ } else if (state.driver.mode === "Edge") {
2302
+ const position = state.driver.index % count;
2303
+ choice = {
2304
+ tag: "one",
2305
+ value: position,
2306
+ driver: { mode: "Edge", index: state.driver.index + 1n },
2307
+ decision: intDecisionAtom(0n, count - 1n, 0n, position)
2308
+ };
2309
+ } else {
2310
+ choice = driverInt(state.driver, 0n, count - 1n, 0n);
2311
+ }
2312
+ if (choice.tag === "error") return doneOutcome(choice.error);
2313
+ const applyChoice = (target2, branch) => {
2314
+ target2.driver = branch.driver;
2315
+ const production = eligible[Number(branch.value)];
2316
+ if (production.kind !== "expr" || production.items.length !== 5 || production.items[4].kind !== "expr" || production.items[4].items.length !== 2)
2317
+ return doneOutcome(
2318
+ machineError(
2319
+ "MalformedSelectedGrammarProduction",
2320
+ expr([sym("Target"), quoteAtom(target)]),
2321
+ expr([sym("Production"), production])
2322
+ )
2323
+ );
2324
+ const template = production.items[4].items[1];
2325
+ const planned = compileTemplatePlanCached(template);
2326
+ if (isErrorAtom(planned))
2327
+ return doneOutcome(machineError("KernelError", expr([sym("OperationResult"), planned])));
2328
+ target2.frames.push({
2329
+ tag: "prod",
2330
+ target,
2331
+ productionIndex: production.items[1],
2332
+ position: Number(branch.value),
2333
+ choiceTree: branch.decision
2334
+ });
2335
+ target2.frames.push({ tag: "plan", instrs: planned, cursor: 0, size });
2336
+ return { tag: "continue" };
2337
+ };
2338
+ return applyChoice(state, choice);
2339
+ }
2340
+ function compileTemplatePlanCached(template) {
2341
+ const cached = templatePlanCache.get(template);
2342
+ if (cached !== void 0) {
2343
+ const body = cached.items[1];
2344
+ return body.items;
2345
+ }
2346
+ const instructions = compileTemplatePlan(template);
2347
+ if (!Array.isArray(instructions)) return instructions;
2348
+ const plan = expr([GRAMMAR_TEMPLATE_PLAN_HEAD, expr(instructions)]);
2349
+ templatePlanCache.set(template, plan);
2350
+ return instructions;
2351
+ }
2352
+ function eligibleListForMachine(productions, target, scope, size) {
2353
+ const looked = grammarEligibleProductions([
2354
+ productions,
2355
+ quoteAtom(target),
2356
+ expr([...scope]),
2357
+ gint(size)
2358
+ ]);
2359
+ if (looked.tag !== "ok" || looked.results.length !== 1)
2360
+ return kernelError(
2361
+ "InvalidGrammarEligibility",
2362
+ expr([sym("Operation"), sym("_fuzz-grammar-machine-op")]),
2363
+ sym("EligibilityFailed")
2364
+ );
2365
+ return looked.results[0];
2366
+ }
2367
+ function runMachineToOutcome(state) {
2368
+ for (; ; ) {
2369
+ const stepped = stepMachine(state);
2370
+ if (stepped.tag === "outcome") return stepped.outcome;
2371
+ }
2372
+ }
2373
+ var grammarMachineOp = (args) => {
2374
+ if (args.length !== 1) return arityError("_fuzz-grammar-machine-op", 1, args.length);
2375
+ const input = args[0];
2376
+ if (input.kind !== "expr" || input.items.length === 0 || input.items[0].kind !== "sym")
2377
+ return operationError(
2378
+ "InvalidGrammarMachineInput",
2379
+ "_fuzz-grammar-machine-op",
2380
+ "ExpectedExpression"
2381
+ );
2382
+ const head = input.items[0].name;
2383
+ let state;
2384
+ if (head === MACHINE_START_HEAD.name && input.items.length === 6) {
2385
+ const source = input.items[1];
2386
+ const target = unquote(input.items[2]);
2387
+ const scopeAtom = input.items[3];
2388
+ const nextId = integralNumberValue(input.items[4]);
2389
+ if (target === void 0 || scopeAtom.kind !== "expr" || nextId === void 0)
2390
+ return operationError(
2391
+ "InvalidGrammarMachineInput",
2392
+ "_fuzz-grammar-machine-op",
2393
+ "MalformedStart"
2394
+ );
2395
+ const request = input.items[5];
2396
+ if (request.kind !== "expr" || request.items.length !== 3 || request.items[0].kind !== "sym" || request.items[0].name !== "WithDriver")
2397
+ return operationError(
2398
+ "InvalidGrammarMachineInput",
2399
+ "_fuzz-grammar-machine-op",
2400
+ "MalformedStart"
2401
+ );
2402
+ const driver = decodeDriver(request.items[1]);
2403
+ if (!("mode" in driver)) return ok(expr([MACHINE_DONE_HEAD, driver]));
2404
+ const size = integralNumberValue(request.items[2]);
2405
+ if (size === void 0)
2406
+ return operationError(
2407
+ "InvalidGrammarMachineInput",
2408
+ "_fuzz-grammar-machine-op",
2409
+ "MalformedStart"
2410
+ );
2411
+ const productions = productionsOfSource(source);
2412
+ if (productions === void 0)
2413
+ return ok(
2414
+ expr([
2415
+ MACHINE_DONE_HEAD,
2416
+ machineError("MalformedGrammarSource", expr([sym("Value"), source]))
2417
+ ])
2418
+ );
2419
+ state = {
2420
+ source,
2421
+ productions,
2422
+ frames: [],
2423
+ values: [],
2424
+ trees: [],
2425
+ scope: [...scopeAtom.items],
2426
+ nextId,
2427
+ driver,
2428
+ cut: void 0
2429
+ };
2430
+ const entered = enterNonterminal(state, target, size);
2431
+ if (entered.tag === "outcome")
2432
+ return {
2433
+ tag: "ok",
2434
+ results: [outcomeAtom(entered.outcome)]
2435
+ };
2436
+ } else if (head === MACHINE_RESUME_HEAD.name && input.items.length === 3) {
2437
+ const decoded = decodeMachineState(input.items[1]);
2438
+ if (!("frames" in decoded)) return ok(expr([MACHINE_DONE_HEAD, decoded]));
2439
+ state = decoded;
2440
+ const sample = input.items[2];
2441
+ const applied = applySubResult(state, sample);
2442
+ if (applied !== void 0) return ok(expr([MACHINE_DONE_HEAD, applied]));
2443
+ } else {
2444
+ return operationError(
2445
+ "InvalidGrammarMachineInput",
2446
+ "_fuzz-grammar-machine-op",
2447
+ "UnknownRequest"
2448
+ );
2449
+ }
2450
+ return ok(outcomeAtom(runMachineToOutcome(state)));
2451
+ };
2452
+ function outcomeAtom(outcome) {
2453
+ if (outcome.tag === "done") return expr([MACHINE_DONE_HEAD, outcome.result]);
2454
+ return expr([MACHINE_NEED_HEAD, outcome.state, outcome.request]);
2455
+ }
2456
+ function applySubResult(state, sample) {
2457
+ const frame = state.frames[state.frames.length - 1];
2458
+ if (frame === void 0 || frame.tag !== "plan" || frame.cursor === 0)
2459
+ return machineError("MalformedGrammarMachineState", expr([sym("Resume"), sym("frame")]));
2460
+ const instr = frame.instrs[frame.cursor - 1];
2461
+ if (instr.kind !== "expr" || instr.items.length !== 2 || instr.items[0].kind !== "sym")
2462
+ return machineError("MalformedGrammarMachineState", expr([sym("Resume"), sym("instruction")]));
2463
+ const instrHead = instr.items[0].name;
2464
+ const isField = instrHead === "GIField";
2465
+ const isUse = instrHead === "GIUse";
2466
+ if (!isField && !isUse)
2467
+ return machineError("MalformedGrammarMachineState", expr([sym("Resume"), sym("instruction")]));
2468
+ if (sample.kind === "expr" && sample.items.length === 4 && sample.items[0].kind === "sym" && sample.items[0].name === FUZZ_SAMPLE_HEAD.name) {
2469
+ const value = sample.items[1];
2470
+ const nextDriver = decodeDriver(sample.items[2]);
2471
+ if (!("mode" in nextDriver)) return nextDriver;
2472
+ const tree = sample.items[3];
2473
+ if (isField) {
2474
+ const generator = instr.items[1];
2475
+ if (containsMarkerValue(value))
2476
+ return machineError(
2477
+ "ForgedGrammarVariableMarker",
2478
+ expr([sym("Generator"), generator]),
2479
+ expr([sym("Value"), value])
2480
+ );
2481
+ state.driver = nextDriver;
2482
+ pushResult(state, value, fieldDecision(generator, tree));
2483
+ return void 0;
2484
+ }
2485
+ const sort = unquote(instr.items[1]);
2486
+ state.driver = nextDriver;
2487
+ pushResult(
2488
+ state,
2489
+ value,
2490
+ expr([
2491
+ DECISION_HEAD,
2492
+ sym("GrammarUse"),
2493
+ expr([sym("Sort"), quoteAtom(sort)]),
2494
+ expr([]),
2495
+ expr([tree])
2496
+ ])
2497
+ );
2498
+ return void 0;
2499
+ }
2500
+ if (sample.kind === "expr" && sample.items.length === 4 && sample.items[0].kind === "sym" && sample.items[0].name === FUZZ_GENERATION_DISCARD_HEAD.name) {
2501
+ if (!isField)
2502
+ return machineError(
2503
+ "MalformedGrammarUseResult",
2504
+ expr([sym("Sort"), instr.items[1]]),
2505
+ expr([sym("Value"), sample])
2506
+ );
2507
+ const nextDriver = decodeDriver(sample.items[2]);
2508
+ if (!("mode" in nextDriver)) return nextDriver;
2509
+ state.driver = nextDriver;
2510
+ state.cut = {
2511
+ reason: sample.items[1],
2512
+ tree: fieldDecision(instr.items[1], sample.items[3])
2513
+ };
2514
+ return void 0;
2515
+ }
2516
+ if (sample.kind === "expr" && sample.items.length >= 1 && sample.items[0].kind === "sym" && sample.items[0].name === FUZZ_GENERATION_ERROR_HEAD.name)
2517
+ return sample;
2518
+ return isField ? machineError(
2519
+ "MalformedGrammarFieldResult",
2520
+ expr([sym("Generator"), instr.items[1]]),
2521
+ expr([sym("Value"), sample])
2522
+ ) : machineError(
2523
+ "MalformedGrammarUseResult",
2524
+ expr([sym("Sort"), instr.items[1]]),
2525
+ expr([sym("Value"), sample])
2526
+ );
2527
+ }
2528
+ var grammarTargetsOp = (args) => {
2529
+ if (args.length !== 1) return arityError("_fuzz-grammar-targets-op", 1, args.length);
2530
+ const productions = args[0];
2531
+ if (productions.kind !== "expr")
2532
+ return operationError(
2533
+ "InvalidGrammarProductions",
2534
+ "_fuzz-grammar-targets-op",
2535
+ "ExpectedExpression"
2536
+ );
2537
+ const seen = /* @__PURE__ */ new Set();
2538
+ const out = [];
2539
+ for (const production of productions.items) {
2540
+ if (production.kind !== "expr" || production.items.length !== 5 || production.items[3].kind !== "expr" || production.items[3].items.length !== 2)
2541
+ return operationError(
2542
+ "InvalidGrammarProductions",
2543
+ "_fuzz-grammar-targets-op",
2544
+ "MalformedProduction"
2545
+ );
2546
+ const target = production.items[3].items[1];
2547
+ const key = structuralAtomKey(target, "Exact");
2548
+ if (!key.ok) return ok(key.reason);
2549
+ if (seen.has(key.key)) continue;
2550
+ seen.add(key.key);
2551
+ out.push(quoteAtom(target));
2552
+ }
2553
+ return ok(expr([sym("GrammarTargets"), expr(out)]));
2554
+ };
2555
+ var grammarValidateReferencesOp = (args) => {
2556
+ if (args.length !== 2) return arityError("_fuzz-grammar-validate-references-op", 2, args.length);
2557
+ const [productions, targets] = args;
2558
+ if (productions.kind !== "expr" || targets.kind !== "expr")
2559
+ return operationError(
2560
+ "InvalidGrammarReferences",
2561
+ "_fuzz-grammar-validate-references-op",
2562
+ "ExpectedExpressions"
2563
+ );
2564
+ const known = /* @__PURE__ */ new Set();
2565
+ for (const quoted of targets.items) {
2566
+ const target = unquote(quoted);
2567
+ if (target === void 0)
2568
+ return operationError(
2569
+ "InvalidGrammarReferences",
2570
+ "_fuzz-grammar-validate-references-op",
2571
+ "MalformedTarget"
2572
+ );
2573
+ const key = structuralAtomKey(target, "Exact");
2574
+ if (!key.ok) return ok(key.reason);
2575
+ known.add(key.key);
2576
+ }
2577
+ for (const production of productions.items) {
2578
+ if (production.kind !== "expr" || production.items.length !== 5 || production.items[4].kind !== "expr" || production.items[4].items.length !== 2)
2579
+ return operationError(
2580
+ "InvalidGrammarReferences",
2581
+ "_fuzz-grammar-validate-references-op",
2582
+ "MalformedProduction"
2583
+ );
2584
+ for (const referenced of templateReferenceTargetAtoms(production.items[4].items[1])) {
2585
+ const key = structuralAtomKey(referenced, "Exact");
2586
+ if (!key.ok) return ok(key.reason);
2587
+ if (!known.has(key.key))
2588
+ return ok(expr([sym("GrammarMissingReference"), quoteAtom(referenced)]));
2589
+ }
2590
+ }
2591
+ return ok(expr([sym("ValidGrammarReferences")]));
2592
+ };
2593
+ var fuzzStackToExpression = (args) => {
2594
+ if (args.length !== 1) return arityError("_fuzz-stack-to-expression", 1, args.length);
2595
+ const items = decodeStack(args[0]);
2596
+ if (isErrorAtom(items))
2597
+ return operationError("InvalidStackTake", "_fuzz-stack-to-expression", "MalformedStack");
2598
+ return ok(expr(items));
2599
+ };
2600
+ var productionDependentsCache = /* @__PURE__ */ new WeakMap();
2601
+ function templateReferenceTargetAtoms(template) {
2602
+ const out = [];
2603
+ const pending = [template];
2604
+ while (pending.length > 0) {
2605
+ const atom = pending.pop();
2606
+ if (atom.kind === "expr" && atom.items.length > 0 && atom.items[0].kind === "sym") {
2607
+ const head = atom.items[0].name;
2608
+ if (head === "Ref" && atom.items.length === 2) {
2609
+ out.push(atom.items[1]);
2610
+ continue;
2611
+ }
2612
+ if (head === GRAMMAR_INDEXED_REFERENCE_HEAD.name && atom.items.length === 4) {
2613
+ out.push(atom.items[1]);
2614
+ continue;
2615
+ }
2616
+ }
2617
+ const indices = grammarTemplateChildIndices(atom);
2618
+ for (let index = indices.length - 1; index >= 0; index -= 1)
2619
+ pending.push(atom.items[indices[index]]);
2620
+ }
2621
+ return out;
2622
+ }
2623
+ var grammarDependentsOf = (args) => {
2624
+ const parsed = parseProductionsTargetArgs(
2625
+ args,
2626
+ "InvalidGrammarDependentsLookup",
2627
+ "_fuzz-grammar-dependents-of"
2628
+ );
2629
+ if ("tag" in parsed) return parsed;
2630
+ const { productions, target } = parsed;
2631
+ let byTarget = productionDependentsCache.get(productions);
2632
+ if (byTarget === void 0) {
2633
+ const collected = /* @__PURE__ */ new Map();
2634
+ for (let index = 0; index < productions.items.length; index += 1) {
2635
+ const production = productions.items[index];
2636
+ if (production.kind !== "expr" || production.items.length !== 5 || production.items[4].kind !== "expr" || production.items[4].items.length !== 2)
2637
+ return operationError(
2638
+ "InvalidGrammarDependentsLookup",
2639
+ "_fuzz-grammar-dependents-of",
2640
+ "MalformedProduction"
2641
+ );
2642
+ for (const target2 of templateReferenceTargetAtoms(production.items[4].items[1])) {
2643
+ const key = structuralAtomKey(target2, "Exact");
2644
+ if (!key.ok) return ok(key.reason);
2645
+ const bucket = collected.get(key.key);
2646
+ if (bucket === void 0) collected.set(key.key, [BigInt(index)]);
2647
+ else if (bucket[bucket.length - 1] !== BigInt(index)) bucket.push(BigInt(index));
2648
+ }
2649
+ }
2650
+ byTarget = /* @__PURE__ */ new Map();
2651
+ for (const [key, indices] of collected)
2652
+ byTarget.set(key, expr(indices.map((value) => gint(value))));
2653
+ productionDependentsCache.set(productions, byTarget);
2654
+ }
2655
+ const targetKey = structuralAtomKey(target, "Exact");
2656
+ if (!targetKey.ok) return ok(targetKey.reason);
2657
+ return ok(expr([sym("GrammarDependents"), byTarget.get(targetKey.key) ?? expr([])]));
2658
+ };
2659
+ var fuzzIndexStack = (args) => {
2660
+ if (args.length !== 1) return arityError("_fuzz-index-stack", 1, args.length);
2661
+ const count = integralNumberValue(args[0]);
2662
+ if (count === void 0 || count < 0n)
2663
+ return operationError("InvalidIndexStack", "_fuzz-index-stack", "ExpectedNonNegativeCount");
2664
+ let stack = sym("FuzzStackBottom");
2665
+ for (let index = Number(count) - 1; index >= 0; index -= 1)
2666
+ stack = expr([FUZZ_STACK_HEAD, gint(BigInt(index)), stack]);
2667
+ return ok(stack);
2668
+ };
2669
+ var templatePlanCache = /* @__PURE__ */ new WeakMap();
2670
+ function compileTemplatePlan(template) {
2671
+ const rootOut = [];
2672
+ const pending = [{ tag: "visit", atom: template, out: rootOut }];
2673
+ while (pending.length > 0) {
2674
+ const task = pending.pop();
2675
+ if (task.tag === "emit-expr") {
2676
+ task.out.push(expr([GI_EXPR_BUILD_HEAD]));
2677
+ continue;
2678
+ }
2679
+ if (task.tag === "emit-bind") {
2680
+ task.out.push(expr([GI_BIND_HEAD, expr([QUOTE_HEAD, task.sort]), expr(task.body)]));
2681
+ continue;
2682
+ }
2683
+ if (task.tag === "emit-scoped") {
2684
+ task.out.push(
2685
+ expr([
2686
+ GI_SCOPED_HEAD,
2687
+ task.normalized,
2688
+ gint(task.minimumNextId),
2689
+ expr([QUOTE_HEAD, task.raw]),
2690
+ expr(task.body)
2691
+ ])
2692
+ );
2693
+ continue;
2694
+ }
2695
+ const { atom, out } = task;
2696
+ if (atom.kind === "expr" && atom.items.length > 0 && atom.items[0].kind === "sym") {
2697
+ const head = atom.items[0].name;
2698
+ if (head === "Literal" && atom.items.length === 2) {
2699
+ out.push(expr([GI_LIT_HEAD, expr([QUOTE_HEAD, atom.items[1]])]));
2700
+ continue;
2701
+ }
2702
+ if (head === "Field" && atom.items.length === 2) {
2703
+ out.push(expr([GI_FIELD_HEAD, atom.items[1]]));
2704
+ continue;
2705
+ }
2706
+ if (head === "Ref" && atom.items.length === 2) {
2707
+ out.push(expr([GI_REF_HEAD, expr([QUOTE_HEAD, atom.items[1]]), gint(0), gint(1)]));
2708
+ continue;
2709
+ }
2710
+ if (head === GRAMMAR_INDEXED_REFERENCE_HEAD.name && atom.items.length === 4) {
2711
+ const ordinal = integralNumberValue(atom.items[2]);
2712
+ const total = integralNumberValue(atom.items[3]);
2713
+ if (ordinal === void 0 || total === void 0)
2714
+ return kernelError(
2715
+ "InvalidGrammarTemplatePlan",
2716
+ expr([sym("Operation"), sym("_fuzz-grammar-template-plan")]),
2717
+ sym("MalformedIndexedReference")
2718
+ );
2719
+ out.push(
2720
+ expr([GI_REF_HEAD, expr([QUOTE_HEAD, atom.items[1]]), gint(ordinal), gint(total)])
2721
+ );
2722
+ continue;
2723
+ }
2724
+ if (head === "Fresh" && atom.items.length === 2) {
2725
+ out.push(expr([GI_FRESH_HEAD, expr([QUOTE_HEAD, atom.items[1]])]));
2726
+ continue;
2727
+ }
2728
+ if (head === "Use" && atom.items.length === 2) {
2729
+ out.push(expr([GI_USE_HEAD, expr([QUOTE_HEAD, atom.items[1]])]));
2730
+ continue;
2731
+ }
2732
+ if (head === "Bind" && atom.items.length === 3) {
2733
+ const body = [];
2734
+ pending.push({ tag: "emit-bind", sort: atom.items[1], body, out });
2735
+ pending.push({ tag: "visit", atom: atom.items[2], out: body });
2736
+ continue;
2737
+ }
2738
+ if (head === "Scoped" && atom.items.length === 3) {
2739
+ const bindings = atom.items[1];
2740
+ if (bindings.kind !== "expr")
2741
+ return kernelError(
2742
+ "InvalidGrammarTemplatePlan",
2743
+ expr([sym("Operation"), sym("_fuzz-grammar-template-plan")]),
2744
+ sym("MalformedScopedBindings")
2745
+ );
2746
+ const normalized = [];
2747
+ const seen = /* @__PURE__ */ new Set();
2748
+ let minimumNextId = 0n;
2749
+ for (const binding of bindings.items) {
2750
+ if (binding.kind !== "expr" || binding.items.length !== 3 || binding.items[0].kind !== "sym" || binding.items[0].name !== "Binding")
2751
+ return kernelError(
2752
+ "InvalidGrammarTemplatePlan",
2753
+ expr([sym("Operation"), sym("_fuzz-grammar-template-plan")]),
2754
+ sym("MalformedScopedBindings")
2755
+ );
2756
+ const id = integralNumberValue(binding.items[2]);
2757
+ if (id === void 0 || id < 0n || seen.has(id.toString()))
2758
+ return kernelError(
2759
+ "InvalidGrammarTemplatePlan",
2760
+ expr([sym("Operation"), sym("_fuzz-grammar-template-plan")]),
2761
+ sym("MalformedScopedBindings")
2762
+ );
2763
+ seen.add(id.toString());
2764
+ normalized.push(
2765
+ expr([sym("GrammarBinding"), expr([QUOTE_HEAD, binding.items[1]]), binding.items[2]])
2766
+ );
2767
+ if (id + 1n > minimumNextId) minimumNextId = id + 1n;
2768
+ }
2769
+ const body = [];
2770
+ pending.push({
2771
+ tag: "emit-scoped",
2772
+ normalized: expr(normalized),
2773
+ minimumNextId,
2774
+ raw: bindings,
2775
+ body,
2776
+ out
2777
+ });
2778
+ pending.push({ tag: "visit", atom: atom.items[2], out: body });
2779
+ continue;
2780
+ }
2781
+ }
2782
+ if (atom.kind === "expr") {
2783
+ out.push(expr([GI_EXPR_ENTER_HEAD, gint(atom.items.length)]));
2784
+ pending.push({ tag: "emit-expr", out });
2785
+ for (let index = atom.items.length - 1; index >= 0; index -= 1)
2786
+ pending.push({ tag: "visit", atom: atom.items[index], out });
2787
+ continue;
2788
+ }
2789
+ out.push(expr([GI_LIT_HEAD, expr([QUOTE_HEAD, atom])]));
2790
+ }
2791
+ return rootOut;
2792
+ }
2793
+ var grammarTemplatePlan = (args) => {
2794
+ if (args.length !== 1) return arityError("_fuzz-grammar-template-plan", 1, args.length);
2795
+ const template = args[0];
2796
+ const cached = templatePlanCache.get(template);
2797
+ if (cached !== void 0) return ok(cached);
2798
+ const instructions = compileTemplatePlan(template);
2799
+ if (isErrorAtom(instructions)) return ok(instructions);
2800
+ const plan = expr([GRAMMAR_TEMPLATE_PLAN_HEAD, expr(instructions)]);
2801
+ templatePlanCache.set(template, plan);
2802
+ return ok(plan);
2803
+ };
2804
+ var fuzzStackPushAll = (args) => {
2805
+ if (args.length !== 2) return arityError("_fuzz-stack-push-all", 2, args.length);
2806
+ const items = args[1];
2807
+ if (items.kind !== "expr")
2808
+ return operationError("InvalidStackPush", "_fuzz-stack-push-all", "ExpectedExpression");
2809
+ let stack = args[0];
2810
+ for (let index = items.items.length - 1; index >= 0; index -= 1)
2811
+ stack = expr([FUZZ_STACK_HEAD, items.items[index], stack]);
2812
+ return ok(stack);
2813
+ };
2814
+ var fuzzStackTake = (args) => {
2815
+ if (args.length !== 2) return arityError("_fuzz-stack-take", 2, args.length);
2816
+ const count = integralNumberValue(args[1]);
2817
+ if (count === void 0 || count < 0n)
2818
+ return operationError("InvalidStackTake", "_fuzz-stack-take", "ExpectedNonNegativeCount");
2819
+ let rest = args[0];
2820
+ const popped = [];
2821
+ for (let taken = 0n; taken < count; taken += 1n) {
2822
+ if (rest.kind !== "expr" || rest.items.length !== 3 || rest.items[0].kind !== "sym" || rest.items[0].name !== FUZZ_STACK_HEAD.name)
2823
+ return operationError("InvalidStackTake", "_fuzz-stack-take", "StackUnderflow");
2824
+ popped.push(rest.items[1]);
2825
+ rest = rest.items[2];
2826
+ }
2827
+ popped.reverse();
2828
+ return ok(expr([FUZZ_STACK_TAKE_HEAD, expr(popped), rest]));
2829
+ };
2830
+ var grammarValidationPlan = (args) => {
2831
+ if (args.length !== 1) return arityError("_fuzz-grammar-validation-plan", 1, args.length);
2832
+ const pending = [{ tag: "visit", atom: args[0] }];
2833
+ const events = [];
2834
+ while (pending.length > 0) {
2835
+ const task = pending.pop();
2836
+ if (task.tag === "scoped-exit") {
2837
+ events.push(expr([GRAMMAR_VALIDATION_SCOPED_EXIT_HEAD]));
2838
+ continue;
2839
+ }
2840
+ const atom = task.atom;
2841
+ if (atom.kind === "expr" && atom.items[0]?.kind === "sym") {
2842
+ const head = atom.items[0].name;
2843
+ if ((head === "Literal" || head === "Ref" || head === "Fresh" || head === "Use") && atom.items.length === 2 || head === "_FuzzGrammarRef" && atom.items.length === 4) {
2844
+ continue;
2845
+ }
2846
+ if (head === "Field" && atom.items.length === 2) {
2847
+ events.push(expr([GRAMMAR_VALIDATION_FIELD_HEAD, expr([QUOTE_HEAD, atom.items[1]])]));
2848
+ continue;
2849
+ }
2850
+ if (head === "Bind" && atom.items.length === 3) {
2851
+ pending.push({ tag: "visit", atom: atom.items[2] });
2852
+ continue;
2853
+ }
2854
+ if (head === "Scoped" && atom.items.length === 3) {
2855
+ events.push(
2856
+ expr([GRAMMAR_VALIDATION_SCOPED_ENTER_HEAD, expr([QUOTE_HEAD, atom.items[1]])])
2857
+ );
2858
+ pending.push({ tag: "scoped-exit" });
2859
+ pending.push({ tag: "visit", atom: atom.items[2] });
2860
+ continue;
2861
+ }
2862
+ if (GRAMMAR_RESERVED_TEMPLATE_HEADS.has(head)) {
2863
+ events.push(expr([GRAMMAR_VALIDATION_MALFORMED_HEAD, expr([QUOTE_HEAD, atom])]));
2864
+ continue;
2865
+ }
2866
+ }
2867
+ if (atom.kind !== "expr") continue;
2868
+ for (let index = atom.items.length - 1; index >= 0; index -= 1)
2869
+ pending.push({ tag: "visit", atom: atom.items[index] });
2870
+ }
2871
+ return ok(expr([GRAMMAR_VALIDATION_PLAN_HEAD, expr(events)]));
2872
+ };
2873
+ var grammarReferenceTargets = (args) => {
2874
+ if (args.length !== 1) return arityError("_fuzz-grammar-template-reference-plan", 1, args.length);
2875
+ const pending = [args[0]];
2876
+ const targets = [];
2877
+ while (pending.length > 0) {
2878
+ const atom = pending.pop();
2879
+ if (atom.kind === "expr" && atom.items[0]?.kind === "sym" && (atom.items[0].name === "Ref" && atom.items.length === 2 || atom.items[0].name === "_FuzzGrammarRef" && atom.items.length === 4)) {
2880
+ targets.push(expr([QUOTE_HEAD, atom.items[1]]));
2881
+ continue;
2882
+ }
2883
+ const indices = grammarTemplateChildIndices(atom);
2884
+ for (let index = indices.length - 1; index >= 0; index -= 1)
2885
+ pending.push(atom.items[indices[index]]);
2886
+ }
2887
+ return ok(expr([GRAMMAR_REFERENCE_TARGETS_HEAD, expr(targets)]));
2888
+ };
2889
+ var atomGround = (args) => {
2890
+ if (args.length !== 1) return arityError("_fuzz-atom-ground", 1, args.length);
2891
+ return ok(gbool(args[0].ground));
2892
+ };
2893
+ var customReplayTree = (args) => {
2894
+ if (args.length !== 2) return arityError("_fuzz-custom-replay-tree", 2, args.length);
2895
+ const [result, expectedMode] = args;
2896
+ if (result.kind === "expr" && result.items.length === 3 && atomEq(result.items[0], FUZZ_GENERATION_ERROR_HEAD)) {
2897
+ return ok(expr([CUSTOM_REPLAY_SKIP_HEAD]));
2898
+ }
2899
+ if (result.kind !== "expr" || result.items.length !== 4 || !atomEq(result.items[0], FUZZ_SAMPLE_HEAD) && !atomEq(result.items[0], FUZZ_GENERATION_DISCARD_HEAD)) {
2900
+ return ok(
2901
+ expr([
2902
+ CUSTOM_REPLAY_PROTOCOL_ERROR_HEAD,
2903
+ sym("MalformedGenerationResult"),
2904
+ expr([sym("Details"), expr([sym("Value"), result])])
2905
+ ])
2906
+ );
2907
+ }
2908
+ const driver = result.items[2];
2909
+ if (driver.kind !== "expr" || driver.items.length !== 3 || !atomEq(driver.items[0], FUZZ_DRIVER_HEAD) || !atomEq(driver.items[1], expectedMode)) {
2910
+ return ok(
2911
+ expr([
2912
+ CUSTOM_REPLAY_PROTOCOL_ERROR_HEAD,
2913
+ sym("CustomDriverMismatch"),
2914
+ expr([
2915
+ sym("Details"),
2916
+ expr([sym("ExpectedMode"), expectedMode]),
2917
+ expr([sym("ActualDriver"), driver])
2918
+ ])
2919
+ ])
2920
+ );
2921
+ }
2922
+ const treeKey = structuralAtomKey(result.items[3], "Replay");
2923
+ if (!treeKey.ok) return ok(expr([CUSTOM_REPLAY_SKIP_HEAD]));
2924
+ return ok(expr([CUSTOM_REPLAY_TREE_HEAD, result.items[3]]));
2925
+ };
2926
+ var customReplayEqual = (args) => {
2927
+ if (args.length !== 2) return arityError("_fuzz-custom-replay-equal", 2, args.length);
2928
+ const [original, replayed] = args;
2929
+ if (original.kind !== "expr" || replayed.kind !== "expr" || original.items.length !== 4 || replayed.items.length !== 4 || !atomEq(original.items[0], replayed.items[0]) || !atomEq(original.items[0], FUZZ_SAMPLE_HEAD) && !atomEq(original.items[0], FUZZ_GENERATION_DISCARD_HEAD)) {
2930
+ return ok(gbool(false));
2931
+ }
2932
+ return ok(
2933
+ gbool(
2934
+ replayAtomEqual(original.items[1], replayed.items[1], true) && atomsEqualForKeyMode(original.items[3], replayed.items[3], "Replay")
2935
+ )
2936
+ );
2937
+ };
2938
+ var bitsOfFloat64 = (args) => {
2939
+ if (args.length !== 1) return arityError("_fuzz-float64-bits", 1, args.length);
2940
+ const value = floatValue(args[0]);
2941
+ if (value === void 0)
2942
+ return operationError("InvalidFloat", "_fuzz-float64-bits", "ExpectedFloat");
2943
+ const [high, low] = float64Words(value);
2944
+ return ok(expr([FLOAT_BITS_HEAD, gint(high), gint(low)]));
2945
+ };
2946
+ var float64OfBits = (args) => {
2947
+ if (args.length !== 2) return arityError("_fuzz-float64-from-bits", 2, args.length);
2948
+ const high = unsigned32Value(args[0]);
2949
+ const low = unsigned32Value(args[1]);
2950
+ if (high === void 0 || low === void 0)
2951
+ return operationError("InvalidFloatBits", "_fuzz-float64-from-bits", "ExpectedUnsigned32Words");
2952
+ return ok(gfloat(float64FromWords(high, low)));
2953
+ };
2954
+ var indexOfFloat64 = (args) => {
2955
+ if (args.length !== 1) return arityError("_fuzz-float64-index", 1, args.length);
2956
+ const value = floatValue(args[0]);
2957
+ if (value === void 0)
2958
+ return operationError("InvalidFloat", "_fuzz-float64-index", "ExpectedFloat");
2959
+ const index = float64Index(value);
2960
+ if (index === void 0)
2961
+ return operationError("InvalidFloat", "_fuzz-float64-index", "NaNHasNoOrderedIndex");
2962
+ return ok(expr([FLOAT_INDEX_HEAD, gint(index)]));
2963
+ };
2964
+ var float64OfIndex = (args) => {
2965
+ if (args.length !== 1) return arityError("_fuzz-float64-from-index", 1, args.length);
2966
+ const index = integralNumberValue(args[0]);
2967
+ if (index === void 0)
2968
+ return operationError("InvalidFloatIndex", "_fuzz-float64-from-index", "ExpectedInteger");
2969
+ const value = float64FromIndex(index);
2970
+ if (value === void 0)
2971
+ return operationError("InvalidFloatIndex", "_fuzz-float64-from-index", "OutOfRange");
2972
+ return ok(gfloat(value));
2973
+ };
2974
+ function unicodeScalarAt(index) {
2975
+ if (index < 0n || index >= UNICODE_SCALAR_COUNT) return void 0;
2976
+ if (index < UNICODE_FIRST_GAP_INDEX) return Number(index);
2977
+ if (index < UNICODE_SECOND_GAP_INDEX) return Number(index + 2048n);
2978
+ return Number(index + 2050n);
2979
+ }
2980
+ var unicodeCharacterAt = (args) => {
2981
+ if (args.length !== 1) return arityError("_fuzz-unicode-character", 1, args.length);
2982
+ const index = integralNumberValue(args[0]);
2983
+ if (index === void 0)
2984
+ return operationError("InvalidCharacterIndex", "_fuzz-unicode-character", "ExpectedInteger");
2985
+ const scalar = unicodeScalarAt(index);
2986
+ if (scalar === void 0)
2987
+ return operationError("InvalidCharacterIndex", "_fuzz-unicode-character", "OutOfRange");
2988
+ return ok(sym(String.fromCodePoint(scalar)));
2989
+ };
2990
+ function replayGroundEqual(left, right) {
2991
+ if (left.exec !== void 0 || right.exec !== void 0 || left.match !== void 0 || right.match !== void 0 || !atomEq(left.typ, groundType(left.value)) || !atomEq(right.typ, groundType(right.value)) || left.value.g !== right.value.g) {
2992
+ return false;
2993
+ }
2994
+ switch (left.value.g) {
2995
+ case "int":
2996
+ return BigInt(left.value.n) === BigInt(right.value.n);
2997
+ case "float":
2998
+ return float64Bits(left.value.n) === float64Bits(right.value.n);
2999
+ case "str":
3000
+ return left.value.s === right.value.s;
3001
+ case "bool":
3002
+ return left.value.b === right.value.b;
3003
+ case "unit":
3004
+ return true;
3005
+ case "error":
3006
+ return left.value.msg === right.value.msg;
3007
+ case "ext":
3008
+ return false;
3009
+ }
3010
+ }
3011
+ function replayAtomEqual(left, right, alphaVariables = false) {
3012
+ const pending = [[left, right]];
3013
+ const leftVariables = /* @__PURE__ */ new Map();
3014
+ const rightVariables = /* @__PURE__ */ new Map();
3015
+ while (pending.length > 0) {
3016
+ const [currentLeft, currentRight] = pending.pop();
3017
+ if (currentLeft.kind !== currentRight.kind) return false;
3018
+ switch (currentLeft.kind) {
3019
+ case "sym":
3020
+ if (currentLeft.name !== currentRight.name) return false;
3021
+ break;
3022
+ case "var": {
3023
+ if (currentRight.kind !== "var") return false;
3024
+ if (!alphaVariables) {
3025
+ if (currentLeft.name !== currentRight.name) return false;
3026
+ break;
3027
+ }
3028
+ const mappedRight = leftVariables.get(currentLeft.name);
3029
+ const mappedLeft = rightVariables.get(currentRight.name);
3030
+ if (mappedRight === void 0 && mappedLeft === void 0) {
3031
+ leftVariables.set(currentLeft.name, currentRight.name);
3032
+ rightVariables.set(currentRight.name, currentLeft.name);
3033
+ } else if (mappedRight !== currentRight.name || mappedLeft !== currentLeft.name) {
3034
+ return false;
3035
+ }
3036
+ break;
3037
+ }
3038
+ case "gnd":
3039
+ if (currentRight.kind !== "gnd" || !replayGroundEqual(currentLeft, currentRight))
3040
+ return false;
3041
+ break;
3042
+ case "expr":
3043
+ if (currentRight.kind !== "expr") return false;
3044
+ if (currentLeft.items.length !== currentRight.items.length) return false;
3045
+ for (let index = 0; index < currentLeft.items.length; index += 1) {
3046
+ pending.push([currentLeft.items[index], currentRight.items[index]]);
3047
+ }
3048
+ break;
3049
+ }
3050
+ }
3051
+ return true;
3052
+ }
3053
+ var replayEqual = (args) => {
3054
+ if (args.length !== 2) return arityError("_fuzz-replay-equal", 2, args.length);
3055
+ return ok(gbool(replayAtomEqual(args[0], args[1])));
3056
+ };
3057
+ function encodeGrounded(atom) {
3058
+ if (atom.value.g === "ext")
3059
+ return kernelError("NonReplayableGroundedValue", sym("ExternalGrounded"));
3060
+ if (atom.exec !== void 0)
3061
+ return kernelError("NonReplayableGroundedValue", sym("ExecutableGrounded"));
3062
+ if (atom.match !== void 0)
3063
+ return kernelError("NonReplayableGroundedValue", sym("CustomMatcher"));
3064
+ if (!atomEq(atom.typ, groundType(atom.value)))
3065
+ return kernelError("NonReplayableGroundedValue", sym("CustomGroundedType"));
3066
+ switch (atom.value.g) {
3067
+ case "int":
3068
+ return expr([ENCODED_INTEGER, gint(atom.value.n)]);
3069
+ case "float":
3070
+ return expr([ENCODED_FLOAT, ...float64Words(atom.value.n).map(gint)]);
3071
+ case "str":
3072
+ return expr([ENCODED_STRING, gstr(atom.value.s)]);
3073
+ case "bool":
3074
+ return expr([ENCODED_BOOLEAN, gbool(atom.value.b)]);
3075
+ case "unit":
3076
+ return expr([ENCODED_UNIT]);
3077
+ case "error":
3078
+ return expr([ENCODED_ERROR, gstr(atom.value.msg)]);
3079
+ }
3080
+ }
3081
+ function isKernelErrorAtom(atom) {
3082
+ return atom.kind === "expr" && atom.items.length > 0 && atomEq(atom.items[0], ERROR_HEAD);
3083
+ }
3084
+ function encodeReplayAtom(atom) {
3085
+ const pending = [{ tag: "atom", atom }];
3086
+ const encoded = [];
3087
+ while (pending.length > 0) {
3088
+ const task = pending.pop();
3089
+ if (task.tag === "expression") {
3090
+ const children = encoded.splice(encoded.length - task.count, task.count);
3091
+ const error = children.find(isKernelErrorAtom);
3092
+ if (error !== void 0) return error;
3093
+ encoded.push(expr([ENCODED_EXPRESSION, expr(children)]));
3094
+ continue;
3095
+ }
3096
+ const current = task.atom;
3097
+ switch (current.kind) {
3098
+ case "sym":
3099
+ encoded.push(expr([ENCODED_SYMBOL, gstr(current.name)]));
3100
+ break;
3101
+ case "var":
3102
+ encoded.push(expr([ENCODED_VARIABLE, gstr(current.name)]));
3103
+ break;
3104
+ case "gnd":
3105
+ encoded.push(encodeGrounded(current));
3106
+ break;
3107
+ case "expr":
3108
+ pending.push({ tag: "expression", count: current.items.length });
3109
+ for (let index = current.items.length - 1; index >= 0; index -= 1) {
3110
+ pending.push({ tag: "atom", atom: current.items[index] });
3111
+ }
3112
+ break;
3113
+ }
3114
+ }
3115
+ const payload = encoded[0];
3116
+ return isKernelErrorAtom(payload) ? payload : expr([ENCODED_ATOM_HEAD, gint(FUZZ_ATOM_CODEC_VERSION), payload]);
3117
+ }
3118
+ function codecError(detail) {
3119
+ return {
3120
+ tag: "error",
3121
+ error: kernelError(
3122
+ "InvalidEncodedAtom",
3123
+ expr([sym("Operation"), sym("_fuzz-decode-atom")]),
3124
+ sym(detail)
3125
+ )
3126
+ };
3127
+ }
3128
+ function payloadString(payload, head) {
3129
+ if (payload.kind !== "expr" || payload.items.length !== 2 || !atomEq(payload.items[0], head)) {
3130
+ return void 0;
3131
+ }
3132
+ const value = payload.items[1];
3133
+ return value.kind === "gnd" && value.value.g === "str" ? value.value.s : void 0;
3134
+ }
3135
+ function decodePayload(payload) {
3136
+ if (payload.kind !== "expr" || payload.items.length === 0) return codecError("MalformedPayload");
3137
+ const head = payload.items[0];
3138
+ if (atomEq(head, ENCODED_SYMBOL)) {
3139
+ const name = payloadString(payload, ENCODED_SYMBOL);
3140
+ return name === void 0 ? codecError("MalformedSymbol") : { tag: "atom", atom: sym(name) };
3141
+ }
3142
+ if (atomEq(head, ENCODED_VARIABLE)) {
3143
+ const name = payloadString(payload, ENCODED_VARIABLE);
3144
+ return name === void 0 ? codecError("MalformedVariable") : { tag: "atom", atom: variable(name) };
3145
+ }
3146
+ if (atomEq(head, ENCODED_EXPRESSION)) {
3147
+ if (payload.items.length !== 2 || payload.items[1].kind !== "expr")
3148
+ return codecError("MalformedExpression");
3149
+ return { tag: "expression", children: payload.items[1].items };
3150
+ }
3151
+ if (atomEq(head, ENCODED_INTEGER)) {
3152
+ if (payload.items.length !== 2 || exactIntegerValue(payload.items[1]) === void 0)
3153
+ return codecError("MalformedInteger");
3154
+ return { tag: "atom", atom: gint(exactIntegerValue(payload.items[1])) };
3155
+ }
3156
+ if (atomEq(head, ENCODED_FLOAT)) {
3157
+ if (payload.items.length !== 3) return codecError("MalformedFloat64Bits");
3158
+ const high = unsigned32Value(payload.items[1]);
3159
+ const low = unsigned32Value(payload.items[2]);
3160
+ if (high === void 0 || low === void 0) return codecError("MalformedFloat64Bits");
3161
+ return { tag: "atom", atom: gfloat(float64FromWords(high, low)) };
3162
+ }
3163
+ if (atomEq(head, ENCODED_STRING)) {
3164
+ const value = payloadString(payload, ENCODED_STRING);
3165
+ return value === void 0 ? codecError("MalformedString") : { tag: "atom", atom: gstr(value) };
3166
+ }
3167
+ if (atomEq(head, ENCODED_BOOLEAN)) {
3168
+ if (payload.items.length !== 2 || payload.items[1].kind !== "gnd" || payload.items[1].value.g !== "bool") {
3169
+ return codecError("MalformedBoolean");
3170
+ }
3171
+ return { tag: "atom", atom: gbool(payload.items[1].value.b) };
3172
+ }
3173
+ if (atomEq(head, ENCODED_UNIT)) {
3174
+ return payload.items.length === 1 ? { tag: "atom", atom: gunit } : codecError("MalformedUnit");
3175
+ }
3176
+ if (atomEq(head, ENCODED_ERROR)) {
3177
+ const message = payloadString(payload, ENCODED_ERROR);
3178
+ return message === void 0 ? codecError("MalformedError") : { tag: "atom", atom: gnd({ g: "error", msg: message }) };
3179
+ }
3180
+ return codecError("UnknownPayloadTag");
3181
+ }
3182
+ function decodeReplayAtom(encoded) {
3183
+ if (encoded.kind !== "expr" || encoded.items.length !== 3 || !atomEq(encoded.items[0], ENCODED_ATOM_HEAD) || exactIntegerValue(encoded.items[1]) !== BigInt(FUZZ_ATOM_CODEC_VERSION)) {
3184
+ return kernelError(
3185
+ "InvalidEncodedAtom",
3186
+ expr([sym("Operation"), sym("_fuzz-decode-atom")]),
3187
+ sym("ExpectedVersion1")
3188
+ );
3189
+ }
3190
+ const pending = [{ tag: "payload", payload: encoded.items[2] }];
3191
+ const decoded = [];
3192
+ while (pending.length > 0) {
3193
+ const task = pending.pop();
3194
+ if (task.tag === "expression") {
3195
+ decoded.push(expr(decoded.splice(decoded.length - task.count, task.count)));
3196
+ continue;
3197
+ }
3198
+ const payload = decodePayload(task.payload);
3199
+ if (payload.tag === "error") return payload.error;
3200
+ if (payload.tag === "atom") {
3201
+ decoded.push(payload.atom);
3202
+ continue;
3203
+ }
3204
+ pending.push({ tag: "expression", count: payload.children.length });
3205
+ for (let index = payload.children.length - 1; index >= 0; index -= 1) {
3206
+ pending.push({ tag: "payload", payload: payload.children[index] });
3207
+ }
3208
+ }
3209
+ return decoded[0];
3210
+ }
3211
+ var encodeAtom = (args) => {
3212
+ if (args.length !== 1) return arityError("_fuzz-encode-atom", 1, args.length);
3213
+ return ok(encodeReplayAtom(args[0]));
3214
+ };
3215
+ var decodeAtom = (args) => {
3216
+ if (args.length !== 1) return arityError("_fuzz-decode-atom", 1, args.length);
3217
+ return ok(decodeReplayAtom(args[0]));
3218
+ };
3219
+ var KERNEL_OPERATIONS = [
3220
+ ["_fuzz-rng-init", rngInit],
3221
+ ["_fuzz-draw-int", drawInt],
3222
+ ["_fuzz-atom-key", atomKey],
3223
+ ["_fuzz-deduplicate-exact", deduplicateExact],
3224
+ ["_fuzz-deduplicate-replay", deduplicateReplay],
3225
+ ["_fuzz-exact-member", exactMember],
3226
+ ["_fuzz-replay-member", replayMember],
3227
+ ["_fuzz-make-variable", makeVariable],
3228
+ ["_fuzz-variable-marker", variableMarker],
3229
+ ["_fuzz-contains-variable-marker", containsVariableMarker],
3230
+ ["_fuzz-materialize-grammar-sample", materializeGrammarSample],
3231
+ ["_fuzz-expression-append", appendExpressionItem],
3232
+ ["_fuzz-expression-concat", concatenateExpressions],
3233
+ ["_fuzz-grammar-summary-alternatives", grammarSummaryAlternatives],
3234
+ ["_fuzz-grammar-summary-replace", grammarSummaryReplace],
3235
+ ["_fuzz-grammar-alternatives-add", grammarAlternativesAdd],
3236
+ ["_fuzz-grammar-template-requirements-op", grammarTemplateRequirements],
3237
+ ["_fuzz-grammar-productivity-op", grammarProductivityOp],
3238
+ ["_fuzz-grammar-targets-op", grammarTargetsOp],
3239
+ ["_fuzz-grammar-validate-references-op", grammarValidateReferencesOp],
3240
+ ["_fuzz-stack-to-expression", fuzzStackToExpression],
3241
+ ["_fuzz-grammar-eligible-productions-op", grammarEligibleProductions],
3242
+ ["_fuzz-grammar-machine-op", grammarMachineOp],
3243
+ ["_fuzz-decision-leaves-op", decisionLeaves],
3244
+ ["_fuzz-grammar-productions-for-target", grammarProductionsForTarget],
3245
+ ["_fuzz-grammar-dependents-of", grammarDependentsOf],
3246
+ ["_fuzz-index-stack", fuzzIndexStack],
3247
+ ["_fuzz-grammar-template-plan", grammarTemplatePlan],
3248
+ ["_fuzz-stack-take", fuzzStackTake],
3249
+ ["_fuzz-stack-push-all", fuzzStackPushAll],
3250
+ ["_fuzz-expression-view", expressionView],
3251
+ ["_fuzz-grammar-field-expressions", grammarFieldExpressions],
3252
+ ["_fuzz-grammar-replace-fields", replaceGrammarFields],
3253
+ ["_fuzz-grammar-index-references", indexGrammarReferences],
3254
+ ["_fuzz-grammar-template-profile", grammarTemplateProfile],
3255
+ ["_fuzz-grammar-validation-plan", grammarValidationPlan],
3256
+ ["_fuzz-grammar-template-reference-plan", grammarReferenceTargets],
3257
+ ["_fuzz-atom-ground", atomGround],
3258
+ ["_fuzz-custom-replay-tree", customReplayTree],
3259
+ ["_fuzz-custom-replay-equal", customReplayEqual],
3260
+ ["_fuzz-float64-bits", bitsOfFloat64],
3261
+ ["_fuzz-float64-from-bits", float64OfBits],
3262
+ ["_fuzz-float64-index", indexOfFloat64],
3263
+ ["_fuzz-float64-from-index", float64OfIndex],
3264
+ ["_fuzz-unicode-character", unicodeCharacterAt],
3265
+ ["_fuzz-replay-equal", replayEqual],
3266
+ ["_fuzz-encode-atom", encodeAtom],
3267
+ ["_fuzz-decode-atom", decodeAtom]
3268
+ ];
3269
+ var registered = false;
3270
+ function registerFuzzKernel() {
3271
+ if (registered) return;
3272
+ for (const [name, operation] of KERNEL_OPERATIONS) {
3273
+ registerBuiltinGroundedOperation(name, operation, "Pure");
3274
+ }
3275
+ registered = true;
3276
+ }
3277
+
3278
+ // src/decode.ts
3279
+ import { format } from "@mettascript/core";
3280
+ var headName = (atom) => atom.kind === "expr" && atom.items.length > 0 && atom.items[0].kind === "sym" ? atom.items[0].name : void 0;
3281
+ function field(atom, label) {
3282
+ if (atom.kind !== "expr") return void 0;
3283
+ for (const item of atom.items) if (headName(item) === label) return item;
3284
+ return void 0;
3285
+ }
3286
+ function fieldValue(atom, label) {
3287
+ const found = field(atom, label);
3288
+ return found?.kind === "expr" && found.items.length === 2 ? found.items[1] : void 0;
3289
+ }
3290
+ function symbolValue(atom) {
3291
+ return atom?.kind === "sym" ? atom.name : void 0;
3292
+ }
3293
+ function integerValue(atom) {
3294
+ if (atom?.kind !== "gnd") return void 0;
3295
+ const value = atom.value;
3296
+ if (value.g !== "int") return void 0;
3297
+ const n = Number(value.n);
3298
+ return Number.isSafeInteger(n) ? n : void 0;
3299
+ }
3300
+ function unquote2(atom) {
3301
+ if (atom?.kind === "expr" && atom.items.length === 2 && headName(atom) === "quote")
3302
+ return atom.items[1];
3303
+ return atom;
3304
+ }
3305
+ function decodeCounts(statistics) {
3306
+ const counts = statistics === void 0 ? void 0 : field(statistics, "Counts");
3307
+ if (counts === void 0) return void 0;
3308
+ const read = (label) => integerValue(fieldValue(counts, label));
3309
+ const passed = read("Passed");
3310
+ const propertyDiscards = read("PropertyDiscards");
3311
+ const generationDiscards = read("GenerationDiscards");
3312
+ const regressions = read("Regressions");
3313
+ const examples = read("Examples");
3314
+ const edges = read("Edges");
3315
+ const random = read("Random");
3316
+ if (passed === void 0 || propertyDiscards === void 0 || generationDiscards === void 0 || regressions === void 0 || examples === void 0 || edges === void 0 || random === void 0)
3317
+ return void 0;
3318
+ return { passed, propertyDiscards, generationDiscards, regressions, examples, edges, random };
3319
+ }
3320
+ function decodeStatistics(atom) {
3321
+ const statistics = field(atom, "FuzzStatistics");
3322
+ if (statistics === void 0) return void 0;
3323
+ const counts = decodeCounts(statistics);
3324
+ if (counts === void 0) return void 0;
3325
+ return {
3326
+ counts,
3327
+ labels: field(statistics, "Labels"),
3328
+ collected: field(statistics, "Collected"),
3329
+ coverage: field(statistics, "Coverage")
3330
+ };
3331
+ }
3332
+ function decodeReachCounts(atom) {
3333
+ const statistics = field(atom, "ReachStatistics");
3334
+ if (statistics === void 0) return void 0;
3335
+ const states = integerValue(fieldValue(statistics, "States"));
3336
+ const transitions = integerValue(fieldValue(statistics, "Transitions"));
3337
+ const depth = integerValue(fieldValue(statistics, "Depth"));
3338
+ if (states === void 0 || transitions === void 0 || depth === void 0) return void 0;
3339
+ return { states, transitions, depth };
3340
+ }
3341
+ function decodeWitness(atom) {
3342
+ const witness = fieldValue(atom, "Witness");
3343
+ if (witness?.kind !== "expr") return [];
3344
+ const steps = [];
3345
+ for (const step of witness.items) {
3346
+ if (step.kind !== "expr" || step.items.length !== 4 || headName(step) !== "Step") continue;
3347
+ const commandIndex = integerValue(step.items[1]);
3348
+ const branch = integerValue(step.items[3]);
3349
+ if (commandIndex === void 0 || branch === void 0) continue;
3350
+ steps.push({ commandIndex, command: step.items[2], branch });
3351
+ }
3352
+ return steps;
3353
+ }
3354
+ function propertyOf(atom) {
3355
+ return symbolValue(fieldValue(atom, "Property"));
3356
+ }
3357
+ function decodeFuzzOutcome(atom) {
3358
+ const head = headName(atom);
3359
+ if (head === void 0)
3360
+ return { kind: "undecodable", reason: "result is not a symbol-headed expression", atom };
3361
+ switch (head) {
3362
+ case "FuzzPassed": {
3363
+ const property = propertyOf(atom);
3364
+ if (property === void 0)
3365
+ return { kind: "undecodable", reason: "FuzzPassed without (Property ...)", atom };
3366
+ return {
3367
+ kind: "passed",
3368
+ property,
3369
+ seed: integerValue(fieldValue(atom, "Seed")),
3370
+ statistics: decodeStatistics(atom),
3371
+ atom
3372
+ };
3373
+ }
3374
+ case "FuzzFailed": {
3375
+ const property = propertyOf(atom);
3376
+ const failureTag = symbolValue(fieldValue(atom, "FailureTag"));
3377
+ if (property === void 0 || failureTag === void 0)
3378
+ return {
3379
+ kind: "undecodable",
3380
+ reason: "FuzzFailed without (Property ...) and (FailureTag ...)",
3381
+ atom
3382
+ };
3383
+ return {
3384
+ kind: "failed",
3385
+ property,
3386
+ phase: symbolValue(fieldValue(atom, "Phase")),
3387
+ caseIndex: integerValue(fieldValue(atom, "CaseIndex")),
3388
+ failureTag,
3389
+ // Both values, because the difference between them is information: the original is what
3390
+ // generation produced and the smallest is what shrinking reduced it to.
3391
+ originalValue: unquote2(fieldValue(atom, "OriginalValue")),
3392
+ originalDetails: fieldValue(atom, "OriginalDetails"),
3393
+ smallestValue: unquote2(fieldValue(atom, "SmallestValue")),
3394
+ smallestDetails: fieldValue(atom, "SmallestDetails"),
3395
+ // A decoded field is the value, not the label around it. `Replay` and the details fields each
3396
+ // wrap one record, so the record comes out; `Shrink` is itself the record, so it comes out whole.
3397
+ replay: fieldValue(atom, "Replay"),
3398
+ shrink: field(atom, "Shrink"),
3399
+ statistics: decodeStatistics(atom),
3400
+ atom
3401
+ };
3402
+ }
3403
+ case "FuzzGaveUp": {
3404
+ const property = propertyOf(atom);
3405
+ const reason = atom.kind === "expr" ? atom.items.slice(1).find((item) => item.kind === "sym") : void 0;
3406
+ if (property === void 0 || reason === void 0)
3407
+ return { kind: "undecodable", reason: "FuzzGaveUp without a property and a reason", atom };
3408
+ return {
3409
+ kind: "gave-up",
3410
+ property,
3411
+ reason: reason.name,
3412
+ statistics: decodeStatistics(atom),
3413
+ atom
3414
+ };
3415
+ }
3416
+ case "FuzzExhaustivelyVerified": {
3417
+ const property = propertyOf(atom);
3418
+ if (property === void 0)
3419
+ return {
3420
+ kind: "undecodable",
3421
+ reason: "FuzzExhaustivelyVerified without (Property ...)",
3422
+ atom
3423
+ };
3424
+ return {
3425
+ kind: "exhaustively-verified",
3426
+ property,
3427
+ domainCount: integerValue(fieldValue(atom, "DomainCount")),
3428
+ enumerated: integerValue(fieldValue(atom, "Enumerated")),
3429
+ atom
3430
+ };
3431
+ }
3432
+ case "FuzzInvalid": {
3433
+ const code = atom.kind === "expr" ? symbolValue(atom.items[1]) : void 0;
3434
+ if (code === void 0)
3435
+ return { kind: "undecodable", reason: "FuzzInvalid without a symbol code", atom };
3436
+ return {
3437
+ kind: "invalid",
3438
+ code,
3439
+ details: atom.kind === "expr" ? atom.items.slice(2) : [],
3440
+ atom
3441
+ };
3442
+ }
3443
+ case "FuzzReachable": {
3444
+ const property = propertyOf(atom);
3445
+ if (property === void 0)
3446
+ return { kind: "undecodable", reason: "FuzzReachable without (Property ...)", atom };
3447
+ const commands = fieldValue(atom, "Commands");
3448
+ return {
3449
+ kind: "reachable",
3450
+ property,
3451
+ depth: integerValue(fieldValue(atom, "Depth")),
3452
+ commands: commands?.kind === "expr" ? commands.items : [],
3453
+ witness: decodeWitness(atom),
3454
+ target: unquote2(fieldValue(atom, "Target")),
3455
+ counts: decodeReachCounts(atom),
3456
+ atom
3457
+ };
3458
+ }
3459
+ case "FuzzUnreachableWithinDepth": {
3460
+ const property = propertyOf(atom);
3461
+ if (property === void 0)
3462
+ return {
3463
+ kind: "undecodable",
3464
+ reason: "FuzzUnreachableWithinDepth without (Property ...)",
3465
+ atom
3466
+ };
3467
+ return {
3468
+ kind: "unreachable-within-depth",
3469
+ property,
3470
+ depth: integerValue(fieldValue(atom, "Depth")),
3471
+ counts: decodeReachCounts(atom),
3472
+ atom
3473
+ };
3474
+ }
3475
+ case "FuzzReachabilityExhausted": {
3476
+ const property = propertyOf(atom);
3477
+ if (property === void 0)
3478
+ return {
3479
+ kind: "undecodable",
3480
+ reason: "FuzzReachabilityExhausted without (Property ...)",
3481
+ atom
3482
+ };
3483
+ return {
3484
+ kind: "reachability-exhausted",
3485
+ property,
3486
+ states: integerValue(fieldValue(atom, "States")),
3487
+ counts: decodeReachCounts(atom),
3488
+ atom
3489
+ };
3490
+ }
3491
+ case "FuzzReachabilityCutoff": {
3492
+ const property = propertyOf(atom);
3493
+ if (property === void 0)
3494
+ return {
3495
+ kind: "undecodable",
3496
+ reason: "FuzzReachabilityCutoff without (Property ...)",
3497
+ atom
3498
+ };
3499
+ return {
3500
+ kind: "reachability-cutoff",
3501
+ property,
3502
+ reason: fieldValue(atom, "Reason"),
3503
+ counts: decodeReachCounts(atom),
3504
+ atom
3505
+ };
3506
+ }
3507
+ default:
3508
+ return { kind: "undecodable", reason: `unknown result head ${head}`, atom };
3509
+ }
3510
+ }
3511
+ var FUZZ_EXIT_OK = 0;
3512
+ var FUZZ_EXIT_PROPERTY_FAILURE = 1;
3513
+ var FUZZ_EXIT_INVALID = 2;
3514
+ var FUZZ_EXIT_INCOMPLETE = 3;
3515
+ function exitCodeForOutcome(outcome) {
3516
+ switch (outcome.kind) {
3517
+ case "passed":
3518
+ case "exhaustively-verified":
3519
+ case "reachable":
3520
+ case "reachability-exhausted":
3521
+ return FUZZ_EXIT_OK;
3522
+ case "failed":
3523
+ return FUZZ_EXIT_PROPERTY_FAILURE;
3524
+ case "invalid":
3525
+ case "undecodable":
3526
+ return FUZZ_EXIT_INVALID;
3527
+ case "gave-up":
3528
+ case "unreachable-within-depth":
3529
+ case "reachability-cutoff":
3530
+ return FUZZ_EXIT_INCOMPLETE;
3531
+ }
3532
+ }
3533
+ var EXIT_PRECEDENCE = [
3534
+ FUZZ_EXIT_INVALID,
3535
+ FUZZ_EXIT_PROPERTY_FAILURE,
3536
+ FUZZ_EXIT_INCOMPLETE,
3537
+ FUZZ_EXIT_OK
3538
+ ];
3539
+ function exitCodeForOutcomes(outcomes) {
3540
+ const seen = new Set(outcomes.map(exitCodeForOutcome));
3541
+ for (const code of EXIT_PRECEDENCE) if (seen.has(code)) return code;
3542
+ return FUZZ_EXIT_OK;
3543
+ }
3544
+ var WITNESS_HEAD = 8;
3545
+ function renderCommands(commands) {
3546
+ const head = commands.slice(0, WITNESS_HEAD).map(format).join(" ");
3547
+ return commands.length <= WITNESS_HEAD ? head : `${head} ... (${commands.length} commands)`;
3548
+ }
3549
+ function renderOutcomeLine(outcome) {
3550
+ switch (outcome.kind) {
3551
+ case "passed": {
3552
+ const counts = outcome.statistics?.counts;
3553
+ const cases = counts === void 0 ? "" : ` ${counts.passed} cases`;
3554
+ const seed = outcome.seed === void 0 ? "" : `, seed ${outcome.seed}`;
3555
+ return `ok ${outcome.property}${cases}${seed}`;
3556
+ }
3557
+ case "exhaustively-verified":
3558
+ return `ok ${outcome.property} exhaustive, ${outcome.domainCount ?? "?"} trees`;
3559
+ case "failed": {
3560
+ const smallest = outcome.smallestValue === void 0 ? "" : ` ${format(outcome.smallestValue)}`;
3561
+ return `FAILED ${outcome.property} ${outcome.failureTag}${smallest}`;
3562
+ }
3563
+ case "gave-up":
3564
+ return `gave up ${outcome.property} ${outcome.reason}`;
3565
+ case "invalid":
3566
+ return `invalid ${outcome.code}`;
3567
+ case "reachable":
3568
+ return `reached ${outcome.property} in ${outcome.depth ?? "?"} steps: ${renderCommands(
3569
+ outcome.commands
3570
+ )}`;
3571
+ case "unreachable-within-depth":
3572
+ return `bounded ${outcome.property} no target at or below depth ${outcome.depth ?? "?"}`;
3573
+ case "reachability-exhausted":
3574
+ return `ok ${outcome.property} unreachable in ${outcome.states ?? "?"} states`;
3575
+ case "reachability-cutoff":
3576
+ return `cutoff ${outcome.property} ${outcome.reason === void 0 ? "" : format(outcome.reason)}`;
3577
+ case "undecodable":
3578
+ return `invalid undecodable result: ${outcome.reason}`;
3579
+ }
3580
+ }
3581
+
3582
+ // src/corpus.ts
3583
+ import { format as format2, gint as gint2, parseAll, standardTokenizer, sym as sym2, expr as expr2 } from "@mettascript/core";
3584
+ var FUZZ_CORPUS_FORMAT = 1;
3585
+ var ENTRY_HEAD = "FuzzCorpusEntry";
3586
+ var KERNEL_ERROR_HEAD = "FuzzKernelError";
3587
+ var HEADER = `; A counterexample MeTTaScript's fuzzer found, kept so later runs replay it first.
3588
+ ; Commit this file: the failure then travels with the code that caused it.
3589
+ ; Written by \`metta fuzz --corpus\`. Values use the versioned replay codec, not source syntax.
3590
+ `;
3591
+ function failed(reason) {
3592
+ return { ok: false, reason };
3593
+ }
3594
+ function isKernelError(atom) {
3595
+ return atom.kind === "expr" && atom.items.length > 0 && atom.items[0]?.kind === "sym" && atom.items[0].name === KERNEL_ERROR_HEAD;
3596
+ }
3597
+ function renderCorpusEntry(entry) {
3598
+ const encoded = encodeReplayAtom(entry.value);
3599
+ if (isKernelError(encoded))
3600
+ return failed(`the value has no storable encoding: ${format2(encoded)}`);
3601
+ const fact = expr2([sym2(ENTRY_HEAD), gint2(FUZZ_CORPUS_FORMAT), sym2(entry.property), encoded]);
3602
+ return { ok: true, value: `${HEADER}${format2(fact)}
3603
+ ` };
3604
+ }
3605
+ function parseCorpusEntries(text) {
3606
+ let tops;
3607
+ try {
3608
+ tops = parseAll(text, standardTokenizer());
3609
+ } catch (error) {
3610
+ return failed(`unreadable: ${error instanceof Error ? error.message : String(error)}`);
3611
+ }
3612
+ if (tops.length === 0) return failed("no entries");
3613
+ const entries = [];
3614
+ for (const top of tops) {
3615
+ if (top.bang) return failed("a corpus file holds data, not queries");
3616
+ const atom = top.atom;
3617
+ if (atom.kind !== "expr" || atom.items.length !== 4 || atom.items[0]?.kind !== "sym" || atom.items[0].name !== ENTRY_HEAD) {
3618
+ return failed(`expected (${ENTRY_HEAD} ${FUZZ_CORPUS_FORMAT} <property> <value>)`);
3619
+ }
3620
+ const version = atom.items[1];
3621
+ if (version.kind !== "gnd" || version.value.g !== "int" || Number(version.value.n) !== FUZZ_CORPUS_FORMAT) {
3622
+ return failed(`unsupported entry format, expected ${FUZZ_CORPUS_FORMAT}`);
3623
+ }
3624
+ const property = atom.items[2];
3625
+ if (property.kind !== "sym") return failed("the property id must be a symbol");
3626
+ const decoded = decodeReplayAtom(atom.items[3]);
3627
+ if (isKernelError(decoded)) return failed(`undecodable value: ${format2(decoded)}`);
3628
+ entries.push({ property: property.name, value: decoded });
3629
+ }
3630
+ return { ok: true, value: entries };
3631
+ }
3632
+ function corpusRegressionFact(entry) {
3633
+ return expr2([sym2("FuzzRegression"), sym2(entry.property), entry.value, sym2("None")]);
3634
+ }
3635
+
3636
+ // src/index.ts
3637
+ var registered2 = false;
3638
+ function registerFuzz() {
3639
+ if (registered2) return;
3640
+ registerFuzzKernel();
3641
+ registerBuiltinModule("fuzz", FUZZ_MODULE_SRC);
3642
+ registered2 = true;
3643
+ }
3644
+ registerFuzz();
3645
+ export {
3646
+ FUZZ_ALPHA_REPLAY_KEY_ALGORITHM,
3647
+ FUZZ_ATOM_CODEC_VERSION,
3648
+ FUZZ_ATOM_KEY_ALGORITHM,
3649
+ FUZZ_CORPUS_FORMAT,
3650
+ FUZZ_EXIT_INCOMPLETE,
3651
+ FUZZ_EXIT_INVALID,
3652
+ FUZZ_EXIT_OK,
3653
+ FUZZ_EXIT_PROPERTY_FAILURE,
3654
+ FUZZ_MODULE_SRC,
3655
+ FUZZ_REPLAY_KEY_ALGORITHM,
3656
+ FUZZ_RNG_ALGORITHM,
3657
+ corpusRegressionFact,
3658
+ decodeFuzzOutcome,
3659
+ exitCodeForOutcome,
3660
+ exitCodeForOutcomes,
3661
+ parseCorpusEntries,
3662
+ registerFuzz,
3663
+ renderCorpusEntry,
3664
+ renderOutcomeLine
3665
+ };