@zvenigora/ng-eval-core 0.14.1 → 0.15.1

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.
@@ -1,8 +1,8 @@
1
1
  import * as i0 from '@angular/core';
2
2
  import { InjectionToken, inject, makeEnvironmentProviders, provideEnvironmentInitializer, Injectable } from '@angular/core';
3
3
  import { sha256 } from 'js-sha256';
4
- import { tokTypes, Parser, parse as parse$1, defaultOptions, version } from 'acorn';
5
4
  import * as walk from 'acorn-walk';
5
+ import { defaultOptions, tokTypes, Parser, parse as parse$1, version } from 'acorn';
6
6
 
7
7
  /**
8
8
  * Represents a registry that stores key-value pairs.
@@ -1174,10 +1174,10 @@ let entriesCreated = 0;
1174
1174
  *
1175
1175
  * A key found before is still the answer while it is still an own key of the
1176
1176
  * object, which is checked without a scan. One deleted or renamed since is
1177
- * scanned for again. A miss stays a miss while the object's own-key count is
1178
- * unchanged; a key added since changes the count, and the object's answers
1179
- * are made afresh. Not caught: a key added in the same interval as another is
1180
- * deleted, which leaves the count as it was, so a cached miss can outlive it.
1177
+ * scanned for again. A miss stays a miss while the object's own names are the
1178
+ * ones it was made from, in order; any difference, a key added in the same
1179
+ * interval as another is deleted included, and the object's answers are made
1180
+ * afresh (`docs/backlog-retired.md` A33).
1181
1181
  */
