@zvenigora/ng-eval-core 0.3.0 → 0.5.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/README.md +145 -9
- package/fesm2022/zvenigora-ng-eval-core.mjs +1290 -157
- package/fesm2022/zvenigora-ng-eval-core.mjs.map +1 -1
- package/package.json +1 -1
- package/types/zvenigora-ng-eval-core.d.ts +331 -8
|
@@ -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
|
-
|
|
912
|
-
|
|
913
|
-
|
|
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`
|
|
945
|
-
*
|
|
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
|
-
|
|
954
|
-
|
|
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
|
|
965
|
-
* company with {@link getFromScopes}
|
|
966
|
-
*
|
|
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
|
-
|
|
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
|
-
|
|
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 <
|
|
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 ??=
|
|
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
|
|
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,426 @@ 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
|
+
/**
|
|
3829
|
+
* The keys an object pattern has already consumed, in source-key terms.
|
|
3830
|
+
*
|
|
3831
|
+
* A rest element binds *the remainder*, so it needs the names the sibling
|
|
3832
|
+
* properties took - and it needs them as they appear on the **source**, which
|
|
3833
|
+
* is `Property.key`, not the name each one bound. For `{ a: x, ...r }` the key
|
|
3834
|
+
* removed from `r` is `a`; `x` was never a source key and removing it would
|
|
3835
|
+
* take the wrong property when the source happens to carry that name too.
|
|
3836
|
+
*/
|
|
3837
|
+
const restOf = (source, taken) => {
|
|
3838
|
+
const object = {};
|
|
3839
|
+
if (!source || typeof source !== 'object') {
|
|
3840
|
+
return object;
|
|
3841
|
+
}
|
|
3842
|
+
const consumed = new Set(taken.map(key => String(key)));
|
|
3843
|
+
for (const key of Object.keys(source)) {
|
|
3844
|
+
if (!consumed.has(key)) {
|
|
3845
|
+
safeSetProperty(object, key, source[key]);
|
|
3846
|
+
}
|
|
3847
|
+
}
|
|
3848
|
+
return object;
|
|
3849
|
+
};
|
|
3850
|
+
const evaluateObjectPattern = (pattern, st, callback, arg) => {
|
|
3851
|
+
let context = {};
|
|
3852
|
+
const taken = [];
|
|
3853
|
+
pattern.properties.map((pattern) => {
|
|
3854
|
+
switch (pattern.type) {
|
|
3855
|
+
case 'Property':
|
|
3856
|
+
{
|
|
3857
|
+
let key;
|
|
3858
|
+
// `computed` is tested first, and that is the whole of a third
|
|
3859
|
+
// defect. `{ [keyName]: q }` parses as `key` an **Identifier** named
|
|
3860
|
+
// `keyName`, so an `Identifier`-first chain took the name it is
|
|
3861
|
+
// spelled with and read `src.keyName` instead of evaluating it and
|
|
3862
|
+
// reading `src[keyName]`. The literal computed form `{ ["a"]: q }`
|
|
3863
|
+
// hid it the way shorthand hid A11 - a `Literal`'s value *is* its
|
|
3864
|
+
// key, so taking the wrong branch landed on the right answer. See
|
|
3865
|
+
// `docs/backlog.md` A14.
|
|
3866
|
+
if (!pattern.computed && pattern.key.type === 'Identifier') {
|
|
3867
|
+
key = pattern.key.name;
|
|
3868
|
+
}
|
|
3869
|
+
else if (!pattern.computed && pattern.key.type === 'Literal') {
|
|
3870
|
+
key = pattern.key.value;
|
|
3871
|
+
}
|
|
3872
|
+
else {
|
|
3873
|
+
// Walked **before** the source property is read, and deliberately:
|
|
3874
|
+
// a computed key is an expression of the *enclosing* scope, not of
|
|
3875
|
+
// the object being destructured. `let { [keyName]: v } = src`
|
|
3876
|
+
// resolves `keyName` where the declaration is written, exactly as
|
|
3877
|
+
// JavaScript does. This is the only `callback` left in the module,
|
|
3878
|
+
// and nothing pushes the source as a scope any more, so there is no
|
|
3879
|
+
// arrangement in which it could resolve against the source.
|
|
3880
|
+
callback(pattern.key, st);
|
|
3881
|
+
key = popVisitorResult(pattern, st);
|
|
3882
|
+
if (typeof key !== 'string' && typeof key !== 'number')
|
|
3883
|
+
throw new Error(`Unsupported property key type: ${pattern.key.type}`);
|
|
3884
|
+
}
|
|
3885
|
+
// **Where `let { a = 1 } = o` actually lands**, which is not where it
|
|
3886
|
+
// was expected to. A default in an object pattern is parsed as
|
|
3887
|
+
// `Property.value` of type `AssignmentPattern`, and this branch is
|
|
3888
|
+
// the only thing that sees it: the recursion below would hand it to
|
|
3889
|
+
// `evaluatePattern`, whose `AssignmentPattern` case is commented out,
|
|
3890
|
+
// so it would reach that function's `default` and be rejected with
|
|
3891
|
+
// the same message one frame further down. Kept here so the rejection
|
|
3892
|
+
// is attributable to the object form, and because it predates the
|
|
3893
|
+
// recursion - before it, nothing reached either `switch` at all and
|
|
3894
|
+
// the form bound silently. The array form (`let [a = 1] = arr`) and
|
|
3895
|
+
// the parameter form (`(a = 1) => a`) go through `evaluatePatterns`
|
|
3896
|
+
// and are covered there.
|
|
3897
|
+
if (pattern.value.type === 'AssignmentPattern') {
|
|
3898
|
+
unsupportedBindingTarget(pattern.value.type);
|
|
3899
|
+
}
|
|
3900
|
+
taken.push(key);
|
|
3901
|
+
// Guarded on the way *in*, which is where the blocklist has to sit
|
|
3902
|
+
// now that the value is a binding target rather than an expression.
|
|
3903
|
+
// `let { __proto__: p } = o` and `let { constructor: { x } } = o`
|
|
3904
|
+
// both stop here, and the nested form is why the read is guarded and
|
|
3905
|
+
// not only the binding name below: a plain read would hand `Function`
|
|
3906
|
+
// to the recursion, and `evaluateIdentifier`'s guard would then be
|
|
3907
|
+
// inspecting the *inner* pattern's names, by which point the escape
|
|
3908
|
+
// has happened.
|
|
3909
|
+
//
|
|
3910
|
+
// Tested explicitly rather than left to `safeGetProperty`, which
|
|
3911
|
+
// returns early for a non-object target **before** it checks the key
|
|
3912
|
+
// - so `(({ valueOf: v }) => v)(o)` with `o` unbound would read
|
|
3913
|
+
// `undefined` and bind quietly. The blocklist applies to the source
|
|
3914
|
+
// key whatever the source turns out to be, which is the net the
|
|
3915
|
+
// declaration and arrow-parameter binders already cast.
|
|
3916
|
+
if (isDangerousProperty(key)) {
|
|
3917
|
+
throw new Error(`Access to dangerous property "${String(key)}" is blocked for security reasons`);
|
|
3918
|
+
}
|
|
3919
|
+
const value = safeGetProperty(arg, key);
|
|
3920
|
+
// The binding target, which may be a name, another object pattern,
|
|
3921
|
+
// or an array pattern. Recursion is the whole repair: `Property.value`
|
|
3922
|
+
// is a *pattern* and is bound against the source property, where it
|
|
3923
|
+
// used to be walked as an **expression** against the source object -
|
|
3924
|
+
// which resolved the wrong name and bound the wrong one. See
|
|
3925
|
+
// `docs/backlog.md` A11.
|
|
3926
|
+
const bound = evaluatePattern(pattern.value, st, callback, value);
|
|
3927
|
+
context = { ...context, ...bound };
|
|
3928
|
+
}
|
|
3929
|
+
break;
|
|
3930
|
+
case 'RestElement':
|
|
3931
|
+
{
|
|
3932
|
+
// The remainder, not the whole source. Acorn requires the rest
|
|
3933
|
+
// element last in an object pattern, so `taken` is complete here.
|
|
3934
|
+
// Binding the whole argument left an already-destructured key on the
|
|
3935
|
+
// rest record - `docs/backlog.md` A13.
|
|
3936
|
+
const object = evaluateRestElement(pattern, st, callback, restOf(arg, taken));
|
|
3937
|
+
context = { ...context, ...object };
|
|
3938
|
+
}
|
|
3939
|
+
break;
|
|
3940
|
+
}
|
|
3941
|
+
});
|
|
3942
|
+
return context;
|
|
3943
|
+
};
|
|
3944
|
+
const evaluateArrayPattern = (pattern, st, callback, args) => {
|
|
3945
|
+
const patterns = pattern.elements.filter(s => !!s);
|
|
3946
|
+
const object = evaluatePatterns(patterns, st, callback, args);
|
|
3947
|
+
return object;
|
|
3948
|
+
};
|
|
3949
|
+
const evaluateRestElement = (pattern, st, callback, args) => {
|
|
3950
|
+
const argument = pattern.argument;
|
|
3951
|
+
const object = evaluatePattern(argument, st, callback, args);
|
|
3952
|
+
return object;
|
|
3953
|
+
};
|
|
3954
|
+
// const evaluateAssignmentPattern = (pattern: AssignmentPattern, st: EvalState, callback: walk.WalkerCallback<EvalState>, args: unknown) => {
|
|
3955
|
+
// const left = evaluatePattern(pattern.left, st, callback, args);
|
|
3956
|
+
// callback(pattern.right, st);
|
|
3957
|
+
// const value = popVisitorResult(pattern, st);
|
|
3958
|
+
// const object = {...left};
|
|
3959
|
+
// return object;
|
|
3960
|
+
// }
|
|
3961
|
+
|
|
3962
|
+
/**
|
|
3963
|
+
* The scope a declaration binds into: the innermost one on the stack.
|
|
3964
|
+
*
|
|
3965
|
+
* Read back from the stack rather than kept as a reference by whoever pushed
|
|
3966
|
+
* it, and that is the load-bearing half. `EvalContext.push` routes through
|
|
3967
|
+
* `fromContext`, which **copies** a plain record into a `Registry` when
|
|
3968
|
+
* `caseInsensitive` is set - so the object a visitor handed to `push` is not
|
|
3969
|
+
* always the object on the stack, and a binding written through the pre-push
|
|
3970
|
+
* record would be written into something nothing ever reads. It is also the
|
|
3971
|
+
* object `EvalState.declareConst` keys on, so both sides have to agree about
|
|
3972
|
+
* which one it is.
|
|
3973
|
+
*
|
|
3974
|
+
* Every route into a declaration pushes one first - `Program` for the top level,
|
|
3975
|
+
* `BlockStatement` for a block - so the absent case means the caller walked a
|
|
3976
|
+
* bare declaration node. Throwing is the answer rather than falling back to
|
|
3977
|
+
* `EvalContext.set`, which would write the caller's own context object: a `let`
|
|
3978
|
+
* that mutates the consumer's data is the behaviour this step exists to remove,
|
|
3979
|
+
* and doing it on an unsupported entry path would be the one place it survived.
|
|
3980
|
+
*/
|
|
3981
|
+
const bindingScope = (st) => {
|
|
3982
|
+
const scope = st.context && st.context.scopes.length > 0
|
|
3983
|
+
? st.context.scopes.peek()
|
|
3984
|
+
: undefined;
|
|
3985
|
+
if (!scope) {
|
|
3986
|
+
throw new Error('A variable declaration requires an enclosing scope.');
|
|
3987
|
+
}
|
|
3988
|
+
return scope;
|
|
3989
|
+
};
|
|
3990
|
+
/**
|
|
3991
|
+
* Binds one declarator's names into `scope`.
|
|
3992
|
+
*
|
|
3993
|
+
* The names come from `evaluatePattern`, which is the binder arrow-function
|
|
3994
|
+
* parameters already use - `Identifier` for the plain form, and the
|
|
3995
|
+
* `ObjectPattern` / `ArrayPattern` / `RestElement` forms for the destructuring
|
|
3996
|
+
* ones. Reusing it is what makes `let [p, q] = arr` work without a second
|
|
3997
|
+
* pattern implementation, and what makes a form it does not implement throw
|
|
3998
|
+
* (`AssignmentPattern`, i.e. `let { a = 1 } = o`) rather than bind nothing.
|
|
3999
|
+
*
|
|
4000
|
+
* The keys are re-checked against the pollution blocklist even though
|
|
4001
|
+
* `evaluatePattern` already wrote them through `safeSetProperty`. One line for
|
|
4002
|
+
* a guard that cannot be reasoned away from this call site: the record arrives
|
|
4003
|
+
* as a `BaseContext`, and the binder's own coverage of it is a property of
|
|
4004
|
+
* `pattern.ts` rather than of this module's contract with it.
|
|
4005
|
+
*
|
|
4006
|
+
* The write itself dispatches through `setContextValue`, not through
|
|
4007
|
+
* `safeSetProperty`. `safeSetProperty` finishes with `Object.defineProperty`,
|
|
4008
|
+
* which suits the plain records `pattern.ts` builds and **not** a scope: a
|
|
4009
|
+
* `caseInsensitive` scope is a Map-backed `Registry`, and defining a property
|
|
4010
|
+
* on the instance inserts nothing into its map. The binding would be written
|
|
4011
|
+
* and then not found, silently, for that option only.
|
|
4012
|
+
*/
|
|
4013
|
+
const bindDeclarator = (declarator, value, kind, scope, st, callback) => {
|
|
4014
|
+
const bindings = evaluatePattern(declarator.id, st, callback, value);
|
|
4015
|
+
for (const key of Object.keys(bindings)) {
|
|
4016
|
+
if (isDangerousProperty(key)) {
|
|
4017
|
+
throw new Error(`Access to dangerous property "${key}" is blocked for security reasons`);
|
|
4018
|
+
}
|
|
4019
|
+
setContextValue(scope, key, bindings[key]);
|
|
4020
|
+
if (kind === 'const') {
|
|
4021
|
+
st.declareConst(scope, key);
|
|
4022
|
+
}
|
|
4023
|
+
}
|
|
4024
|
+
};
|
|
4025
|
+
/**
|
|
4026
|
+
* Evaluates a variable declaration: `let` and `const`, in the plain and
|
|
4027
|
+
* destructuring forms.
|
|
4028
|
+
*
|
|
4029
|
+
* Pushes {@link EMPTY_COMPLETION} on every exit path - a declaration produces no
|
|
4030
|
+
* completion value in JavaScript, and the sentinel rather than `undefined` is
|
|
4031
|
+
* what keeps `let x = 1` from winning over an earlier statement's value inside a
|
|
4032
|
+
* block. Pops one value per declarator that has an initialiser, and none for one
|
|
4033
|
+
* that does not, which is the arithmetic § 3.1's table states for this visitor.
|
|
4034
|
+
*
|
|
4035
|
+
* **No hoisting.** A binding exists from the point its declaration is reached,
|
|
4036
|
+
* so a read before it resolves the enclosing context rather than raising a
|
|
4037
|
+
* temporal-dead-zone error. An uninitialised `let` binds `undefined` and still
|
|
4038
|
+
* *shadows*, because `EvalContext.get` resolves a pushed scope by presence
|
|
4039
|
+
* rather than by value.
|
|
4040
|
+
*
|
|
4041
|
+
* **`var` is rejected here, not by the statement dispatcher.** The dispatcher
|
|
4042
|
+
* switches on node *type*, and `var x = 1` is a `VariableDeclaration` exactly as
|
|
4043
|
+
* `let x = 1` is - so registering this visitor is what stopped `var` reaching the
|
|
4044
|
+
* throwing `default:`. Function-scoped hoisting is a second scoping model beside
|
|
4045
|
+
* block scoping and is out of scope for this phase, so the rejection had to move
|
|
4046
|
+
* rather than disappear.
|
|
4047
|
+
*
|
|
4048
|
+
* No scope is pushed here: a declaration binds into the scope its enclosing
|
|
4049
|
+
* statement list already pushed, so there is no `try`/`finally` to pair and
|
|
4050
|
+
* nothing this visitor can leave behind on `EvalContext`.
|
|
4051
|
+
*/
|
|
4052
|
+
const variableDeclarationVisitor = (node, st, callback) => {
|
|
4053
|
+
// Above `beforeVisitor`, deliberately. Four paths through this visitor throw,
|
|
4054
|
+
// and three of them have to throw from inside the bracket - they need the
|
|
4055
|
+
// walk to have started. This one reads `node.kind` and nothing else, so
|
|
4056
|
+
// rejecting before the hook dispatch keeps the most reachable of the four
|
|
4057
|
+
// from opening a frame it never closes. The others are covered the way every
|
|
4058
|
+
// throwing visitor in this library is: `evaluate`'s `catch` unwinds the open
|
|
4059
|
+
// nodes to its walk base.
|
|
4060
|
+
if (node.kind !== 'let' && node.kind !== 'const') {
|
|
4061
|
+
throw new Error(`Unsupported variable declaration kind: ${node.kind}`);
|
|
4062
|
+
}
|
|
4063
|
+
beforeVisitor(node, st);
|
|
4064
|
+
const scope = bindingScope(st);
|
|
4065
|
+
for (const declarator of node.declarations) {
|
|
4066
|
+
let value = undefined;
|
|
4067
|
+
if (declarator.init) {
|
|
4068
|
+
callback(declarator.init, st);
|
|
4069
|
+
value = popVisitorResult(node, st);
|
|
4070
|
+
}
|
|
4071
|
+
bindDeclarator(declarator, value, node.kind, scope, st, callback);
|
|
4072
|
+
}
|
|
4073
|
+
pushVisitorResult(node, st, EMPTY_COMPLETION);
|
|
4074
|
+
afterVisitor(node, st);
|
|
4075
|
+
};
|
|
4076
|
+
/**
|
|
4077
|
+
* Assigns to `key`, preferring a binding the evaluation itself created.
|
|
4078
|
+
*
|
|
4079
|
+
* The shared write path for `assignment-expression.ts` and
|
|
4080
|
+
* `update-expression.ts`. It lives in this module rather than one of its own on
|
|
4081
|
+
* the precedent `dispatchStatement` set in `program.ts`: the `const` kinds it
|
|
4082
|
+
* enforces are recorded here, and two importers is not yet a utility module. A
|
|
4083
|
+
* third is when it earns one.
|
|
4084
|
+
*
|
|
4085
|
+
* Order matters, and both steps are one lookup:
|
|
4086
|
+
*
|
|
4087
|
+
* 1. `scopeHolding` finds the innermost pushed scope that **binds** the key, or
|
|
4088
|
+
* nothing. This is the same pass `EvalContext.get` resolves through, which is
|
|
4089
|
+
* why it is asked of the context rather than re-walked here.
|
|
4090
|
+
* 2. A `const` in that scope is rejected before anything is written.
|
|
4091
|
+
* 3. Otherwise `setInScope` writes it - and when no scope bound the key at all,
|
|
4092
|
+
* `set` does, which is the fallback `eval-signals` overrides to enforce its
|
|
4093
|
+
* read-only policy. Routing around it would disable that policy silently.
|
|
4094
|
+
*
|
|
4095
|
+
* **The scope is resolved twice - here, and again inside `setInScope` - and that
|
|
4096
|
+
* is a cost, not a free abstraction.** `scopeHolding` goes through
|
|
4097
|
+
* `Stack.asArray()`, which copies and reverses, so each pass allocates. An
|
|
4098
|
+
* identifier write therefore costs two short scans plus two small arrays where
|
|
4099
|
+
* the pre-Phase-2 `set` cost none.
|
|
4100
|
+
*
|
|
4101
|
+
* Kept because `setInScope` is the single place that knows how to write a scope
|
|
4102
|
+
* - a `Registry` under `caseInsensitive`, a plain record otherwise - and
|
|
4103
|
+
* writing directly from here would put that dispatch in two modules, which is
|
|
4104
|
+
* the one mistake in this area that is silent when made wrong. The honest
|
|
4105
|
+
* alternative is to let `setInScope` take an already-resolved scope; that widens
|
|
4106
|
+
* a signature this phase has published and is step 5's call, not this step's,
|
|
4107
|
+
* because step 5 is where the cost multiplies: `for (let i = 0; i < n; i++)`
|
|
4108
|
+
* runs this path once per iteration, on top of the `get` in the test and the
|
|
4109
|
+
* `get` in the update. Recorded in the plan's step 5 rather than left here.
|
|
4110
|
+
*/
|
|
4111
|
+
const assignToBinding = (st, key, value, name) => {
|
|
4112
|
+
if (!st.context) {
|
|
4113
|
+
throw new Error(`Context is not set.`);
|
|
4114
|
+
}
|
|
4115
|
+
const scope = st.context.scopeHolding(key);
|
|
4116
|
+
if (!scope) {
|
|
4117
|
+
st.context.set(key, value);
|
|
4118
|
+
return;
|
|
4119
|
+
}
|
|
4120
|
+
if (st.isConstBinding(scope, key)) {
|
|
4121
|
+
throw new Error(`Assignment to constant variable "${name}".`);
|
|
4122
|
+
}
|
|
4123
|
+
st.context.setInScope(key, value);
|
|
4124
|
+
};
|
|
4125
|
+
|
|
3362
4126
|
const assignmentOperators = {
|
|
3363
4127
|
'=': (left, value) => { return left = value; },
|
|
3364
4128
|
'+=': (left, value) => { return left += value; },
|
|
@@ -3395,7 +4159,12 @@ const assignmentExpressionVisitor = (node, st, callback) => {
|
|
|
3395
4159
|
? st.context.getKey(node.left.name)
|
|
3396
4160
|
: node.left.name;
|
|
3397
4161
|
const value = func(left, right);
|
|
3398
|
-
|
|
4162
|
+
// Scope first, the caller's object second. Before Phase 2 this was
|
|
4163
|
+
// `st.context.set(key, value)`, which consults no scope at all - so
|
|
4164
|
+
// `(x => (x = 99))(1)` wrote `99` into the caller's own object and left the
|
|
4165
|
+
// arrow's parameter untouched. See `assignToBinding` for why the fallback
|
|
4166
|
+
// to `set` is load-bearing rather than tidy.
|
|
4167
|
+
assignToBinding(st, key, value, node.left.name);
|
|
3399
4168
|
pushVisitorResult(node, st, value);
|
|
3400
4169
|
}
|
|
3401
4170
|
else if (node.left.type === 'MemberExpression') {
|
|
@@ -3423,7 +4192,11 @@ const updateExpressionVisitor = (node, st, callback) => {
|
|
|
3423
4192
|
: node.argument.name;
|
|
3424
4193
|
const value = st.context?.get(key);
|
|
3425
4194
|
const newValue = updateOperators[node.operator](value);
|
|
3426
|
-
|
|
4195
|
+
// The same redirection as `assignment-expression.ts`, and the site that
|
|
4196
|
+
// matters for `for (let i = 0; …; i++)`: without it every loop counter this
|
|
4197
|
+
// library runs would be written into the consumer's context object, and
|
|
4198
|
+
// left there.
|
|
4199
|
+
assignToBinding(st, key, newValue, node.argument.name);
|
|
3427
4200
|
pushVisitorResult(node, st, node.prefix ? newValue : value);
|
|
3428
4201
|
}
|
|
3429
4202
|
else if (node.argument.type === 'MemberExpression') {
|
|
@@ -3466,6 +4239,59 @@ const extractExpression = (program) => {
|
|
|
3466
4239
|
return undefined;
|
|
3467
4240
|
};
|
|
3468
4241
|
|
|
4242
|
+
/**
|
|
4243
|
+
* Applies § 3.1's rule 4: the empty-completion sentinel never leaves an
|
|
4244
|
+
* evaluation's return value.
|
|
4245
|
+
*
|
|
4246
|
+
* It is converted here, at the walk boundary, rather than in the `Program`
|
|
4247
|
+
* visitor. `arrow-function-expression.ts` calls `evaluate` on a
|
|
4248
|
+
* `BlockStatement` for a block-bodied arrow, so a conversion sited in `Program`
|
|
4249
|
+
* would let `x => { }` hand the sentinel straight to a consumer. Converting
|
|
4250
|
+
* where the walk ends covers both entry points by construction.
|
|
4251
|
+
*/
|
|
4252
|
+
const completionValue = (value) => value === EMPTY_COMPLETION ? undefined : value;
|
|
4253
|
+
/**
|
|
4254
|
+
* The merged visitor table every walk dispatches through: this library's
|
|
4255
|
+
* visitors laid over `acorn-walk`'s base walker, built once.
|
|
4256
|
+
*
|
|
4257
|
+
* **`walk.recursive` merges per call, and the merge is not cheap.** Handed a
|
|
4258
|
+
* `funcs` object it calls `walk.make(funcs, base)`, which allocates an object
|
|
4259
|
+
* and copies every entry onto it - once per `evaluate`, not once per node.
|
|
4260
|
+
* Measured on the built bundle, walking a single `Literal`, which visits one
|
|
4261
|
+
* node and so is almost entirely this fixed cost:
|
|
4262
|
+
*
|
|
4263
|
+
* | visitor entries | per-call merge | merged once |
|
|
4264
|
+
* | --------------- | -------------- | ----------- |
|
|
4265
|
+
* | 19 (before statements) | 0.422 us | - |
|
|
4266
|
+
* | 22 (with statements) | 1.045 us | 0.226 us |
|
|
4267
|
+
*
|
|
4268
|
+
* Three more entries more than doubled it, which is a cliff rather than a
|
|
4269
|
+
* slope - the copy crosses a threshold where the engine stops treating the
|
|
4270
|
+
* result as a fast-property object. Merging once removes the whole class of
|
|
4271
|
+
* problem: it is faster than the pre-statement baseline, and it stops the
|
|
4272
|
+
* remaining statement visitors of this phase from making it worse again.
|
|
4273
|
+
*
|
|
4274
|
+
* `{}` is still passed as `funcs` at the call sites so that `make` has nothing
|
|
4275
|
+
* to copy; the per-walk object is then an empty `Object.create(DEFAULT_VISITORS)`
|
|
4276
|
+
* and every lookup is a prototype hit.
|
|
4277
|
+
*
|
|
4278
|
+
* Frozen, and lazily built, for two different reasons:
|
|
4279
|
+
*
|
|
4280
|
+
* - **Frozen** because this table is shared by every walk in the process -
|
|
4281
|
+
* `EvalService` is `providedIn: 'root'` - so a visitor that wrote to it would
|
|
4282
|
+
* reach every later evaluation, including other consumers'. Nothing writes to
|
|
4283
|
+
* it today; freezing is what keeps that true, turning a silent cross-walk
|
|
4284
|
+
* mutation into a throw. `getDefaultVisitors()` still returns a **fresh,
|
|
4285
|
+
* mutable** object to anyone who calls it, so no caller loses anything.
|
|
4286
|
+
* - **Lazily** because a module-level `const` deadlocks the flattened bundle:
|
|
4287
|
+
* `arrow-function-expression.ts` imports `evaluate`, so this module is
|
|
4288
|
+
* initialised first and `getDefaultVisitors()` at module scope reads that
|
|
4289
|
+
* visitor before its binding exists. Measured, not guessed - the built
|
|
4290
|
+
* package threw `Cannot access 'arrowFunctionExpressionVisitor' before
|
|
4291
|
+
* initialization` on import.
|
|
4292
|
+
*/
|
|
4293
|
+
let defaultVisitors;
|
|
4294
|
+
const mergedVisitors = () => (defaultVisitors ??= Object.freeze(walk.make(getDefaultVisitors())));
|
|
3469
4295
|
/**
|
|
3470
4296
|
* Evaluates the given node and returns the result.
|
|
3471
4297
|
*
|
|
@@ -3478,11 +4304,22 @@ const evaluate = (node, state) => {
|
|
|
3478
4304
|
state.result.start();
|
|
3479
4305
|
// Captured inside the `if (node)` block on purpose: callers reach the early
|
|
3480
4306
|
// return above with a bare state that has no hooks to read. Do not hoist.
|
|
3481
|
-
|
|
4307
|
+
//
|
|
4308
|
+
// The mark is recorded on the state as well as held here, so that
|
|
4309
|
+
// `EvalHooks.exit` - called from a visitor, which has no route to this
|
|
4310
|
+
// local - can tell a node open in this walk from one open only in an
|
|
4311
|
+
// enclosing walk. Pushed under the same guard the mark is read under, and
|
|
4312
|
+
// the local `hooked` keeps the pair symmetric if a hook is registered
|
|
4313
|
+
// mid-walk.
|
|
4314
|
+
const hooked = state.hasHooks;
|
|
4315
|
+
const mark = hooked ? state.hooks.pushWalkBase(state) : 0;
|
|
4316
|
+
// Unguarded, unlike the walk base above: the iteration budget refills on
|
|
4317
|
+
// the outermost entry whether or not hooks are registered. See
|
|
4318
|
+
// `EvalState.walkDepth` on why these are two fields and not one.
|
|
4319
|
+
state.enterWalk();
|
|
3482
4320
|
try {
|
|
3483
|
-
|
|
3484
|
-
|
|
3485
|
-
const value = popVisitorResult(node, state);
|
|
4321
|
+
walk.recursive(node, state, {}, mergedVisitors());
|
|
4322
|
+
const value = completionValue(popVisitorResult(node, state));
|
|
3486
4323
|
state.result.stop();
|
|
3487
4324
|
state.result.setSuccess(value);
|
|
3488
4325
|
return value;
|
|
@@ -3493,12 +4330,29 @@ const evaluate = (node, state) => {
|
|
|
3493
4330
|
// walk left open. Unwinding to the mark rather than to the bottom is what
|
|
3494
4331
|
// stops a nested evaluate - the arrow-function body runs on this same
|
|
3495
4332
|
// state - from draining the enclosing walk's open nodes.
|
|
4333
|
+
// Reads `state.hasHooks` rather than the `hooked` local captured above,
|
|
4334
|
+
// and the difference is deliberate but narrow: if a hook was registered
|
|
4335
|
+
// *during* this walk then `hooked` is false, no base was pushed, `mark`
|
|
4336
|
+
// is 0, and this unwinds the whole stack - including an enclosing walk's
|
|
4337
|
+
// frames, which is the boundary crossing the walk base exists to stop.
|
|
4338
|
+
// Left as it was rather than tightened here, because narrowing it would
|
|
4339
|
+
// change what a mid-walk registration observes on an already-published
|
|
4340
|
+
// path, which is not this step's to decide.
|
|
3496
4341
|
if (state.hasHooks) {
|
|
3497
4342
|
state.hooks.unwindTo(mark, error, state);
|
|
3498
4343
|
}
|
|
3499
4344
|
state.result.setFailure(error);
|
|
3500
4345
|
throw error;
|
|
3501
4346
|
}
|
|
4347
|
+
finally {
|
|
4348
|
+
// Both in a `finally`: a walk that threw still has to restore the
|
|
4349
|
+
// enclosing walk's bound and depth, or every later evaluation on this
|
|
4350
|
+
// state carries this one's nesting.
|
|
4351
|
+
state.exitWalk();
|
|
4352
|
+
if (hooked) {
|
|
4353
|
+
state.hooks.popWalkBase(state);
|
|
4354
|
+
}
|
|
4355
|
+
}
|
|
3502
4356
|
}
|
|
3503
4357
|
return undefined;
|
|
3504
4358
|
};
|
|
@@ -3567,11 +4421,27 @@ const evaluateAsync = async (ast, state) => {
|
|
|
3567
4421
|
state.result.start();
|
|
3568
4422
|
// Captured after the `!ast` early return above, for the same reason the sync
|
|
3569
4423
|
// entry point captures inside its `if (node)` block. Do not hoist.
|
|
3570
|
-
const
|
|
4424
|
+
const hooked = state.hasHooks;
|
|
4425
|
+
const mark = hooked ? state.hooks.pushWalkBase(state) : 0;
|
|
4426
|
+
state.enterWalk();
|
|
3571
4427
|
try {
|
|
3572
|
-
|
|
3573
|
-
walk
|
|
3574
|
-
|
|
4428
|
+
let value;
|
|
4429
|
+
// The walk bookkeeping is released here rather than in a `finally` on the
|
|
4430
|
+
// outer try, because the walk ends here: everything below this block is
|
|
4431
|
+
// promise resolution on an already-finished traversal. Holding the walk
|
|
4432
|
+
// base and the depth across the `await` would leave an independent
|
|
4433
|
+
// evaluation that interleaved on this state looking like a nested walk -
|
|
4434
|
+
// and § 3.4's budget refills only on the outermost entry.
|
|
4435
|
+
try {
|
|
4436
|
+
walk.recursive(ast, state, {}, mergedVisitors());
|
|
4437
|
+
value = completionValue(popVisitorResult(ast, state));
|
|
4438
|
+
}
|
|
4439
|
+
finally {
|
|
4440
|
+
state.exitWalk();
|
|
4441
|
+
if (hooked) {
|
|
4442
|
+
state.hooks.popWalkBase(state);
|
|
4443
|
+
}
|
|
4444
|
+
}
|
|
3575
4445
|
// Enhanced promise handling - recursively await all promises
|
|
3576
4446
|
try {
|
|
3577
4447
|
value = await awaitAllPromises(value);
|
|
@@ -3665,145 +4535,408 @@ const arrowFunctionExpressionVisitor = (node, st, callback) => {
|
|
|
3665
4535
|
beforeVisitor(node, st);
|
|
3666
4536
|
const fn = (...arrowArgs) => {
|
|
3667
4537
|
const newContext = evaluatePatterns(node.params, st, callback, arrowArgs);
|
|
4538
|
+
// The scope stack lives on EvalContext, not on the per-walk EvalState, and
|
|
4539
|
+
// one EvalContext can back any number of evaluations - so a scope this
|
|
4540
|
+
// closure fails to pop outlives the walk and is read first by every later
|
|
4541
|
+
// evaluation on the same context. The body is re-entrant `evaluate`, which
|
|
4542
|
+
// rethrows, so the pop needs `finally`.
|
|
4543
|
+
//
|
|
4544
|
+
// The `try` opens *after* the push, never around it. `push` is optionally
|
|
4545
|
+
// chained: bringing it inside would pair a `finally` pop with a push that
|
|
4546
|
+
// the same optional chain had skipped, and would swallow a throw from
|
|
4547
|
+
// evaluatePatterns into a pop as well.
|
|
3668
4548
|
st.context?.push(newContext);
|
|
3669
|
-
|
|
3670
|
-
|
|
3671
|
-
|
|
4549
|
+
try {
|
|
4550
|
+
return evaluate(node.body, st);
|
|
4551
|
+
}
|
|
4552
|
+
finally {
|
|
4553
|
+
st.context?.pop();
|
|
4554
|
+
}
|
|
3672
4555
|
};
|
|
3673
4556
|
pushVisitorResult(node, st, fn);
|
|
3674
4557
|
afterVisitor(node, st);
|
|
3675
4558
|
};
|
|
3676
4559
|
|
|
3677
|
-
|
|
3678
|
-
|
|
3679
|
-
|
|
3680
|
-
|
|
3681
|
-
|
|
3682
|
-
|
|
3683
|
-
|
|
3684
|
-
|
|
3685
|
-
|
|
3686
|
-
|
|
3687
|
-
|
|
3688
|
-
|
|
3689
|
-
|
|
3690
|
-
|
|
3691
|
-
|
|
3692
|
-
|
|
3693
|
-
|
|
3694
|
-
|
|
3695
|
-
|
|
3696
|
-
|
|
3697
|
-
|
|
3698
|
-
|
|
3699
|
-
|
|
3700
|
-
|
|
3701
|
-
|
|
3702
|
-
|
|
3703
|
-
|
|
3704
|
-
|
|
3705
|
-
|
|
3706
|
-
|
|
3707
|
-
|
|
3708
|
-
|
|
3709
|
-
|
|
3710
|
-
|
|
3711
|
-
|
|
3712
|
-
|
|
3713
|
-
|
|
3714
|
-
|
|
3715
|
-
|
|
3716
|
-
|
|
3717
|
-
|
|
3718
|
-
|
|
3719
|
-
|
|
3720
|
-
|
|
4560
|
+
/**
|
|
4561
|
+
* Walks one statement and returns its completion value.
|
|
4562
|
+
*
|
|
4563
|
+
* The statement dispatcher for the whole family, and the single place § 3.1's
|
|
4564
|
+
* rule 2 - one `popVisitorResult` per `callback` - is discharged for every
|
|
4565
|
+
* caller. Four visitors import it: `Program` and `BlockStatement` walk a
|
|
4566
|
+
* statement list, `IfStatement` a branch, and `ForStatement` an `init` and a
|
|
4567
|
+
* body.
|
|
4568
|
+
*
|
|
4569
|
+
* **It is explicit, and its `default` throws.** A node type this library does
|
|
4570
|
+
* not implement raises rather than falling through to `acorn-walk`'s base
|
|
4571
|
+
* walker, which would visit the subtree as an expression and strand whatever it
|
|
4572
|
+
* pushed - `while (false) { 1 }` used to evaluate to `1` that way. Three
|
|
4573
|
+
* visitors in this library already push nothing on one path of an `if`/`else if`
|
|
4574
|
+
* chain over node types (`docs/backlog.md` A2); a `switch` whose `default`
|
|
4575
|
+
* throws is how this family gains no fourth member.
|
|
4576
|
+
*
|
|
4577
|
+
* **Why this module exists.** It lived in `program.ts` for steps 1 to 5, on the
|
|
4578
|
+
* rule that a shared helper earns its own file at its *third* importer -
|
|
4579
|
+
* otherwise a visitor module has quietly become a utility module that also
|
|
4580
|
+
* happens to export a visitor. `if-statement.ts` met that condition in step 4,
|
|
4581
|
+
* which recorded it MET AND DEFERRED rather than unmet: no step's file list
|
|
4582
|
+
* admitted creating a module and rewriting three imports, and step 4 was not the
|
|
4583
|
+
* place to widen its own scope. The plan named step 6 as the date so that
|
|
4584
|
+
* `ForStatement` would not arrive in step 5 as a *fourth* importer against a
|
|
4585
|
+
* rule that had declined to fire twice. This is that move. The rejection surface
|
|
4586
|
+
* did not change with it - a pure relocation, gated by the existing suite.
|
|
4587
|
+
*
|
|
4588
|
+
* @returns the statement's completion value, which is `EMPTY_COMPLETION`
|
|
4589
|
+
* (`../classes/eval`) for a statement that produced nothing. The sentinel is not
|
|
4590
|
+
* imported here: this module never compares against it, and an import kept only
|
|
4591
|
+
* for a doc link is an unused binding the lint config rejects.
|
|
4592
|
+
*/
|
|
4593
|
+
const dispatchStatement = (statement, st, callback) => {
|
|
4594
|
+
switch (statement.type) {
|
|
4595
|
+
// `VariableDeclaration` covers `var` as well, and cannot not: this `switch`
|
|
4596
|
+
// reads the node *type*, and `var x = 1` is a `VariableDeclaration` exactly
|
|
4597
|
+
// as `let x = 1` is. Listing it here is therefore what stopped `var`
|
|
4598
|
+
// reaching the `default:` below; the rejection moved into the visitor,
|
|
4599
|
+
// which can read `kind`.
|
|
4600
|
+
//
|
|
4601
|
+
// `ForStatement` is the classic three-part form *only*. `ForOfStatement`,
|
|
4602
|
+
// `ForInStatement`, `WhileStatement` and `DoWhileStatement` are distinct
|
|
4603
|
+
// node types and stay out of the phase (§ 2), so they reach the `default`
|
|
4604
|
+
// below unchanged - unlike `var`, which shares a type with `let` and had to
|
|
4605
|
+
// be rejected one level down.
|
|
4606
|
+
case 'ExpressionStatement':
|
|
4607
|
+
case 'EmptyStatement':
|
|
4608
|
+
case 'BlockStatement':
|
|
4609
|
+
case 'VariableDeclaration':
|
|
4610
|
+
case 'IfStatement':
|
|
4611
|
+
case 'ForStatement':
|
|
4612
|
+
callback(statement, st);
|
|
4613
|
+
return popVisitorResult(statement, st);
|
|
4614
|
+
default:
|
|
4615
|
+
throw new Error(`Unsupported statement type: ${statement.type}`);
|
|
4616
|
+
}
|
|
3721
4617
|
};
|
|
3722
|
-
|
|
3723
|
-
|
|
3724
|
-
|
|
3725
|
-
|
|
3726
|
-
|
|
3727
|
-
|
|
3728
|
-
|
|
3729
|
-
|
|
3730
|
-
|
|
3731
|
-
|
|
3732
|
-
|
|
3733
|
-
|
|
3734
|
-
|
|
3735
|
-
|
|
4618
|
+
|
|
4619
|
+
/**
|
|
4620
|
+
* Evaluates a program: the root node of every walk that reaches this library
|
|
4621
|
+
* through `EvalService`, since its parser options leave `extractExpressions`
|
|
4622
|
+
* off and so hand `evaluate` the whole `Program`.
|
|
4623
|
+
*
|
|
4624
|
+
* Keeps the last **non-empty** completion value, per JavaScript's
|
|
4625
|
+
* completion-value semantics, and pushes exactly one value however many
|
|
4626
|
+
* statements the body holds. A program whose statements all produced nothing -
|
|
4627
|
+
* `;`, or a source that is only whitespace - pushes {@link EMPTY_COMPLETION},
|
|
4628
|
+
* which the walk boundary in `evaluate` converts to `undefined`. The conversion
|
|
4629
|
+
* is deliberately not done here: `arrow-function-expression.ts` calls
|
|
4630
|
+
* `evaluate` on a `BlockStatement` for a block-bodied arrow, so a `Program`-side
|
|
4631
|
+
* conversion would leave that entry point handing the sentinel to a consumer.
|
|
4632
|
+
*
|
|
4633
|
+
* **The program-level scope is required.** It is the only scope a top-level
|
|
4634
|
+
* `let` can bind into; without it a declaration would have nowhere to go but
|
|
4635
|
+
* `EvalContext.set`, which writes the caller's own context object - and is the
|
|
4636
|
+
* method `eval-signals` overrides to enforce its read-only policy. `get`
|
|
4637
|
+
* searches `scopes` first and falls through on a miss, so an empty program
|
|
4638
|
+
* scope costs no outer resolution.
|
|
4639
|
+
*
|
|
4640
|
+
* The pop is in a `finally` because the scope stack lives on `EvalContext`, not
|
|
4641
|
+
* on the per-walk `EvalState`, and one context can back any number of
|
|
4642
|
+
* evaluations: a scope this visitor failed to pop would outlive the walk and be
|
|
4643
|
+
* read first by every later evaluation on that context. The `try` opens *after*
|
|
4644
|
+
* the push, never around it - `push` is optionally chained, so bringing it
|
|
4645
|
+
* inside would pair a `finally` pop with a push the same optional chain had
|
|
4646
|
+
* skipped.
|
|
4647
|
+
*/
|
|
4648
|
+
const programVisitor = (node, st, callback) => {
|
|
4649
|
+
beforeVisitor(node, st);
|
|
4650
|
+
let completion = EMPTY_COMPLETION;
|
|
4651
|
+
st.context?.push({}, st.options);
|
|
4652
|
+
try {
|
|
4653
|
+
for (const statement of node.body) {
|
|
4654
|
+
const value = dispatchStatement(statement, st, callback);
|
|
4655
|
+
if (value !== EMPTY_COMPLETION) {
|
|
4656
|
+
completion = value;
|
|
4657
|
+
}
|
|
4658
|
+
}
|
|
3736
4659
|
}
|
|
3737
|
-
|
|
4660
|
+
finally {
|
|
4661
|
+
st.context?.pop();
|
|
4662
|
+
}
|
|
4663
|
+
pushVisitorResult(node, st, completion);
|
|
4664
|
+
afterVisitor(node, st);
|
|
3738
4665
|
};
|
|
3739
|
-
|
|
3740
|
-
|
|
3741
|
-
|
|
3742
|
-
|
|
4666
|
+
|
|
4667
|
+
/**
|
|
4668
|
+
* Evaluates an expression statement: its completion value is its expression's.
|
|
4669
|
+
*
|
|
4670
|
+
* A pass-through, and registered rather than left to `acorn-walk`'s base walker
|
|
4671
|
+
* for two reasons. The base walker fires no hooks, so a statement would be
|
|
4672
|
+
* invisible to a consumer watching the walk; and § 3.1's rule that every
|
|
4673
|
+
* statement visitor pushes exactly one value would have an exception whose only
|
|
4674
|
+
* justification is that this one happens to be cheap.
|
|
4675
|
+
*/
|
|
4676
|
+
const expressionStatementVisitor = (node, st, callback) => {
|
|
4677
|
+
beforeVisitor(node, st);
|
|
4678
|
+
callback(node.expression, st);
|
|
4679
|
+
const value = popVisitorResult(node, st);
|
|
4680
|
+
pushVisitorResult(node, st, value);
|
|
4681
|
+
afterVisitor(node, st);
|
|
3743
4682
|
};
|
|
3744
|
-
|
|
3745
|
-
|
|
3746
|
-
|
|
3747
|
-
|
|
3748
|
-
|
|
3749
|
-
|
|
4683
|
+
|
|
4684
|
+
/**
|
|
4685
|
+
* Evaluates an empty statement: it produces nothing, so it pushes
|
|
4686
|
+
* {@link EMPTY_COMPLETION} and an enclosing statement list keeps whatever
|
|
4687
|
+
* preceded it.
|
|
4688
|
+
*
|
|
4689
|
+
* One line of behaviour, and it exists because the statement dispatcher's
|
|
4690
|
+
* `default` throws: without it `a;;b` and `if (x) ;` would start raising
|
|
4691
|
+
* "unsupported statement type", which is a divergence from JavaScript nobody
|
|
4692
|
+
* chose.
|
|
4693
|
+
*/
|
|
4694
|
+
const emptyStatementVisitor = (node, st) => {
|
|
4695
|
+
beforeVisitor(node, st);
|
|
4696
|
+
pushVisitorResult(node, st, EMPTY_COMPLETION);
|
|
4697
|
+
afterVisitor(node, st);
|
|
3750
4698
|
};
|
|
3751
|
-
|
|
3752
|
-
|
|
3753
|
-
|
|
3754
|
-
|
|
3755
|
-
|
|
3756
|
-
|
|
3757
|
-
|
|
3758
|
-
|
|
3759
|
-
|
|
3760
|
-
|
|
3761
|
-
|
|
3762
|
-
|
|
3763
|
-
|
|
3764
|
-
|
|
3765
|
-
|
|
3766
|
-
|
|
3767
|
-
|
|
3768
|
-
|
|
3769
|
-
|
|
3770
|
-
|
|
3771
|
-
|
|
3772
|
-
|
|
3773
|
-
|
|
3774
|
-
|
|
3775
|
-
|
|
3776
|
-
|
|
3777
|
-
|
|
3778
|
-
|
|
3779
|
-
|
|
3780
|
-
|
|
3781
|
-
|
|
3782
|
-
|
|
3783
|
-
|
|
3784
|
-
|
|
3785
|
-
|
|
4699
|
+
|
|
4700
|
+
/**
|
|
4701
|
+
* Evaluates a block statement: a scope, a statement list, and one completion
|
|
4702
|
+
* value.
|
|
4703
|
+
*
|
|
4704
|
+
* Keeps the last **non-empty** completion value, per JavaScript's
|
|
4705
|
+
* completion-value semantics, and pushes exactly one value however many
|
|
4706
|
+
* statements the body holds. A block whose statements all produced nothing -
|
|
4707
|
+
* `{ }`, or `{ ; }` - pushes {@link EMPTY_COMPLETION} for its enclosing
|
|
4708
|
+
* statement list to skip over. The sentinel is converted to `undefined` at the
|
|
4709
|
+
* walk boundary in `evaluate`, which is why this visitor may return it to a
|
|
4710
|
+
* caller that is itself a walk root: `arrow-function-expression.ts` calls
|
|
4711
|
+
* `evaluate` on this node for a block-bodied arrow, so `x => { }` reaches a
|
|
4712
|
+
* consumer through the same conversion a `Program` does.
|
|
4713
|
+
*
|
|
4714
|
+
* **The block scope is unobservable in this step, and is pushed anyway.**
|
|
4715
|
+
* Nothing binds into it until `VariableDeclaration` lands, and an empty scope
|
|
4716
|
+
* shadows nothing now that `EvalContext.get` resolves a scope by presence
|
|
4717
|
+
* rather than by value. Pushing it here rather than with the first binding
|
|
4718
|
+
* keeps the scope arithmetic in one place: the depth a nested block reports is
|
|
4719
|
+
* a property of the block, not of whether its body happened to declare
|
|
4720
|
+
* anything.
|
|
4721
|
+
*
|
|
4722
|
+
* `st.options` is passed to `push` because `fromContext` copies a plain record
|
|
4723
|
+
* into a `Registry` when `caseInsensitive` is set. Omitting them would make a
|
|
4724
|
+
* block's bindings case-**sensitive** inside an otherwise case-insensitive
|
|
4725
|
+
* evaluation - a silent wrong answer rather than an error, and one no assertion
|
|
4726
|
+
* in this step can reach, since a scope nothing binds into resolves nothing
|
|
4727
|
+
* either way.
|
|
4728
|
+
*
|
|
4729
|
+
* The pop is in a `finally` because the scope stack lives on `EvalContext`, not
|
|
4730
|
+
* on the per-walk `EvalState`, and one context can back any number of
|
|
4731
|
+
* evaluations: a scope this visitor failed to pop would outlive the walk and be
|
|
4732
|
+
* read first by every later evaluation on that context. The `try` opens *after*
|
|
4733
|
+
* the push, never around it - `push` is optionally chained, so bringing it
|
|
4734
|
+
* inside would pair a `finally` pop with a push the same optional chain had
|
|
4735
|
+
* skipped.
|
|
4736
|
+
*/
|
|
4737
|
+
const blockStatementVisitor = (node, st, callback) => {
|
|
4738
|
+
beforeVisitor(node, st);
|
|
4739
|
+
let completion = EMPTY_COMPLETION;
|
|
4740
|
+
st.context?.push({}, st.options);
|
|
4741
|
+
try {
|
|
4742
|
+
for (const statement of node.body) {
|
|
4743
|
+
const value = dispatchStatement(statement, st, callback);
|
|
4744
|
+
if (value !== EMPTY_COMPLETION) {
|
|
4745
|
+
completion = value;
|
|
4746
|
+
}
|
|
3786
4747
|
}
|
|
3787
|
-
}
|
|
3788
|
-
|
|
4748
|
+
}
|
|
4749
|
+
finally {
|
|
4750
|
+
st.context?.pop();
|
|
4751
|
+
}
|
|
4752
|
+
pushVisitorResult(node, st, completion);
|
|
4753
|
+
afterVisitor(node, st);
|
|
3789
4754
|
};
|
|
3790
|
-
|
|
3791
|
-
|
|
3792
|
-
|
|
3793
|
-
|
|
4755
|
+
|
|
4756
|
+
/**
|
|
4757
|
+
* Evaluates an `if` statement: one test, and **exactly one branch or neither**.
|
|
4758
|
+
*
|
|
4759
|
+
* The behavioural fix in the plan's § 1.1 table. `acorn-walk`'s base walker
|
|
4760
|
+
* visits both branches regardless of the test, so `if (a) { 1 } else { 2 }` with
|
|
4761
|
+
* `a` true measured `2` - the `else` value was pushed last and won - and any
|
|
4762
|
+
* call or assignment in the untaken branch had already run. The value was the
|
|
4763
|
+
* smaller half of that: a visitor that walked both branches and then *selected*
|
|
4764
|
+
* by the test would return `1` and still run them both, which is why the specs
|
|
4765
|
+
* assert on an uncalled `jest.fn` and an unwritten source key beside the value.
|
|
4766
|
+
*
|
|
4767
|
+
* Completion value, per § 3.1: the branch's own, unchanged. A taken branch that
|
|
4768
|
+
* produced nothing propagates {@link EMPTY_COMPLETION} - `if (true) { }` pushes
|
|
4769
|
+
* the sentinel exactly as `if (false) { 1 }` does, by two different routes - and
|
|
4770
|
+
* a branch that genuinely produced `undefined` pushes that, so an enclosing
|
|
4771
|
+
* statement list keeps it over an earlier value. Mapping either onto the other
|
|
4772
|
+
* here would collapse the distinction the sentinel exists for.
|
|
4773
|
+
*
|
|
4774
|
+
* Arithmetic: pops 1 for the test, plus 1 for the branch when one runs; pushes
|
|
4775
|
+
* exactly 1 on both exit paths.
|
|
4776
|
+
*
|
|
4777
|
+
* **The branches go through `dispatchStatement`, not a raw `callback`.** A
|
|
4778
|
+
* branch is a `Statement`, and a raw callback would hand a type this library
|
|
4779
|
+
* does not implement to the base walker, which walks it as an expression and
|
|
4780
|
+
* strands whatever it pushed. That is the silent fall-through family § 1.7
|
|
4781
|
+
* names and § 3.1 promises to add no member to.
|
|
4782
|
+
*
|
|
4783
|
+
* **The margin is narrower than it first looks, and the specs say so where an
|
|
4784
|
+
* earlier draft of this docblock did not.** Every registered statement type -
|
|
4785
|
+
* `BlockStatement`, `ExpressionStatement`, `IfStatement` itself for an
|
|
4786
|
+
* `else if` chain, `VariableDeclaration` - is reached by a raw `callback` just
|
|
4787
|
+
* as well, because `acorn-walk` finds the registered visitor before it reaches
|
|
4788
|
+
* its base walker. So neither `if (a) { while (false) { 1 } }` nor an `else if`
|
|
4789
|
+
* chain discriminates: the block re-dispatches, and the chain arrives back here
|
|
4790
|
+
* either way. The one position that does is a **bare** branch body of an
|
|
4791
|
+
* unregistered type - `if (a) function f() { }` - where nothing stands between
|
|
4792
|
+
* this visitor and the base walker. Measured: swapping in a raw callback reddens
|
|
4793
|
+
* that case alone.
|
|
4794
|
+
*
|
|
4795
|
+
* It is still the right call, for the reason `dispatch-statement.ts` gives rather
|
|
4796
|
+
* than for a reason the suite can show: rule 2's single `callback`/`pop` pair
|
|
4797
|
+
* lives in one place, so the guarantee holds for whatever bare statement type a
|
|
4798
|
+
* later phase registers without this visitor being revisited.
|
|
4799
|
+
*
|
|
4800
|
+
* This visitor was `dispatchStatement`'s **third** importer, which is the
|
|
4801
|
+
* condition for giving it a module of its own. **Step 6 made that move**: the
|
|
4802
|
+
* dispatcher now lives in `dispatch-statement.ts`, with the rule and its history
|
|
4803
|
+
* in that module's docblock.
|
|
4804
|
+
*
|
|
4805
|
+
* **It pushes no scope, and there is no `try`/`finally` to pair.** Four routes a
|
|
4806
|
+
* binding could arrive by, all closed: a block body gets its scope from
|
|
4807
|
+
* `blockStatementVisitor`; `if (a) let x = 1` does not parse, since a lexical
|
|
4808
|
+
* declaration is not a legal bare statement body; `if (a) var x = 1` does parse,
|
|
4809
|
+
* reaches the dispatcher as a `VariableDeclaration`, and is rejected on `kind`
|
|
4810
|
+
* inside `variableDeclarationVisitor`; and `if (a) function f() { }` parses
|
|
4811
|
+
* under Annex B and is rejected by `dispatchStatement`'s throwing `default`.
|
|
4812
|
+
*
|
|
4813
|
+
* **The fourth is closed by the dispatcher and not by anything here**, which is
|
|
4814
|
+
* the one a later phase can reopen: a phase that registers `FunctionDeclaration`
|
|
4815
|
+
* gives this visitor a bare binding form with no enclosing block, and the
|
|
4816
|
+
* no-scope argument has to be re-made rather than inherited. `if (a) label: var
|
|
4817
|
+
* x = 1` is the same family. As of this step this visitor touches `EvalContext`
|
|
4818
|
+
* not at all, and the balance its specs assert on a reused context is the
|
|
4819
|
+
* enclosing visitors' to keep.
|
|
4820
|
+
*/
|
|
4821
|
+
const ifStatementVisitor = (node, st, callback) => {
|
|
4822
|
+
beforeVisitor(node, st);
|
|
4823
|
+
callback(node.test, st);
|
|
4824
|
+
const test = popVisitorResult(node, st);
|
|
4825
|
+
let completion = EMPTY_COMPLETION;
|
|
4826
|
+
if (test) {
|
|
4827
|
+
completion = dispatchStatement(node.consequent, st, callback);
|
|
4828
|
+
}
|
|
4829
|
+
else if (node.alternate) {
|
|
4830
|
+
completion = dispatchStatement(node.alternate, st, callback);
|
|
4831
|
+
}
|
|
4832
|
+
pushVisitorResult(node, st, completion);
|
|
4833
|
+
afterVisitor(node, st);
|
|
3794
4834
|
};
|
|
3795
|
-
|
|
3796
|
-
|
|
3797
|
-
|
|
3798
|
-
|
|
4835
|
+
|
|
4836
|
+
/**
|
|
4837
|
+
* Evaluates a classic three-part `for` statement.
|
|
4838
|
+
*
|
|
4839
|
+
* § 1.1's row measured **`NaN`** with three stranded values before Phase 2: the
|
|
4840
|
+
* base walker handed the declarator's `id` to `identifierVisitor`, so `i`
|
|
4841
|
+
* resolved against the context rather than binding, and `i < 3` compared
|
|
4842
|
+
* `undefined`. Since step 1 the row throws from `dispatchStatement`'s `default`;
|
|
4843
|
+
* this visitor is what returns `2`.
|
|
4844
|
+
*
|
|
4845
|
+
* `for…of`, `for…in`, `while` and `do…while` stay out of the phase (§ 2) and
|
|
4846
|
+
* keep throwing - they are separate node types and reach the dispatcher's
|
|
4847
|
+
* `default` unchanged.
|
|
4848
|
+
*
|
|
4849
|
+
* **One scope for the loop, not one per iteration.** A draft of the plan
|
|
4850
|
+
* specified a fresh scope per iteration, seeded from the head and copied back
|
|
4851
|
+
* after `update`, on the reasoning that this is what makes a closure capture its
|
|
4852
|
+
* own iteration's binding. It makes **no observable difference here**: the
|
|
4853
|
+
* closure `arrow-function-expression.ts` builds captures `st`, not a scope
|
|
4854
|
+
* chain, and resolves its free variables against `st.context` *as it is when the
|
|
4855
|
+
* closure is called* - by which time this loop has popped everything it pushed.
|
|
4856
|
+
* So the per-iteration design would have allocated a scope and copied bindings
|
|
4857
|
+
* twice per iteration to buy a property no spec can assert (§ 3.6.5). Giving
|
|
4858
|
+
* closures a captured scope chain is real work in
|
|
4859
|
+
* `arrow-function-expression.ts` and is what a later phase would have to do
|
|
4860
|
+
* first.
|
|
4861
|
+
*
|
|
4862
|
+
* **`init` has two node shapes and they take two routes.** `for (let i = 0; …)`
|
|
4863
|
+
* parses `init` as a `VariableDeclaration`, which is a `Statement` and goes
|
|
4864
|
+
* through `dispatchStatement`; `for (i = 0; …)` parses it as an `Expression` and
|
|
4865
|
+
* takes a raw `callback`. Both pop exactly one - the declaration's `EMPTY`, or
|
|
4866
|
+
* the expression's value - so § 3.1's arithmetic is identical for the two and
|
|
4867
|
+
* the split is invisible to it. What depends on the split is the throwing
|
|
4868
|
+
* `default`: only the `dispatchStatement` route has one, so an `init` that is a
|
|
4869
|
+
* statement type this library does not implement is rejected rather than handed
|
|
4870
|
+
* to the base walker. `body` is a `Statement` and dispatches for the same
|
|
4871
|
+
* reason; `test` and `update` are expressions and do not.
|
|
4872
|
+
*
|
|
4873
|
+
* Arithmetic (§ 3.1): pops 1 for `init` when present, then per iteration 1 for
|
|
4874
|
+
* `test` (when present), 1 for `body` and 1 for `update` (when present) - one
|
|
4875
|
+
* per `callback` or `dispatchStatement`, as rule 2 requires. Pushes exactly one
|
|
4876
|
+
* value on every exit path: the last **non-empty** body value, or
|
|
4877
|
+
* {@link EMPTY_COMPLETION} when the loop ran zero iterations or every iteration
|
|
4878
|
+
* produced nothing. An absent `test` is `true`.
|
|
4879
|
+
*
|
|
4880
|
+
* **The budget is the only terminator for `for (;;)`** - with no `break`,
|
|
4881
|
+
* `continue` or `return` in this phase (§ 2) there is no other way out, and a
|
|
4882
|
+
* runaway loop that silently returned a partial value is the failure § 3.4
|
|
4883
|
+
* exists to prevent. `chargeIteration` throws when the budget is spent; it is
|
|
4884
|
+
* called from this loop and nowhere else in the library, which is why an
|
|
4885
|
+
* expression with no `for` in it pays nothing for the bound.
|
|
4886
|
+
*
|
|
4887
|
+
* The pop is in a `finally` because the scope stack lives on `EvalContext`, not
|
|
4888
|
+
* on the per-walk `EvalState`, and one context can back any number of
|
|
4889
|
+
* evaluations: a scope this visitor failed to pop would outlive the walk and be
|
|
4890
|
+
* read first by every later evaluation on that context. This is the visitor with
|
|
4891
|
+
* the **highest push multiplicity** in the family and the shape of A9's own
|
|
4892
|
+
* precondition argument - a `for` body throwing on iteration 3 - so every exit
|
|
4893
|
+
* path matters: `init`, `test`, `body` and `update` can each throw, the
|
|
4894
|
+
* dispatcher can reject the body, and the budget can end the loop from inside
|
|
4895
|
+
* the `try`. The `try` opens *after* the push, never around it - `push` is
|
|
4896
|
+
* optionally chained, so bringing it inside would pair a `finally` pop with a
|
|
4897
|
+
* push the same optional chain had skipped.
|
|
4898
|
+
*/
|
|
4899
|
+
const forStatementVisitor = (node, st, callback) => {
|
|
4900
|
+
beforeVisitor(node, st);
|
|
4901
|
+
let completion = EMPTY_COMPLETION;
|
|
4902
|
+
st.context?.push({}, st.options);
|
|
4903
|
+
try {
|
|
4904
|
+
if (node.init) {
|
|
4905
|
+
if (node.init.type === 'VariableDeclaration') {
|
|
4906
|
+
dispatchStatement(node.init, st, callback);
|
|
4907
|
+
}
|
|
4908
|
+
else {
|
|
4909
|
+
callback(node.init, st);
|
|
4910
|
+
popVisitorResult(node, st);
|
|
4911
|
+
}
|
|
4912
|
+
}
|
|
4913
|
+
for (;;) {
|
|
4914
|
+
if (node.test) {
|
|
4915
|
+
callback(node.test, st);
|
|
4916
|
+
if (!popVisitorResult(node, st)) {
|
|
4917
|
+
break;
|
|
4918
|
+
}
|
|
4919
|
+
}
|
|
4920
|
+
// Charged once the test has admitted the iteration, so a loop that runs
|
|
4921
|
+
// `n` bodies charges `n` - which is what `iterationsRemaining` is asserted
|
|
4922
|
+
// against - and a loop whose test is false at the top charges nothing.
|
|
4923
|
+
st.chargeIteration();
|
|
4924
|
+
const value = dispatchStatement(node.body, st, callback);
|
|
4925
|
+
if (value !== EMPTY_COMPLETION) {
|
|
4926
|
+
completion = value;
|
|
4927
|
+
}
|
|
4928
|
+
if (node.update) {
|
|
4929
|
+
callback(node.update, st);
|
|
4930
|
+
popVisitorResult(node, st);
|
|
4931
|
+
}
|
|
4932
|
+
}
|
|
4933
|
+
}
|
|
4934
|
+
finally {
|
|
4935
|
+
st.context?.pop();
|
|
4936
|
+
}
|
|
4937
|
+
pushVisitorResult(node, st, completion);
|
|
4938
|
+
afterVisitor(node, st);
|
|
3799
4939
|
};
|
|
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
4940
|
|
|
3808
4941
|
const defaultEvalScopeOptions = {
|
|
3809
4942
|
global: false,
|
|
@@ -4726,5 +5859,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.8", ngImpor
|
|
|
4726
5859
|
* Generated bundle index. Do not edit.
|
|
4727
5860
|
*/
|
|
4728
5861
|
|
|
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 };
|
|
5862
|
+
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
5863
|
//# sourceMappingURL=zvenigora-ng-eval-core.mjs.map
|