@zvenigora/ng-eval-core 0.3.0 → 0.4.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.
@@ -908,9 +908,12 @@ class EvalContext {
908
908
  * @returns The value associated with the key, or undefined if not found.
909
909
  */
910
910
  get(key) {
911
- const scoped = this.getFromScopes(key);
912
- if (scoped !== undefined) {
913
- return scoped;
911
+ // Presence, not value: a scope that *binds* the key answers, even when the
912
+ // value bound is `undefined`. See {@link scopeHolding} for why the two are
913
+ // not the same question, and what reading the value instead let through.
914
+ const scope = this.scopeHolding(key);
915
+ if (scope) {
916
+ return getContextValue(scope, key);
914
917
  }
915
918
  if (this._original) {
916
919
  const value = getContextValue(this._original, key);
@@ -941,18 +944,68 @@ class EvalContext {
941
944
  * implementation. A second copy of the order would drift - `getKey` already
942
945
  * shows what that looks like when it does.
943
946
  *
944
- * A binding whose value is `undefined` reads as absent here, exactly as it
945
- * does in {@link get}, which falls through to the original context for it.
947
+ * A binding whose value is `undefined` is **found** here, and no longer reads
948
+ * as absent - see {@link scopeHolding}.
946
949
  *
947
950
  * @param key - The key to retrieve the value for.
948
951
  * @returns The value bound by the innermost scope holding the key, or
949
- * undefined when no pushed scope holds it.
952
+ * undefined when no pushed scope holds it. The two cases are no longer
953
+ * distinguishable from the return value alone; ask {@link hasInScopes}.
950
954
  */
951
955
  getFromScopes(key) {
956
+ const scope = this.scopeHolding(key);
957
+ return scope ? getContextValue(scope, key) : undefined;
958
+ }
959
+ /**
960
+ * The innermost pushed scope that **binds** `key`, or undefined when none
961
+ * does. The single pass behind {@link get}'s step 1, {@link getFromScopes}
962
+ * and {@link hasInScopes}, so the three cannot disagree about what the scope
963
+ * stack holds.
964
+ *
965
+ * **Binding, not value, and that is the whole point.** Reading the value and
966
+ * treating `undefined` as absent - which is what this used to do - has two
967
+ * consequences that look unrelated and are the same bug:
968
+ *
969
+ * - `let x;` could not shadow. A scope binding `x` to `undefined` fell
970
+ * through to the caller's context, so a declared-but-unset name read
971
+ * whatever the consumer happened to have under it.
972
+ * - **A plain-object scope answered for every `Object.prototype` name.**
973
+ * `getContextValue` reads a plain record as `scope[key]`, which walks the
974
+ * prototype chain, so an *empty* scope resolved `toString`, `constructor`,
975
+ * `valueOf` and friends to the prototype's own members - shadowing
976
+ * `original`, `priorScopes` and `lookups`, all four of which come later in
977
+ * {@link get}'s order. Empty as a binding surface is not empty as a lookup
978
+ * surface. `hasContextKey` is own-properties-only, which closes it.
979
+ *
980
+ * The second was invisible while only `arrow-function-expression.ts` and
981
+ * `pattern.ts` pushed scopes, because a walk that pushed none could not hit
982
+ * it; a program-level scope on every evaluation made it reachable from every
983
+ * expression, which is how it was found.
984
+ *
985
+ * It also removes an asymmetry between the two scope shapes: `fromContext`
986
+ * copies a plain record into a `Registry` when `caseInsensitive` is set, and
987
+ * a `Registry` is Map-backed, so the prototype names leaked on the
988
+ * case-sensitive path and not on the case-insensitive one. Both now ask the
989
+ * same own-key question.
990
+ *
991
+ * **Public since Phase 2 step 3, and the reason is the write sites.**
992
+ * `assignment-expression.ts` and `update-expression.ts` need the *scope* and
993
+ * not a yes/no: `const` kinds are recorded against the scope object on
994
+ * `EvalState`, so a write has to know which scope it is about to land in
995
+ * before it can decide whether the binding is reassignable. Publishing the
996
+ * single pass is what keeps that question answered by the same code as
997
+ * {@link get}'s step 1. The alternative was a second copy of the
998
+ * innermost-scope walk at each write site, which is the defect
999
+ * `docs/backlog.md` A4 and A10 already describe - two copies of one
1000
+ * resolution order, drifting - reproduced on purpose.
1001
+ *
1002
+ * @param key - The key to look for.
1003
+ * @returns The innermost scope binding the key, or undefined.
1004
+ */
1005
+ scopeHolding(key) {
952
1006
  for (const scope of this._scopes.asArray()) {
953
- const value = getContextValue(scope, key);
954
- if (value !== undefined) {
955
- return value;
1007
+ if (hasContextKey(scope, key)) {
1008
+ return scope;
956
1009
  }
957
1010
  }
958
1011
  return undefined;
@@ -961,9 +1014,10 @@ class EvalContext {
961
1014
  * Whether any scope pushed during this evaluation *binds* the key - the
962
1015
  * question the read hooks' `scoped` flag asks.
963
1016
  *
964
- * Deliberately about binding rather than about value, which is where it parts
965
- * company with {@link getFromScopes}: a parameter bound to `undefined` is
966
- * still a parameter, but `get` falls through past it to the original context.
1017
+ * Deliberately about binding rather than about value. It no longer parts
1018
+ * company with {@link getFromScopes} over it: both go through
1019
+ * {@link scopeHolding}, and `get` resolves a scope binding whatever its
1020
+ * value, which is the divergence this docblock used to record as deliberate.
967
1021
  * Reading the flag off the value would make it depend on the *data* - the
968
1022
  * same arrow function over `[{ name: 'a' }]` and over `[undefined]` would
969
1023
  * report different bindings, and a dependency tracker's output would vary
@@ -978,12 +1032,7 @@ class EvalContext {
978
1032
  * @returns True when a pushed scope holds the key, whatever its value.
979
1033
  */
980
1034
  hasInScopes(key) {
981
- for (const scope of this._scopes.asArray()) {
982
- if (hasContextKey(scope, key)) {
983
- return true;
984
- }
985
- }
986
- return false;
1035
+ return this.scopeHolding(key) !== undefined;
987
1036
  }
988
1037
  /**
989
1038
  * Retrieves the `this` value of the specified key from the evaluation context.
@@ -1057,6 +1106,50 @@ class EvalContext {
1057
1106
  obj[key] = value;
1058
1107
  }
1059
1108
  }
1109
+ /**
1110
+ * Assigns to the innermost pushed scope that **binds** `key`, and reports
1111
+ * whether one did.
1112
+ *
1113
+ * The scope-aware half of the write path: `assignment-expression.ts` and
1114
+ * `update-expression.ts` try this first and fall back to {@link set}. Before
1115
+ * Phase 2 they only had {@link set}, which writes `_original` and consults no
1116
+ * scope at all - so `(x => (x = 99))(1)` wrote `99` into the *caller's*
1117
+ * object and left the arrow's parameter scope untouched.
1118
+ *
1119
+ * **Binding-presence, not scope-presence, and the fallback is load-bearing.**
1120
+ * `eval-signals` enforces a read-only policy by subclassing this class and
1121
+ * overriding {@link set} to throw, so every write that reaches the consumer's
1122
+ * data goes through the one method it overrides. An implementation that wrote
1123
+ * the innermost scope unconditionally - or created the binding when it was
1124
+ * absent - would route such a write around that override and silently disable
1125
+ * the policy of a published library, with every suite still green. Returning
1126
+ * false when nothing binds the key is what keeps {@link set} reachable.
1127
+ *
1128
+ * What it deliberately relaxes: a write to a binding the expression itself
1129
+ * created - an arrow parameter, or a `let` - no longer reaches {@link set},
1130
+ * because it mutates nothing the caller owns.
1131
+ *
1132
+ * The write dispatches through `setContextValue` rather than through the
1133
+ * prototype-pollution guard's `safeSetProperty`, and the difference is not
1134
+ * cosmetic: {@link push} normalises a plain record into a `Registry` when
1135
+ * `caseInsensitive` is set, and `Object.defineProperty` on a `Registry` would
1136
+ * define a property on the instance while inserting nothing into its map. No
1137
+ * guard is lost - this method only ever writes a key some scope already
1138
+ * *binds*, and a binding can only have been created through the guarded
1139
+ * declaration path, which rejects every blocklisted name.
1140
+ *
1141
+ * @param key - The key to assign to.
1142
+ * @param value - The value to assign.
1143
+ * @returns True when a pushed scope bound the key and received the write.
1144
+ */
1145
+ setInScope(key, value) {
1146
+ const scope = this.scopeHolding(key);
1147
+ if (!scope) {
1148
+ return false;
1149
+ }
1150
+ setContextValue(scope, key, value);
1151
+ return true;
1152
+ }
1060
1153
  /**
1061
1154
  * Pushes a context to the scope stack.
1062
1155
  * @param context - The context to push.
@@ -1270,6 +1363,30 @@ const POLICIES = ['collect', 'throw', 'ignore'];
1270
1363
  * message text it would have to keep in sync by hand.
1271
1364
  */
1272
1365
  const ASYNC_HOOK_MESSAGE = 'async hook returned a promise; it will not be awaited';
1366
+ /**
1367
+ * The completion value of a statement that produced nothing.
1368
+ *
1369
+ * JavaScript's completion-value semantics keep the last **non-empty** value, and
1370
+ * empty is not the same as `undefined`: `{ 'a'; noop() }` is `undefined` because
1371
+ * the call genuinely produced one, while `{ 'a'; ; }` is `'a'` because the empty
1372
+ * statement produced nothing at all. A statement visitor that produced no value
1373
+ * therefore pushes this rather than `undefined`, and an enclosing block keeps the
1374
+ * last value that is not this.
1375
+ *
1376
+ * It never reaches an evaluation's return value: `evaluate` and `evaluateAsync`
1377
+ * convert it to `undefined` at the walk boundary, immediately after popping the
1378
+ * result. It **is** reachable in a hook event, because `afterVisitor` reads the
1379
+ * value positionally off the top of the result stack - so an 'after' hook on a
1380
+ * statement that produced nothing observes this sentinel. Hiding it there is not
1381
+ * available: the alternatives are calling `afterVisitor` before the push, which
1382
+ * reports the neighbour's value, or normalising inside `afterVisitor`, which puts
1383
+ * a per-node cost on the hot path for a case only statements produce.
1384
+ *
1385
+ * Exported for that reason, on the precedent of {@link ASYNC_HOOK_MESSAGE}: a
1386
+ * consumer whose hook receives it can recognise it by identity rather than by
1387
+ * guessing at a value it would have to keep in sync by hand.
1388
+ */
1389
+ const EMPTY_COMPLETION = Symbol('eval-core:empty-completion');
1273
1390
  /**
1274
1391
  * Reads the error policy out of the evaluation options. `EvalOptions` is a union
1275
1392
  * and does not index directly, so the read goes through a cast - the same one
@@ -1522,6 +1639,21 @@ class EvalHooks {
1522
1639
  * every genuinely-open enclosing frame, and leave a later real failure with
1523
1640
  * nothing to unwind.
1524
1641
  *
1642
+ * **"Open" means open in *this* walk.** Both routes below are bounded by the
1643
+ * current walk base ({@link EvalHookBookkeeping.walkBases}), so a node open
1644
+ * only in an enclosing walk falls into case 3 by either route - which is the
1645
+ * behaviour case 3 already specifies for "not open at all". `evaluate` is
1646
+ * re-entered with the same state from an arrow-function body, so without the
1647
+ * bound a nested walk closing a node it never opened would flush the
1648
+ * enclosing walk's frames under `completed: false` events a consumer reads as
1649
+ * ordinary completions, and leave that walk's own `unwindTo(mark)` with
1650
+ * nothing left to unwind.
1651
+ *
1652
+ * The bound is needed on the **identity fast path** as much as on the scan:
1653
+ * when a nested walk has opened nothing yet, the top of the stack *is* the
1654
+ * enclosing walk's node, so the cheap route crosses the boundary without ever
1655
+ * reaching the scan.
1656
+ *
1525
1657
  * Popping positionally instead would be correct only if every visitor
1526
1658
  * bracketed its body exactly. `await-expression.ts` does not - it catches a
1527
1659
  * child's synchronous throw and continues to its own `afterVisitor` - so a
@@ -1540,14 +1672,18 @@ class EvalHooks {
1540
1672
  */
1541
1673
  exit(state, node) {
1542
1674
  const open = state.hookBookkeeping.open;
1543
- if (open.length > 0 && open[open.length - 1] === node) {
1675
+ const base = this.walkBase(state);
1676
+ if (open.length > base && open[open.length - 1] === node) {
1544
1677
  open.pop();
1545
1678
  return;
1546
1679
  }
1547
1680
  // The innermost occurrence is the one being closed: a node can legitimately
1548
1681
  // be open twice, since an arrow-function body is re-walked on every call.
1682
+ // `lastIndexOf` returns -1 when the node is absent, which the same
1683
+ // comparison rejects - "below this walk's base" and "not open at all" are
1684
+ // the same case here.
1549
1685
  const index = open.lastIndexOf(node);
1550
- if (index < 0) {
1686
+ if (index < base) {
1551
1687
  return;
1552
1688
  }
1553
1689
  while (open.length > index + 1) {
@@ -1569,6 +1705,41 @@ class EvalHooks {
1569
1705
  depth(state) {
1570
1706
  return state.hookBookkeeping.open.length;
1571
1707
  }
1708
+ /**
1709
+ * Records that a walk is starting at the state's current open depth, and
1710
+ * returns that depth. Called by `evaluate` / `evaluateAsync` on entry, under
1711
+ * their `hasHooks` guard, and paired with {@link popWalkBase} in a `finally`.
1712
+ *
1713
+ * The returned value is the same mark those entry points hand to
1714
+ * {@link unwindTo}, so they capture it once rather than reading the depth
1715
+ * twice.
1716
+ */
1717
+ pushWalkBase(state) {
1718
+ const bookkeeping = state.hookBookkeeping;
1719
+ const base = bookkeeping.open.length;
1720
+ bookkeeping.walkBases.push(base);
1721
+ return base;
1722
+ }
1723
+ /**
1724
+ * Drops the innermost walk base. Called from the `finally` of the `evaluate`
1725
+ * that pushed it, so an entry point whose walk threw still restores the
1726
+ * enclosing walk's bound.
1727
+ */
1728
+ popWalkBase(state) {
1729
+ state.hookBookkeeping.walkBases.pop();
1730
+ }
1731
+ /**
1732
+ * The open depth the innermost walk in progress started at, and the floor
1733
+ * {@link exit} will not reach below.
1734
+ *
1735
+ * Zero when no base has been pushed, which leaves `exit` behaving exactly as
1736
+ * it did before the bound existed - the correct answer for a walk that began
1737
+ * before any hook was registered, since it pushed no base.
1738
+ */
1739
+ walkBase(state) {
1740
+ const bases = state.hookBookkeeping.walkBases;
1741
+ return bases.length > 0 ? bases[bases.length - 1] : 0;
1742
+ }
1572
1743
  /**
1573
1744
  * Fires 'after' for every node the state has open above `mark`, innermost
1574
1745
  * first, marked incomplete. Invoked from the catch in `evaluate`, so that a
@@ -1771,6 +1942,34 @@ const adoptHooks = (options) => {
1771
1942
  * Whether the caller asked for per-node timings. Same cast, same reason.
1772
1943
  */
1773
1944
  const readTrackTime = (options) => !!options?.['trackTime'];
1945
+ /**
1946
+ * The iteration budget one evaluation gets when the caller names no other.
1947
+ *
1948
+ * Sized in the Phase 2 plan's § 3.4 rather than picked: a loop iteration is
1949
+ * roughly three walks at the measured ~1.4 M simple walks per second, so
1950
+ * ~2 microseconds, and 100,000 of them is ~0.2 s before the throw. Short enough
1951
+ * that a Jest spec fails fast rather than timing out at five seconds, and short
1952
+ * enough that a browser tab stutters rather than freezes - and far above any
1953
+ * expression a rule author writes by hand.
1954
+ */
1955
+ const DEFAULT_MAX_ITERATIONS = 100000;
1956
+ /**
1957
+ * The iteration budget the options ask for, or the default.
1958
+ *
1959
+ * Same cast as the two readers above, same reason. A non-numeric or negative
1960
+ * value falls back rather than throwing: options are a permissive record that
1961
+ * nothing validates, and the budget exists to bound a runaway loop, so a
1962
+ * malformed one must not become a *smaller* bound than the default by accident.
1963
+ * `0` is honoured - a caller forbidding loops entirely is a coherent thing to
1964
+ * ask for - and `Infinity` opts out, which is why the test is not
1965
+ * `Number.isFinite`.
1966
+ */
1967
+ const readMaxIterations = (options) => {
1968
+ const value = options?.['maxIterations'];
1969
+ return typeof value === 'number' && !Number.isNaN(value) && value >= 0
1970
+ ? value
1971
+ : DEFAULT_MAX_ITERATIONS;
1972
+ };
1774
1973
  /**
1775
1974
  * Represents the evaluation state, which includes the context, result, and options.
1776
1975
  */
@@ -1866,11 +2065,156 @@ class EvalState {
1866
2065
  * @internal Not part of the published API.
1867
2066
  */
1868
2067
  get hookBookkeeping() {
1869
- return (this._hookBookkeeping ??= { open: [], errors: [], timings: new Map() });
2068
+ return (this._hookBookkeeping ??=
2069
+ { open: [], errors: [], timings: new Map(), walkBases: [] });
2070
+ }
2071
+ /**
2072
+ * How many `evaluate` / `evaluateAsync` calls on this state are currently on
2073
+ * the JavaScript stack: 0 between evaluations, 1 during an ordinary walk, and
2074
+ * more while a nested walk runs - an arrow-function body is re-entrant
2075
+ * `evaluate` on this same state.
2076
+ *
2077
+ * Maintained by {@link enterWalk} / {@link exitWalk}, which the entry points
2078
+ * pair around their walk, the exit in a `finally` so a throw still restores
2079
+ * the count.
2080
+ *
2081
+ * **Deliberately not merged with `EvalHookBookkeeping.walkBases`**, which
2082
+ * tracks the same nesting one level down. That stack is pushed only under
2083
+ * {@link hasHooks}, because bounding `EvalHooks.exit` is meaningless with no
2084
+ * hooks to dispatch; this counter must be maintained unconditionally, because
2085
+ * § 3.4's iteration budget refills on the outermost entry and a loop is
2086
+ * bounded whether or not anyone is listening. One field cannot be both
2087
+ * guarded and unguarded, so there are two.
2088
+ *
2089
+ * @internal Not part of the published API.
2090
+ */
2091
+ get walkDepth() {
2092
+ return this._walkDepth;
2093
+ }
2094
+ /**
2095
+ * Records that a walk is starting on this state and returns the new depth, so
2096
+ * a caller can recognise the outermost entry as `=== 1` without a second
2097
+ * read.
2098
+ *
2099
+ * **Refills {@link iterationsRemaining} on the outermost entry**, which is
2100
+ * what makes § 3.4's budget per-`evaluate` rather than per-state. It happens
2101
+ * here rather than at the entry points so that both of them - and any later
2102
+ * one - get it without a second copy of the 0 -> 1 test; the depth this
2103
+ * method already owns is the only thing the decision needs.
2104
+ *
2105
+ * @internal Not part of the published API.
2106
+ */
2107
+ enterWalk() {
2108
+ const depth = ++this._walkDepth;
2109
+ // § 3.4's refill, and the 0 -> 1 test is the whole of it. A nested walk -
2110
+ // an arrow-function body, which re-enters `evaluate` on this same state -
2111
+ // shares whatever the enclosing walk has left, so an escaped closure cannot
2112
+ // buy itself a fresh budget by being called again. The options are re-read
2113
+ // per outermost walk rather than in the constructor because they are a
2114
+ // mutable record the caller keeps a reference to.
2115
+ if (depth === 1) {
2116
+ this._iterationBudget = readMaxIterations(this._options);
2117
+ this._iterationsRemaining = this._iterationBudget;
2118
+ }
2119
+ return depth;
2120
+ }
2121
+ /**
2122
+ * Records that a walk has finished. Called from the entry point's `finally`.
2123
+ *
2124
+ * @internal Not part of the published API.
2125
+ */
2126
+ exitWalk() {
2127
+ this._walkDepth--;
2128
+ }
2129
+ /**
2130
+ * How many loop iterations this evaluation may still run.
2131
+ *
2132
+ * Refilled by {@link enterWalk} on the outermost entry from
2133
+ * `options.maxIterations`, defaulting to 100,000, and spent one at a time by
2134
+ * {@link chargeIteration}. `Infinity` when the caller opted out.
2135
+ *
2136
+ * Readable mainly so a spec can assert what a walk charged: nothing in the
2137
+ * library reads it except {@link chargeIteration}, and no expression without a
2138
+ * `for` in it moves it.
2139
+ *
2140
+ * @internal Not part of the published API.
2141
+ */
2142
+ get iterationsRemaining() {
2143
+ return this._iterationsRemaining;
2144
+ }
2145
+ /**
2146
+ * Charges one loop iteration against the budget, throwing when it is spent.
2147
+ *
2148
+ * Called from `for-statement.ts`'s iteration loop and **nowhere else**, which
2149
+ * is § 3.4's cost argument in its literal form: the no-loop path does not
2150
+ * execute a cheaper version of this check, it does not reach the call site at
2151
+ * all. The rejected alternative - a per-node fuel counter in `beforeVisitor` -
2152
+ * would have been on the hot path of every evaluation in the library, to bound
2153
+ * a recursion depth this phase does not introduce.
2154
+ *
2155
+ * The message names the **configured** budget rather than the default, since a
2156
+ * caller who set `maxIterations` needs to recognise their own number in it.
2157
+ *
2158
+ * @internal Not part of the published API.
2159
+ */
2160
+ chargeIteration() {
2161
+ if (this._iterationsRemaining <= 0) {
2162
+ throw new Error(`Iteration budget exhausted after ${this._iterationBudget} iterations`);
2163
+ }
2164
+ this._iterationsRemaining--;
2165
+ }
2166
+ /**
2167
+ * Records that `key` was declared `const` in `scope`, so a later write to it
2168
+ * can be rejected.
2169
+ *
2170
+ * **Keyed by the scope *object*, and beside the scope rather than in it.** A
2171
+ * metadata key written onto the scope record would itself be resolvable as a
2172
+ * binding name - `getContextValue` reads the same surface a declaration binds
2173
+ * into - so `let __kind` would be readable from an expression. A `WeakMap`
2174
+ * hanging off the state has neither problem, and it is checked at the write
2175
+ * site only, so reads pay nothing.
2176
+ *
2177
+ * **The scope passed here must be the one on the stack**, not the record a
2178
+ * visitor built to push: `EvalContext.push` routes through `fromContext`,
2179
+ * which *copies* a plain record into a `Registry` when `caseInsensitive` is
2180
+ * set. Keying on the pre-push record would file every `const` under an object
2181
+ * the write site can never produce, and `caseInsensitive` alone would lose
2182
+ * const-ness silently. `EvalContext.scopeHolding` returns the stack's object,
2183
+ * which is what both sides use.
2184
+ *
2185
+ * The entries die with the scopes: scope objects are created per block entry
2186
+ * and dropped when the block exits, so nothing here outlives the walk even
2187
+ * though the state may.
2188
+ *
2189
+ * @internal Not part of the published API.
2190
+ */
2191
+ declareConst(scope, key) {
2192
+ const bindings = (this._constBindings ??= new WeakMap());
2193
+ const keys = bindings.get(scope);
2194
+ if (keys) {
2195
+ keys.add(key);
2196
+ }
2197
+ else {
2198
+ bindings.set(scope, new Set([key]));
2199
+ }
2200
+ }
2201
+ /**
2202
+ * Whether `key` was declared `const` in `scope`.
2203
+ *
2204
+ * Asked by `assignment-expression.ts` and `update-expression.ts` of the scope
2205
+ * the write is about to land in, so an inner `let` of a name an outer scope
2206
+ * declared `const` stays writable - the kind belongs to the binding, not to
2207
+ * the name.
2208
+ *
2209
+ * @internal Not part of the published API.
2210
+ */
2211
+ isConstBinding(scope, key) {
2212
+ return !!this._constBindings?.get(scope)?.has(key);
1870
2213
  }
1871
2214
  /**
1872
2215
  * Drops every per-run record this state holds: the collected hook errors, the
1873
- * open-node stack, and the accumulated timings.
2216
+ * open-node stack, the accumulated timings, and the walk bases bounding
2217
+ * `EvalHooks.exit`.
1874
2218
  *
1875
2219
  * It resets the whole record rather than only the errors, which is why it is
1876
2220
  * not named for them. `EvalHooks.clear` cannot reach any of this - the
@@ -1902,6 +2246,9 @@ class EvalState {
1902
2246
  * @param isAsync Indicates whether the evaluation is asynchronous.
1903
2247
  */
1904
2248
  constructor(context, result, options, isAsync) {
2249
+ this._walkDepth = 0;
2250
+ this._iterationBudget = DEFAULT_MAX_ITERATIONS;
2251
+ this._iterationsRemaining = DEFAULT_MAX_ITERATIONS;
1905
2252
  this._context = context;
1906
2253
  this._result = result;
1907
2254
  this._options = options;
@@ -3356,9 +3703,374 @@ const getDefaultVisitors = () => {
3356
3703
  visitors['AssignmentExpression'] = assignmentExpressionVisitor;
3357
3704
  visitors['UpdateExpression'] = updateExpressionVisitor;
3358
3705
  visitors['ArrowFunctionExpression'] = arrowFunctionExpressionVisitor;
3706
+ // The statement family. `Program` is the root of every walk that arrives
3707
+ // through `EvalService`, whose parser options leave `extractExpressions` off.
3708
+ visitors['Program'] = programVisitor;
3709
+ visitors['ExpressionStatement'] = expressionStatementVisitor;
3710
+ visitors['EmptyStatement'] = emptyStatementVisitor;
3711
+ visitors['BlockStatement'] = blockStatementVisitor;
3712
+ visitors['VariableDeclaration'] = variableDeclarationVisitor;
3713
+ visitors['IfStatement'] = ifStatementVisitor;
3714
+ visitors['ForStatement'] = forStatementVisitor;
3359
3715
  return visitors;
3360
3716
  };
3361
3717
 
3718
+ // based on evalArrowContext
3719
+ // https://github.com/6utt3rfly/jse-eval/blob/main/index.ts
3720
+ /**
3721
+ * The one answer this module gives to a binding target it does not implement.
3722
+ *
3723
+ * Both entry points used to fall out of their `switch` and return an empty
3724
+ * context - `evaluatePatterns` past a `case`-less type, `evaluatePattern` past
3725
+ * the `return {}` at the end - so `let { a = 1 } = o` and `((a = 1) => a)(x)`
3726
+ * bound nothing, threw nothing, and left the caller to read the miss as a
3727
+ * value. That is the shape `docs/backlog.md` A2 records three instances of in
3728
+ * the two write visitors, and Phase 2 requires a throwing `default:` in every
3729
+ * new statement dispatcher; a phase that promises not to add a fourth member of
3730
+ * that family cannot leave this one open either.
3731
+ *
3732
+ * `AssignmentPattern` is the reachable case - it is commented out below - and
3733
+ * the message names the node type so a consumer can tell which form was
3734
+ * rejected.
3735
+ */
3736
+ const unsupportedBindingTarget = (type) => {
3737
+ throw new Error(`${type} is not supported as a binding target.`);
3738
+ };
3739
+ const evaluatePatterns = (patterns, st, callback, args) => {
3740
+ let context = {};
3741
+ patterns.map((pattern, i) => {
3742
+ switch (pattern.type) {
3743
+ case 'Identifier':
3744
+ {
3745
+ const object = evaluateIdentifier(pattern, st, args[i]);
3746
+ context = { ...context, ...object };
3747
+ }
3748
+ break;
3749
+ case 'MemberExpression':
3750
+ {
3751
+ const object = evaluateMemberExpression(pattern);
3752
+ context = { ...context, ...object };
3753
+ }
3754
+ break;
3755
+ case 'ObjectPattern':
3756
+ {
3757
+ const object = evaluateObjectPattern(pattern, st, callback, args[i]);
3758
+ context = { ...context, ...object };
3759
+ }
3760
+ break;
3761
+ case 'ArrayPattern':
3762
+ {
3763
+ const object = evaluateArrayPattern(pattern, st, callback, args[i]);
3764
+ context = { ...context, ...object };
3765
+ }
3766
+ break;
3767
+ case 'RestElement':
3768
+ {
3769
+ const object = evaluateRestElement(pattern, st, callback, args.slice(i));
3770
+ context = { ...context, ...object };
3771
+ }
3772
+ break;
3773
+ // case 'AssignmentPattern': {
3774
+ // const object = evaluateAssignmentPattern(pattern, st, callback, args[i]);
3775
+ // context = {...context, ...object};
3776
+ // }
3777
+ // break;
3778
+ default:
3779
+ unsupportedBindingTarget(pattern.type);
3780
+ }
3781
+ });
3782
+ return context;
3783
+ };
3784
+ const evaluatePattern = (pattern, st, callback, arg) => {
3785
+ switch (pattern.type) {
3786
+ case 'Identifier':
3787
+ return evaluateIdentifier(pattern, st, arg);
3788
+ case 'MemberExpression':
3789
+ return evaluateMemberExpression(pattern);
3790
+ case 'ObjectPattern':
3791
+ return evaluateObjectPattern(pattern, st, callback, arg);
3792
+ case 'ArrayPattern':
3793
+ return evaluateArrayPattern(pattern, st, callback, arg);
3794
+ case 'RestElement':
3795
+ return evaluateRestElement(pattern, st, callback, arg);
3796
+ // case 'AssignmentPattern':
3797
+ // return evaluateAssignmentPattern(pattern, st, callback, arg);
3798
+ }
3799
+ return unsupportedBindingTarget(pattern.type);
3800
+ };
3801
+ // The binding write goes through the prototype-pollution guard, for the reason
3802
+ // the other three guarded visitors do: on a plain record `__proto__` is a
3803
+ // setter, so `let __proto__ = { … }` and `({ __proto__ }) => …` would replace
3804
+ // this object's prototype instead of naming a binding. Declarations are a new
3805
+ // way to reach this line - before Phase 2 only an arrow parameter did - so the
3806
+ // surface widened and the guard is what keeps the blocklist covering it.
3807
+ const evaluateIdentifier = (pattern, st, arg) => {
3808
+ const object = {};
3809
+ safeSetProperty(object, pattern.name, arg);
3810
+ return object;
3811
+ };
3812
+ // Module-private, and down to the one parameter it reads: deleting the log
3813
+ // below left `st`, `callback` and `arg` unused, and the two call sites are both
3814
+ // in this file.
3815
+ const evaluateMemberExpression = (pattern) => {
3816
+ if (pattern.type === 'MemberExpression') {
3817
+ // The node type is the only part of this a caller could act on. What stood
3818
+ // here before was `console.log(pattern, st, callback, arg)` - `st` being the
3819
+ // whole EvalState, i.e. the caller's entire evaluation context dumped to the
3820
+ // console of any application whose user wrote that pattern. Unreachable
3821
+ // today because acorn rejects a MemberExpression binding target in a
3822
+ // parameter list, and deleted ahead of the work that widens what reaches
3823
+ // here. See docs/backlog.md B2.
3824
+ throw new Error(`${pattern.type} is not supported as a binding target.`);
3825
+ }
3826
+ return {};
3827
+ };
3828
+ const evaluateObjectPattern = (pattern, st, callback, arg) => {
3829
+ let context = {};
3830
+ pattern.properties.map((pattern) => {
3831
+ switch (pattern.type) {
3832
+ case 'Property':
3833
+ {
3834
+ let key;
3835
+ if (pattern.key.type === 'Identifier') {
3836
+ key = pattern.key.name;
3837
+ }
3838
+ else if (pattern.key.type === 'Literal') {
3839
+ key = pattern.key.value;
3840
+ }
3841
+ else {
3842
+ callback(pattern.key, st);
3843
+ key = popVisitorResult(pattern, st);
3844
+ if (typeof key !== 'string' && typeof key !== 'number')
3845
+ throw new Error(`Unsupported property key type: ${pattern.key.type}`);
3846
+ }
3847
+ // **Where `let { a = 1 } = o` actually lands**, which is not where
3848
+ // it was expected to. A default in an object pattern is parsed as
3849
+ // `Property.value` of type `AssignmentPattern` - so it is handed to
3850
+ // `callback` below and walked as an *expression*, and reaches neither
3851
+ // of this module's two `switch` defaults. Rejecting it there would
3852
+ // have left the object form of the very example that names the
3853
+ // divergence still binding silently; the array form
3854
+ // (`let [a = 1] = arr`) and the parameter form (`(a = 1) => a`) do go
3855
+ // through `evaluatePatterns`, and are covered there.
3856
+ if (pattern.value.type === 'AssignmentPattern') {
3857
+ unsupportedBindingTarget(pattern.value.type);
3858
+ }
3859
+ const ctx = arg;
3860
+ // `finally`, for the reason given at the other push site in
3861
+ // arrow-function-expression.ts: the scope stack is on EvalContext,
3862
+ // which outlives this walk, so a scope left behind here shadows a
3863
+ // source key on every later evaluation against the same context.
3864
+ // The `try` opens after the push, never around it.
3865
+ st.context?.push(ctx);
3866
+ let value;
3867
+ try {
3868
+ callback(pattern.value, st);
3869
+ value = popVisitorResult(pattern, st);
3870
+ }
3871
+ finally {
3872
+ st.context?.pop();
3873
+ }
3874
+ // Guarded for the same reason `evaluateIdentifier` is: the key comes
3875
+ // from the *pattern*, so `let { __proto__: p } = o` names `__proto__`
3876
+ // here and a raw assignment would set this record's prototype.
3877
+ const pair = {};
3878
+ safeSetProperty(pair, key, value);
3879
+ context = { ...context, ...pair };
3880
+ }
3881
+ break;
3882
+ case 'RestElement':
3883
+ {
3884
+ const object = evaluateRestElement(pattern, st, callback, arg);
3885
+ context = { ...context, ...object };
3886
+ }
3887
+ break;
3888
+ }
3889
+ });
3890
+ return context;
3891
+ };
3892
+ const evaluateArrayPattern = (pattern, st, callback, args) => {
3893
+ const patterns = pattern.elements.filter(s => !!s);
3894
+ const object = evaluatePatterns(patterns, st, callback, args);
3895
+ return object;
3896
+ };
3897
+ const evaluateRestElement = (pattern, st, callback, args) => {
3898
+ const argument = pattern.argument;
3899
+ const object = evaluatePattern(argument, st, callback, args);
3900
+ return object;
3901
+ };
3902
+ // const evaluateAssignmentPattern = (pattern: AssignmentPattern, st: EvalState, callback: walk.WalkerCallback<EvalState>, args: unknown) => {
3903
+ // const left = evaluatePattern(pattern.left, st, callback, args);
3904
+ // callback(pattern.right, st);
3905
+ // const value = popVisitorResult(pattern, st);
3906
+ // const object = {...left};
3907
+ // return object;
3908
+ // }
3909
+
3910
+ /**
3911
+ * The scope a declaration binds into: the innermost one on the stack.
3912
+ *
3913
+ * Read back from the stack rather than kept as a reference by whoever pushed
3914
+ * it, and that is the load-bearing half. `EvalContext.push` routes through
3915
+ * `fromContext`, which **copies** a plain record into a `Registry` when
3916
+ * `caseInsensitive` is set - so the object a visitor handed to `push` is not
3917
+ * always the object on the stack, and a binding written through the pre-push
3918
+ * record would be written into something nothing ever reads. It is also the
3919
+ * object `EvalState.declareConst` keys on, so both sides have to agree about
3920
+ * which one it is.
3921
+ *
3922
+ * Every route into a declaration pushes one first - `Program` for the top level,
3923
+ * `BlockStatement` for a block - so the absent case means the caller walked a
3924
+ * bare declaration node. Throwing is the answer rather than falling back to
3925
+ * `EvalContext.set`, which would write the caller's own context object: a `let`
3926
+ * that mutates the consumer's data is the behaviour this step exists to remove,
3927
+ * and doing it on an unsupported entry path would be the one place it survived.
3928
+ */
3929
+ const bindingScope = (st) => {
3930
+ const scope = st.context && st.context.scopes.length > 0
3931
+ ? st.context.scopes.peek()
3932
+ : undefined;
3933
+ if (!scope) {
3934
+ throw new Error('A variable declaration requires an enclosing scope.');
3935
+ }
3936
+ return scope;
3937
+ };
3938
+ /**
3939
+ * Binds one declarator's names into `scope`.
3940
+ *
3941
+ * The names come from `evaluatePattern`, which is the binder arrow-function
3942
+ * parameters already use - `Identifier` for the plain form, and the
3943
+ * `ObjectPattern` / `ArrayPattern` / `RestElement` forms for the destructuring
3944
+ * ones. Reusing it is what makes `let [p, q] = arr` work without a second
3945
+ * pattern implementation, and what makes a form it does not implement throw
3946
+ * (`AssignmentPattern`, i.e. `let { a = 1 } = o`) rather than bind nothing.
3947
+ *
3948
+ * The keys are re-checked against the pollution blocklist even though
3949
+ * `evaluatePattern` already wrote them through `safeSetProperty`. One line for
3950
+ * a guard that cannot be reasoned away from this call site: the record arrives
3951
+ * as a `BaseContext`, and the binder's own coverage of it is a property of
3952
+ * `pattern.ts` rather than of this module's contract with it.
3953
+ *
3954
+ * The write itself dispatches through `setContextValue`, not through
3955
+ * `safeSetProperty`. `safeSetProperty` finishes with `Object.defineProperty`,
3956
+ * which suits the plain records `pattern.ts` builds and **not** a scope: a
3957
+ * `caseInsensitive` scope is a Map-backed `Registry`, and defining a property
3958
+ * on the instance inserts nothing into its map. The binding would be written
3959
+ * and then not found, silently, for that option only.
3960
+ */
3961
+ const bindDeclarator = (declarator, value, kind, scope, st, callback) => {
3962
+ const bindings = evaluatePattern(declarator.id, st, callback, value);
3963
+ for (const key of Object.keys(bindings)) {
3964
+ if (isDangerousProperty(key)) {
3965
+ throw new Error(`Access to dangerous property "${key}" is blocked for security reasons`);
3966
+ }
3967
+ setContextValue(scope, key, bindings[key]);
3968
+ if (kind === 'const') {
3969
+ st.declareConst(scope, key);
3970
+ }
3971
+ }
3972
+ };
3973
+ /**
3974
+ * Evaluates a variable declaration: `let` and `const`, in the plain and
3975
+ * destructuring forms.
3976
+ *
3977
+ * Pushes {@link EMPTY_COMPLETION} on every exit path - a declaration produces no
3978
+ * completion value in JavaScript, and the sentinel rather than `undefined` is
3979
+ * what keeps `let x = 1` from winning over an earlier statement's value inside a
3980
+ * block. Pops one value per declarator that has an initialiser, and none for one
3981
+ * that does not, which is the arithmetic § 3.1's table states for this visitor.
3982
+ *
3983
+ * **No hoisting.** A binding exists from the point its declaration is reached,
3984
+ * so a read before it resolves the enclosing context rather than raising a
3985
+ * temporal-dead-zone error. An uninitialised `let` binds `undefined` and still
3986
+ * *shadows*, because `EvalContext.get` resolves a pushed scope by presence
3987
+ * rather than by value.
3988
+ *
3989
+ * **`var` is rejected here, not by the statement dispatcher.** The dispatcher
3990
+ * switches on node *type*, and `var x = 1` is a `VariableDeclaration` exactly as
3991
+ * `let x = 1` is - so registering this visitor is what stopped `var` reaching the
3992
+ * throwing `default:`. Function-scoped hoisting is a second scoping model beside
3993
+ * block scoping and is out of scope for this phase, so the rejection had to move
3994
+ * rather than disappear.
3995
+ *
3996
+ * No scope is pushed here: a declaration binds into the scope its enclosing
3997
+ * statement list already pushed, so there is no `try`/`finally` to pair and
3998
+ * nothing this visitor can leave behind on `EvalContext`.
3999
+ */
4000
+ const variableDeclarationVisitor = (node, st, callback) => {
4001
+ // Above `beforeVisitor`, deliberately. Four paths through this visitor throw,
4002
+ // and three of them have to throw from inside the bracket - they need the
4003
+ // walk to have started. This one reads `node.kind` and nothing else, so
4004
+ // rejecting before the hook dispatch keeps the most reachable of the four
4005
+ // from opening a frame it never closes. The others are covered the way every
4006
+ // throwing visitor in this library is: `evaluate`'s `catch` unwinds the open
4007
+ // nodes to its walk base.
4008
+ if (node.kind !== 'let' && node.kind !== 'const') {
4009
+ throw new Error(`Unsupported variable declaration kind: ${node.kind}`);
4010
+ }
4011
+ beforeVisitor(node, st);
4012
+ const scope = bindingScope(st);
4013
+ for (const declarator of node.declarations) {
4014
+ let value = undefined;
4015
+ if (declarator.init) {
4016
+ callback(declarator.init, st);
4017
+ value = popVisitorResult(node, st);
4018
+ }
4019
+ bindDeclarator(declarator, value, node.kind, scope, st, callback);
4020
+ }
4021
+ pushVisitorResult(node, st, EMPTY_COMPLETION);
4022
+ afterVisitor(node, st);
4023
+ };
4024
+ /**
4025
+ * Assigns to `key`, preferring a binding the evaluation itself created.
4026
+ *
4027
+ * The shared write path for `assignment-expression.ts` and
4028
+ * `update-expression.ts`. It lives in this module rather than one of its own on
4029
+ * the precedent `dispatchStatement` set in `program.ts`: the `const` kinds it
4030
+ * enforces are recorded here, and two importers is not yet a utility module. A
4031
+ * third is when it earns one.
4032
+ *
4033
+ * Order matters, and both steps are one lookup:
4034
+ *
4035
+ * 1. `scopeHolding` finds the innermost pushed scope that **binds** the key, or
4036
+ * nothing. This is the same pass `EvalContext.get` resolves through, which is
4037
+ * why it is asked of the context rather than re-walked here.
4038
+ * 2. A `const` in that scope is rejected before anything is written.
4039
+ * 3. Otherwise `setInScope` writes it - and when no scope bound the key at all,
4040
+ * `set` does, which is the fallback `eval-signals` overrides to enforce its
4041
+ * read-only policy. Routing around it would disable that policy silently.
4042
+ *
4043
+ * **The scope is resolved twice - here, and again inside `setInScope` - and that
4044
+ * is a cost, not a free abstraction.** `scopeHolding` goes through
4045
+ * `Stack.asArray()`, which copies and reverses, so each pass allocates. An
4046
+ * identifier write therefore costs two short scans plus two small arrays where
4047
+ * the pre-Phase-2 `set` cost none.
4048
+ *
4049
+ * Kept because `setInScope` is the single place that knows how to write a scope
4050
+ * - a `Registry` under `caseInsensitive`, a plain record otherwise - and
4051
+ * writing directly from here would put that dispatch in two modules, which is
4052
+ * the one mistake in this area that is silent when made wrong. The honest
4053
+ * alternative is to let `setInScope` take an already-resolved scope; that widens
4054
+ * a signature this phase has published and is step 5's call, not this step's,
4055
+ * because step 5 is where the cost multiplies: `for (let i = 0; i < n; i++)`
4056
+ * runs this path once per iteration, on top of the `get` in the test and the
4057
+ * `get` in the update. Recorded in the plan's step 5 rather than left here.
4058
+ */
4059
+ const assignToBinding = (st, key, value, name) => {
4060
+ if (!st.context) {
4061
+ throw new Error(`Context is not set.`);
4062
+ }
4063
+ const scope = st.context.scopeHolding(key);
4064
+ if (!scope) {
4065
+ st.context.set(key, value);
4066
+ return;
4067
+ }
4068
+ if (st.isConstBinding(scope, key)) {
4069
+ throw new Error(`Assignment to constant variable "${name}".`);
4070
+ }
4071
+ st.context.setInScope(key, value);
4072
+ };
4073
+
3362
4074
  const assignmentOperators = {
3363
4075
  '=': (left, value) => { return left = value; },
3364
4076
  '+=': (left, value) => { return left += value; },
@@ -3395,7 +4107,12 @@ const assignmentExpressionVisitor = (node, st, callback) => {
3395
4107
  ? st.context.getKey(node.left.name)
3396
4108
  : node.left.name;
3397
4109
  const value = func(left, right);
3398
- st.context.set(key, value);
4110
+ // Scope first, the caller's object second. Before Phase 2 this was
4111
+ // `st.context.set(key, value)`, which consults no scope at all - so
4112
+ // `(x => (x = 99))(1)` wrote `99` into the caller's own object and left the
4113
+ // arrow's parameter untouched. See `assignToBinding` for why the fallback
4114
+ // to `set` is load-bearing rather than tidy.
4115
+ assignToBinding(st, key, value, node.left.name);
3399
4116
  pushVisitorResult(node, st, value);
3400
4117
  }
3401
4118
  else if (node.left.type === 'MemberExpression') {
@@ -3423,7 +4140,11 @@ const updateExpressionVisitor = (node, st, callback) => {
3423
4140
  : node.argument.name;
3424
4141
  const value = st.context?.get(key);
3425
4142
  const newValue = updateOperators[node.operator](value);
3426
- st.context?.set(key, newValue);
4143
+ // The same redirection as `assignment-expression.ts`, and the site that
4144
+ // matters for `for (let i = 0; …; i++)`: without it every loop counter this
4145
+ // library runs would be written into the consumer's context object, and
4146
+ // left there.
4147
+ assignToBinding(st, key, newValue, node.argument.name);
3427
4148
  pushVisitorResult(node, st, node.prefix ? newValue : value);
3428
4149
  }
3429
4150
  else if (node.argument.type === 'MemberExpression') {
@@ -3466,6 +4187,59 @@ const extractExpression = (program) => {
3466
4187
  return undefined;
3467
4188
  };
3468
4189
 
4190
+ /**
4191
+ * Applies § 3.1's rule 4: the empty-completion sentinel never leaves an
4192
+ * evaluation's return value.
4193
+ *
4194
+ * It is converted here, at the walk boundary, rather than in the `Program`
4195
+ * visitor. `arrow-function-expression.ts` calls `evaluate` on a
4196
+ * `BlockStatement` for a block-bodied arrow, so a conversion sited in `Program`
4197
+ * would let `x => { }` hand the sentinel straight to a consumer. Converting
4198
+ * where the walk ends covers both entry points by construction.
4199
+ */
4200
+ const completionValue = (value) => value === EMPTY_COMPLETION ? undefined : value;
4201
+ /**
4202
+ * The merged visitor table every walk dispatches through: this library's
4203
+ * visitors laid over `acorn-walk`'s base walker, built once.
4204
+ *
4205
+ * **`walk.recursive` merges per call, and the merge is not cheap.** Handed a
4206
+ * `funcs` object it calls `walk.make(funcs, base)`, which allocates an object
4207
+ * and copies every entry onto it - once per `evaluate`, not once per node.
4208
+ * Measured on the built bundle, walking a single `Literal`, which visits one
4209
+ * node and so is almost entirely this fixed cost:
4210
+ *
4211
+ * | visitor entries | per-call merge | merged once |
4212
+ * | --------------- | -------------- | ----------- |
4213
+ * | 19 (before statements) | 0.422 us | - |
4214
+ * | 22 (with statements) | 1.045 us | 0.226 us |
4215
+ *
4216
+ * Three more entries more than doubled it, which is a cliff rather than a
4217
+ * slope - the copy crosses a threshold where the engine stops treating the
4218
+ * result as a fast-property object. Merging once removes the whole class of
4219
+ * problem: it is faster than the pre-statement baseline, and it stops the
4220
+ * remaining statement visitors of this phase from making it worse again.
4221
+ *
4222
+ * `{}` is still passed as `funcs` at the call sites so that `make` has nothing
4223
+ * to copy; the per-walk object is then an empty `Object.create(DEFAULT_VISITORS)`
4224
+ * and every lookup is a prototype hit.
4225
+ *
4226
+ * Frozen, and lazily built, for two different reasons:
4227
+ *
4228
+ * - **Frozen** because this table is shared by every walk in the process -
4229
+ * `EvalService` is `providedIn: 'root'` - so a visitor that wrote to it would
4230
+ * reach every later evaluation, including other consumers'. Nothing writes to
4231
+ * it today; freezing is what keeps that true, turning a silent cross-walk
4232
+ * mutation into a throw. `getDefaultVisitors()` still returns a **fresh,
4233
+ * mutable** object to anyone who calls it, so no caller loses anything.
4234
+ * - **Lazily** because a module-level `const` deadlocks the flattened bundle:
4235
+ * `arrow-function-expression.ts` imports `evaluate`, so this module is
4236
+ * initialised first and `getDefaultVisitors()` at module scope reads that
4237
+ * visitor before its binding exists. Measured, not guessed - the built
4238
+ * package threw `Cannot access 'arrowFunctionExpressionVisitor' before
4239
+ * initialization` on import.
4240
+ */
4241
+ let defaultVisitors;
4242
+ const mergedVisitors = () => (defaultVisitors ??= Object.freeze(walk.make(getDefaultVisitors())));
3469
4243
  /**
3470
4244
  * Evaluates the given node and returns the result.
3471
4245
  *
@@ -3478,11 +4252,22 @@ const evaluate = (node, state) => {
3478
4252
  state.result.start();
3479
4253
  // Captured inside the `if (node)` block on purpose: callers reach the early
3480
4254
  // return above with a bare state that has no hooks to read. Do not hoist.
3481
- const mark = state.hasHooks ? state.hooks.depth(state) : 0;
4255
+ //
4256
+ // The mark is recorded on the state as well as held here, so that
4257
+ // `EvalHooks.exit` - called from a visitor, which has no route to this
4258
+ // local - can tell a node open in this walk from one open only in an
4259
+ // enclosing walk. Pushed under the same guard the mark is read under, and
4260
+ // the local `hooked` keeps the pair symmetric if a hook is registered
4261
+ // mid-walk.
4262
+ const hooked = state.hasHooks;
4263
+ const mark = hooked ? state.hooks.pushWalkBase(state) : 0;
4264
+ // Unguarded, unlike the walk base above: the iteration budget refills on
4265
+ // the outermost entry whether or not hooks are registered. See
4266
+ // `EvalState.walkDepth` on why these are two fields and not one.
4267
+ state.enterWalk();
3482
4268
  try {
3483
- const visitors = getDefaultVisitors();
3484
- walk.recursive(node, state, visitors);
3485
- const value = popVisitorResult(node, state);
4269
+ walk.recursive(node, state, {}, mergedVisitors());
4270
+ const value = completionValue(popVisitorResult(node, state));
3486
4271
  state.result.stop();
3487
4272
  state.result.setSuccess(value);
3488
4273
  return value;
@@ -3493,12 +4278,29 @@ const evaluate = (node, state) => {
3493
4278
  // walk left open. Unwinding to the mark rather than to the bottom is what
3494
4279
  // stops a nested evaluate - the arrow-function body runs on this same
3495
4280
  // state - from draining the enclosing walk's open nodes.
4281
+ // Reads `state.hasHooks` rather than the `hooked` local captured above,
4282
+ // and the difference is deliberate but narrow: if a hook was registered
4283
+ // *during* this walk then `hooked` is false, no base was pushed, `mark`
4284
+ // is 0, and this unwinds the whole stack - including an enclosing walk's
4285
+ // frames, which is the boundary crossing the walk base exists to stop.
4286
+ // Left as it was rather than tightened here, because narrowing it would
4287
+ // change what a mid-walk registration observes on an already-published
4288
+ // path, which is not this step's to decide.
3496
4289
  if (state.hasHooks) {
3497
4290
  state.hooks.unwindTo(mark, error, state);
3498
4291
  }
3499
4292
  state.result.setFailure(error);
3500
4293
  throw error;
3501
4294
  }
4295
+ finally {
4296
+ // Both in a `finally`: a walk that threw still has to restore the
4297
+ // enclosing walk's bound and depth, or every later evaluation on this
4298
+ // state carries this one's nesting.
4299
+ state.exitWalk();
4300
+ if (hooked) {
4301
+ state.hooks.popWalkBase(state);
4302
+ }
4303
+ }
3502
4304
  }
3503
4305
  return undefined;
3504
4306
  };
@@ -3567,11 +4369,27 @@ const evaluateAsync = async (ast, state) => {
3567
4369
  state.result.start();
3568
4370
  // Captured after the `!ast` early return above, for the same reason the sync
3569
4371
  // entry point captures inside its `if (node)` block. Do not hoist.
3570
- const mark = state.hasHooks ? state.hooks.depth(state) : 0;
4372
+ const hooked = state.hasHooks;
4373
+ const mark = hooked ? state.hooks.pushWalkBase(state) : 0;
4374
+ state.enterWalk();
3571
4375
  try {
3572
- const visitors = getDefaultVisitors();
3573
- walk.recursive(ast, state, visitors);
3574
- let value = popVisitorResult(ast, state);
4376
+ let value;
4377
+ // The walk bookkeeping is released here rather than in a `finally` on the
4378
+ // outer try, because the walk ends here: everything below this block is
4379
+ // promise resolution on an already-finished traversal. Holding the walk
4380
+ // base and the depth across the `await` would leave an independent
4381
+ // evaluation that interleaved on this state looking like a nested walk -
4382
+ // and § 3.4's budget refills only on the outermost entry.
4383
+ try {
4384
+ walk.recursive(ast, state, {}, mergedVisitors());
4385
+ value = completionValue(popVisitorResult(ast, state));
4386
+ }
4387
+ finally {
4388
+ state.exitWalk();
4389
+ if (hooked) {
4390
+ state.hooks.popWalkBase(state);
4391
+ }
4392
+ }
3575
4393
  // Enhanced promise handling - recursively await all promises
3576
4394
  try {
3577
4395
  value = await awaitAllPromises(value);
@@ -3665,145 +4483,408 @@ const arrowFunctionExpressionVisitor = (node, st, callback) => {
3665
4483
  beforeVisitor(node, st);
3666
4484
  const fn = (...arrowArgs) => {
3667
4485
  const newContext = evaluatePatterns(node.params, st, callback, arrowArgs);
4486
+ // The scope stack lives on EvalContext, not on the per-walk EvalState, and
4487
+ // one EvalContext can back any number of evaluations - so a scope this
4488
+ // closure fails to pop outlives the walk and is read first by every later
4489
+ // evaluation on the same context. The body is re-entrant `evaluate`, which
4490
+ // rethrows, so the pop needs `finally`.
4491
+ //
4492
+ // The `try` opens *after* the push, never around it. `push` is optionally
4493
+ // chained: bringing it inside would pair a `finally` pop with a push that
4494
+ // the same optional chain had skipped, and would swallow a throw from
4495
+ // evaluatePatterns into a pop as well.
3668
4496
  st.context?.push(newContext);
3669
- const value = evaluate(node.body, st);
3670
- st.context?.pop();
3671
- return value;
4497
+ try {
4498
+ return evaluate(node.body, st);
4499
+ }
4500
+ finally {
4501
+ st.context?.pop();
4502
+ }
3672
4503
  };
3673
4504
  pushVisitorResult(node, st, fn);
3674
4505
  afterVisitor(node, st);
3675
4506
  };
3676
4507
 
3677
- // based on evalArrowContext
3678
- // https://github.com/6utt3rfly/jse-eval/blob/main/index.ts
3679
- const evaluatePatterns = (patterns, st, callback, args) => {
3680
- let context = {};
3681
- patterns.map((pattern, i) => {
3682
- switch (pattern.type) {
3683
- case 'Identifier':
3684
- {
3685
- const object = evaluateIdentifier(pattern, st, args[i]);
3686
- context = { ...context, ...object };
3687
- }
3688
- break;
3689
- case 'MemberExpression':
3690
- {
3691
- const object = evaluateMemberExpression(pattern, st, callback, args[i]);
3692
- context = { ...context, ...object };
3693
- }
3694
- break;
3695
- case 'ObjectPattern':
3696
- {
3697
- const object = evaluateObjectPattern(pattern, st, callback, args[i]);
3698
- context = { ...context, ...object };
3699
- }
3700
- break;
3701
- case 'ArrayPattern':
3702
- {
3703
- const object = evaluateArrayPattern(pattern, st, callback, args[i]);
3704
- context = { ...context, ...object };
3705
- }
3706
- break;
3707
- case 'RestElement':
3708
- {
3709
- const object = evaluateRestElement(pattern, st, callback, args.slice(i));
3710
- context = { ...context, ...object };
3711
- }
3712
- break;
3713
- // case 'AssignmentPattern': {
3714
- // const object = evaluateAssignmentPattern(pattern, st, callback, args[i]);
3715
- // context = {...context, ...object};
3716
- // }
3717
- // break;
3718
- }
3719
- });
3720
- return context;
4508
+ /**
4509
+ * Walks one statement and returns its completion value.
4510
+ *
4511
+ * The statement dispatcher for the whole family, and the single place § 3.1's
4512
+ * rule 2 - one `popVisitorResult` per `callback` - is discharged for every
4513
+ * caller. Four visitors import it: `Program` and `BlockStatement` walk a
4514
+ * statement list, `IfStatement` a branch, and `ForStatement` an `init` and a
4515
+ * body.
4516
+ *
4517
+ * **It is explicit, and its `default` throws.** A node type this library does
4518
+ * not implement raises rather than falling through to `acorn-walk`'s base
4519
+ * walker, which would visit the subtree as an expression and strand whatever it
4520
+ * pushed - `while (false) { 1 }` used to evaluate to `1` that way. Three
4521
+ * visitors in this library already push nothing on one path of an `if`/`else if`
4522
+ * chain over node types (`docs/backlog.md` A2); a `switch` whose `default`
4523
+ * throws is how this family gains no fourth member.
4524
+ *
4525
+ * **Why this module exists.** It lived in `program.ts` for steps 1 to 5, on the
4526
+ * rule that a shared helper earns its own file at its *third* importer -
4527
+ * otherwise a visitor module has quietly become a utility module that also
4528
+ * happens to export a visitor. `if-statement.ts` met that condition in step 4,
4529
+ * which recorded it MET AND DEFERRED rather than unmet: no step's file list
4530
+ * admitted creating a module and rewriting three imports, and step 4 was not the
4531
+ * place to widen its own scope. The plan named step 6 as the date so that
4532
+ * `ForStatement` would not arrive in step 5 as a *fourth* importer against a
4533
+ * rule that had declined to fire twice. This is that move. The rejection surface
4534
+ * did not change with it - a pure relocation, gated by the existing suite.
4535
+ *
4536
+ * @returns the statement's completion value, which is `EMPTY_COMPLETION`
4537
+ * (`../classes/eval`) for a statement that produced nothing. The sentinel is not
4538
+ * imported here: this module never compares against it, and an import kept only
4539
+ * for a doc link is an unused binding the lint config rejects.
4540
+ */
4541
+ const dispatchStatement = (statement, st, callback) => {
4542
+ switch (statement.type) {
4543
+ // `VariableDeclaration` covers `var` as well, and cannot not: this `switch`
4544
+ // reads the node *type*, and `var x = 1` is a `VariableDeclaration` exactly
4545
+ // as `let x = 1` is. Listing it here is therefore what stopped `var`
4546
+ // reaching the `default:` below; the rejection moved into the visitor,
4547
+ // which can read `kind`.
4548
+ //
4549
+ // `ForStatement` is the classic three-part form *only*. `ForOfStatement`,
4550
+ // `ForInStatement`, `WhileStatement` and `DoWhileStatement` are distinct
4551
+ // node types and stay out of the phase (§ 2), so they reach the `default`
4552
+ // below unchanged - unlike `var`, which shares a type with `let` and had to
4553
+ // be rejected one level down.
4554
+ case 'ExpressionStatement':
4555
+ case 'EmptyStatement':
4556
+ case 'BlockStatement':
4557
+ case 'VariableDeclaration':
4558
+ case 'IfStatement':
4559
+ case 'ForStatement':
4560
+ callback(statement, st);
4561
+ return popVisitorResult(statement, st);
4562
+ default:
4563
+ throw new Error(`Unsupported statement type: ${statement.type}`);
4564
+ }
3721
4565
  };
3722
- const evaluatePattern = (pattern, st, callback, arg) => {
3723
- switch (pattern.type) {
3724
- case 'Identifier':
3725
- return evaluateIdentifier(pattern, st, arg);
3726
- case 'MemberExpression':
3727
- return evaluateMemberExpression(pattern, st, callback, arg);
3728
- case 'ObjectPattern':
3729
- return evaluateObjectPattern(pattern, st, callback, arg);
3730
- case 'ArrayPattern':
3731
- return evaluateArrayPattern(pattern, st, callback, arg);
3732
- case 'RestElement':
3733
- return evaluateRestElement(pattern, st, callback, arg);
3734
- // case 'AssignmentPattern':
3735
- // return evaluateAssignmentPattern(pattern, st, callback, arg);
4566
+
4567
+ /**
4568
+ * Evaluates a program: the root node of every walk that reaches this library
4569
+ * through `EvalService`, since its parser options leave `extractExpressions`
4570
+ * off and so hand `evaluate` the whole `Program`.
4571
+ *
4572
+ * Keeps the last **non-empty** completion value, per JavaScript's
4573
+ * completion-value semantics, and pushes exactly one value however many
4574
+ * statements the body holds. A program whose statements all produced nothing -
4575
+ * `;`, or a source that is only whitespace - pushes {@link EMPTY_COMPLETION},
4576
+ * which the walk boundary in `evaluate` converts to `undefined`. The conversion
4577
+ * is deliberately not done here: `arrow-function-expression.ts` calls
4578
+ * `evaluate` on a `BlockStatement` for a block-bodied arrow, so a `Program`-side
4579
+ * conversion would leave that entry point handing the sentinel to a consumer.
4580
+ *
4581
+ * **The program-level scope is required.** It is the only scope a top-level
4582
+ * `let` can bind into; without it a declaration would have nowhere to go but
4583
+ * `EvalContext.set`, which writes the caller's own context object - and is the
4584
+ * method `eval-signals` overrides to enforce its read-only policy. `get`
4585
+ * searches `scopes` first and falls through on a miss, so an empty program
4586
+ * scope costs no outer resolution.
4587
+ *
4588
+ * The pop is in a `finally` because the scope stack lives on `EvalContext`, not
4589
+ * on the per-walk `EvalState`, and one context can back any number of
4590
+ * evaluations: a scope this visitor failed to pop would outlive the walk and be
4591
+ * read first by every later evaluation on that context. The `try` opens *after*
4592
+ * the push, never around it - `push` is optionally chained, so bringing it
4593
+ * inside would pair a `finally` pop with a push the same optional chain had
4594
+ * skipped.
4595
+ */
4596
+ const programVisitor = (node, st, callback) => {
4597
+ beforeVisitor(node, st);
4598
+ let completion = EMPTY_COMPLETION;
4599
+ st.context?.push({}, st.options);
4600
+ try {
4601
+ for (const statement of node.body) {
4602
+ const value = dispatchStatement(statement, st, callback);
4603
+ if (value !== EMPTY_COMPLETION) {
4604
+ completion = value;
4605
+ }
4606
+ }
3736
4607
  }
3737
- return {};
4608
+ finally {
4609
+ st.context?.pop();
4610
+ }
4611
+ pushVisitorResult(node, st, completion);
4612
+ afterVisitor(node, st);
3738
4613
  };
3739
- const evaluateIdentifier = (pattern, st, arg) => {
3740
- const object = {};
3741
- object[pattern.name] = arg;
3742
- return object;
4614
+
4615
+ /**
4616
+ * Evaluates an expression statement: its completion value is its expression's.
4617
+ *
4618
+ * A pass-through, and registered rather than left to `acorn-walk`'s base walker
4619
+ * for two reasons. The base walker fires no hooks, so a statement would be
4620
+ * invisible to a consumer watching the walk; and § 3.1's rule that every
4621
+ * statement visitor pushes exactly one value would have an exception whose only
4622
+ * justification is that this one happens to be cheap.
4623
+ */
4624
+ const expressionStatementVisitor = (node, st, callback) => {
4625
+ beforeVisitor(node, st);
4626
+ callback(node.expression, st);
4627
+ const value = popVisitorResult(node, st);
4628
+ pushVisitorResult(node, st, value);
4629
+ afterVisitor(node, st);
3743
4630
  };
3744
- const evaluateMemberExpression = (pattern, st, callback, arg) => {
3745
- if (pattern.type === 'MemberExpression') {
3746
- console.log(pattern, st, callback, arg);
3747
- throw new Error('evaluateMemberExpression is not implemented.');
3748
- }
3749
- return {};
4631
+
4632
+ /**
4633
+ * Evaluates an empty statement: it produces nothing, so it pushes
4634
+ * {@link EMPTY_COMPLETION} and an enclosing statement list keeps whatever
4635
+ * preceded it.
4636
+ *
4637
+ * One line of behaviour, and it exists because the statement dispatcher's
4638
+ * `default` throws: without it `a;;b` and `if (x) ;` would start raising
4639
+ * "unsupported statement type", which is a divergence from JavaScript nobody
4640
+ * chose.
4641
+ */
4642
+ const emptyStatementVisitor = (node, st) => {
4643
+ beforeVisitor(node, st);
4644
+ pushVisitorResult(node, st, EMPTY_COMPLETION);
4645
+ afterVisitor(node, st);
3750
4646
  };
3751
- const evaluateObjectPattern = (pattern, st, callback, arg) => {
3752
- let context = {};
3753
- pattern.properties.map((pattern) => {
3754
- switch (pattern.type) {
3755
- case 'Property':
3756
- {
3757
- let key;
3758
- if (pattern.key.type === 'Identifier') {
3759
- key = pattern.key.name;
3760
- }
3761
- else if (pattern.key.type === 'Literal') {
3762
- key = pattern.key.value;
3763
- }
3764
- else {
3765
- callback(pattern.key, st);
3766
- key = popVisitorResult(pattern, st);
3767
- if (typeof key !== 'string' && typeof key !== 'number')
3768
- throw new Error(`Unsupported property key type: ${pattern.key.type}`);
3769
- }
3770
- const ctx = arg;
3771
- st.context?.push(ctx);
3772
- callback(pattern.value, st);
3773
- const value = popVisitorResult(pattern, st);
3774
- st.context?.pop();
3775
- const pair = {};
3776
- pair[key] = value;
3777
- context = { ...context, ...pair };
3778
- }
3779
- break;
3780
- case 'RestElement':
3781
- {
3782
- const object = evaluateRestElement(pattern, st, callback, arg);
3783
- context = { ...context, ...object };
3784
- }
3785
- break;
4647
+
4648
+ /**
4649
+ * Evaluates a block statement: a scope, a statement list, and one completion
4650
+ * value.
4651
+ *
4652
+ * Keeps the last **non-empty** completion value, per JavaScript's
4653
+ * completion-value semantics, and pushes exactly one value however many
4654
+ * statements the body holds. A block whose statements all produced nothing -
4655
+ * `{ }`, or `{ ; }` - pushes {@link EMPTY_COMPLETION} for its enclosing
4656
+ * statement list to skip over. The sentinel is converted to `undefined` at the
4657
+ * walk boundary in `evaluate`, which is why this visitor may return it to a
4658
+ * caller that is itself a walk root: `arrow-function-expression.ts` calls
4659
+ * `evaluate` on this node for a block-bodied arrow, so `x => { }` reaches a
4660
+ * consumer through the same conversion a `Program` does.
4661
+ *
4662
+ * **The block scope is unobservable in this step, and is pushed anyway.**
4663
+ * Nothing binds into it until `VariableDeclaration` lands, and an empty scope
4664
+ * shadows nothing now that `EvalContext.get` resolves a scope by presence
4665
+ * rather than by value. Pushing it here rather than with the first binding
4666
+ * keeps the scope arithmetic in one place: the depth a nested block reports is
4667
+ * a property of the block, not of whether its body happened to declare
4668
+ * anything.
4669
+ *
4670
+ * `st.options` is passed to `push` because `fromContext` copies a plain record
4671
+ * into a `Registry` when `caseInsensitive` is set. Omitting them would make a
4672
+ * block's bindings case-**sensitive** inside an otherwise case-insensitive
4673
+ * evaluation - a silent wrong answer rather than an error, and one no assertion
4674
+ * in this step can reach, since a scope nothing binds into resolves nothing
4675
+ * either way.
4676
+ *
4677
+ * The pop is in a `finally` because the scope stack lives on `EvalContext`, not
4678
+ * on the per-walk `EvalState`, and one context can back any number of
4679
+ * evaluations: a scope this visitor failed to pop would outlive the walk and be
4680
+ * read first by every later evaluation on that context. The `try` opens *after*
4681
+ * the push, never around it - `push` is optionally chained, so bringing it
4682
+ * inside would pair a `finally` pop with a push the same optional chain had
4683
+ * skipped.
4684
+ */
4685
+ const blockStatementVisitor = (node, st, callback) => {
4686
+ beforeVisitor(node, st);
4687
+ let completion = EMPTY_COMPLETION;
4688
+ st.context?.push({}, st.options);
4689
+ try {
4690
+ for (const statement of node.body) {
4691
+ const value = dispatchStatement(statement, st, callback);
4692
+ if (value !== EMPTY_COMPLETION) {
4693
+ completion = value;
4694
+ }
3786
4695
  }
3787
- });
3788
- return context;
4696
+ }
4697
+ finally {
4698
+ st.context?.pop();
4699
+ }
4700
+ pushVisitorResult(node, st, completion);
4701
+ afterVisitor(node, st);
3789
4702
  };
3790
- const evaluateArrayPattern = (pattern, st, callback, args) => {
3791
- const patterns = pattern.elements.filter(s => !!s);
3792
- const object = evaluatePatterns(patterns, st, callback, args);
3793
- return object;
4703
+
4704
+ /**
4705
+ * Evaluates an `if` statement: one test, and **exactly one branch or neither**.
4706
+ *
4707
+ * The behavioural fix in the plan's § 1.1 table. `acorn-walk`'s base walker
4708
+ * visits both branches regardless of the test, so `if (a) { 1 } else { 2 }` with
4709
+ * `a` true measured `2` - the `else` value was pushed last and won - and any
4710
+ * call or assignment in the untaken branch had already run. The value was the
4711
+ * smaller half of that: a visitor that walked both branches and then *selected*
4712
+ * by the test would return `1` and still run them both, which is why the specs
4713
+ * assert on an uncalled `jest.fn` and an unwritten source key beside the value.
4714
+ *
4715
+ * Completion value, per § 3.1: the branch's own, unchanged. A taken branch that
4716
+ * produced nothing propagates {@link EMPTY_COMPLETION} - `if (true) { }` pushes
4717
+ * the sentinel exactly as `if (false) { 1 }` does, by two different routes - and
4718
+ * a branch that genuinely produced `undefined` pushes that, so an enclosing
4719
+ * statement list keeps it over an earlier value. Mapping either onto the other
4720
+ * here would collapse the distinction the sentinel exists for.
4721
+ *
4722
+ * Arithmetic: pops 1 for the test, plus 1 for the branch when one runs; pushes
4723
+ * exactly 1 on both exit paths.
4724
+ *
4725
+ * **The branches go through `dispatchStatement`, not a raw `callback`.** A
4726
+ * branch is a `Statement`, and a raw callback would hand a type this library
4727
+ * does not implement to the base walker, which walks it as an expression and
4728
+ * strands whatever it pushed. That is the silent fall-through family § 1.7
4729
+ * names and § 3.1 promises to add no member to.
4730
+ *
4731
+ * **The margin is narrower than it first looks, and the specs say so where an
4732
+ * earlier draft of this docblock did not.** Every registered statement type -
4733
+ * `BlockStatement`, `ExpressionStatement`, `IfStatement` itself for an
4734
+ * `else if` chain, `VariableDeclaration` - is reached by a raw `callback` just
4735
+ * as well, because `acorn-walk` finds the registered visitor before it reaches
4736
+ * its base walker. So neither `if (a) { while (false) { 1 } }` nor an `else if`
4737
+ * chain discriminates: the block re-dispatches, and the chain arrives back here
4738
+ * either way. The one position that does is a **bare** branch body of an
4739
+ * unregistered type - `if (a) function f() { }` - where nothing stands between
4740
+ * this visitor and the base walker. Measured: swapping in a raw callback reddens
4741
+ * that case alone.
4742
+ *
4743
+ * It is still the right call, for the reason `dispatch-statement.ts` gives rather
4744
+ * than for a reason the suite can show: rule 2's single `callback`/`pop` pair
4745
+ * lives in one place, so the guarantee holds for whatever bare statement type a
4746
+ * later phase registers without this visitor being revisited.
4747
+ *
4748
+ * This visitor was `dispatchStatement`'s **third** importer, which is the
4749
+ * condition for giving it a module of its own. **Step 6 made that move**: the
4750
+ * dispatcher now lives in `dispatch-statement.ts`, with the rule and its history
4751
+ * in that module's docblock.
4752
+ *
4753
+ * **It pushes no scope, and there is no `try`/`finally` to pair.** Four routes a
4754
+ * binding could arrive by, all closed: a block body gets its scope from
4755
+ * `blockStatementVisitor`; `if (a) let x = 1` does not parse, since a lexical
4756
+ * declaration is not a legal bare statement body; `if (a) var x = 1` does parse,
4757
+ * reaches the dispatcher as a `VariableDeclaration`, and is rejected on `kind`
4758
+ * inside `variableDeclarationVisitor`; and `if (a) function f() { }` parses
4759
+ * under Annex B and is rejected by `dispatchStatement`'s throwing `default`.
4760
+ *
4761
+ * **The fourth is closed by the dispatcher and not by anything here**, which is
4762
+ * the one a later phase can reopen: a phase that registers `FunctionDeclaration`
4763
+ * gives this visitor a bare binding form with no enclosing block, and the
4764
+ * no-scope argument has to be re-made rather than inherited. `if (a) label: var
4765
+ * x = 1` is the same family. As of this step this visitor touches `EvalContext`
4766
+ * not at all, and the balance its specs assert on a reused context is the
4767
+ * enclosing visitors' to keep.
4768
+ */
4769
+ const ifStatementVisitor = (node, st, callback) => {
4770
+ beforeVisitor(node, st);
4771
+ callback(node.test, st);
4772
+ const test = popVisitorResult(node, st);
4773
+ let completion = EMPTY_COMPLETION;
4774
+ if (test) {
4775
+ completion = dispatchStatement(node.consequent, st, callback);
4776
+ }
4777
+ else if (node.alternate) {
4778
+ completion = dispatchStatement(node.alternate, st, callback);
4779
+ }
4780
+ pushVisitorResult(node, st, completion);
4781
+ afterVisitor(node, st);
3794
4782
  };
3795
- const evaluateRestElement = (pattern, st, callback, args) => {
3796
- const argument = pattern.argument;
3797
- const object = evaluatePattern(argument, st, callback, args);
3798
- return object;
4783
+
4784
+ /**
4785
+ * Evaluates a classic three-part `for` statement.
4786
+ *
4787
+ * § 1.1's row measured **`NaN`** with three stranded values before Phase 2: the
4788
+ * base walker handed the declarator's `id` to `identifierVisitor`, so `i`
4789
+ * resolved against the context rather than binding, and `i < 3` compared
4790
+ * `undefined`. Since step 1 the row throws from `dispatchStatement`'s `default`;
4791
+ * this visitor is what returns `2`.
4792
+ *
4793
+ * `for…of`, `for…in`, `while` and `do…while` stay out of the phase (§ 2) and
4794
+ * keep throwing - they are separate node types and reach the dispatcher's
4795
+ * `default` unchanged.
4796
+ *
4797
+ * **One scope for the loop, not one per iteration.** A draft of the plan
4798
+ * specified a fresh scope per iteration, seeded from the head and copied back
4799
+ * after `update`, on the reasoning that this is what makes a closure capture its
4800
+ * own iteration's binding. It makes **no observable difference here**: the
4801
+ * closure `arrow-function-expression.ts` builds captures `st`, not a scope
4802
+ * chain, and resolves its free variables against `st.context` *as it is when the
4803
+ * closure is called* - by which time this loop has popped everything it pushed.
4804
+ * So the per-iteration design would have allocated a scope and copied bindings
4805
+ * twice per iteration to buy a property no spec can assert (§ 3.6.5). Giving
4806
+ * closures a captured scope chain is real work in
4807
+ * `arrow-function-expression.ts` and is what a later phase would have to do
4808
+ * first.
4809
+ *
4810
+ * **`init` has two node shapes and they take two routes.** `for (let i = 0; …)`
4811
+ * parses `init` as a `VariableDeclaration`, which is a `Statement` and goes
4812
+ * through `dispatchStatement`; `for (i = 0; …)` parses it as an `Expression` and
4813
+ * takes a raw `callback`. Both pop exactly one - the declaration's `EMPTY`, or
4814
+ * the expression's value - so § 3.1's arithmetic is identical for the two and
4815
+ * the split is invisible to it. What depends on the split is the throwing
4816
+ * `default`: only the `dispatchStatement` route has one, so an `init` that is a
4817
+ * statement type this library does not implement is rejected rather than handed
4818
+ * to the base walker. `body` is a `Statement` and dispatches for the same
4819
+ * reason; `test` and `update` are expressions and do not.
4820
+ *
4821
+ * Arithmetic (§ 3.1): pops 1 for `init` when present, then per iteration 1 for
4822
+ * `test` (when present), 1 for `body` and 1 for `update` (when present) - one
4823
+ * per `callback` or `dispatchStatement`, as rule 2 requires. Pushes exactly one
4824
+ * value on every exit path: the last **non-empty** body value, or
4825
+ * {@link EMPTY_COMPLETION} when the loop ran zero iterations or every iteration
4826
+ * produced nothing. An absent `test` is `true`.
4827
+ *
4828
+ * **The budget is the only terminator for `for (;;)`** - with no `break`,
4829
+ * `continue` or `return` in this phase (§ 2) there is no other way out, and a
4830
+ * runaway loop that silently returned a partial value is the failure § 3.4
4831
+ * exists to prevent. `chargeIteration` throws when the budget is spent; it is
4832
+ * called from this loop and nowhere else in the library, which is why an
4833
+ * expression with no `for` in it pays nothing for the bound.
4834
+ *
4835
+ * The pop is in a `finally` because the scope stack lives on `EvalContext`, not
4836
+ * on the per-walk `EvalState`, and one context can back any number of
4837
+ * evaluations: a scope this visitor failed to pop would outlive the walk and be
4838
+ * read first by every later evaluation on that context. This is the visitor with
4839
+ * the **highest push multiplicity** in the family and the shape of A9's own
4840
+ * precondition argument - a `for` body throwing on iteration 3 - so every exit
4841
+ * path matters: `init`, `test`, `body` and `update` can each throw, the
4842
+ * dispatcher can reject the body, and the budget can end the loop from inside
4843
+ * the `try`. The `try` opens *after* the push, never around it - `push` is
4844
+ * optionally chained, so bringing it inside would pair a `finally` pop with a
4845
+ * push the same optional chain had skipped.
4846
+ */
4847
+ const forStatementVisitor = (node, st, callback) => {
4848
+ beforeVisitor(node, st);
4849
+ let completion = EMPTY_COMPLETION;
4850
+ st.context?.push({}, st.options);
4851
+ try {
4852
+ if (node.init) {
4853
+ if (node.init.type === 'VariableDeclaration') {
4854
+ dispatchStatement(node.init, st, callback);
4855
+ }
4856
+ else {
4857
+ callback(node.init, st);
4858
+ popVisitorResult(node, st);
4859
+ }
4860
+ }
4861
+ for (;;) {
4862
+ if (node.test) {
4863
+ callback(node.test, st);
4864
+ if (!popVisitorResult(node, st)) {
4865
+ break;
4866
+ }
4867
+ }
4868
+ // Charged once the test has admitted the iteration, so a loop that runs
4869
+ // `n` bodies charges `n` - which is what `iterationsRemaining` is asserted
4870
+ // against - and a loop whose test is false at the top charges nothing.
4871
+ st.chargeIteration();
4872
+ const value = dispatchStatement(node.body, st, callback);
4873
+ if (value !== EMPTY_COMPLETION) {
4874
+ completion = value;
4875
+ }
4876
+ if (node.update) {
4877
+ callback(node.update, st);
4878
+ popVisitorResult(node, st);
4879
+ }
4880
+ }
4881
+ }
4882
+ finally {
4883
+ st.context?.pop();
4884
+ }
4885
+ pushVisitorResult(node, st, completion);
4886
+ afterVisitor(node, st);
3799
4887
  };
3800
- // const evaluateAssignmentPattern = (pattern: AssignmentPattern, st: EvalState, callback: walk.WalkerCallback<EvalState>, args: unknown) => {
3801
- // const left = evaluatePattern(pattern.left, st, callback, args);
3802
- // callback(pattern.right, st);
3803
- // const value = popVisitorResult(pattern, st);
3804
- // const object = {...left};
3805
- // return object;
3806
- // }
3807
4888
 
3808
4889
  const defaultEvalScopeOptions = {
3809
4890
  global: false,
@@ -4726,5 +5807,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.8", ngImpor
4726
5807
  * Generated bundle index. Do not edit.
4727
5808
  */
4728
5809
 
4729
- export { ASYNC_HOOK_MESSAGE, BaseRegistry, Cache, CaseInsensitiveRegistry, CompilerService, DiscoveryService, EvalContext, EvalHooks, EvalResult, EvalScope, EvalService, EvalState, EvalTrace, ParserService, Queue, RecursiveVisitorResultType, Registry, Stack, call, callAsync, compile, compileAsync, createDependencyTracker, createTimingHook, defaultParserOptions, evaluate, evaluateAsync, extract, extractExpression, fromContext, getContextKey, getContextValue, isRegistryContext, parse };
5810
+ export { ASYNC_HOOK_MESSAGE, BaseRegistry, Cache, CaseInsensitiveRegistry, CompilerService, DiscoveryService, EMPTY_COMPLETION, EvalContext, EvalHooks, EvalResult, EvalScope, EvalService, EvalState, EvalTrace, ParserService, Queue, RecursiveVisitorResultType, Registry, Stack, call, callAsync, compile, compileAsync, createDependencyTracker, createTimingHook, defaultParserOptions, evaluate, evaluateAsync, extract, extractExpression, fromContext, getContextKey, getContextValue, isRegistryContext, parse };
4730
5811
  //# sourceMappingURL=zvenigora-ng-eval-core.mjs.map