1182
1182
  function getCachedCaseInsensitiveProperty(obj, searchKey, equalIgnoreCase) {
1183
1183
  if (!obj || typeof obj !== 'object') {
@@ -1190,8 +1190,8 @@ function getCachedCaseInsensitiveProperty(obj, searchKey, equalIgnoreCase) {
1190
1190
  return cached;
1191
1191
  }
1192
1192
  const ownKeys = Object.getOwnPropertyNames(obj);
1193
- if (!entry || entry.keyCount !== ownKeys.length) {
1194
- entry = { keyCount: ownKeys.length, found: new Map() };
1193
+ if (!entry || !sameNames(entry.keys, ownKeys)) {
1194
+ entry = { keys: ownKeys, found: new Map() };
1195
1195
  propertyLookupCache.set(obj, entry);
1196
1196
  entriesCreated++;
1197
1197
  }
@@ -1202,6 +1202,17 @@ function getCachedCaseInsensitiveProperty(obj, searchKey, equalIgnoreCase) {
1202
1202
  entry.found.set(lowered, foundKey);
1203
1203
  return foundKey;
1204
1204
  }
1205
+ const sameNames = (a, b) => {
1206
+ if (a.length !== b.length) {
1207
+ return false;
1208
+ }
1209
+ for (let i = 0; i < a.length; i++) {
1210
+ if (a[i] !== b[i]) {
1211
+ return false;
1212
+ }
1213
+ }
1214
+ return true;
1215
+ };
1205
1216
  /**
1206
1217
  * Clears the property lookup cache (for testing or memory management)
1207
1218
  */
@@ -1210,8 +1221,9 @@ function clearPropertyLookupCache() {
1210
1221
  entriesCreated = 0;
1211
1222
  }
1212
1223
  /**
1213
- * Gets current property lookup cache statistics: the number of objects given
1214
- * an entry since the last clear, live or collected.
1224
+ * Gets current property lookup cache statistics: the number of entries made
1225
+ * since the last clear, live or collected; an object gets a new one when a
1226
+ * lookup that is not a cached hit finds its own names changed.
1215
1227
  */
1216
1228
  function getPropertyLookupCacheStats() {
1217
1229
  return {
@@ -3268,28 +3280,57 @@ const importExpressionVisitor = (node, st) => {
3268
3280
  throw new Error('Function call blocked for security reasons: import');
3269
3281
  };
3270
3282
 
3271
- // Default timeout for await expressions (30 seconds)
3272
- const DEFAULT_AWAIT_TIMEOUT = 30000;
3273
- /**
3274
- * Creates a timeout promise that rejects after the specified timeout
3275
- */
3276
- const createTimeoutPromise = (timeout) => {
3277
- return new Promise((_, reject) => {
3278
- setTimeout(() => {
3279
- reject(new Error(`Await expression timed out after ${timeout}ms`));
3280
- }, timeout);
3281
- });
3282
- };
3283
- /**
3284
- * Safely wraps a value in a promise if it's not already a promise
3285
- */
3286
- const ensurePromise = (value) => {
3287
- if (value && typeof value === 'object' && 'then' in value) {
3288
- return value;
3283
+ // The refusal names `await` and the rule (`docs/backlog-retired.md` A24).
3284
+ const AWAIT_POSITION_MESSAGE = 'Unsupported await position: an await is evaluated only as the result of the expression - the whole expression, an arrow function\'s expression body, or the last statement of a program or of an arrow function\'s block body.';
3285
+ const asAwait = (node) => {
3286
+ const inner = unwrapParentheses(node);
3287
+ return inner.type === 'AwaitExpression' ? inner : undefined;
3288
+ };
3289
+ const lastStatementAwait = (body) => {
3290
+ const last = body[body.length - 1];
3291
+ return last?.type === 'ExpressionStatement' ? asAwait(last.expression) : undefined;
3292
+ };
3293
+ /**
3294
+ * The one `await` a walk rooted at `root` accepts, the one whose value is the
3295
+ * walk's result: the root itself; or the expression of the last statement of
3296
+ * a `Program`, or of an arrow function's `BlockStatement` body when
3297
+ * `arrowBody` is set. Read off the root one level deep, so nothing is
3298
+ * traversed, and computed per walk, so nothing is stored: the same node is
3299
+ * accepted as one walk's root and refused as another's operand
3300
+ * (`docs/backlog-retired.md` A24).
3301
+ *
3302
+ * Under `preserveParens` the root and the last statement's expression are
3303
+ * unwrapped first, as the assignment and update visitors unwrap their
3304
+ * targets, so `(await p)` is accepted where `await p` is. Only those two
3305
+ * places are unwrapped: a parenthesised operand, `((await p)) * 10`, is still
3306
+ * an operand, and the walk refuses it.
3307
+ *
3308
+ * @param root The node the walk starts at.
3309
+ * @param arrowBody Whether the walk is an arrow function's body.
3310
+ * @returns The accepted `await`, or `undefined`.
3311
+ */
3312
+ const acceptedAwait = (root, arrowBody) => {
3313
+ const rootAwait = asAwait(root);
3314
+ if (rootAwait) {
3315
+ return rootAwait;
3316
+ }
3317
+ if (!arrowBody && root.type === 'Program') {
3318
+ return lastStatementAwait(root.body);
3319
+ }
3320
+ if (arrowBody && root.type === 'BlockStatement') {
3321
+ return lastStatementAwait(root.body);
3289
3322
  }
3290
- return Promise.resolve(value);
3323
+ return undefined;
3291
3324
  };
3292
- const awaitVisitor = (node, st, callback) => {
3325
+ const awaitVisitor = (node, st, callback, accepted = false) => {
3326
+ // Above `beforeVisitor`, as the `var` kind check is: the refusal reads the
3327
+ // node's position and nothing else, so a refused `await` fires no hook and
3328
+ // leaves no trace entry. The default table's entry refuses every `await`;
3329
+ // a walk that has an accepted one passes `accepted` for it alone
3330
+ // (`functions/evaluate.ts`).
3331
+ if (!accepted) {
3332
+ throw new Error(AWAIT_POSITION_MESSAGE);
3333
+ }
3293
3334
  beforeVisitor(node, st);
3294
3335
  // Outside any `Promise` executor, and uncaught here, as in every other
3295
3336
  // visitor: a synchronous throw from the operand propagates synchronously, and
@@ -3299,30 +3340,10 @@ const awaitVisitor = (node, st, callback) => {
3299
3340
  // (`docs/backlog-retired.md` A1).
3300
3341
  callback(node.argument, st);
3301
3342
  const value = popVisitorResult(node, st);
3302
- // Convert value to promise if it's not already one
3303
- const valuePromise = ensurePromise(value);
3304
- // Get timeout from context or use default
3305
- const contextObj = st.context?.original;
3306
- const timeout = (contextObj && typeof contextObj['__awaitTimeout'] === 'number'
3307
- ? contextObj['__awaitTimeout']
3308
- : DEFAULT_AWAIT_TIMEOUT);
3309
- // Race between the actual promise and timeout
3310
- const promise = Promise.race([
3311
- valuePromise,
3312
- createTimeoutPromise(timeout)
3313
- ])
3314
- .catch((error) => {
3315
- // Enhance error information with context
3316
- const enhancedError = error instanceof Error
3317
- ? error
3318
- : new Error(`Await expression failed: ${String(error)}`);
3319
- // Add source location information if available
3320
- if (node.start !== undefined && node.end !== undefined) {
3321
- enhancedError.message += ` at position ${node.start}-${node.end}`;
3322
- }
3323
- throw enhancedError;
3324
- });
3325
- pushVisitorResult(node, st, promise);
3343
+ // Passed through unchanged: nothing races it, wraps it, reads a timeout
3344
+ // for it or rewrites its rejection (`docs/backlog-retired.md` A25). A
3345
+ // promise that reaches the result is resolved there by `evaluateAsync`.
3346
+ pushVisitorResult(node, st, value);
3326
3347
  afterVisitor(node, st);
3327
3348
  };
3328
3349
 
@@ -3530,16 +3551,56 @@ const templateLiteralVisitor = (node, st, callback) => {
3530
3551
  };
3531
3552
 
3532
3553
  /**
3533
- * The tag's arguments: the template's cooked strings, then the value of each
3534
- * of its expressions, evaluated in order.
3554
+ * Each template site's template object, by its `TemplateLiteral` node.
3555
+ *
3556
+ * A module-level weak collection keyed by an AST node and never cleared, as
3557
+ * `dangerous-values.ts`' `exemptNodes` is, and keyed by an object as
3558
+ * `property-lookup-cache.ts` is: an entry lives exactly as long as its node,
3559
+ * and nothing one node holds can be read for another. What it does not do,
3560
+ * beside that cache: it has no clear and no statistics, and is never
3561
+ * invalidated, since a node's strings do not change - for an AST its caller
3562
+ * leaves alone; one that rewrites a node's `quasis` after a first evaluation
3563
+ * keeps the old object, as `exemptNodes` keeps its marks. The object is shared
3564
+ * by every walk of the node, over any state and context, and through a
3565
+ * `ParserService`'s parse cache by every consumer of that service - in an
3566
+ * application, the root singleton - parsing the same text with the same
3567
+ * options. That is safe because the object is frozen and holds only the
3568
+ * template's own strings.
3569
+ */
3570
+ const templateObjects = new WeakMap();
3571
+ /**
3572
+ * The site's template object, as JavaScript builds it: the cooked strings,
3573
+ * an invalid escape's cooked string `undefined`, with a non-enumerable `raw`
3574
+ * of the uncooked strings, both frozen, and the same object every time the
3575
+ * site runs (`docs/backlog-retired.md` A38). Up to 0.14.1 it was a plain array
3576
+ * of the cooked strings, built on every evaluation, with no `raw`.
3577
+ *
3578
+ * Not added to `st.createdObjects`: the walk did not create it for the
3579
+ * expression to hold, as `EvalMemberWrite.createdByEvaluation` defines
3580
+ * created, so a write policy is asked about it as about any other object.
3581
+ */
3582
+ const templateObject = (quasi) => {
3583
+ let strings = templateObjects.get(quasi);
3584
+ if (!strings) {
3585
+ const cooked = quasi.quasis.map((element) => element.value.cooked ?? undefined);
3586
+ const raw = Object.freeze(quasi.quasis.map((element) => element.value.raw));
3587
+ // Not writable, enumerable or configurable, as JavaScript defines it.
3588
+ Object.defineProperty(cooked, 'raw', { value: raw });
3589
+ strings = Object.freeze(cooked);
3590
+ templateObjects.set(quasi, strings);
3591
+ }
3592
+ return strings;
3593
+ };
3594
+ /**
3595
+ * The tag's arguments: the template object, then the value of each of its
3596
+ * expressions, evaluated in order.
3535
3597
  */
3536
3598
  const templateArguments = (node, st, callback) => {
3537
3599
  const values = node.quasi.expressions.map((expression) => {
3538
3600
  callback(expression, st);
3539
3601
  return popVisitorResult(node, st);
3540
3602
  });
3541
- const strings = node.quasi.quasis.map((templateElement) => templateElement.value.cooked);
3542
- return [strings, ...values];
3603
+ return [templateObject(node.quasi), ...values];
3543
3604
  };
3544
3605
  /**
3545
3606
  * Calls the tag as a call calls its callee (`call-expression.ts`): past the
@@ -3963,6 +4024,53 @@ const evaluateRestElement = (pattern, st, callback, args) => {
3963
4024
  // return object;
3964
4025
  // }
3965
4026
 
4027
+ /**
4028
+ * The statement types `dispatchStatement` walks, and the one place they are
4029
+ * listed.
4030
+ *
4031
+ * `VariableDeclaration` covers `var` as well, and cannot not: this table reads
4032
+ * the node *type*, and `var x = 1` is a `VariableDeclaration` exactly as
4033
+ * `let x = 1` is. Listing it here is therefore what stops `var` reaching the
4034
+ * dispatcher's throw; its rejection is `declarationKindRefusal`, below, which
4035
+ * the visitor calls because it can read `kind`.
4036
+ *
4037
+ * `ForStatement` is the classic three-part form *only*. `ForOfStatement`,
4038
+ * `ForInStatement`, `WhileStatement` and `DoWhileStatement` are distinct node
4039
+ * types and stay out of the table, so they are refused unchanged - unlike
4040
+ * `var`, which shares a type with `let` and is refused one level down.
4041
+ */
4042
+ const SUPPORTED_STATEMENT_TYPES = new Set([
4043
+ 'ExpressionStatement',
4044
+ 'EmptyStatement',
4045
+ 'BlockStatement',
4046
+ 'VariableDeclaration',
4047
+ 'IfStatement',
4048
+ 'ForStatement',
4049
+ ]);
4050
+ /** The `VariableDeclaration` kinds the declaration visitor binds. */
4051
+ const SUPPORTED_DECLARATION_KINDS = new Set(['let', 'const']);
4052
+ /**
4053
+ * The message evaluation throws for a statement whose type it does not walk,
4054
+ * or `undefined` for one it does.
4055
+ *
4056
+ * `dispatchStatement` throws it, and `findUnsupportedStatement` reports it, so
4057
+ * the evaluator and the export cannot disagree about a type (`docs/backlog.md`
4058
+ * D13).
4059
+ */
4060
+ const statementTypeRefusal = (statement) => SUPPORTED_STATEMENT_TYPES.has(statement.type)
4061
+ ? undefined
4062
+ : `Unsupported statement type: ${statement.type}`;
4063
+ /**
4064
+ * The message evaluation throws for a declaration whose kind it does not bind,
4065
+ * `var` among them, or `undefined` for `let` and `const`.
4066
+ *
4067
+ * `variableDeclarationVisitor` throws it above its `beforeVisitor`, and
4068
+ * `findUnsupportedStatement` reports it.
4069
+ */
4070
+ const declarationKindRefusal = (declaration) => SUPPORTED_DECLARATION_KINDS.has(declaration.kind)
4071
+ ? undefined
4072
+ : `Unsupported variable declaration kind: ${declaration.kind}`;
4073
+
3966
4074
  /**
3967
4075
  * The scope a declaration binds into: the innermost one on the stack.
3968
4076
  *
@@ -4046,7 +4154,7 @@ const bindDeclarator = (declarator, value, kind, scope, st, callback) => {
4046
4154
  * **`var` is rejected here, not by the statement dispatcher.** The dispatcher
4047
4155
  * switches on node *type*, and `var x = 1` is a `VariableDeclaration` exactly as
4048
4156
  * `let x = 1` is - so registering this visitor is what stopped `var` reaching the
4049
- * throwing `default:`. Function-scoped hoisting is a second scoping model beside
4157
+ * dispatcher's throw. Function-scoped hoisting is a second scoping model beside
4050
4158
  * block scoping and is out of scope for this phase, so the rejection had to move
4051
4159
  * rather than disappear.
4052
4160
  *
@@ -4062,8 +4170,11 @@ const variableDeclarationVisitor = (node, st, callback) => {
4062
4170
  // from opening a frame it never closes. The others are covered the way every
4063
4171
  // throwing visitor in this library is: `evaluate`'s `catch` unwinds the open
4064
4172
  // nodes to its walk base.
4065
- if (node.kind !== 'let' && node.kind !== 'const') {
4066
- throw new Error(`Unsupported variable declaration kind: ${node.kind}`);
4173
+ // The kinds are `statement-support.ts`' table, which
4174
+ // `findUnsupportedStatement` reads too.
4175
+ const refusal = declarationKindRefusal(node);
4176
+ if (refusal !== undefined) {
4177
+ throw new Error(refusal);
4067
4178
  }
4068
4179
  beforeVisitor(node, st);
4069
4180
  const scope = bindingScope(st);
@@ -4345,238 +4456,13 @@ const updateExpressionVisitor = (node, st, callback) => {
4345
4456
  afterVisitor(node, st);
4346
4457
  };
4347
4458
 
4348
- /**
4349
- * @description
4350
- * The colon-joined name grammar of `docs/colon-identifiers/phase-9-plan.md`
4351
- * § 3.4, as an acorn plugin (§ 3.5). `parse` uses the parser built here when
4352
- * `colonIdentifiers` is set, and acorn's own `parse` otherwise. No source text
4353
- * is rewritten, so every position acorn reports is a position in what the
4354
- * author wrote. Not re-exported from any barrel.
4355
- *
4356
- * Of acorn's documented API this module uses `Parser.extend`, `tokTypes` and
4357
- * the `input` member. Everything else it touches is an acorn internal,
4358
- * undeclared in acorn's `.d.ts`, and this is the complete list — what § 8 q3
4359
- * checks at the `acorn` peer floor:
4360
- *
4361
- * - members read: `pos`, `start`, `type`, `value`, `keywords`;
4362
- * - members written: `pos`, `containsEsc`;
4363
- * - methods overridden, each calling acorn's own through `super`: `readWord`,
4364
- * `finishToken`, `parsePropertyName`, `parseStatement`, `unexpected`;
4365
- * - methods called: `finishToken`, `raise`;
4366
- * - what the overrides assume of acorn's tokenizer: `readToken` is the only
4367
- * caller of `readWord`, with `pos` at the token's first character; every
4368
- * token is finished through `finishToken`, in source order, before the next
4369
- * is read — except that a `/` read as `slash` is finished again as
4370
- * `regexp`, and neither type is counted here; `?.`, `??` and `??=` are never
4371
- * `question` tokens; the `}` that closes a `${` is finished as `braceR`; the
4372
- * constructor reads no token;
4373
- * - what they assume of acorn's parser: every key of an object literal, an
4374
- * object pattern or a class body is read through `parsePropertyName`, with
4375
- * the key as the current token; every statement through `parseStatement`,
4376
- * with its first token as the current token; a colon the grammar cannot
4377
- * place reaches `unexpected`, from `expect` or `semicolon`, with `type` and
4378
- * `start` still at that colon.
4379
- *
4380
- * The token types it compares by identity, from `tokTypes`: `name`, `colon`,
4381
- * `question`, `comma`, `semi`, `parenL`, `parenR`, `bracketL`, `bracketR`,
4382
- * `braceL`, `braceR`, `dollarBraceL`.
4383
- */
4384
- const COLON = 58;
4385
- /** `[A-Za-z_$]`: the first character of a name that may join. */
4386
- const isFirstChar = (code) => (code >= 65 && code <= 90) || (code >= 97 && code <= 122) || code === 95 || code === 36;
4387
- /** `[A-Za-z0-9_$]`: any later character, and a segment's first. */
4388
- const isSegmentChar = (code) => isFirstChar(code) || (code >= 48 && code <= 57);
4389
- /** Whether a `:segment` starts at `pos`: a colon with a segment character after it. */
4390
- const joinsAt = (input, pos) => input.charCodeAt(pos) === COLON && isSegmentChar(input.charCodeAt(pos + 1));
4391
- const colonIdentifiers = (Base) => {
4392
- class ColonParser extends Base {
4393
- constructor() {
4394
- super(...arguments);
4395
- /** Never empty: the top level is never closed. */
4396
- this.levels = [{ pending: 0 }];
4397
- /**
4398
- * The level the current token was read at: for a `(`, `[`, `{` or `${`,
4399
- * the one around the level it opened.
4400
- */
4401
- this.tokenLevel = this.levels[0];
4402
- }
4403
- get level() {
4404
- return this.levels[this.levels.length - 1];
4405
- }
4406
- /**
4407
- * Reads a colon-joined name as one `name` token when one starts at `pos`
4408
- * and no `?` at this level is waiting for its `:` (§ 3.4, 1). In every
4409
- * other case acorn's own `readWord`, so a word that does not join is read
4410
- * exactly as acorn reads it.
4411
- */
4412
- readWord() {
4413
- const end = this.colonNameEnd();
4414
- if (end === undefined) {
4415
- return super.readWord();
4416
- }
4417
- const name = this.input.slice(this.pos, end);
4418
- if (this.level.pending > 0) {
4419
- this.level.suppressed = name;
4420
- return super.readWord();
4421
- }
4422
- this.pos = end;
4423
- this.containsEsc = false;
4424
- this.finishToken(tokTypes.name, name);
4425
- }
4426
- /**
4427
- * Where the colon name that starts at `pos` ends — its longest match — or
4428
- * `undefined` when none does: the first segment is not ASCII, is a keyword
4429
- * of the parse's `ecmaVersion`, or has no `:segment` directly after it.
4430
- */
4431
- colonNameEnd() {
4432
- const input = this.input;
4433
- let end = this.pos;
4434
- if (!isFirstChar(input.charCodeAt(end))) {
4435
- return undefined;
4436
- }
4437
- do {
4438
- end++;
4439
- } while (isSegmentChar(input.charCodeAt(end)));
4440
- if (!joinsAt(input, end) || this.keywords.test(input.slice(this.pos, end))) {
4441
- return undefined;
4442
- }
4443
- do {
4444
- end += 2;
4445
- while (isSegmentChar(input.charCodeAt(end))) {
4446
- end++;
4447
- }
4448
- } while (joinsAt(input, end));
4449
- return end;
4450
- }
4451
- /**
4452
- * Keeps the levels after acorn has finished the token, recording the one
4453
- * the token was read at: `(`, `[`, `{` and `${` open a level and `)`, `]`
4454
- * and `}` close it; a `?` is counted at its level and a `:` there
4455
- * uncounts it. `?.` and `??` are other token types, and count for nothing.
4456
- */
4457
- finishToken(type, value) {
4458
- super.finishToken(type, value);
4459
- const level = this.level;
4460
- this.tokenLevel = level;
4461
- switch (type) {
4462
- case tokTypes.parenL:
4463
- case tokTypes.bracketL:
4464
- case tokTypes.braceL:
4465
- case tokTypes.dollarBraceL:
4466
- this.levels.push({ pending: 0 });
4467
- break;
4468
- case tokTypes.parenR:
4469
- case tokTypes.bracketR:
4470
- case tokTypes.braceR:
4471
- if (this.levels.length > 1) {
4472
- this.levels.pop();
4473
- }
4474
- break;
4475
- case tokTypes.question:
4476
- level.pending++;
4477
- break;
4478
- case tokTypes.colon:
4479
- if (level.pending > 0) {
4480
- level.pending--;
4481
- }
4482
- break;
4483
- case tokTypes.comma:
4484
- case tokTypes.semi:
4485
- level.suppressed = undefined;
4486
- break;
4487
- }
4488
- }
4489
- /**
4490
- * Refuses a colon name as an object key, in a literal or a pattern alike
4491
- * (§ 3.4, 2): `{Q1:1}` is `{Q1: 1}` to JavaScript and a shorthand to the
4492
- * grammar, and keeping either would answer some author wrongly. Only a
4493
- * joined token is a `name` holding a colon.
4494
- */
4495
- parsePropertyName(prop) {
4496
- const name = this.value;
4497
- if (this.type === tokTypes.name && typeof name === 'string' && name.includes(':')) {
4498
- const first = name.slice(0, name.indexOf(':'));
4499
- this.raise(this.start, `Colon-joined name '${name}' cannot be an object key: ` +
4500
- `write '${first}: ...' with a space for a property, or quote the key`);
4501
- }
4502
- return super.parsePropertyName(prop);
4503
- }
4504
- /**
4505
- * Forgets the name not joined at the level a statement starts at: the
4506
- * statement boundary ended the conditional whose consequent lost it. A
4507
- * semicolon acorn inserts at a line break is such a boundary, and no `;`
4508
- * token marks it.
4509
- */
4510
- parseStatement(...args) {
4511
- this.tokenLevel.suppressed = undefined;
4512
- return super.parseStatement(...args);
4513
- }
4514
- /**
4515
- * acorn's own error, with the hint of § 3.4, 1 when the unexpected token
4516
- * is a `:` at a level that did not join a name since its last `,`, `;` or
4517
- * statement start: the colon the name lost to the conditional. Any other
4518
- * error is left as acorn words it.
4519
- */
4520
- unexpected(pos) {
4521
- const suppressed = this.tokenLevel.suppressed;
4522
- if (suppressed !== undefined && this.type === tokTypes.colon &&
4523
- (pos === undefined || pos === this.start)) {
4524
- return this.raise(this.start, 'Unexpected token: a colon-joined name in the ' +
4525
- `consequent of a conditional needs parentheses: (${suppressed})`);
4526
- }
4527
- return super.unexpected(pos);
4528
- }
4529
- }
4530
- return ColonParser;
4531
- };
4532
- /**
4533
- * acorn's `Parser` with the grammar, built once, at module load. `extend`
4534
- * returns a subclass, so acorn's own `Parser`, which `acorn.parse` uses, is
4535
- * left as it was.
4536
- */
4537
- const ColonIdentifiersParser = Parser.extend(colonIdentifiers);
4538
-
4539
- /**
4540
- * @description
4541
- * Parses expression and returns ES6/ES2020 AST.
4542
- * With `colonIdentifiers` set the parser is the colon-joined name grammar's;
4543
- * otherwise it is acorn's own `parse`.
4544
- * @param expr expression to parse
4545
- * @param options parser options
4546
- */
4547
- const parse = (expr, options) => {
4548
- options = { ecmaVersion: 2020, ...options };
4549
- const acornOptions = { ecmaVersion: 2020, ...options };
4550
- const program = options.colonIdentifiers
4551
- ? ColonIdentifiersParser.parse(expr, acornOptions)
4552
- : parse$1(expr, acornOptions);
4553
- if (!options.extractExpressions) {
4554
- return program;
4555
- }
4556
- return extractExpression(program);
4557
- };
4558
- /**
4559
- * @description
4560
- * Walks through the AST and extracts first expression.
4561
- * @param expr expression to parse
4562
- */
4563
- const extractExpression = (program) => {
4564
- if (program.body.length === 1) {
4565
- const expression = program.body[0];
4566
- if (expression.type === 'ExpressionStatement') {
4567
- return expression.expression;
4568
- }
4569
- }
4570
- return undefined;
4571
- };
4572
-
4573
4459
  /**
4574
4460
  * Applies § 3.1's rule 4: the empty-completion sentinel never leaves an
4575
4461
  * evaluation's return value.
4576
4462
  *
4577
4463
  * It is converted here, at the walk boundary, rather than in the `Program`
4578
- * visitor. `arrow-function-expression.ts` calls `evaluate` on a
4579
- * `BlockStatement` for a block-bodied arrow, so a conversion sited in `Program`
4464
+ * visitor. `arrow-function-expression.ts` walks a `BlockStatement` for a
4465
+ * block-bodied arrow, so a conversion sited in `Program`
4580
4466
  * would let `x => { }` hand the sentinel straight to a consumer. Converting
4581
4467
  * where the walk ends covers both entry points by construction.
4582
4468
  */
@@ -4615,7 +4501,7 @@ const completionValue = (value) => value === EMPTY_COMPLETION ? undefined : valu
4615
4501
  * mutation into a throw. `getDefaultVisitors()` still returns a **fresh,
4616
4502
  * mutable** object to anyone who calls it, so no caller loses anything.
4617
4503
  * - **Lazily** because a module-level `const` deadlocks the flattened bundle:
4618
- * `arrow-function-expression.ts` imports `evaluate`, so this module is
4504
+ * `arrow-function-expression.ts` imports `walkWithoutResult`, so this module is
4619
4505
  * initialised first and `getDefaultVisitors()` at module scope reads that
4620
4506
  * visitor before its binding exists. Measured, not guessed - the built
4621
4507
  * package threw `Cannot access 'arrowFunctionExpressionVisitor' before
@@ -4624,66 +4510,121 @@ const completionValue = (value) => value === EMPTY_COMPLETION ? undefined : valu
4624
4510
  let defaultVisitors;
4625
4511
  const mergedVisitors = () => (defaultVisitors ??= Object.freeze(walk.make(getDefaultVisitors())));
4626
4512
  /**
4627
- * Evaluates the given node and returns the result.
4628
- *
4629
- * @param node The node to evaluate.
4513
+ * The table a walk rooted at `root` dispatches through: the shared one, whose
4514
+ * `AwaitExpression` entry refuses every `await`, or - when the root has an
4515
+ * accepted `await` (`acceptedAwait`) - a fresh object over it whose own entry
4516
+ * accepts that node alone (`docs/backlog-retired.md` A24).
4517
+ *
4518
+ * The answer travels with the walk, not on the state or the node: the arrow
4519
+ * function's nested walk builds its own from its own root, so an enclosing
4520
+ * walk's accepted `await` is never in scope where it is not one. The entry is
4521
+ * defined, not assigned: `walk.make` would assign a `funcs` key onto an object
4522
+ * over the frozen table, which throws in strict mode. A walk with no accepted
4523
+ * `await` takes the shared table and pays nothing; one that has one builds a
4524
+ * single object, uncached.
4525
+ */
4526
+ const visitorsFor = (root, arrowBody) => {
4527
+ const accepted = acceptedAwait(root, arrowBody);
4528
+ return accepted
4529
+ ? Object.create(mergedVisitors(), {
4530
+ AwaitExpression: {
4531
+ value: (n, s, c) => awaitVisitor(n, s, c, n === accepted),
4532
+ },
4533
+ })
4534
+ : mergedVisitors();
4535
+ };
4536
+ /**
4537
+ * Walks the node on the state and returns its completion value, recording no
4538
+ * outcome: everything {@link evaluate} does except `state.result`'s `start`,
4539
+ * `stop`, `setSuccess` and `setFailure`.
4540
+ *
4541
+ * **The arrow-function body's walk** (`arrow-function-expression.ts`). That
4542
+ * body runs on the walk's own state, during the walk, after it, many times or
4543
+ * never, and up to 0.14.1 it ran through `evaluate` - so every call of an arrow
4544
+ * wrote its outcome, value and start time over the enclosing walk's result, and
4545
+ * a closure called after the walk wrote over the finished one
4546
+ * (`docs/backlog-retired.md` A27). The result now describes the entry-point walk alone.
4547
+ *
4548
+ * Not exported from the package: `functions/public-api.ts` does not list it.
4549
+ *
4550
+ * @param node The node to walk.
4630
4551
  * @param state The evaluation state.
4631
- * @returns The result of the evaluation.
4552
+ * @param arrowBody Whether the node is an arrow function's body, which
4553
+ * decides the `await` it accepts (`visitorsFor`).
4554
+ * @returns The node's completion value.
4555
+ */
4556
+ const walkWithoutResult = (node, state, arrowBody = false) => {
4557
+ // The mark is recorded on the state as well as held here, so that
4558
+ // `EvalHooks.exit` - called from a visitor, which has no route to this
4559
+ // local - can tell a node open in this walk from one open only in an
4560
+ // enclosing walk. Pushed under the same guard the mark is read under, and
4561
+ // the local `hooked` keeps the pair symmetric if a hook is registered
4562
+ // mid-walk.
4563
+ const hooked = state.hasHooks;
4564
+ const mark = hooked ? state.hooks.pushWalkBase(state) : 0;
4565
+ // Unguarded, unlike the walk base above: the iteration budget refills on
4566
+ // the outermost entry whether or not hooks are registered. See
4567
+ // `EvalState.walkDepth` on why these are two fields and not one.
4568
+ state.enterWalk();
4569
+ try {
4570
+ walk.recursive(node, state, {}, visitorsFor(node, arrowBody));
4571
+ return completionValue(popVisitorResult(node, state));
4572
+ }
4573
+ catch (error) {
4574
+ // A visitor that throws skips its afterVisitor, so close whatever this
4575
+ // walk left open. Unwinding to the mark rather than to the bottom is what
4576
+ // stops a nested walk - the arrow-function body runs on this same
4577
+ // state - from draining the enclosing walk's open nodes.
4578
+ // Reads `state.hasHooks` rather than the `hooked` local captured above,
4579
+ // and the difference is deliberate but narrow: if a hook was registered
4580
+ // *during* this walk then `hooked` is false, no base was pushed, `mark`
4581
+ // is 0, and this unwinds the whole stack - including an enclosing walk's
4582
+ // frames, which is the boundary crossing the walk base exists to stop.
4583
+ // Left as it was rather than tightened here, because narrowing it would
4584
+ // change what a mid-walk registration observes on an already-published
4585
+ // path, which is not this step's to decide.
4586
+ if (state.hasHooks) {
4587
+ state.hooks.unwindTo(mark, error, state);
4588
+ }
4589
+ throw error;
4590
+ }
4591
+ finally {
4592
+ // Both in a `finally`: a walk that threw still has to restore the
4593
+ // enclosing walk's bound and depth, or every later evaluation on this
4594
+ // state carries this one's nesting.
4595
+ state.exitWalk();
4596
+ if (hooked) {
4597
+ state.hooks.popWalkBase(state);
4598
+ }
4599
+ }
4600
+ };
4601
+ /**
4602
+ * Evaluates the given node and returns the result.
4603
+ *
4604
+ * Records the walk's outcome on `state.result`. An arrow function's body,
4605
+ * walked on the same state whenever the function is called, records nothing
4606
+ * there.
4607
+ *
4608
+ * @param node The node to evaluate.
4609
+ * @param state The evaluation state.
4610
+ * @returns The result of the evaluation.
4632
4611
  */
4633
4612
  const evaluate = (node, state) => {
4613
+ // The `if (node)` guard comes first on purpose: callers reach the early
4614
+ // return below with a bare state that has no result or hooks to read.
4634
4615
  if (node) {
4635
4616
  state.result.start();
4636
- // Captured inside the `if (node)` block on purpose: callers reach the early
4637
- // return above with a bare state that has no hooks to read. Do not hoist.
4638
- //
4639
- // The mark is recorded on the state as well as held here, so that
4640
- // `EvalHooks.exit` - called from a visitor, which has no route to this
4641
- // local - can tell a node open in this walk from one open only in an
4642
- // enclosing walk. Pushed under the same guard the mark is read under, and
4643
- // the local `hooked` keeps the pair symmetric if a hook is registered
4644
- // mid-walk.
4645
- const hooked = state.hasHooks;
4646
- const mark = hooked ? state.hooks.pushWalkBase(state) : 0;
4647
- // Unguarded, unlike the walk base above: the iteration budget refills on
4648
- // the outermost entry whether or not hooks are registered. See
4649
- // `EvalState.walkDepth` on why these are two fields and not one.
4650
- state.enterWalk();
4651
4617
  try {
4652
- walk.recursive(node, state, {}, mergedVisitors());
4653
- const value = completionValue(popVisitorResult(node, state));
4618
+ const value = walkWithoutResult(node, state);
4654
4619
  state.result.stop();
4655
4620
  state.result.setSuccess(value);
4656
4621
  return value;
4657
4622
  }
4658
4623
  catch (error) {
4659
4624
  state.result.stop();
4660
- // A visitor that throws skips its afterVisitor, so close whatever this
4661
- // walk left open. Unwinding to the mark rather than to the bottom is what
4662
- // stops a nested evaluate - the arrow-function body runs on this same
4663
- // state - from draining the enclosing walk's open nodes.
4664
- // Reads `state.hasHooks` rather than the `hooked` local captured above,
4665
- // and the difference is deliberate but narrow: if a hook was registered
4666
- // *during* this walk then `hooked` is false, no base was pushed, `mark`
4667
- // is 0, and this unwinds the whole stack - including an enclosing walk's
4668
- // frames, which is the boundary crossing the walk base exists to stop.
4669
- // Left as it was rather than tightened here, because narrowing it would
4670
- // change what a mid-walk registration observes on an already-published
4671
- // path, which is not this step's to decide.
4672
- if (state.hasHooks) {
4673
- state.hooks.unwindTo(mark, error, state);
4674
- }
4675
4625
  state.result.setFailure(error);
4676
4626
  throw error;
4677
4627
  }
4678
- finally {
4679
- // Both in a `finally`: a walk that threw still has to restore the
4680
- // enclosing walk's bound and depth, or every later evaluation on this
4681
- // state carries this one's nesting.
4682
- state.exitWalk();
4683
- if (hooked) {
4684
- state.hooks.popWalkBase(state);
4685
- }
4686
- }
4687
4628
  }
4688
4629
  return undefined;
4689
4630
  };
@@ -4751,7 +4692,8 @@ const evaluateAsync = async (ast, state) => {
4751
4692
  }
4752
4693
  state.result.start();
4753
4694
  // Captured after the `!ast` early return above, for the same reason the sync
4754
- // entry point captures inside its `if (node)` block. Do not hoist.
4695
+ // entry point captures only once it has a node, in `walkWithoutResult`. Do
4696
+ // not hoist.
4755
4697
  const hooked = state.hasHooks;
4756
4698
  const mark = hooked ? state.hooks.pushWalkBase(state) : 0;
4757
4699
  state.enterWalk();
@@ -4764,7 +4706,7 @@ const evaluateAsync = async (ast, state) => {
4764
4706
  // evaluation that interleaved on this state looking like a nested walk -
4765
4707
  // and § 3.4's budget refills only on the outermost entry.
4766
4708
  try {
4767
- walk.recursive(ast, state, {}, mergedVisitors());
4709
+ walk.recursive(ast, state, {}, visitorsFor(ast, false));
4768
4710
  value = completionValue(popVisitorResult(ast, state));
4769
4711
  }
4770
4712
  finally {
@@ -4789,7 +4731,6 @@ const evaluateAsync = async (ast, state) => {
4789
4731
  return value;
4790
4732
  }
4791
4733
  catch (error) {
4792
- state.result.stop();
4793
4734
  // The walk here is synchronous too, so it strands open nodes on a throw
4794
4735
  // exactly as the sync entry point does. This catch also receives the
4795
4736
  // rethrow from the awaitAllPromises handler above; in that case the walk
@@ -4798,70 +4739,14 @@ const evaluateAsync = async (ast, state) => {
4798
4739
  if (state.hasHooks) {
4799
4740
  state.hooks.unwindTo(mark, error, state);
4800
4741
  }
4742
+ // After the unwind, as on the sync path, so a hook that fires during the
4743
+ // cleanup reads `duration` `undefined` there too: the walk has not ended.
4744
+ state.result.stop();
4801
4745
  state.result.setFailure(error);
4802
4746
  throw error;
4803
4747
  }
4804
4748
  };
4805
4749
 
4806
- /**
4807
- * Compiles the given node and returns a function that can be used to evaluate it.
4808
- *
4809
- * @param node The node to compile.
4810
- * @returns A function that takes an `EvalState` and returns the result of evaluating the node.
4811
- */
4812
- const compile = (node) => {
4813
- return evaluate.bind(null, node);
4814
- };
4815
- /**
4816
- * Compiles the given node asynchronously.
4817
- *
4818
- * @param node - The node to compile.
4819
- * @returns A function that takes an `EvalState` object and returns a `Promise` that resolves to the compiled result.
4820
- */
4821
- const compileAsync = (node) => {
4822
- return evaluateAsync.bind(null, node);
4823
- };
4824
- /**
4825
- * Calls the provided function with the given state and returns the result.
4826
- *
4827
- * @param fn The function to be called.
4828
- * @param state The state to be passed to the function.
4829
- * @returns The result of calling the function.
4830
- */
4831
- const call = (fn, state) => {
4832
- const value = fn(state);
4833
- return value;
4834
- };
4835
- /**
4836
- * Calls an asynchronous function with the given state and returns a promise that resolves to the result.
4837
- * @param fn The asynchronous function to call.
4838
- * @param state The state to pass to the function.
4839
- * @returns A promise that resolves to the result of the function.
4840
- */
4841
- const callAsync = (fn, state) => {
4842
- const promise = fn(state);
4843
- return promise;
4844
- };
4845
-
4846
- /**
4847
- * Finds all nodes of a specific type in the given AST.
4848
- *
4849
- * @param ast The AST to search in.
4850
- * @param searchType The type of nodes to search for.
4851
- * @returns An array of nodes of the specified type if found, otherwise undefined.
4852
- */
4853
- const extract = (node, searchType) => {
4854
- if (node) {
4855
- const state = [];
4856
- const visitors = {
4857
- [searchType]: (node) => { state.push(node); return; }
4858
- };
4859
- walk.simple(node, visitors);
4860
- return state.length > 0 ? state : undefined;
4861
- }
4862
- return undefined;
4863
- };
4864
-
4865
4750
  const arrowFunctionExpressionVisitor = (node, st, callback) => {
4866
4751
  beforeVisitor(node, st);
4867
4752
  const fn = (...arrowArgs) => {
@@ -4869,7 +4754,7 @@ const arrowFunctionExpressionVisitor = (node, st, callback) => {
4869
4754
  // The scope stack lives on EvalContext, not on the per-walk EvalState, and
4870
4755
  // one EvalContext can back any number of evaluations - so a scope this
4871
4756
  // closure fails to pop outlives the walk and is read first by every later
4872
- // evaluation on the same context. The body is re-entrant `evaluate`, which
4757
+ // evaluation on the same context. The body is a re-entrant walk, which
4873
4758
  // rethrows, so the pop needs `finally`.
4874
4759
  //
4875
4760
  // The `try` opens *after* the push, never around it. `contextPush` skips
@@ -4880,12 +4765,18 @@ const arrowFunctionExpressionVisitor = (node, st, callback) => {
4880
4765
  // Both take the method from the context's class (`context-method.ts`).
4881
4766
  // This site is the one an expression could reach twice over: a planted
4882
4767
  // own `push` would be invoked here with the real context as its `this`,
4883
- // and - since this closure's body is a re-entrant `evaluate` that pushes
4768
+ // and - since this closure's body is a re-entrant walk that pushes
4884
4769
  // again - a plant that evaluates anything recurses until the stack is
4885
4770
  // gone, leaving a reused context unusable (`docs/backlog.md` A42).
4886
4771
  contextPush(st.context, newContext, st.options);
4887
4772
  try {
4888
- return evaluate(node.body, st);
4773
+ // `walkWithoutResult`, not `evaluate`: the body's walk records nothing
4774
+ // on `st.result`, which describes the entry-point walk alone - during
4775
+ // that walk and after it, however often this closure is called
4776
+ // (`docs/backlog-retired.md` A27). As an arrow's body, it accepts the
4777
+ // `await` of an expression body or of a block body's last statement
4778
+ // (`docs/backlog-retired.md` A24).
4779
+ return walkWithoutResult(node.body, st, true);
4889
4780
  }
4890
4781
  finally {
4891
4782
  contextPop(st.context);
@@ -4907,13 +4798,15 @@ const arrowFunctionExpressionVisitor = (node, st, callback) => {
4907
4798
  * statement list, `IfStatement` a branch, and `ForStatement` an `init` and a
4908
4799
  * body.
4909
4800
  *
4910
- * **It is explicit, and its `default` throws.** A node type this library does
4911
- * not implement raises rather than falling through to `acorn-walk`'s base
4912
- * walker, which would visit the subtree as an expression and strand whatever it
4913
- * pushed - `while (false) { 1 }` used to evaluate to `1` that way. Three
4914
- * visitors in this library already push nothing on one path of an `if`/`else if`
4915
- * chain over node types (`docs/backlog.md` A2); a `switch` whose `default`
4916
- * throws is how this family gains no fourth member.
4801
+ * **It is explicit, and a type outside its table throws.** A node type this
4802
+ * library does not implement raises rather than falling through to
4803
+ * `acorn-walk`'s base walker, which would visit the subtree as an expression and
4804
+ * strand whatever it pushed - `while (false) { 1 }` used to evaluate to `1` that
4805
+ * way. Three visitors in this library already push nothing on one path of an
4806
+ * `if`/`else if` chain over node types (`docs/backlog.md` A2); a table whose
4807
+ * miss throws is how this family gains no fourth member. The table and its
4808
+ * message are `statementTypeRefusal`'s, in `statement-support.ts`, since D13:
4809
+ * this was a `switch` whose `default` threw until then.
4917
4810
  *
4918
4811
  * **Why this module exists.** It lived in `program.ts` for steps 1 to 5, on the
4919
4812
  * rule that a shared helper earns its own file at its *third* importer -
@@ -4932,29 +4825,14 @@ const arrowFunctionExpressionVisitor = (node, st, callback) => {
4932
4825
  * for a doc link is an unused binding the lint config rejects.
4933
4826
  */
4934
4827
  const dispatchStatement = (statement, st, callback) => {
4935
- switch (statement.type) {
4936
- // `VariableDeclaration` covers `var` as well, and cannot not: this `switch`
4937
- // reads the node *type*, and `var x = 1` is a `VariableDeclaration` exactly
4938
- // as `let x = 1` is. Listing it here is therefore what stopped `var`
4939
- // reaching the `default:` below; the rejection moved into the visitor,
4940
- // which can read `kind`.
4941
- //
4942
- // `ForStatement` is the classic three-part form *only*. `ForOfStatement`,
4943
- // `ForInStatement`, `WhileStatement` and `DoWhileStatement` are distinct
4944
- // node types and stay out of the phase (§ 2), so they reach the `default`
4945
- // below unchanged - unlike `var`, which shares a type with `let` and had to
4946
- // be rejected one level down.
4947
- case 'ExpressionStatement':
4948
- case 'EmptyStatement':
4949
- case 'BlockStatement':
4950
- case 'VariableDeclaration':
4951
- case 'IfStatement':
4952
- case 'ForStatement':
4953
- callback(statement, st);
4954
- return popVisitorResult(statement, st);
4955
- default:
4956
- throw new Error(`Unsupported statement type: ${statement.type}`);
4828
+ // The types walked are `statement-support.ts`' table, which
4829
+ // `findUnsupportedStatement` reads too, so the two cannot disagree.
4830
+ const refusal = statementTypeRefusal(statement);
4831
+ if (refusal !== undefined) {
4832
+ throw new Error(refusal);
4957
4833
  }
4834
+ callback(statement, st);
4835
+ return popVisitorResult(statement, st);
4958
4836
  };
4959
4837
 
4960
4838
  /**
@@ -4966,9 +4844,9 @@ const dispatchStatement = (statement, st, callback) => {
4966
4844
  * completion-value semantics, and pushes exactly one value however many
4967
4845
  * statements the body holds. A program whose statements all produced nothing -
4968
4846
  * `;`, or a source that is only whitespace - pushes {@link EMPTY_COMPLETION},
4969
- * which the walk boundary in `evaluate` converts to `undefined`. The conversion
4970
- * is deliberately not done here: `arrow-function-expression.ts` calls
4971
- * `evaluate` on a `BlockStatement` for a block-bodied arrow, so a `Program`-side
4847
+ * which the walk boundary in `evaluate.ts` converts to `undefined`. The
4848
+ * conversion is deliberately not done here: `arrow-function-expression.ts`
4849
+ * walks a `BlockStatement` for a block-bodied arrow, so a `Program`-side
4972
4850
  * conversion would leave that entry point handing the sentinel to a consumer.
4973
4851
  *
4974
4852
  * **The program-level scope is required.** It is the only scope a top-level
@@ -5032,10 +4910,10 @@ const expressionStatementVisitor = (node, st, callback) => {
5032
4910
  * {@link EMPTY_COMPLETION} and an enclosing statement list keeps whatever
5033
4911
  * preceded it.
5034
4912
  *
5035
- * One line of behaviour, and it exists because the statement dispatcher's
5036
- * `default` throws: without it `a;;b` and `if (x) ;` would start raising
5037
- * "unsupported statement type", which is a divergence from JavaScript nobody
5038
- * chose.
4913
+ * One line of behaviour, and it exists because the statement dispatcher
4914
+ * throws for a type outside its table: without it `a;;b` and `if (x) ;` would
4915
+ * start raising "unsupported statement type", which is a divergence from
4916
+ * JavaScript nobody chose.
5039
4917
  */
5040
4918
  const emptyStatementVisitor = (node, st) => {
5041
4919
  beforeVisitor(node, st);
@@ -5052,10 +4930,10 @@ const emptyStatementVisitor = (node, st) => {
5052
4930
  * statements the body holds. A block whose statements all produced nothing -
5053
4931
  * `{ }`, or `{ ; }` - pushes {@link EMPTY_COMPLETION} for its enclosing
5054
4932
  * statement list to skip over. The sentinel is converted to `undefined` at the
5055
- * walk boundary in `evaluate`, which is why this visitor may return it to a
5056
- * caller that is itself a walk root: `arrow-function-expression.ts` calls
5057
- * `evaluate` on this node for a block-bodied arrow, so `x => { }` reaches a
5058
- * consumer through the same conversion a `Program` does.
4933
+ * walk boundary in `evaluate.ts`, which is why this visitor may return it to a
4934
+ * caller that is itself a walk root: `arrow-function-expression.ts` walks this
4935
+ * node for a block-bodied arrow, so `x => { }` reaches a consumer through the
4936
+ * same conversion a `Program` does.
5059
4937
  *
5060
4938
  * **The block scope is unobservable in this step, and is pushed anyway.**
5061
4939
  * Nothing binds into it until `VariableDeclaration` lands, and an empty scope
@@ -5155,7 +5033,7 @@ const blockStatementVisitor = (node, st, callback) => {
5155
5033
  * declaration is not a legal bare statement body; `if (a) var x = 1` does parse,
5156
5034
  * reaches the dispatcher as a `VariableDeclaration`, and is rejected on `kind`
5157
5035
  * inside `variableDeclarationVisitor`; and `if (a) function f() { }` parses
5158
- * under Annex B and is rejected by `dispatchStatement`'s throwing `default`.
5036
+ * under Annex B and is rejected by `dispatchStatement`, whose table omits it.
5159
5037
  *
5160
5038
  * **The fourth is closed by the dispatcher and not by anything here**, which is
5161
5039
  * the one a later phase can reopen: a phase that registers `FunctionDeclaration`
@@ -5186,12 +5064,12 @@ const ifStatementVisitor = (node, st, callback) => {
5186
5064
  * § 1.1's row measured **`NaN`** with three stranded values before Phase 2: the
5187
5065
  * base walker handed the declarator's `id` to `identifierVisitor`, so `i`
5188
5066
  * resolved against the context rather than binding, and `i < 3` compared
5189
- * `undefined`. Since step 1 the row throws from `dispatchStatement`'s `default`;
5190
- * this visitor is what returns `2`.
5067
+ * `undefined`. Since step 1 the row throws from `dispatchStatement`, which
5068
+ * refuses a type outside its table; this visitor is what returns `2`.
5191
5069
  *
5192
5070
  * `for…of`, `for…in`, `while` and `do…while` stay out of the phase (§ 2) and
5193
- * keep throwing - they are separate node types and reach the dispatcher's
5194
- * `default` unchanged.
5071
+ * keep throwing - they are separate node types, outside the dispatcher's table,
5072
+ * and are refused unchanged.
5195
5073
  *
5196
5074
  * **One scope for the loop, not one per iteration.** A draft of the plan
5197
5075
  * specified a fresh scope per iteration, seeded from the head and copied back
@@ -5211,10 +5089,10 @@ const ifStatementVisitor = (node, st, callback) => {
5211
5089
  * through `dispatchStatement`; `for (i = 0; …)` parses it as an `Expression` and
5212
5090
  * takes a raw `callback`. Both pop exactly one - the declaration's `EMPTY`, or
5213
5091
  * the expression's value - so § 3.1's arithmetic is identical for the two and
5214
- * the split is invisible to it. What depends on the split is the throwing
5215
- * `default`: only the `dispatchStatement` route has one, so an `init` that is a
5216
- * statement type this library does not implement is rejected rather than handed
5217
- * to the base walker. `body` is a `Statement` and dispatches for the same
5092
+ * the split is invisible to it. What depends on the split is the refusal of a
5093
+ * type outside the table: only the `dispatchStatement` route has one, so an
5094
+ * `init` that is a statement type this library does not implement is rejected
5095
+ * rather than handed to the base walker. `body` is a `Statement` and dispatches for the same
5218
5096
  * reason; `test` and `update` are expressions and do not.
5219
5097
  *
5220
5098
  * Arithmetic (§ 3.1): pops 1 for `init` when present, then per iteration 1 for
@@ -5856,6 +5734,22 @@ class EvalTrace extends Array {
5856
5734
 
5857
5735
  /**
5858
5736
  * Represents the result of an evaluation.
5737
+ *
5738
+ * **The outcome describes the last entry-point walk on the state**: its
5739
+ * {@link value}, {@link error}, {@link errorMessage}, {@link isSuccess},
5740
+ * {@link isError}, {@link isUndefined} and {@link duration}. Each entry point
5741
+ * resets the outcome when its walk starts and writes it when the walk ends - for
5742
+ * `evalAsync` and its kin, once the result's promises have settled, so between
5743
+ * return and settlement a walk that did not throw reports neither success nor
5744
+ * failure. An arrow function's body runs a walk of its own on the same state,
5745
+ * and it changes nothing here: not while the enclosing walk runs, and not when
5746
+ * a function the walk built is called later. Up to 0.14.1 it overwrote all of it
5747
+ * (`docs/backlog-retired.md` A27). Two `evalAsync` runs interleaved on one
5748
+ * state share one outcome: the later start resets it, and the last to settle
5749
+ * writes it.
5750
+ *
5751
+ * The {@link trace} is not part of the outcome: it spans every evaluation run on
5752
+ * the state, and only {@link clearTrace} resets it.
5859
5753
  */
5860
5754
  class EvalResult {
5861
5755
  /**
@@ -5865,37 +5759,45 @@ class EvalResult {
5865
5759
  return this._stack;
5866
5760
  }
5867
5761
  /**
5868
- * Gets the evaluated value.
5762
+ * Gets the evaluated value: the last entry-point walk's, and `undefined`
5763
+ * once that walk failed or while it is pending.
5869
5764
  */
5870
5765
  get value() {
5871
5766
  return this._value;
5872
5767
  }
5873
5768
  /**
5874
- * Gets the error that occurred during evaluation.
5769
+ * Gets the error the last entry-point walk failed with, and `undefined` once
5770
+ * it succeeded or while it is pending. An error an arrow function's body
5771
+ * threw and something in the walk caught is not the walk's.
5875
5772
  */
5876
5773
  get error() {
5877
5774
  return this._error;
5878
5775
  }
5879
5776
  /**
5880
- * Gets the error message associated with the evaluation error.
5777
+ * Gets {@link error}'s message when it is an `Error`, and `undefined`
5778
+ * otherwise.
5881
5779
  */
5882
5780
  get errorMessage() {
5883
5781
  return this._errorMessage;
5884
5782
  }
5885
5783
  /**
5886
- * Gets whether the evaluation resulted in an error.
5784
+ * Gets whether the last entry-point walk failed: `undefined` while it is
5785
+ * pending.
5887
5786
  */
5888
5787
  get isError() {
5889
5788
  return this._isError;
5890
5789
  }
5891
5790
  /**
5892
- * Gets whether the evaluation was successful.
5791
+ * Gets whether the last entry-point walk succeeded: `undefined` while it is
5792
+ * pending.
5893
5793
  */
5894
5794
  get isSuccess() {
5895
5795
  return this._isSuccess;
5896
5796
  }
5897
5797
  /**
5898
- * Gets whether the evaluated value is undefined.
5798
+ * Gets whether {@link value} is `undefined`, once the last entry-point walk
5799
+ * has ended - including after a failure, which clears the value. `undefined`
5800
+ * while it is pending.
5899
5801
  */
5900
5802
  get isUndefined() {
5901
5803
  return this._isUndefined;
@@ -5946,7 +5848,8 @@ class EvalResult {
5946
5848
  return this._context.options;
5947
5849
  }
5948
5850
  /**
5949
- * Gets the duration of the evaluation result.
5851
+ * Gets the duration of the last entry-point walk, an arrow function's body
5852
+ * called inside it included: `undefined` while it is pending.
5950
5853
  * @returns The duration in milliseconds.
5951
5854
  */
5952
5855
  get duration() {
@@ -6045,10 +5948,24 @@ class EvalResult {
6045
5948
  this._traceTruncated = false;
6046
5949
  }
6047
5950
  /**
6048
- * Starts the evaluation process.
5951
+ * Starts the evaluation process, and resets the outcome: {@link value},
5952
+ * {@link error}, {@link errorMessage}, {@link isSuccess}, {@link isError},
5953
+ * {@link isUndefined} and {@link duration} read `undefined` until the walk
5954
+ * ends. Leaves the
5955
+ * {@link trace}, {@link tracePushCount} and {@link traceTruncated} alone,
5956
+ * since the trace spans every evaluation on the state (`docs/backlog.md`
5957
+ * A15). Up to 0.14.1 it reset nothing, so a reused state reported the last
5958
+ * run's error until something overwrote it (A27).
6049
5959
  */
6050
5960
  start() {
6051
5961
  this._startDate = performance.now();
5962
+ this._endDate = undefined;
5963
+ this._value = undefined;
5964
+ this._error = undefined;
5965
+ this._errorMessage = undefined;
5966
+ this._isSuccess = undefined;
5967
+ this._isError = undefined;
5968
+ this._isUndefined = undefined;
6052
5969
  }
6053
5970
  /**
6054
5971
  * Stops the evaluation and records the end date.
@@ -6058,29 +5975,33 @@ class EvalResult {
6058
5975
  return this.duration;
6059
5976
  }
6060
5977
  /**
6061
- * Sets the success value of the evaluation result.
5978
+ * Sets the success value of the evaluation result, writing every outcome
5979
+ * field: the error and its message are cleared.
6062
5980
  *
6063
5981
  * @param value The value to set as the success value.
6064
5982
  * @returns void
6065
5983
  */
6066
5984
  setSuccess(value) {
6067
5985
  this._value = value;
5986
+ this._error = undefined;
5987
+ this._errorMessage = undefined;
6068
5988
  this._isSuccess = true;
6069
5989
  this._isError = false;
6070
- this._isUndefined = false;
5990
+ this._isUndefined = value === undefined;
6071
5991
  }
6072
5992
  /**
6073
- * Sets the failure state of the evaluation result.
5993
+ * Sets the failure state of the evaluation result, writing every outcome
5994
+ * field: the value is cleared, and the message is the error's when it is an
5995
+ * `Error`.
6074
5996
  * @param error The error object associated with the failure.
6075
5997
  */
6076
5998
  setFailure(error) {
5999
+ this._value = undefined;
6077
6000
  this._error = error;
6078
- if (error instanceof Error) {
6079
- this._errorMessage = error.message;
6080
- }
6001
+ this._errorMessage = error instanceof Error ? error.message : undefined;
6081
6002
  this._isSuccess = false;
6082
6003
  this._isError = true;
6083
- this._isUndefined = false;
6004
+ this._isUndefined = true;
6084
6005
  }
6085
6006
  }
6086
6007
 
@@ -6380,7 +6301,7 @@ class EvalHooks {
6380
6301
  * **"Open" means open in *this* walk.** Both routes below are bounded by the
6381
6302
  * current walk base ({@link EvalHookBookkeeping.walkBases}), so a node open
6382
6303
  * only in an enclosing walk falls into case 3 by either route - which is the
6383
- * behaviour case 3 already specifies for "not open at all". `evaluate` is
6304
+ * behaviour case 3 already specifies for "not open at all". The walk is
6384
6305
  * re-entered with the same state from an arrow-function body, so without the
6385
6306
  * bound a nested walk closing a node it never opened would flush the
6386
6307
  * enclosing walk's frames under `completed: false` events a consumer reads as
@@ -6437,7 +6358,7 @@ class EvalHooks {
6437
6358
  }
6438
6359
  /**
6439
6360
  * How many nodes the state has open. Captured as a mark before a walk, since
6440
- * `evaluate` is re-entered with the same state from an arrow-function body.
6361
+ * the walk is re-entered with the same state from an arrow-function body.
6441
6362
  *
6442
6363
  * This is a method rather than a getter because the stack it measures lives
6443
6364
  * on the state, not on this registry.
@@ -6447,10 +6368,11 @@ class EvalHooks {
6447
6368
  }
6448
6369
  /**
6449
6370
  * Records that a walk is starting at the state's current open depth, and
6450
- * returns that depth. Called by `evaluate` / `evaluateAsync` on entry, under
6451
- * their `hasHooks` guard, and paired with {@link popWalkBase} in a `finally`.
6371
+ * returns that depth. Called on entry by every walk - `evaluate`'s, an
6372
+ * arrow-function body's and `evaluateAsync`'s - under a `hasHooks` guard,
6373
+ * and paired with {@link popWalkBase} in a `finally`.
6452
6374
  *
6453
- * The returned value is the same mark those entry points hand to
6375
+ * The returned value is the same mark those walks hand to
6454
6376
  * {@link unwindTo}, so they capture it once rather than reading the depth
6455
6377
  * twice.
6456
6378
  */
@@ -6461,9 +6383,9 @@ class EvalHooks {
6461
6383
  return base;
6462
6384
  }
6463
6385
  /**
6464
- * Drops the innermost walk base. Called from the `finally` of the `evaluate`
6465
- * that pushed it, so an entry point whose walk threw still restores the
6466
- * enclosing walk's bound.
6386
+ * Drops the innermost walk base. Called from the `finally` of the walk that
6387
+ * pushed it, so a walk that threw still restores the enclosing walk's
6388
+ * bound.
6467
6389
  */
6468
6390
  popWalkBase(state) {
6469
6391
  state.hookBookkeeping.walkBases.pop();
@@ -6482,12 +6404,12 @@ class EvalHooks {
6482
6404
  }
6483
6405
  /**
6484
6406
  * Fires 'after' for every node the state has open above `mark`, innermost
6485
- * first, marked incomplete. Invoked from the catch in `evaluate`, so that a
6407
+ * first, marked incomplete. Invoked from the catch of every walk, so that a
6486
6408
  * visitor which throws still leaves every 'before' matched by exactly one
6487
6409
  * 'after'.
6488
6410
  *
6489
6411
  * Unwinding to a mark rather than to the bottom is what keeps a nested
6490
- * `evaluate` from draining the enclosing walk's open nodes when a host
6412
+ * walk from draining the enclosing walk's open nodes when a host
6491
6413
  * function swallows the nested throw.
6492
6414
  *
6493
6415
  * Idempotent, so the sync and async entry points can both call it.
@@ -6835,10 +6757,9 @@ class EvalState {
6835
6757
  { open: [], errors: [], timings: new Map(), walkBases: [] });
6836
6758
  }
6837
6759
  /**
6838
- * How many `evaluate` / `evaluateAsync` calls on this state are currently on
6839
- * the JavaScript stack: 0 between evaluations, 1 during an ordinary walk, and
6840
- * more while a nested walk runs - an arrow-function body is re-entrant
6841
- * `evaluate` on this same state.
6760
+ * How many walks on this state are currently on the JavaScript stack: 0
6761
+ * between evaluations, 1 during an ordinary walk, and more while a nested
6762
+ * walk runs - an arrow-function body is a re-entrant walk on this same state.
6842
6763
  *
6843
6764
  * Maintained by {@link enterWalk} / {@link exitWalk}, which the entry points
6844
6765
  * pair around their walk, the exit in a `finally` so a throw still restores
@@ -6873,7 +6794,7 @@ class EvalState {
6873
6794
  enterWalk() {
6874
6795
  const depth = ++this._walkDepth;
6875
6796
  // § 3.4's refill, and the 0 -> 1 test is the whole of it. A nested walk -
6876
- // an arrow-function body, which re-enters `evaluate` on this same state -
6797
+ // an arrow-function body, which re-enters the walk on this same state -
6877
6798
  // shares whatever the enclosing walk has left, so an escaped closure cannot
6878
6799
  // buy itself a fresh budget by being called again. The options are re-read
6879
6800
  // per outermost walk rather than in the constructor because they are a
@@ -7106,6 +7027,15 @@ class EvalState {
7106
7027
  }
7107
7028
  }
7108
7029
 
7030
+ /**
7031
+ * The options `EvalService` and `CompilerService` pass on every parse, as
7032
+ * this object itself; `ParserService` and `DiscoveryService` copy it when
7033
+ * constructed. Read it or copy it; do not write into it. A value written into
7034
+ * it is not reliably seen: the parse cache remembers it by identity, so a text
7035
+ * cached before the write can keep its reading, and one parsed while it held
7036
+ * the value can keep that reading after it is written back
7037
+ * (`docs/backlog-retired.md` A34).
7038
+ */
7109
7039
  const defaultParserOptions = {
7110
7040
  ...defaultOptions,
7111
7041
  ecmaVersion: 2020,
@@ -7258,6 +7188,336 @@ class BaseEval {
7258
7188
  }
7259
7189
  }
7260
7190
 
7191
+ /**
7192
+ * @description
7193
+ * The colon-joined name grammar of `docs/colon-identifiers/phase-9-plan.md`
7194
+ * § 3.4, as an acorn plugin (§ 3.5). `parse` uses the parser built here when
7195
+ * `colonIdentifiers` is set, and acorn's own `parse` otherwise. No source text
7196
+ * is rewritten, so every position acorn reports is a position in what the
7197
+ * author wrote. Not re-exported from any barrel.
7198
+ *
7199
+ * Of acorn's documented API this module uses `Parser.extend`, `tokTypes` and
7200
+ * the `input` member. Everything else it touches is an acorn internal,
7201
+ * undeclared in acorn's `.d.ts`, and this is the complete list — what § 8 q3
7202
+ * checks at the `acorn` peer floor:
7203
+ *
7204
+ * - members read: `pos`, `start`, `type`, `value`, `keywords`;
7205
+ * - members written: `pos`, `containsEsc`;
7206
+ * - methods overridden, each calling acorn's own through `super`: `readWord`,
7207
+ * `finishToken`, `parsePropertyName`, `parseStatement`, `unexpected`;
7208
+ * - methods called: `finishToken`, `raise`;
7209
+ * - what the overrides assume of acorn's tokenizer: `readToken` is the only
7210
+ * caller of `readWord`, with `pos` at the token's first character; every
7211
+ * token is finished through `finishToken`, in source order, before the next
7212
+ * is read — except that a `/` read as `slash` is finished again as
7213
+ * `regexp`, and neither type is counted here; `?.`, `??` and `??=` are never
7214
+ * `question` tokens; the `}` that closes a `${` is finished as `braceR`; the
7215
+ * constructor reads no token;
7216
+ * - what they assume of acorn's parser: every key of an object literal, an
7217
+ * object pattern or a class body is read through `parsePropertyName`, with
7218
+ * the key as the current token; every statement through `parseStatement`,
7219
+ * with its first token as the current token; a colon the grammar cannot
7220
+ * place reaches `unexpected`, from `expect` or `semicolon`, with `type` and
7221
+ * `start` still at that colon.
7222
+ *
7223
+ * The token types it compares by identity, from `tokTypes`: `name`, `colon`,
7224
+ * `question`, `comma`, `semi`, `parenL`, `parenR`, `bracketL`, `bracketR`,
7225
+ * `braceL`, `braceR`, `dollarBraceL`.
7226
+ */
7227
+ const COLON = 58;
7228
+ /** `[A-Za-z_$]`: the first character of a name that may join. */
7229
+ const isFirstChar = (code) => (code >= 65 && code <= 90) || (code >= 97 && code <= 122) || code === 95 || code === 36;
7230
+ /** `[A-Za-z0-9_$]`: any later character, and a segment's first. */
7231
+ const isSegmentChar = (code) => isFirstChar(code) || (code >= 48 && code <= 57);
7232
+ /** Whether a `:segment` starts at `pos`: a colon with a segment character after it. */
7233
+ const joinsAt = (input, pos) => input.charCodeAt(pos) === COLON && isSegmentChar(input.charCodeAt(pos + 1));
7234
+ const colonIdentifiers = (Base) => {
7235
+ class ColonParser extends Base {
7236
+ constructor() {
7237
+ super(...arguments);
7238
+ /** Never empty: the top level is never closed. */
7239
+ this.levels = [{ pending: 0 }];
7240
+ /**
7241
+ * The level the current token was read at: for a `(`, `[`, `{` or `${`,
7242
+ * the one around the level it opened.
7243
+ */
7244
+ this.tokenLevel = this.levels[0];
7245
+ }
7246
+ get level() {
7247
+ return this.levels[this.levels.length - 1];
7248
+ }
7249
+ /**
7250
+ * Reads a colon-joined name as one `name` token when one starts at `pos`
7251
+ * and no `?` at this level is waiting for its `:` (§ 3.4, 1). In every
7252
+ * other case acorn's own `readWord`, so a word that does not join is read
7253
+ * exactly as acorn reads it.
7254
+ */
7255
+ readWord() {
7256
+ const end = this.colonNameEnd();
7257
+ if (end === undefined) {
7258
+ return super.readWord();
7259
+ }
7260
+ const name = this.input.slice(this.pos, end);
7261
+ if (this.level.pending > 0) {
7262
+ this.level.suppressed = name;
7263
+ return super.readWord();
7264
+ }
7265
+ this.pos = end;
7266
+ this.containsEsc = false;
7267
+ this.finishToken(tokTypes.name, name);
7268
+ }
7269
+ /**
7270
+ * Where the colon name that starts at `pos` ends — its longest match — or
7271
+ * `undefined` when none does: the first segment is not ASCII, is a keyword
7272
+ * of the parse's `ecmaVersion`, or has no `:segment` directly after it.
7273
+ */
7274
+ colonNameEnd() {
7275
+ const input = this.input;
7276
+ let end = this.pos;
7277
+ if (!isFirstChar(input.charCodeAt(end))) {
7278
+ return undefined;
7279
+ }
7280
+ do {
7281
+ end++;
7282
+ } while (isSegmentChar(input.charCodeAt(end)));
7283
+ if (!joinsAt(input, end) || this.keywords.test(input.slice(this.pos, end))) {
7284
+ return undefined;
7285
+ }
7286
+ do {
7287
+ end += 2;
7288
+ while (isSegmentChar(input.charCodeAt(end))) {
7289
+ end++;
7290
+ }
7291
+ } while (joinsAt(input, end));
7292
+ return end;
7293
+ }
7294
+ /**
7295
+ * Keeps the levels after acorn has finished the token, recording the one
7296
+ * the token was read at: `(`, `[`, `{` and `${` open a level and `)`, `]`
7297
+ * and `}` close it; a `?` is counted at its level and a `:` there
7298
+ * uncounts it. `?.` and `??` are other token types, and count for nothing.
7299
+ */
7300
+ finishToken(type, value) {
7301
+ super.finishToken(type, value);
7302
+ const level = this.level;
7303
+ this.tokenLevel = level;
7304
+ switch (type) {
7305
+ case tokTypes.parenL:
7306
+ case tokTypes.bracketL:
7307
+ case tokTypes.braceL:
7308
+ case tokTypes.dollarBraceL:
7309
+ this.levels.push({ pending: 0 });
7310
+ break;
7311
+ case tokTypes.parenR:
7312
+ case tokTypes.bracketR:
7313
+ case tokTypes.braceR:
7314
+ if (this.levels.length > 1) {
7315
+ this.levels.pop();
7316
+ }
7317
+ break;
7318
+ case tokTypes.question:
7319
+ level.pending++;
7320
+ break;
7321
+ case tokTypes.colon:
7322
+ if (level.pending > 0) {
7323
+ level.pending--;
7324
+ }
7325
+ break;
7326
+ case tokTypes.comma:
7327
+ case tokTypes.semi:
7328
+ level.suppressed = undefined;
7329
+ break;
7330
+ }
7331
+ }
7332
+ /**
7333
+ * Refuses a colon name as an object key, in a literal or a pattern alike
7334
+ * (§ 3.4, 2): `{Q1:1}` is `{Q1: 1}` to JavaScript and a shorthand to the
7335
+ * grammar, and keeping either would answer some author wrongly. Only a
7336
+ * joined token is a `name` holding a colon.
7337
+ */
7338
+ parsePropertyName(prop) {
7339
+ const name = this.value;
7340
+ if (this.type === tokTypes.name && typeof name === 'string' && name.includes(':')) {
7341
+ const first = name.slice(0, name.indexOf(':'));
7342
+ this.raise(this.start, `Colon-joined name '${name}' cannot be an object key: ` +
7343
+ `write '${first}: ...' with a space for a property, or quote the key`);
7344
+ }
7345
+ return super.parsePropertyName(prop);
7346
+ }
7347
+ /**
7348
+ * Forgets the name not joined at the level a statement starts at: the
7349
+ * statement boundary ended the conditional whose consequent lost it. A
7350
+ * semicolon acorn inserts at a line break is such a boundary, and no `;`
7351
+ * token marks it.
7352
+ */
7353
+ parseStatement(...args) {
7354
+ this.tokenLevel.suppressed = undefined;
7355
+ return super.parseStatement(...args);
7356
+ }
7357
+ /**
7358
+ * acorn's own error, with the hint of § 3.4, 1 when the unexpected token
7359
+ * is a `:` at a level that did not join a name since its last `,`, `;` or
7360
+ * statement start: the colon the name lost to the conditional. Any other
7361
+ * error is left as acorn words it.
7362
+ */
7363
+ unexpected(pos) {
7364
+ const suppressed = this.tokenLevel.suppressed;
7365
+ if (suppressed !== undefined && this.type === tokTypes.colon &&
7366
+ (pos === undefined || pos === this.start)) {
7367
+ return this.raise(this.start, 'Unexpected token: a colon-joined name in the ' +
7368
+ `consequent of a conditional needs parentheses: (${suppressed})`);
7369
+ }
7370
+ return super.unexpected(pos);
7371
+ }
7372
+ }
7373
+ return ColonParser;
7374
+ };
7375
+ /**
7376
+ * acorn's `Parser` with the grammar, built once, at module load. `extend`
7377
+ * returns a subclass, so acorn's own `Parser`, which `acorn.parse` uses, is
7378
+ * left as it was.
7379
+ */
7380
+ const ColonIdentifiersParser = Parser.extend(colonIdentifiers);
7381
+
7382
+ /**
7383
+ * @description
7384
+ * Parses expression and returns ES6/ES2020 AST.
7385
+ * With `colonIdentifiers` set the parser is the colon-joined name grammar's;
7386
+ * otherwise it is acorn's own `parse`.
7387
+ * @param expr expression to parse
7388
+ * @param options parser options
7389
+ */
7390
+ const parse = (expr, options) => {
7391
+ options = { ecmaVersion: 2020, ...options };
7392
+ const acornOptions = { ecmaVersion: 2020, ...options };
7393
+ const program = options.colonIdentifiers
7394
+ ? ColonIdentifiersParser.parse(expr, acornOptions)
7395
+ : parse$1(expr, acornOptions);
7396
+ if (!options.extractExpressions) {
7397
+ return program;
7398
+ }
7399
+ return extractExpression(program);
7400
+ };
7401
+ /**
7402
+ * @description
7403
+ * Walks through the AST and extracts first expression.
7404
+ * @param expr expression to parse
7405
+ */
7406
+ const extractExpression = (program) => {
7407
+ if (program.body.length === 1) {
7408
+ const expression = program.body[0];
7409
+ if (expression.type === 'ExpressionStatement') {
7410
+ return expression.expression;
7411
+ }
7412
+ }
7413
+ return undefined;
7414
+ };
7415
+
7416
+ /**
7417
+ * Compiles the given node and returns a function that can be used to evaluate it.
7418
+ *
7419
+ * @param node The node to compile.
7420
+ * @returns A function that takes an `EvalState` and returns the result of evaluating the node.
7421
+ */
7422
+ const compile = (node) => {
7423
+ return evaluate.bind(null, node);
7424
+ };
7425
+ /**
7426
+ * Compiles the given node asynchronously.
7427
+ *
7428
+ * @param node - The node to compile.
7429
+ * @returns A function that takes an `EvalState` object and returns a `Promise` that resolves to the compiled result.
7430
+ */
7431
+ const compileAsync = (node) => {
7432
+ return evaluateAsync.bind(null, node);
7433
+ };
7434
+ /**
7435
+ * Calls the provided function with the given state and returns the result.
7436
+ *
7437
+ * @param fn The function to be called.
7438
+ * @param state The state to be passed to the function.
7439
+ * @returns The result of calling the function.
7440
+ */
7441
+ const call = (fn, state) => {
7442
+ const value = fn(state);
7443
+ return value;
7444
+ };
7445
+ /**
7446
+ * Calls an asynchronous function with the given state and returns a promise that resolves to the result.
7447
+ * @param fn The asynchronous function to call.
7448
+ * @param state The state to pass to the function.
7449
+ * @returns A promise that resolves to the result of the function.
7450
+ */
7451
+ const callAsync = (fn, state) => {
7452
+ const promise = fn(state);
7453
+ return promise;
7454
+ };
7455
+
7456
+ /**
7457
+ * Finds all nodes of a specific type in the given AST.
7458
+ *
7459
+ * @param ast The AST to search in.
7460
+ * @param searchType The type of nodes to search for.
7461
+ * @returns An array of nodes of the specified type if found, otherwise undefined.
7462
+ */
7463
+ const extract = (node, searchType) => {
7464
+ if (node) {
7465
+ const state = [];
7466
+ const visitors = {
7467
+ [searchType]: (node) => { state.push(node); return; }
7468
+ };
7469
+ walk.simple(node, visitors);
7470
+ return state.length > 0 ? state : undefined;
7471
+ }
7472
+ return undefined;
7473
+ };
7474
+
7475
+ /**
7476
+ * Whether a node is a statement or a module declaration. Every member of
7477
+ * acorn's `Statement` and `ModuleDeclaration` unions is named `…Statement` or
7478
+ * `…Declaration`, and no other node type is: a declarator is a
7479
+ * `VariableDeclarator`.
7480
+ */
7481
+ const isStatement = (node) => /(?:Statement|Declaration)$/.test(node.type);
7482
+ /** The message evaluation throws for this statement, or `undefined`. */
7483
+ const refusalOf = (statement) => statementTypeRefusal(statement)
7484
+ ?? (statement.type === 'VariableDeclaration' ? declarationKindRefusal(statement) : undefined);
7485
+ /**
7486
+ * Finds the first statement in a tree that evaluation would refuse.
7487
+ *
7488
+ * Evaluation refuses a statement only when the walk reaches it, so one in an
7489
+ * arrow function's body that is never called, or in a branch not taken, throws
7490
+ * nothing. This reads the whole tree instead - function bodies, untaken
7491
+ * branches and class bodies included - against the same table the evaluator
7492
+ * uses, and returns the message evaluation throws for that statement.
7493
+ *
7494
+ * "First" is source order, the lowest `start`, so a refused statement inside
7495
+ * another refused one is reported after it, as evaluation would meet the outer
7496
+ * one first.
7497
+ *
7498
+ * @param node The AST to search, as `parse` returns it.
7499
+ * @returns The statement and its message, or `undefined` when the tree holds
7500
+ * none, or `node` is `undefined`.
7501
+ */
7502
+ const findUnsupportedStatement = (node) => {
7503
+ if (!node) {
7504
+ return undefined;
7505
+ }
7506
+ let first;
7507
+ // `walk.full` calls back in post-order, an enclosing statement after the
7508
+ // ones inside it, so the first one visited is not the first in the source.
7509
+ walk.full(node, (visited) => {
7510
+ if (!isStatement(visited)) {
7511
+ return;
7512
+ }
7513
+ const message = refusalOf(visited);
7514
+ if (message !== undefined && (first === undefined || visited.start < first.statement.start)) {
7515
+ first = { statement: visited, message };
7516
+ }
7517
+ });
7518
+ return first;
7519
+ };
7520
+
7261
7521
  /**
7262
7522
  * The options a cached AST cannot honour: acorn calls each callback as it
7263
7523
  * parses, and appends to a caller's `program` node. A parse carrying any of
@@ -7323,7 +7583,7 @@ const buildParseFingerprint = (options) => {
7323
7583
  * object the `parserOptions` getter returns, an options object a caller passes
7324
7584
  * again after writing into it, or the exported `defaultParserOptions`. A change
7325
7585
  * through the `parserOptions` setter installs a new object, and is seen
7326
- * (`docs/backlog.md` A34).
7586
+ * (`docs/backlog-retired.md` A34).
7327
7587
  */
7328
7588
  const parseFingerprint = (memo, serviceOptions, callOptions) => {
7329
7589
  let byCall = memo.get(serviceOptions);
@@ -7409,6 +7669,15 @@ class ParserService {
7409
7669
  /**
7410
7670
  * Gets the parser options: the constructor's, or the last value given to
7411
7671
  * the setter.
7672
+ *
7673
+ * Replace the object through the setter rather than write into the one this
7674
+ * returns: a value written into it is not reliably seen. The parse cache,
7675
+ * and `CompilerService`'s cache of compiled strings, remember each pair of
7676
+ * options objects, this one and a call's, by identity, not by their values.
7677
+ * A later parse through a pair seen before the write, as `EvalService`'s and
7678
+ * `CompilerService`'s are, keeps a cached text's earlier reading and caches
7679
+ * a new text as if the options had not changed; a parse through a new
7680
+ * call-options object sees the write (`docs/backlog-retired.md` A34).
7412
7681
  */
7413
7682
  get parserOptions() {
7414
7683
  return this._parserOptions;
@@ -7504,7 +7773,10 @@ class ParserService {
7504
7773
  * @description
7505
7774
  * Parses expression and returns ES6/ES2023 AST.
7506
7775
  * @param expr expression to parse
7507
- * @param options optional parser options
7776
+ * @param options optional parser options, merged over `parserOptions`. Pass
7777
+ * a new object for new options: a value written into an object already
7778
+ * passed is not reliably seen, since the cache remembers the object by
7779
+ * identity (`docs/backlog-retired.md` A34).
7508
7780
  * @returns The parsed AST (Abstract Syntax Tree).
7509
7781
  */
7510
7782
  parse(expr, options) {
@@ -7759,7 +8031,7 @@ class CompilerService extends BaseEval {
7759
8031
  * the `ParserService.parserOptions` setter reaches a string compiled before
7760
8032
  * it (`docs/colon-identifiers/phase-9-plan.md` § 3.2). The memo is
7761
8033
  * `ParserService`'s kind, and a write in place goes unseen here as there
7762
- * (`docs/backlog.md` A34). `null` when that parse bypasses `ParserService`'s
8034
+ * (`docs/backlog-retired.md` A34). `null` when that parse bypasses `ParserService`'s
7763
8035
  * cache - a callback or a `program` among its options, or a value JSON
7764
8036
  * cannot hold - and this cache then bypasses too, since a cached function
7765
8037
  * runs no callback.
@@ -8005,5 +8277,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.2.3", ngImpor
8005
8277
  * Generated bundle index. Do not edit.
8006
8278
  */
8007
8279
 
8008
- export { ASYNC_HOOK_MESSAGE, BaseRegistry, Cache, CaseInsensitiveRegistry, CompilerService, DiscoveryService, EMPTY_COMPLETION, EvalContext, EvalHooks, EvalResult, EvalScope, EvalService, EvalState, EvalTrace, ParserService, Registry, Stack, call, callAsync, compile, compileAsync, createDependencyTracker, createTimingHook, defaultParserOptions, evaluate, evaluateAsync, extract, extractExpression, fromContext, getContextValue, parse, provideColonIdentifiers };
8280
+ export { ASYNC_HOOK_MESSAGE, BaseRegistry, Cache, CaseInsensitiveRegistry, CompilerService, DiscoveryService, EMPTY_COMPLETION, EvalContext, EvalHooks, EvalResult, EvalScope, EvalService, EvalState, EvalTrace, ParserService, Registry, Stack, call, callAsync, compile, compileAsync, createDependencyTracker, createTimingHook, defaultParserOptions, evaluate, evaluateAsync, extract, extractExpression, findUnsupportedStatement, fromContext, getContextValue, parse, provideColonIdentifiers };
8009
8281
  //# sourceMappingURL=zvenigora-ng-eval-core.mjs.map