@zvenigora/ng-eval-core 0.14.0 → 0.15.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.
@@ -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.
@@ -1279,7 +1279,6 @@ const refuseThisValue = (node) => {
1279
1279
  }
1280
1280
  };
1281
1281
 
1282
- // import { getCachedVisitorResult, setCachedVisitorResult } from './visitor-result-cache';
1283
1282
  /**
1284
1283
  * Reconstructs the dotted source path of a member chain (`a.b.c`).
1285
1284
  *
@@ -1328,16 +1327,7 @@ const readPath = (node) => {
1328
1327
  */
1329
1328
  const memberExpressionVisitor = (node, st, callback) => {
1330
1329
  beforeVisitor(node, st);
1331
- // Disable visitor result caching for now due to context sensitivity issues
1332
- // const cachedResult = getCachedVisitorResult(node, st.context);
1333
- // if (cachedResult !== undefined) {
1334
- // pushVisitorResult(node, st, cachedResult);
1335
- // afterVisitor(node, st);
1336
- // return;
1337
- // }
1338
1330
  const [, , value] = evaluateMember(node, st, callback);
1339
- // Disable visitor result caching for now
1340
- // setCachedVisitorResult(node, st.context, value);
1341
1331
  pushVisitorResult(node, st, value);
1342
1332
  afterVisitor(node, st);
1343
1333
  };
@@ -1767,10 +1757,11 @@ const contextSetInScope = (context, key, value) => methodOf(context, 'setInScope
1767
1757
  * `EvalContext.push` as the class defines it, for a context that may be
1768
1758
  * undefined.
1769
1759
  *
1770
- * The optional receiver is deliberate: every scope push in the evaluator is
1771
- * written `st.context?.push(...)`, and its pop is paired with it by a
1772
- * `finally`. Both wrappers no-op on an absent context, so a walk with no
1773
- * context pushes nothing and pops nothing, exactly as the optional chain did.
1760
+ * The optional receiver is deliberate: every scope push in the evaluator
1761
+ * calls `contextPush(st.context, ...)`, and its pop, `contextPop`, runs in the
1762
+ * `finally` of a `try` opened on the next line. Both wrappers no-op on an
1763
+ * absent context, so a walk with no context pushes nothing and pops nothing,
1764
+ * exactly as the `st.context?.push(...)` optional chain they replaced did.
1774
1765
  */
1775
1766
  const contextPush = (context, scope, options) => {
1776
1767
  if (!context) {
@@ -3113,7 +3104,6 @@ const literalVisitor = (node, st) => {
3113
3104
  afterVisitor(node, st);
3114
3105
  };
3115
3106
 
3116
- // import { getCachedVisitorResult, setCachedVisitorResult } from './visitor-result-cache';
3117
3107
  /**
3118
3108
  * Converts value to primitive for comparison operations
3119
3109
  */
@@ -3260,20 +3250,11 @@ const evaluateBinaryOperation = (operator, left, right) => {
3260
3250
  */
3261
3251
  const binaryExpressionVisitor = (node, st, callback) => {
3262
3252
  beforeVisitor(node, st);
3263
- // Disable visitor result caching for now due to context sensitivity issues
3264
- // const cachedResult = getCachedVisitorResult(node, st.context);
3265
- // if (cachedResult !== undefined) {
3266
- // pushVisitorResult(node, st, cachedResult);
3267
- // afterVisitor(node, st);
3268
- // return;
3269
- // }
3270
3253
  callback(node.left, st);
3271
3254
  const left = popVisitorResult(node, st);
3272
3255
  callback(node.right, st);
3273
3256
  const right = popVisitorResult(node, st);
3274
3257
  const value = evaluateBinaryOperation(node.operator, left, right);
3275
- // Disable visitor result caching for now
3276
- // setCachedVisitorResult(node, st.context, value);
3277
3258
  pushVisitorResult(node, st, value);
3278
3259
  afterVisitor(node, st);
3279
3260
  };
@@ -3287,28 +3268,57 @@ const importExpressionVisitor = (node, st) => {
3287
3268
  throw new Error('Function call blocked for security reasons: import');
3288
3269
  };
3289
3270
 
3290
- // Default timeout for await expressions (30 seconds)
3291
- const DEFAULT_AWAIT_TIMEOUT = 30000;
3292
- /**
3293
- * Creates a timeout promise that rejects after the specified timeout
3294
- */
3295
- const createTimeoutPromise = (timeout) => {
3296
- return new Promise((_, reject) => {
3297
- setTimeout(() => {
3298
- reject(new Error(`Await expression timed out after ${timeout}ms`));
3299
- }, timeout);
3300
- });
3301
- };
3302
- /**
3303
- * Safely wraps a value in a promise if it's not already a promise
3304
- */
3305
- const ensurePromise = (value) => {
3306
- if (value && typeof value === 'object' && 'then' in value) {
3307
- return value;
3271
+ // The refusal names `await` and the rule (`docs/backlog-retired.md` A24).
3272
+ 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.';
3273
+ const asAwait = (node) => {
3274
+ const inner = unwrapParentheses(node);
3275
+ return inner.type === 'AwaitExpression' ? inner : undefined;
3276
+ };
3277
+ const lastStatementAwait = (body) => {
3278
+ const last = body[body.length - 1];
3279
+ return last?.type === 'ExpressionStatement' ? asAwait(last.expression) : undefined;
3280
+ };
3281
+ /**
3282
+ * The one `await` a walk rooted at `root` accepts, the one whose value is the
3283
+ * walk's result: the root itself; or the expression of the last statement of
3284
+ * a `Program`, or of an arrow function's `BlockStatement` body when
3285
+ * `arrowBody` is set. Read off the root one level deep, so nothing is
3286
+ * traversed, and computed per walk, so nothing is stored: the same node is
3287
+ * accepted as one walk's root and refused as another's operand
3288
+ * (`docs/backlog-retired.md` A24).
3289
+ *
3290
+ * Under `preserveParens` the root and the last statement's expression are
3291
+ * unwrapped first, as the assignment and update visitors unwrap their
3292
+ * targets, so `(await p)` is accepted where `await p` is. Only those two
3293
+ * places are unwrapped: a parenthesised operand, `((await p)) * 10`, is still
3294
+ * an operand, and the walk refuses it.
3295
+ *
3296
+ * @param root The node the walk starts at.
3297
+ * @param arrowBody Whether the walk is an arrow function's body.
3298
+ * @returns The accepted `await`, or `undefined`.
3299
+ */
3300
+ const acceptedAwait = (root, arrowBody) => {
3301
+ const rootAwait = asAwait(root);
3302
+ if (rootAwait) {
3303
+ return rootAwait;
3304
+ }
3305
+ if (!arrowBody && root.type === 'Program') {
3306
+ return lastStatementAwait(root.body);
3307
+ }
3308
+ if (arrowBody && root.type === 'BlockStatement') {
3309
+ return lastStatementAwait(root.body);
3308
3310
  }
3309
- return Promise.resolve(value);
3311
+ return undefined;
3310
3312
  };
3311
- const awaitVisitor = (node, st, callback) => {
3313
+ const awaitVisitor = (node, st, callback, accepted = false) => {
3314
+ // Above `beforeVisitor`, as the `var` kind check is: the refusal reads the
3315
+ // node's position and nothing else, so a refused `await` fires no hook and
3316
+ // leaves no trace entry. The default table's entry refuses every `await`;
3317
+ // a walk that has an accepted one passes `accepted` for it alone
3318
+ // (`functions/evaluate.ts`).
3319
+ if (!accepted) {
3320
+ throw new Error(AWAIT_POSITION_MESSAGE);
3321
+ }
3312
3322
  beforeVisitor(node, st);
3313
3323
  // Outside any `Promise` executor, and uncaught here, as in every other
3314
3324
  // visitor: a synchronous throw from the operand propagates synchronously, and
@@ -3318,30 +3328,10 @@ const awaitVisitor = (node, st, callback) => {
3318
3328
  // (`docs/backlog-retired.md` A1).
3319
3329
  callback(node.argument, st);
3320
3330
  const value = popVisitorResult(node, st);
3321
- // Convert value to promise if it's not already one
3322
- const valuePromise = ensurePromise(value);
3323
- // Get timeout from context or use default
3324
- const contextObj = st.context?.original;
3325
- const timeout = (contextObj && typeof contextObj['__awaitTimeout'] === 'number'
3326
- ? contextObj['__awaitTimeout']
3327
- : DEFAULT_AWAIT_TIMEOUT);
3328
- // Race between the actual promise and timeout
3329
- const promise = Promise.race([
3330
- valuePromise,
3331
- createTimeoutPromise(timeout)
3332
- ])
3333
- .catch((error) => {
3334
- // Enhance error information with context
3335
- const enhancedError = error instanceof Error
3336
- ? error
3337
- : new Error(`Await expression failed: ${String(error)}`);
3338
- // Add source location information if available
3339
- if (node.start !== undefined && node.end !== undefined) {
3340
- enhancedError.message += ` at position ${node.start}-${node.end}`;
3341
- }
3342
- throw enhancedError;
3343
- });
3344
- pushVisitorResult(node, st, promise);
3331
+ // Passed through unchanged: nothing races it, wraps it, reads a timeout
3332
+ // for it or rewrites its rejection (`docs/backlog-retired.md` A25). A
3333
+ // promise that reaches the result is resolved there by `evaluateAsync`.
3334
+ pushVisitorResult(node, st, value);
3345
3335
  afterVisitor(node, st);
3346
3336
  };
3347
3337
 
@@ -3549,16 +3539,56 @@ const templateLiteralVisitor = (node, st, callback) => {
3549
3539
  };
3550
3540
 
3551
3541
  /**
3552
- * The tag's arguments: the template's cooked strings, then the value of each
3553
- * of its expressions, evaluated in order.
3542
+ * Each template site's template object, by its `TemplateLiteral` node.
3543
+ *
3544
+ * A module-level weak collection keyed by an AST node and never cleared, as
3545
+ * `dangerous-values.ts`' `exemptNodes` is, and keyed by an object as
3546
+ * `property-lookup-cache.ts` is: an entry lives exactly as long as its node,
3547
+ * and nothing one node holds can be read for another. What it does not do,
3548
+ * beside that cache: it has no clear and no statistics, and is never
3549
+ * invalidated, since a node's strings do not change - for an AST its caller
3550
+ * leaves alone; one that rewrites a node's `quasis` after a first evaluation
3551
+ * keeps the old object, as `exemptNodes` keeps its marks. The object is shared
3552
+ * by every walk of the node, over any state and context, and through a
3553
+ * `ParserService`'s parse cache by every consumer of that service - in an
3554
+ * application, the root singleton - parsing the same text with the same
3555
+ * options. That is safe because the object is frozen and holds only the
3556
+ * template's own strings.
3557
+ */
3558
+ const templateObjects = new WeakMap();
3559
+ /**
3560
+ * The site's template object, as JavaScript builds it: the cooked strings,
3561
+ * an invalid escape's cooked string `undefined`, with a non-enumerable `raw`
3562
+ * of the uncooked strings, both frozen, and the same object every time the
3563
+ * site runs (`docs/backlog-retired.md` A38). Up to 0.14.1 it was a plain array
3564
+ * of the cooked strings, built on every evaluation, with no `raw`.
3565
+ *
3566
+ * Not added to `st.createdObjects`: the walk did not create it for the
3567
+ * expression to hold, as `EvalMemberWrite.createdByEvaluation` defines
3568
+ * created, so a write policy is asked about it as about any other object.
3569
+ */
3570
+ const templateObject = (quasi) => {
3571
+ let strings = templateObjects.get(quasi);
3572
+ if (!strings) {
3573
+ const cooked = quasi.quasis.map((element) => element.value.cooked ?? undefined);
3574
+ const raw = Object.freeze(quasi.quasis.map((element) => element.value.raw));
3575
+ // Not writable, enumerable or configurable, as JavaScript defines it.
3576
+ Object.defineProperty(cooked, 'raw', { value: raw });
3577
+ strings = Object.freeze(cooked);
3578
+ templateObjects.set(quasi, strings);
3579
+ }
3580
+ return strings;
3581
+ };
3582
+ /**
3583
+ * The tag's arguments: the template object, then the value of each of its
3584
+ * expressions, evaluated in order.
3554
3585
  */
3555
3586
  const templateArguments = (node, st, callback) => {
3556
3587
  const values = node.quasi.expressions.map((expression) => {
3557
3588
  callback(expression, st);
3558
3589
  return popVisitorResult(node, st);
3559
3590
  });
3560
- const strings = node.quasi.quasis.map((templateElement) => templateElement.value.cooked);
3561
- return [strings, ...values];
3591
+ return [templateObject(node.quasi), ...values];
3562
3592
  };
3563
3593
  /**
3564
3594
  * Calls the tag as a call calls its callee (`call-expression.ts`): past the
@@ -3982,6 +4012,53 @@ const evaluateRestElement = (pattern, st, callback, args) => {
3982
4012
  // return object;
3983
4013
  // }
3984
4014
 
4015
+ /**
4016
+ * The statement types `dispatchStatement` walks, and the one place they are
4017
+ * listed.
4018
+ *
4019
+ * `VariableDeclaration` covers `var` as well, and cannot not: this table reads
4020
+ * the node *type*, and `var x = 1` is a `VariableDeclaration` exactly as
4021
+ * `let x = 1` is. Listing it here is therefore what stops `var` reaching the
4022
+ * dispatcher's throw; its rejection is `declarationKindRefusal`, below, which
4023
+ * the visitor calls because it can read `kind`.
4024
+ *
4025
+ * `ForStatement` is the classic three-part form *only*. `ForOfStatement`,
4026
+ * `ForInStatement`, `WhileStatement` and `DoWhileStatement` are distinct node
4027
+ * types and stay out of the table, so they are refused unchanged - unlike
4028
+ * `var`, which shares a type with `let` and is refused one level down.
4029
+ */
4030
+ const SUPPORTED_STATEMENT_TYPES = new Set([
4031
+ 'ExpressionStatement',
4032
+ 'EmptyStatement',
4033
+ 'BlockStatement',
4034
+ 'VariableDeclaration',
4035
+ 'IfStatement',
4036
+ 'ForStatement',
4037
+ ]);
4038
+ /** The `VariableDeclaration` kinds the declaration visitor binds. */
4039
+ const SUPPORTED_DECLARATION_KINDS = new Set(['let', 'const']);
4040
+ /**
4041
+ * The message evaluation throws for a statement whose type it does not walk,
4042
+ * or `undefined` for one it does.
4043
+ *
4044
+ * `dispatchStatement` throws it, and `findUnsupportedStatement` reports it, so
4045
+ * the evaluator and the export cannot disagree about a type (`docs/backlog.md`
4046
+ * D13).
4047
+ */
4048
+ const statementTypeRefusal = (statement) => SUPPORTED_STATEMENT_TYPES.has(statement.type)
4049
+ ? undefined
4050
+ : `Unsupported statement type: ${statement.type}`;
4051
+ /**
4052
+ * The message evaluation throws for a declaration whose kind it does not bind,
4053
+ * `var` among them, or `undefined` for `let` and `const`.
4054
+ *
4055
+ * `variableDeclarationVisitor` throws it above its `beforeVisitor`, and
4056
+ * `findUnsupportedStatement` reports it.
4057
+ */
4058
+ const declarationKindRefusal = (declaration) => SUPPORTED_DECLARATION_KINDS.has(declaration.kind)
4059
+ ? undefined
4060
+ : `Unsupported variable declaration kind: ${declaration.kind}`;
4061
+
3985
4062
  /**
3986
4063
  * The scope a declaration binds into: the innermost one on the stack.
3987
4064
  *
@@ -4065,7 +4142,7 @@ const bindDeclarator = (declarator, value, kind, scope, st, callback) => {
4065
4142
  * **`var` is rejected here, not by the statement dispatcher.** The dispatcher
4066
4143
  * switches on node *type*, and `var x = 1` is a `VariableDeclaration` exactly as
4067
4144
  * `let x = 1` is - so registering this visitor is what stopped `var` reaching the
4068
- * throwing `default:`. Function-scoped hoisting is a second scoping model beside
4145
+ * dispatcher's throw. Function-scoped hoisting is a second scoping model beside
4069
4146
  * block scoping and is out of scope for this phase, so the rejection had to move
4070
4147
  * rather than disappear.
4071
4148
  *
@@ -4081,8 +4158,11 @@ const variableDeclarationVisitor = (node, st, callback) => {
4081
4158
  // from opening a frame it never closes. The others are covered the way every
4082
4159
  // throwing visitor in this library is: `evaluate`'s `catch` unwinds the open
4083
4160
  // nodes to its walk base.
4084
- if (node.kind !== 'let' && node.kind !== 'const') {
4085
- throw new Error(`Unsupported variable declaration kind: ${node.kind}`);
4161
+ // The kinds are `statement-support.ts`' table, which
4162
+ // `findUnsupportedStatement` reads too.
4163
+ const refusal = declarationKindRefusal(node);
4164
+ if (refusal !== undefined) {
4165
+ throw new Error(refusal);
4086
4166
  }
4087
4167
  beforeVisitor(node, st);
4088
4168
  const scope = bindingScope(st);
@@ -4364,238 +4444,13 @@ const updateExpressionVisitor = (node, st, callback) => {
4364
4444
  afterVisitor(node, st);
4365
4445
  };
4366
4446
 
4367
- /**
4368
- * @description
4369
- * The colon-joined name grammar of `docs/colon-identifiers/phase-9-plan.md`
4370
- * § 3.4, as an acorn plugin (§ 3.5). `parse` uses the parser built here when
4371
- * `colonIdentifiers` is set, and acorn's own `parse` otherwise. No source text
4372
- * is rewritten, so every position acorn reports is a position in what the
4373
- * author wrote. Not re-exported from any barrel.
4374
- *
4375
- * Of acorn's documented API this module uses `Parser.extend`, `tokTypes` and
4376
- * the `input` member. Everything else it touches is an acorn internal,
4377
- * undeclared in acorn's `.d.ts`, and this is the complete list — what § 8 q3
4378
- * checks at the `acorn` peer floor:
4379
- *
4380
- * - members read: `pos`, `start`, `type`, `value`, `keywords`;
4381
- * - members written: `pos`, `containsEsc`;
4382
- * - methods overridden, each calling acorn's own through `super`: `readWord`,
4383
- * `finishToken`, `parsePropertyName`, `parseStatement`, `unexpected`;
4384
- * - methods called: `finishToken`, `raise`;
4385
- * - what the overrides assume of acorn's tokenizer: `readToken` is the only
4386
- * caller of `readWord`, with `pos` at the token's first character; every
4387
- * token is finished through `finishToken`, in source order, before the next
4388
- * is read — except that a `/` read as `slash` is finished again as
4389
- * `regexp`, and neither type is counted here; `?.`, `??` and `??=` are never
4390
- * `question` tokens; the `}` that closes a `${` is finished as `braceR`; the
4391
- * constructor reads no token;
4392
- * - what they assume of acorn's parser: every key of an object literal, an
4393
- * object pattern or a class body is read through `parsePropertyName`, with
4394
- * the key as the current token; every statement through `parseStatement`,
4395
- * with its first token as the current token; a colon the grammar cannot
4396
- * place reaches `unexpected`, from `expect` or `semicolon`, with `type` and
4397
- * `start` still at that colon.
4398
- *
4399
- * The token types it compares by identity, from `tokTypes`: `name`, `colon`,
4400
- * `question`, `comma`, `semi`, `parenL`, `parenR`, `bracketL`, `bracketR`,
4401
- * `braceL`, `braceR`, `dollarBraceL`.
4402
- */
4403
- const COLON = 58;
4404
- /** `[A-Za-z_$]`: the first character of a name that may join. */
4405
- const isFirstChar = (code) => (code >= 65 && code <= 90) || (code >= 97 && code <= 122) || code === 95 || code === 36;
4406
- /** `[A-Za-z0-9_$]`: any later character, and a segment's first. */
4407
- const isSegmentChar = (code) => isFirstChar(code) || (code >= 48 && code <= 57);
4408
- /** Whether a `:segment` starts at `pos`: a colon with a segment character after it. */
4409
- const joinsAt = (input, pos) => input.charCodeAt(pos) === COLON && isSegmentChar(input.charCodeAt(pos + 1));
4410
- const colonIdentifiers = (Base) => {
4411
- class ColonParser extends Base {
4412
- constructor() {
4413
- super(...arguments);
4414
- /** Never empty: the top level is never closed. */
4415
- this.levels = [{ pending: 0 }];
4416
- /**
4417
- * The level the current token was read at: for a `(`, `[`, `{` or `${`,
4418
- * the one around the level it opened.
4419
- */
4420
- this.tokenLevel = this.levels[0];
4421
- }
4422
- get level() {
4423
- return this.levels[this.levels.length - 1];
4424
- }
4425
- /**
4426
- * Reads a colon-joined name as one `name` token when one starts at `pos`
4427
- * and no `?` at this level is waiting for its `:` (§ 3.4, 1). In every
4428
- * other case acorn's own `readWord`, so a word that does not join is read
4429
- * exactly as acorn reads it.
4430
- */
4431
- readWord() {
4432
- const end = this.colonNameEnd();
4433
- if (end === undefined) {
4434
- return super.readWord();
4435
- }
4436
- const name = this.input.slice(this.pos, end);
4437
- if (this.level.pending > 0) {
4438
- this.level.suppressed = name;
4439
- return super.readWord();
4440
- }
4441
- this.pos = end;
4442
- this.containsEsc = false;
4443
- this.finishToken(tokTypes.name, name);
4444
- }
4445
- /**
4446
- * Where the colon name that starts at `pos` ends — its longest match — or
4447
- * `undefined` when none does: the first segment is not ASCII, is a keyword
4448
- * of the parse's `ecmaVersion`, or has no `:segment` directly after it.
4449
- */
4450
- colonNameEnd() {
4451
- const input = this.input;
4452
- let end = this.pos;
4453
- if (!isFirstChar(input.charCodeAt(end))) {
4454
- return undefined;
4455
- }
4456
- do {
4457
- end++;
4458
- } while (isSegmentChar(input.charCodeAt(end)));
4459
- if (!joinsAt(input, end) || this.keywords.test(input.slice(this.pos, end))) {
4460
- return undefined;
4461
- }
4462
- do {
4463
- end += 2;
4464
- while (isSegmentChar(input.charCodeAt(end))) {
4465
- end++;
4466
- }
4467
- } while (joinsAt(input, end));
4468
- return end;
4469
- }
4470
- /**
4471
- * Keeps the levels after acorn has finished the token, recording the one
4472
- * the token was read at: `(`, `[`, `{` and `${` open a level and `)`, `]`
4473
- * and `}` close it; a `?` is counted at its level and a `:` there
4474
- * uncounts it. `?.` and `??` are other token types, and count for nothing.
4475
- */
4476
- finishToken(type, value) {
4477
- super.finishToken(type, value);
4478
- const level = this.level;
4479
- this.tokenLevel = level;
4480
- switch (type) {
4481
- case tokTypes.parenL:
4482
- case tokTypes.bracketL:
4483
- case tokTypes.braceL:
4484
- case tokTypes.dollarBraceL:
4485
- this.levels.push({ pending: 0 });
4486
- break;
4487
- case tokTypes.parenR:
4488
- case tokTypes.bracketR:
4489
- case tokTypes.braceR:
4490
- if (this.levels.length > 1) {
4491
- this.levels.pop();
4492
- }
4493
- break;
4494
- case tokTypes.question:
4495
- level.pending++;
4496
- break;
4497
- case tokTypes.colon:
4498
- if (level.pending > 0) {
4499
- level.pending--;
4500
- }
4501
- break;
4502
- case tokTypes.comma:
4503
- case tokTypes.semi:
4504
- level.suppressed = undefined;
4505
- break;
4506
- }
4507
- }
4508
- /**
4509
- * Refuses a colon name as an object key, in a literal or a pattern alike
4510
- * (§ 3.4, 2): `{Q1:1}` is `{Q1: 1}` to JavaScript and a shorthand to the
4511
- * grammar, and keeping either would answer some author wrongly. Only a
4512
- * joined token is a `name` holding a colon.
4513
- */
4514
- parsePropertyName(prop) {
4515
- const name = this.value;
4516
- if (this.type === tokTypes.name && typeof name === 'string' && name.includes(':')) {
4517
- const first = name.slice(0, name.indexOf(':'));
4518
- this.raise(this.start, `Colon-joined name '${name}' cannot be an object key: ` +
4519
- `write '${first}: ...' with a space for a property, or quote the key`);
4520
- }
4521
- return super.parsePropertyName(prop);
4522
- }
4523
- /**
4524
- * Forgets the name not joined at the level a statement starts at: the
4525
- * statement boundary ended the conditional whose consequent lost it. A
4526
- * semicolon acorn inserts at a line break is such a boundary, and no `;`
4527
- * token marks it.
4528
- */
4529
- parseStatement(...args) {
4530
- this.tokenLevel.suppressed = undefined;
4531
- return super.parseStatement(...args);
4532
- }
4533
- /**
4534
- * acorn's own error, with the hint of § 3.4, 1 when the unexpected token
4535
- * is a `:` at a level that did not join a name since its last `,`, `;` or
4536
- * statement start: the colon the name lost to the conditional. Any other
4537
- * error is left as acorn words it.
4538
- */
4539
- unexpected(pos) {
4540
- const suppressed = this.tokenLevel.suppressed;
4541
- if (suppressed !== undefined && this.type === tokTypes.colon &&
4542
- (pos === undefined || pos === this.start)) {
4543
- return this.raise(this.start, 'Unexpected token: a colon-joined name in the ' +
4544
- `consequent of a conditional needs parentheses: (${suppressed})`);
4545
- }
4546
- return super.unexpected(pos);
4547
- }
4548
- }
4549
- return ColonParser;
4550
- };
4551
- /**
4552
- * acorn's `Parser` with the grammar, built once, at module load. `extend`
4553
- * returns a subclass, so acorn's own `Parser`, which `acorn.parse` uses, is
4554
- * left as it was.
4555
- */
4556
- const ColonIdentifiersParser = Parser.extend(colonIdentifiers);
4557
-
4558
- /**
4559
- * @description
4560
- * Parses expression and returns ES6/ES2020 AST.
4561
- * With `colonIdentifiers` set the parser is the colon-joined name grammar's;
4562
- * otherwise it is acorn's own `parse`.
4563
- * @param expr expression to parse
4564
- * @param options parser options
4565
- */
4566
- const parse = (expr, options) => {
4567
- options = { ecmaVersion: 2020, ...options };
4568
- const acornOptions = { ecmaVersion: 2020, ...options };
4569
- const program = options.colonIdentifiers
4570
- ? ColonIdentifiersParser.parse(expr, acornOptions)
4571
- : parse$1(expr, acornOptions);
4572
- if (!options.extractExpressions) {
4573
- return program;
4574
- }
4575
- return extractExpression(program);
4576
- };
4577
- /**
4578
- * @description
4579
- * Walks through the AST and extracts first expression.
4580
- * @param expr expression to parse
4581
- */
4582
- const extractExpression = (program) => {
4583
- if (program.body.length === 1) {
4584
- const expression = program.body[0];
4585
- if (expression.type === 'ExpressionStatement') {
4586
- return expression.expression;
4587
- }
4588
- }
4589
- return undefined;
4590
- };
4591
-
4592
4447
  /**
4593
4448
  * Applies § 3.1's rule 4: the empty-completion sentinel never leaves an
4594
4449
  * evaluation's return value.
4595
4450
  *
4596
4451
  * It is converted here, at the walk boundary, rather than in the `Program`
4597
- * visitor. `arrow-function-expression.ts` calls `evaluate` on a
4598
- * `BlockStatement` for a block-bodied arrow, so a conversion sited in `Program`
4452
+ * visitor. `arrow-function-expression.ts` walks a `BlockStatement` for a
4453
+ * block-bodied arrow, so a conversion sited in `Program`
4599
4454
  * would let `x => { }` hand the sentinel straight to a consumer. Converting
4600
4455
  * where the walk ends covers both entry points by construction.
4601
4456
  */
@@ -4634,7 +4489,7 @@ const completionValue = (value) => value === EMPTY_COMPLETION ? undefined : valu
4634
4489
  * mutation into a throw. `getDefaultVisitors()` still returns a **fresh,
4635
4490
  * mutable** object to anyone who calls it, so no caller loses anything.
4636
4491
  * - **Lazily** because a module-level `const` deadlocks the flattened bundle:
4637
- * `arrow-function-expression.ts` imports `evaluate`, so this module is
4492
+ * `arrow-function-expression.ts` imports `walkWithoutResult`, so this module is
4638
4493
  * initialised first and `getDefaultVisitors()` at module scope reads that
4639
4494
  * visitor before its binding exists. Measured, not guessed - the built
4640
4495
  * package threw `Cannot access 'arrowFunctionExpressionVisitor' before
@@ -4643,66 +4498,121 @@ const completionValue = (value) => value === EMPTY_COMPLETION ? undefined : valu
4643
4498
  let defaultVisitors;
4644
4499
  const mergedVisitors = () => (defaultVisitors ??= Object.freeze(walk.make(getDefaultVisitors())));
4645
4500
  /**
4646
- * Evaluates the given node and returns the result.
4647
- *
4648
- * @param node The node to evaluate.
4501
+ * The table a walk rooted at `root` dispatches through: the shared one, whose
4502
+ * `AwaitExpression` entry refuses every `await`, or - when the root has an
4503
+ * accepted `await` (`acceptedAwait`) - a fresh object over it whose own entry
4504
+ * accepts that node alone (`docs/backlog-retired.md` A24).
4505
+ *
4506
+ * The answer travels with the walk, not on the state or the node: the arrow
4507
+ * function's nested walk builds its own from its own root, so an enclosing
4508
+ * walk's accepted `await` is never in scope where it is not one. The entry is
4509
+ * defined, not assigned: `walk.make` would assign a `funcs` key onto an object
4510
+ * over the frozen table, which throws in strict mode. A walk with no accepted
4511
+ * `await` takes the shared table and pays nothing; one that has one builds a
4512
+ * single object, uncached.
4513
+ */
4514
+ const visitorsFor = (root, arrowBody) => {
4515
+ const accepted = acceptedAwait(root, arrowBody);
4516
+ return accepted
4517
+ ? Object.create(mergedVisitors(), {
4518
+ AwaitExpression: {
4519
+ value: (n, s, c) => awaitVisitor(n, s, c, n === accepted),
4520
+ },
4521
+ })
4522
+ : mergedVisitors();
4523
+ };
4524
+ /**
4525
+ * Walks the node on the state and returns its completion value, recording no
4526
+ * outcome: everything {@link evaluate} does except `state.result`'s `start`,
4527
+ * `stop`, `setSuccess` and `setFailure`.
4528
+ *
4529
+ * **The arrow-function body's walk** (`arrow-function-expression.ts`). That
4530
+ * body runs on the walk's own state, during the walk, after it, many times or
4531
+ * never, and up to 0.14.1 it ran through `evaluate` - so every call of an arrow
4532
+ * wrote its outcome, value and start time over the enclosing walk's result, and
4533
+ * a closure called after the walk wrote over the finished one
4534
+ * (`docs/backlog-retired.md` A27). The result now describes the entry-point walk alone.
4535
+ *
4536
+ * Not exported from the package: `functions/public-api.ts` does not list it.
4537
+ *
4538
+ * @param node The node to walk.
4649
4539
  * @param state The evaluation state.
4650
- * @returns The result of the evaluation.
4651
- */
4652
- const evaluate = (node, state) => {
4653
- if (node) {
4654
- state.result.start();
4655
- // Captured inside the `if (node)` block on purpose: callers reach the early
4656
- // return above with a bare state that has no hooks to read. Do not hoist.
4657
- //
4658
- // The mark is recorded on the state as well as held here, so that
4659
- // `EvalHooks.exit` - called from a visitor, which has no route to this
4660
- // local - can tell a node open in this walk from one open only in an
4661
- // enclosing walk. Pushed under the same guard the mark is read under, and
4662
- // the local `hooked` keeps the pair symmetric if a hook is registered
4663
- // mid-walk.
4664
- const hooked = state.hasHooks;
4665
- const mark = hooked ? state.hooks.pushWalkBase(state) : 0;
4666
- // Unguarded, unlike the walk base above: the iteration budget refills on
4667
- // the outermost entry whether or not hooks are registered. See
4668
- // `EvalState.walkDepth` on why these are two fields and not one.
4669
- state.enterWalk();
4670
- try {
4671
- walk.recursive(node, state, {}, mergedVisitors());
4672
- const value = completionValue(popVisitorResult(node, state));
4673
- state.result.stop();
4540
+ * @param arrowBody Whether the node is an arrow function's body, which
4541
+ * decides the `await` it accepts (`visitorsFor`).
4542
+ * @returns The node's completion value.
4543
+ */
4544
+ const walkWithoutResult = (node, state, arrowBody = false) => {
4545
+ // The mark is recorded on the state as well as held here, so that
4546
+ // `EvalHooks.exit` - called from a visitor, which has no route to this
4547
+ // local - can tell a node open in this walk from one open only in an
4548
+ // enclosing walk. Pushed under the same guard the mark is read under, and
4549
+ // the local `hooked` keeps the pair symmetric if a hook is registered
4550
+ // mid-walk.
4551
+ const hooked = state.hasHooks;
4552
+ const mark = hooked ? state.hooks.pushWalkBase(state) : 0;
4553
+ // Unguarded, unlike the walk base above: the iteration budget refills on
4554
+ // the outermost entry whether or not hooks are registered. See
4555
+ // `EvalState.walkDepth` on why these are two fields and not one.
4556
+ state.enterWalk();
4557
+ try {
4558
+ walk.recursive(node, state, {}, visitorsFor(node, arrowBody));
4559
+ return completionValue(popVisitorResult(node, state));
4560
+ }
4561
+ catch (error) {
4562
+ // A visitor that throws skips its afterVisitor, so close whatever this
4563
+ // walk left open. Unwinding to the mark rather than to the bottom is what
4564
+ // stops a nested walk - the arrow-function body runs on this same
4565
+ // state - from draining the enclosing walk's open nodes.
4566
+ // Reads `state.hasHooks` rather than the `hooked` local captured above,
4567
+ // and the difference is deliberate but narrow: if a hook was registered
4568
+ // *during* this walk then `hooked` is false, no base was pushed, `mark`
4569
+ // is 0, and this unwinds the whole stack - including an enclosing walk's
4570
+ // frames, which is the boundary crossing the walk base exists to stop.
4571
+ // Left as it was rather than tightened here, because narrowing it would
4572
+ // change what a mid-walk registration observes on an already-published
4573
+ // path, which is not this step's to decide.
4574
+ if (state.hasHooks) {
4575
+ state.hooks.unwindTo(mark, error, state);
4576
+ }
4577
+ throw error;
4578
+ }
4579
+ finally {
4580
+ // Both in a `finally`: a walk that threw still has to restore the
4581
+ // enclosing walk's bound and depth, or every later evaluation on this
4582
+ // state carries this one's nesting.
4583
+ state.exitWalk();
4584
+ if (hooked) {
4585
+ state.hooks.popWalkBase(state);
4586
+ }
4587
+ }
4588
+ };
4589
+ /**
4590
+ * Evaluates the given node and returns the result.
4591
+ *
4592
+ * Records the walk's outcome on `state.result`. An arrow function's body,
4593
+ * walked on the same state whenever the function is called, records nothing
4594
+ * there.
4595
+ *
4596
+ * @param node The node to evaluate.
4597
+ * @param state The evaluation state.
4598
+ * @returns The result of the evaluation.
4599
+ */
4600
+ const evaluate = (node, state) => {
4601
+ // The `if (node)` guard comes first on purpose: callers reach the early
4602
+ // return below with a bare state that has no result or hooks to read.
4603
+ if (node) {
4604
+ state.result.start();
4605
+ try {
4606
+ const value = walkWithoutResult(node, state);
4607
+ state.result.stop();
4674
4608
  state.result.setSuccess(value);
4675
4609
  return value;
4676
4610
  }
4677
4611
  catch (error) {
4678
4612
  state.result.stop();
4679
- // A visitor that throws skips its afterVisitor, so close whatever this
4680
- // walk left open. Unwinding to the mark rather than to the bottom is what
4681
- // stops a nested evaluate - the arrow-function body runs on this same
4682
- // state - from draining the enclosing walk's open nodes.
4683
- // Reads `state.hasHooks` rather than the `hooked` local captured above,
4684
- // and the difference is deliberate but narrow: if a hook was registered
4685
- // *during* this walk then `hooked` is false, no base was pushed, `mark`
4686
- // is 0, and this unwinds the whole stack - including an enclosing walk's
4687
- // frames, which is the boundary crossing the walk base exists to stop.
4688
- // Left as it was rather than tightened here, because narrowing it would
4689
- // change what a mid-walk registration observes on an already-published
4690
- // path, which is not this step's to decide.
4691
- if (state.hasHooks) {
4692
- state.hooks.unwindTo(mark, error, state);
4693
- }
4694
4613
  state.result.setFailure(error);
4695
4614
  throw error;
4696
4615
  }
4697
- finally {
4698
- // Both in a `finally`: a walk that threw still has to restore the
4699
- // enclosing walk's bound and depth, or every later evaluation on this
4700
- // state carries this one's nesting.
4701
- state.exitWalk();
4702
- if (hooked) {
4703
- state.hooks.popWalkBase(state);
4704
- }
4705
- }
4706
4616
  }
4707
4617
  return undefined;
4708
4618
  };
@@ -4770,7 +4680,8 @@ const evaluateAsync = async (ast, state) => {
4770
4680
  }
4771
4681
  state.result.start();
4772
4682
  // Captured after the `!ast` early return above, for the same reason the sync
4773
- // entry point captures inside its `if (node)` block. Do not hoist.
4683
+ // entry point captures only once it has a node, in `walkWithoutResult`. Do
4684
+ // not hoist.
4774
4685
  const hooked = state.hasHooks;
4775
4686
  const mark = hooked ? state.hooks.pushWalkBase(state) : 0;
4776
4687
  state.enterWalk();
@@ -4783,7 +4694,7 @@ const evaluateAsync = async (ast, state) => {
4783
4694
  // evaluation that interleaved on this state looking like a nested walk -
4784
4695
  // and § 3.4's budget refills only on the outermost entry.
4785
4696
  try {
4786
- walk.recursive(ast, state, {}, mergedVisitors());
4697
+ walk.recursive(ast, state, {}, visitorsFor(ast, false));
4787
4698
  value = completionValue(popVisitorResult(ast, state));
4788
4699
  }
4789
4700
  finally {
@@ -4808,7 +4719,6 @@ const evaluateAsync = async (ast, state) => {
4808
4719
  return value;
4809
4720
  }
4810
4721
  catch (error) {
4811
- state.result.stop();
4812
4722
  // The walk here is synchronous too, so it strands open nodes on a throw
4813
4723
  // exactly as the sync entry point does. This catch also receives the
4814
4724
  // rethrow from the awaitAllPromises handler above; in that case the walk
@@ -4817,70 +4727,14 @@ const evaluateAsync = async (ast, state) => {
4817
4727
  if (state.hasHooks) {
4818
4728
  state.hooks.unwindTo(mark, error, state);
4819
4729
  }
4730
+ // After the unwind, as on the sync path, so a hook that fires during the
4731
+ // cleanup reads `duration` `undefined` there too: the walk has not ended.
4732
+ state.result.stop();
4820
4733
  state.result.setFailure(error);
4821
4734
  throw error;
4822
4735
  }
4823
4736
  };
4824
4737
 
4825
- /**
4826
- * Compiles the given node and returns a function that can be used to evaluate it.
4827
- *
4828
- * @param node The node to compile.
4829
- * @returns A function that takes an `EvalState` and returns the result of evaluating the node.
4830
- */
4831
- const compile = (node) => {
4832
- return evaluate.bind(null, node);
4833
- };
4834
- /**
4835
- * Compiles the given node asynchronously.
4836
- *
4837
- * @param node - The node to compile.
4838
- * @returns A function that takes an `EvalState` object and returns a `Promise` that resolves to the compiled result.
4839
- */
4840
- const compileAsync = (node) => {
4841
- return evaluateAsync.bind(null, node);
4842
- };
4843
- /**
4844
- * Calls the provided function with the given state and returns the result.
4845
- *
4846
- * @param fn The function to be called.
4847
- * @param state The state to be passed to the function.
4848
- * @returns The result of calling the function.
4849
- */
4850
- const call = (fn, state) => {
4851
- const value = fn(state);
4852
- return value;
4853
- };
4854
- /**
4855
- * Calls an asynchronous function with the given state and returns a promise that resolves to the result.
4856
- * @param fn The asynchronous function to call.
4857
- * @param state The state to pass to the function.
4858
- * @returns A promise that resolves to the result of the function.
4859
- */
4860
- const callAsync = (fn, state) => {
4861
- const promise = fn(state);
4862
- return promise;
4863
- };
4864
-
4865
- /**
4866
- * Finds all nodes of a specific type in the given AST.
4867
- *
4868
- * @param ast The AST to search in.
4869
- * @param searchType The type of nodes to search for.
4870
- * @returns An array of nodes of the specified type if found, otherwise undefined.
4871
- */
4872
- const extract = (node, searchType) => {
4873
- if (node) {
4874
- const state = [];
4875
- const visitors = {
4876
- [searchType]: (node) => { state.push(node); return; }
4877
- };
4878
- walk.simple(node, visitors);
4879
- return state.length > 0 ? state : undefined;
4880
- }
4881
- return undefined;
4882
- };
4883
-
4884
4738
  const arrowFunctionExpressionVisitor = (node, st, callback) => {
4885
4739
  beforeVisitor(node, st);
4886
4740
  const fn = (...arrowArgs) => {
@@ -4888,7 +4742,7 @@ const arrowFunctionExpressionVisitor = (node, st, callback) => {
4888
4742
  // The scope stack lives on EvalContext, not on the per-walk EvalState, and
4889
4743
  // one EvalContext can back any number of evaluations - so a scope this
4890
4744
  // closure fails to pop outlives the walk and is read first by every later
4891
- // evaluation on the same context. The body is re-entrant `evaluate`, which
4745
+ // evaluation on the same context. The body is a re-entrant walk, which
4892
4746
  // rethrows, so the pop needs `finally`.
4893
4747
  //
4894
4748
  // The `try` opens *after* the push, never around it. `contextPush` skips
@@ -4899,12 +4753,18 @@ const arrowFunctionExpressionVisitor = (node, st, callback) => {
4899
4753
  // Both take the method from the context's class (`context-method.ts`).
4900
4754
  // This site is the one an expression could reach twice over: a planted
4901
4755
  // own `push` would be invoked here with the real context as its `this`,
4902
- // and - since this closure's body is a re-entrant `evaluate` that pushes
4756
+ // and - since this closure's body is a re-entrant walk that pushes
4903
4757
  // again - a plant that evaluates anything recurses until the stack is
4904
4758
  // gone, leaving a reused context unusable (`docs/backlog.md` A42).
4905
- contextPush(st.context, newContext);
4759
+ contextPush(st.context, newContext, st.options);
4906
4760
  try {
4907
- return evaluate(node.body, st);
4761
+ // `walkWithoutResult`, not `evaluate`: the body's walk records nothing
4762
+ // on `st.result`, which describes the entry-point walk alone - during
4763
+ // that walk and after it, however often this closure is called
4764
+ // (`docs/backlog-retired.md` A27). As an arrow's body, it accepts the
4765
+ // `await` of an expression body or of a block body's last statement
4766
+ // (`docs/backlog-retired.md` A24).
4767
+ return walkWithoutResult(node.body, st, true);
4908
4768
  }
4909
4769
  finally {
4910
4770
  contextPop(st.context);
@@ -4926,13 +4786,15 @@ const arrowFunctionExpressionVisitor = (node, st, callback) => {
4926
4786
  * statement list, `IfStatement` a branch, and `ForStatement` an `init` and a
4927
4787
  * body.
4928
4788
  *
4929
- * **It is explicit, and its `default` throws.** A node type this library does
4930
- * not implement raises rather than falling through to `acorn-walk`'s base
4931
- * walker, which would visit the subtree as an expression and strand whatever it
4932
- * pushed - `while (false) { 1 }` used to evaluate to `1` that way. Three
4933
- * visitors in this library already push nothing on one path of an `if`/`else if`
4934
- * chain over node types (`docs/backlog.md` A2); a `switch` whose `default`
4935
- * throws is how this family gains no fourth member.
4789
+ * **It is explicit, and a type outside its table throws.** A node type this
4790
+ * library does not implement raises rather than falling through to
4791
+ * `acorn-walk`'s base walker, which would visit the subtree as an expression and
4792
+ * strand whatever it pushed - `while (false) { 1 }` used to evaluate to `1` that
4793
+ * way. Three visitors in this library already push nothing on one path of an
4794
+ * `if`/`else if` chain over node types (`docs/backlog.md` A2); a table whose
4795
+ * miss throws is how this family gains no fourth member. The table and its
4796
+ * message are `statementTypeRefusal`'s, in `statement-support.ts`, since D13:
4797
+ * this was a `switch` whose `default` threw until then.
4936
4798
  *
4937
4799
  * **Why this module exists.** It lived in `program.ts` for steps 1 to 5, on the
4938
4800
  * rule that a shared helper earns its own file at its *third* importer -
@@ -4951,29 +4813,14 @@ const arrowFunctionExpressionVisitor = (node, st, callback) => {
4951
4813
  * for a doc link is an unused binding the lint config rejects.
4952
4814
  */
4953
4815
  const dispatchStatement = (statement, st, callback) => {
4954
- switch (statement.type) {
4955
- // `VariableDeclaration` covers `var` as well, and cannot not: this `switch`
4956
- // reads the node *type*, and `var x = 1` is a `VariableDeclaration` exactly
4957
- // as `let x = 1` is. Listing it here is therefore what stopped `var`
4958
- // reaching the `default:` below; the rejection moved into the visitor,
4959
- // which can read `kind`.
4960
- //
4961
- // `ForStatement` is the classic three-part form *only*. `ForOfStatement`,
4962
- // `ForInStatement`, `WhileStatement` and `DoWhileStatement` are distinct
4963
- // node types and stay out of the phase (§ 2), so they reach the `default`
4964
- // below unchanged - unlike `var`, which shares a type with `let` and had to
4965
- // be rejected one level down.
4966
- case 'ExpressionStatement':
4967
- case 'EmptyStatement':
4968
- case 'BlockStatement':
4969
- case 'VariableDeclaration':
4970
- case 'IfStatement':
4971
- case 'ForStatement':
4972
- callback(statement, st);
4973
- return popVisitorResult(statement, st);
4974
- default:
4975
- throw new Error(`Unsupported statement type: ${statement.type}`);
4816
+ // The types walked are `statement-support.ts`' table, which
4817
+ // `findUnsupportedStatement` reads too, so the two cannot disagree.
4818
+ const refusal = statementTypeRefusal(statement);
4819
+ if (refusal !== undefined) {
4820
+ throw new Error(refusal);
4976
4821
  }
4822
+ callback(statement, st);
4823
+ return popVisitorResult(statement, st);
4977
4824
  };
4978
4825
 
4979
4826
  /**
@@ -4985,9 +4832,9 @@ const dispatchStatement = (statement, st, callback) => {
4985
4832
  * completion-value semantics, and pushes exactly one value however many
4986
4833
  * statements the body holds. A program whose statements all produced nothing -
4987
4834
  * `;`, or a source that is only whitespace - pushes {@link EMPTY_COMPLETION},
4988
- * which the walk boundary in `evaluate` converts to `undefined`. The conversion
4989
- * is deliberately not done here: `arrow-function-expression.ts` calls
4990
- * `evaluate` on a `BlockStatement` for a block-bodied arrow, so a `Program`-side
4835
+ * which the walk boundary in `evaluate.ts` converts to `undefined`. The
4836
+ * conversion is deliberately not done here: `arrow-function-expression.ts`
4837
+ * walks a `BlockStatement` for a block-bodied arrow, so a `Program`-side
4991
4838
  * conversion would leave that entry point handing the sentinel to a consumer.
4992
4839
  *
4993
4840
  * **The program-level scope is required.** It is the only scope a top-level
@@ -5051,10 +4898,10 @@ const expressionStatementVisitor = (node, st, callback) => {
5051
4898
  * {@link EMPTY_COMPLETION} and an enclosing statement list keeps whatever
5052
4899
  * preceded it.
5053
4900
  *
5054
- * One line of behaviour, and it exists because the statement dispatcher's
5055
- * `default` throws: without it `a;;b` and `if (x) ;` would start raising
5056
- * "unsupported statement type", which is a divergence from JavaScript nobody
5057
- * chose.
4901
+ * One line of behaviour, and it exists because the statement dispatcher
4902
+ * throws for a type outside its table: without it `a;;b` and `if (x) ;` would
4903
+ * start raising "unsupported statement type", which is a divergence from
4904
+ * JavaScript nobody chose.
5058
4905
  */
5059
4906
  const emptyStatementVisitor = (node, st) => {
5060
4907
  beforeVisitor(node, st);
@@ -5071,10 +4918,10 @@ const emptyStatementVisitor = (node, st) => {
5071
4918
  * statements the body holds. A block whose statements all produced nothing -
5072
4919
  * `{ }`, or `{ ; }` - pushes {@link EMPTY_COMPLETION} for its enclosing
5073
4920
  * statement list to skip over. The sentinel is converted to `undefined` at the
5074
- * walk boundary in `evaluate`, which is why this visitor may return it to a
5075
- * caller that is itself a walk root: `arrow-function-expression.ts` calls
5076
- * `evaluate` on this node for a block-bodied arrow, so `x => { }` reaches a
5077
- * consumer through the same conversion a `Program` does.
4921
+ * walk boundary in `evaluate.ts`, which is why this visitor may return it to a
4922
+ * caller that is itself a walk root: `arrow-function-expression.ts` walks this
4923
+ * node for a block-bodied arrow, so `x => { }` reaches a consumer through the
4924
+ * same conversion a `Program` does.
5078
4925
  *
5079
4926
  * **The block scope is unobservable in this step, and is pushed anyway.**
5080
4927
  * Nothing binds into it until `VariableDeclaration` lands, and an empty scope
@@ -5174,7 +5021,7 @@ const blockStatementVisitor = (node, st, callback) => {
5174
5021
  * declaration is not a legal bare statement body; `if (a) var x = 1` does parse,
5175
5022
  * reaches the dispatcher as a `VariableDeclaration`, and is rejected on `kind`
5176
5023
  * inside `variableDeclarationVisitor`; and `if (a) function f() { }` parses
5177
- * under Annex B and is rejected by `dispatchStatement`'s throwing `default`.
5024
+ * under Annex B and is rejected by `dispatchStatement`, whose table omits it.
5178
5025
  *
5179
5026
  * **The fourth is closed by the dispatcher and not by anything here**, which is
5180
5027
  * the one a later phase can reopen: a phase that registers `FunctionDeclaration`
@@ -5205,12 +5052,12 @@ const ifStatementVisitor = (node, st, callback) => {
5205
5052
  * § 1.1's row measured **`NaN`** with three stranded values before Phase 2: the
5206
5053
  * base walker handed the declarator's `id` to `identifierVisitor`, so `i`
5207
5054
  * resolved against the context rather than binding, and `i < 3` compared
5208
- * `undefined`. Since step 1 the row throws from `dispatchStatement`'s `default`;
5209
- * this visitor is what returns `2`.
5055
+ * `undefined`. Since step 1 the row throws from `dispatchStatement`, which
5056
+ * refuses a type outside its table; this visitor is what returns `2`.
5210
5057
  *
5211
5058
  * `for…of`, `for…in`, `while` and `do…while` stay out of the phase (§ 2) and
5212
- * keep throwing - they are separate node types and reach the dispatcher's
5213
- * `default` unchanged.
5059
+ * keep throwing - they are separate node types, outside the dispatcher's table,
5060
+ * and are refused unchanged.
5214
5061
  *
5215
5062
  * **One scope for the loop, not one per iteration.** A draft of the plan
5216
5063
  * specified a fresh scope per iteration, seeded from the head and copied back
@@ -5230,10 +5077,10 @@ const ifStatementVisitor = (node, st, callback) => {
5230
5077
  * through `dispatchStatement`; `for (i = 0; …)` parses it as an `Expression` and
5231
5078
  * takes a raw `callback`. Both pop exactly one - the declaration's `EMPTY`, or
5232
5079
  * the expression's value - so § 3.1's arithmetic is identical for the two and
5233
- * the split is invisible to it. What depends on the split is the throwing
5234
- * `default`: only the `dispatchStatement` route has one, so an `init` that is a
5235
- * statement type this library does not implement is rejected rather than handed
5236
- * to the base walker. `body` is a `Statement` and dispatches for the same
5080
+ * the split is invisible to it. What depends on the split is the refusal of a
5081
+ * type outside the table: only the `dispatchStatement` route has one, so an
5082
+ * `init` that is a statement type this library does not implement is rejected
5083
+ * rather than handed to the base walker. `body` is a `Statement` and dispatches for the same
5237
5084
  * reason; `test` and `update` are expressions and do not.
5238
5085
  *
5239
5086
  * Arithmetic (§ 3.1): pops 1 for `init` when present, then per iteration 1 for
@@ -5875,6 +5722,22 @@ class EvalTrace extends Array {
5875
5722
 
5876
5723
  /**
5877
5724
  * Represents the result of an evaluation.
5725
+ *
5726
+ * **The outcome describes the last entry-point walk on the state**: its
5727
+ * {@link value}, {@link error}, {@link errorMessage}, {@link isSuccess},
5728
+ * {@link isError}, {@link isUndefined} and {@link duration}. Each entry point
5729
+ * resets the outcome when its walk starts and writes it when the walk ends - for
5730
+ * `evalAsync` and its kin, once the result's promises have settled, so between
5731
+ * return and settlement a walk that did not throw reports neither success nor
5732
+ * failure. An arrow function's body runs a walk of its own on the same state,
5733
+ * and it changes nothing here: not while the enclosing walk runs, and not when
5734
+ * a function the walk built is called later. Up to 0.14.1 it overwrote all of it
5735
+ * (`docs/backlog-retired.md` A27). Two `evalAsync` runs interleaved on one
5736
+ * state share one outcome: the later start resets it, and the last to settle
5737
+ * writes it.
5738
+ *
5739
+ * The {@link trace} is not part of the outcome: it spans every evaluation run on
5740
+ * the state, and only {@link clearTrace} resets it.
5878
5741
  */
5879
5742
  class EvalResult {
5880
5743
  /**
@@ -5884,37 +5747,45 @@ class EvalResult {
5884
5747
  return this._stack;
5885
5748
  }
5886
5749
  /**
5887
- * Gets the evaluated value.
5750
+ * Gets the evaluated value: the last entry-point walk's, and `undefined`
5751
+ * once that walk failed or while it is pending.
5888
5752
  */
5889
5753
  get value() {
5890
5754
  return this._value;
5891
5755
  }
5892
5756
  /**
5893
- * Gets the error that occurred during evaluation.
5757
+ * Gets the error the last entry-point walk failed with, and `undefined` once
5758
+ * it succeeded or while it is pending. An error an arrow function's body
5759
+ * threw and something in the walk caught is not the walk's.
5894
5760
  */
5895
5761
  get error() {
5896
5762
  return this._error;
5897
5763
  }
5898
5764
  /**
5899
- * Gets the error message associated with the evaluation error.
5765
+ * Gets {@link error}'s message when it is an `Error`, and `undefined`
5766
+ * otherwise.
5900
5767
  */
5901
5768
  get errorMessage() {
5902
5769
  return this._errorMessage;
5903
5770
  }
5904
5771
  /**
5905
- * Gets whether the evaluation resulted in an error.
5772
+ * Gets whether the last entry-point walk failed: `undefined` while it is
5773
+ * pending.
5906
5774
  */
5907
5775
  get isError() {
5908
5776
  return this._isError;
5909
5777
  }
5910
5778
  /**
5911
- * Gets whether the evaluation was successful.
5779
+ * Gets whether the last entry-point walk succeeded: `undefined` while it is
5780
+ * pending.
5912
5781
  */
5913
5782
  get isSuccess() {
5914
5783
  return this._isSuccess;
5915
5784
  }
5916
5785
  /**
5917
- * Gets whether the evaluated value is undefined.
5786
+ * Gets whether {@link value} is `undefined`, once the last entry-point walk
5787
+ * has ended - including after a failure, which clears the value. `undefined`
5788
+ * while it is pending.
5918
5789
  */
5919
5790
  get isUndefined() {
5920
5791
  return this._isUndefined;
@@ -5965,7 +5836,8 @@ class EvalResult {
5965
5836
  return this._context.options;
5966
5837
  }
5967
5838
  /**
5968
- * Gets the duration of the evaluation result.
5839
+ * Gets the duration of the last entry-point walk, an arrow function's body
5840
+ * called inside it included: `undefined` while it is pending.
5969
5841
  * @returns The duration in milliseconds.
5970
5842
  */
5971
5843
  get duration() {
@@ -6064,10 +5936,24 @@ class EvalResult {
6064
5936
  this._traceTruncated = false;
6065
5937
  }
6066
5938
  /**
6067
- * Starts the evaluation process.
5939
+ * Starts the evaluation process, and resets the outcome: {@link value},
5940
+ * {@link error}, {@link errorMessage}, {@link isSuccess}, {@link isError},
5941
+ * {@link isUndefined} and {@link duration} read `undefined` until the walk
5942
+ * ends. Leaves the
5943
+ * {@link trace}, {@link tracePushCount} and {@link traceTruncated} alone,
5944
+ * since the trace spans every evaluation on the state (`docs/backlog.md`
5945
+ * A15). Up to 0.14.1 it reset nothing, so a reused state reported the last
5946
+ * run's error until something overwrote it (A27).
6068
5947
  */
6069
5948
  start() {
6070
5949
  this._startDate = performance.now();
5950
+ this._endDate = undefined;
5951
+ this._value = undefined;
5952
+ this._error = undefined;
5953
+ this._errorMessage = undefined;
5954
+ this._isSuccess = undefined;
5955
+ this._isError = undefined;
5956
+ this._isUndefined = undefined;
6071
5957
  }
6072
5958
  /**
6073
5959
  * Stops the evaluation and records the end date.
@@ -6077,29 +5963,33 @@ class EvalResult {
6077
5963
  return this.duration;
6078
5964
  }
6079
5965
  /**
6080
- * Sets the success value of the evaluation result.
5966
+ * Sets the success value of the evaluation result, writing every outcome
5967
+ * field: the error and its message are cleared.
6081
5968
  *
6082
5969
  * @param value The value to set as the success value.
6083
5970
  * @returns void
6084
5971
  */
6085
5972
  setSuccess(value) {
6086
5973
  this._value = value;
5974
+ this._error = undefined;
5975
+ this._errorMessage = undefined;
6087
5976
  this._isSuccess = true;
6088
5977
  this._isError = false;
6089
- this._isUndefined = false;
5978
+ this._isUndefined = value === undefined;
6090
5979
  }
6091
5980
  /**
6092
- * Sets the failure state of the evaluation result.
5981
+ * Sets the failure state of the evaluation result, writing every outcome
5982
+ * field: the value is cleared, and the message is the error's when it is an
5983
+ * `Error`.
6093
5984
  * @param error The error object associated with the failure.
6094
5985
  */
6095
5986
  setFailure(error) {
5987
+ this._value = undefined;
6096
5988
  this._error = error;
6097
- if (error instanceof Error) {
6098
- this._errorMessage = error.message;
6099
- }
5989
+ this._errorMessage = error instanceof Error ? error.message : undefined;
6100
5990
  this._isSuccess = false;
6101
5991
  this._isError = true;
6102
- this._isUndefined = false;
5992
+ this._isUndefined = true;
6103
5993
  }
6104
5994
  }
6105
5995
 
@@ -6399,7 +6289,7 @@ class EvalHooks {
6399
6289
  * **"Open" means open in *this* walk.** Both routes below are bounded by the
6400
6290
  * current walk base ({@link EvalHookBookkeeping.walkBases}), so a node open
6401
6291
  * only in an enclosing walk falls into case 3 by either route - which is the
6402
- * behaviour case 3 already specifies for "not open at all". `evaluate` is
6292
+ * behaviour case 3 already specifies for "not open at all". The walk is
6403
6293
  * re-entered with the same state from an arrow-function body, so without the
6404
6294
  * bound a nested walk closing a node it never opened would flush the
6405
6295
  * enclosing walk's frames under `completed: false` events a consumer reads as
@@ -6456,7 +6346,7 @@ class EvalHooks {
6456
6346
  }
6457
6347
  /**
6458
6348
  * How many nodes the state has open. Captured as a mark before a walk, since
6459
- * `evaluate` is re-entered with the same state from an arrow-function body.
6349
+ * the walk is re-entered with the same state from an arrow-function body.
6460
6350
  *
6461
6351
  * This is a method rather than a getter because the stack it measures lives
6462
6352
  * on the state, not on this registry.
@@ -6466,10 +6356,11 @@ class EvalHooks {
6466
6356
  }
6467
6357
  /**
6468
6358
  * Records that a walk is starting at the state's current open depth, and
6469
- * returns that depth. Called by `evaluate` / `evaluateAsync` on entry, under
6470
- * their `hasHooks` guard, and paired with {@link popWalkBase} in a `finally`.
6359
+ * returns that depth. Called on entry by every walk - `evaluate`'s, an
6360
+ * arrow-function body's and `evaluateAsync`'s - under a `hasHooks` guard,
6361
+ * and paired with {@link popWalkBase} in a `finally`.
6471
6362
  *
6472
- * The returned value is the same mark those entry points hand to
6363
+ * The returned value is the same mark those walks hand to
6473
6364
  * {@link unwindTo}, so they capture it once rather than reading the depth
6474
6365
  * twice.
6475
6366
  */
@@ -6480,9 +6371,9 @@ class EvalHooks {
6480
6371
  return base;
6481
6372
  }
6482
6373
  /**
6483
- * Drops the innermost walk base. Called from the `finally` of the `evaluate`
6484
- * that pushed it, so an entry point whose walk threw still restores the
6485
- * enclosing walk's bound.
6374
+ * Drops the innermost walk base. Called from the `finally` of the walk that
6375
+ * pushed it, so a walk that threw still restores the enclosing walk's
6376
+ * bound.
6486
6377
  */
6487
6378
  popWalkBase(state) {
6488
6379
  state.hookBookkeeping.walkBases.pop();
@@ -6501,12 +6392,12 @@ class EvalHooks {
6501
6392
  }
6502
6393
  /**
6503
6394
  * Fires 'after' for every node the state has open above `mark`, innermost
6504
- * first, marked incomplete. Invoked from the catch in `evaluate`, so that a
6395
+ * first, marked incomplete. Invoked from the catch of every walk, so that a
6505
6396
  * visitor which throws still leaves every 'before' matched by exactly one
6506
6397
  * 'after'.
6507
6398
  *
6508
6399
  * Unwinding to a mark rather than to the bottom is what keeps a nested
6509
- * `evaluate` from draining the enclosing walk's open nodes when a host
6400
+ * walk from draining the enclosing walk's open nodes when a host
6510
6401
  * function swallows the nested throw.
6511
6402
  *
6512
6403
  * Idempotent, so the sync and async entry points can both call it.
@@ -6854,10 +6745,9 @@ class EvalState {
6854
6745
  { open: [], errors: [], timings: new Map(), walkBases: [] });
6855
6746
  }
6856
6747
  /**
6857
- * How many `evaluate` / `evaluateAsync` calls on this state are currently on
6858
- * the JavaScript stack: 0 between evaluations, 1 during an ordinary walk, and
6859
- * more while a nested walk runs - an arrow-function body is re-entrant
6860
- * `evaluate` on this same state.
6748
+ * How many walks on this state are currently on the JavaScript stack: 0
6749
+ * between evaluations, 1 during an ordinary walk, and more while a nested
6750
+ * walk runs - an arrow-function body is a re-entrant walk on this same state.
6861
6751
  *
6862
6752
  * Maintained by {@link enterWalk} / {@link exitWalk}, which the entry points
6863
6753
  * pair around their walk, the exit in a `finally` so a throw still restores
@@ -6892,7 +6782,7 @@ class EvalState {
6892
6782
  enterWalk() {
6893
6783
  const depth = ++this._walkDepth;
6894
6784
  // § 3.4's refill, and the 0 -> 1 test is the whole of it. A nested walk -
6895
- // an arrow-function body, which re-enters `evaluate` on this same state -
6785
+ // an arrow-function body, which re-enters the walk on this same state -
6896
6786
  // shares whatever the enclosing walk has left, so an escaped closure cannot
6897
6787
  // buy itself a fresh budget by being called again. The options are re-read
6898
6788
  // per outermost walk rather than in the constructor because they are a
@@ -7277,6 +7167,336 @@ class BaseEval {
7277
7167
  }
7278
7168
  }
7279
7169
 
7170
+ /**
7171
+ * @description
7172
+ * The colon-joined name grammar of `docs/colon-identifiers/phase-9-plan.md`
7173
+ * § 3.4, as an acorn plugin (§ 3.5). `parse` uses the parser built here when
7174
+ * `colonIdentifiers` is set, and acorn's own `parse` otherwise. No source text
7175
+ * is rewritten, so every position acorn reports is a position in what the
7176
+ * author wrote. Not re-exported from any barrel.
7177
+ *
7178
+ * Of acorn's documented API this module uses `Parser.extend`, `tokTypes` and
7179
+ * the `input` member. Everything else it touches is an acorn internal,
7180
+ * undeclared in acorn's `.d.ts`, and this is the complete list — what § 8 q3
7181
+ * checks at the `acorn` peer floor:
7182
+ *
7183
+ * - members read: `pos`, `start`, `type`, `value`, `keywords`;
7184
+ * - members written: `pos`, `containsEsc`;
7185
+ * - methods overridden, each calling acorn's own through `super`: `readWord`,
7186
+ * `finishToken`, `parsePropertyName`, `parseStatement`, `unexpected`;
7187
+ * - methods called: `finishToken`, `raise`;
7188
+ * - what the overrides assume of acorn's tokenizer: `readToken` is the only
7189
+ * caller of `readWord`, with `pos` at the token's first character; every
7190
+ * token is finished through `finishToken`, in source order, before the next
7191
+ * is read — except that a `/` read as `slash` is finished again as
7192
+ * `regexp`, and neither type is counted here; `?.`, `??` and `??=` are never
7193
+ * `question` tokens; the `}` that closes a `${` is finished as `braceR`; the
7194
+ * constructor reads no token;
7195
+ * - what they assume of acorn's parser: every key of an object literal, an
7196
+ * object pattern or a class body is read through `parsePropertyName`, with
7197
+ * the key as the current token; every statement through `parseStatement`,
7198
+ * with its first token as the current token; a colon the grammar cannot
7199
+ * place reaches `unexpected`, from `expect` or `semicolon`, with `type` and
7200
+ * `start` still at that colon.
7201
+ *
7202
+ * The token types it compares by identity, from `tokTypes`: `name`, `colon`,
7203
+ * `question`, `comma`, `semi`, `parenL`, `parenR`, `bracketL`, `bracketR`,
7204
+ * `braceL`, `braceR`, `dollarBraceL`.
7205
+ */
7206
+ const COLON = 58;
7207
+ /** `[A-Za-z_$]`: the first character of a name that may join. */
7208
+ const isFirstChar = (code) => (code >= 65 && code <= 90) || (code >= 97 && code <= 122) || code === 95 || code === 36;
7209
+ /** `[A-Za-z0-9_$]`: any later character, and a segment's first. */
7210
+ const isSegmentChar = (code) => isFirstChar(code) || (code >= 48 && code <= 57);
7211
+ /** Whether a `:segment` starts at `pos`: a colon with a segment character after it. */
7212
+ const joinsAt = (input, pos) => input.charCodeAt(pos) === COLON && isSegmentChar(input.charCodeAt(pos + 1));
7213
+ const colonIdentifiers = (Base) => {
7214
+ class ColonParser extends Base {
7215
+ constructor() {
7216
+ super(...arguments);
7217
+ /** Never empty: the top level is never closed. */
7218
+ this.levels = [{ pending: 0 }];
7219
+ /**
7220
+ * The level the current token was read at: for a `(`, `[`, `{` or `${`,
7221
+ * the one around the level it opened.
7222
+ */
7223
+ this.tokenLevel = this.levels[0];
7224
+ }
7225
+ get level() {
7226
+ return this.levels[this.levels.length - 1];
7227
+ }
7228
+ /**
7229
+ * Reads a colon-joined name as one `name` token when one starts at `pos`
7230
+ * and no `?` at this level is waiting for its `:` (§ 3.4, 1). In every
7231
+ * other case acorn's own `readWord`, so a word that does not join is read
7232
+ * exactly as acorn reads it.
7233
+ */
7234
+ readWord() {
7235
+ const end = this.colonNameEnd();
7236
+ if (end === undefined) {
7237
+ return super.readWord();
7238
+ }
7239
+ const name = this.input.slice(this.pos, end);
7240
+ if (this.level.pending > 0) {
7241
+ this.level.suppressed = name;
7242
+ return super.readWord();
7243
+ }
7244
+ this.pos = end;
7245
+ this.containsEsc = false;
7246
+ this.finishToken(tokTypes.name, name);
7247
+ }
7248
+ /**
7249
+ * Where the colon name that starts at `pos` ends — its longest match — or
7250
+ * `undefined` when none does: the first segment is not ASCII, is a keyword
7251
+ * of the parse's `ecmaVersion`, or has no `:segment` directly after it.
7252
+ */
7253
+ colonNameEnd() {
7254
+ const input = this.input;
7255
+ let end = this.pos;
7256
+ if (!isFirstChar(input.charCodeAt(end))) {
7257
+ return undefined;
7258
+ }
7259
+ do {
7260
+ end++;
7261
+ } while (isSegmentChar(input.charCodeAt(end)));
7262
+ if (!joinsAt(input, end) || this.keywords.test(input.slice(this.pos, end))) {
7263
+ return undefined;
7264
+ }
7265
+ do {
7266
+ end += 2;
7267
+ while (isSegmentChar(input.charCodeAt(end))) {
7268
+ end++;
7269
+ }
7270
+ } while (joinsAt(input, end));
7271
+ return end;
7272
+ }
7273
+ /**
7274
+ * Keeps the levels after acorn has finished the token, recording the one
7275
+ * the token was read at: `(`, `[`, `{` and `${` open a level and `)`, `]`
7276
+ * and `}` close it; a `?` is counted at its level and a `:` there
7277
+ * uncounts it. `?.` and `??` are other token types, and count for nothing.
7278
+ */
7279
+ finishToken(type, value) {
7280
+ super.finishToken(type, value);
7281
+ const level = this.level;
7282
+ this.tokenLevel = level;
7283
+ switch (type) {
7284
+ case tokTypes.parenL:
7285
+ case tokTypes.bracketL:
7286
+ case tokTypes.braceL:
7287
+ case tokTypes.dollarBraceL:
7288
+ this.levels.push({ pending: 0 });
7289
+ break;
7290
+ case tokTypes.parenR:
7291
+ case tokTypes.bracketR:
7292
+ case tokTypes.braceR:
7293
+ if (this.levels.length > 1) {
7294
+ this.levels.pop();
7295
+ }
7296
+ break;
7297
+ case tokTypes.question:
7298
+ level.pending++;
7299
+ break;
7300
+ case tokTypes.colon:
7301
+ if (level.pending > 0) {
7302
+ level.pending--;
7303
+ }
7304
+ break;
7305
+ case tokTypes.comma:
7306
+ case tokTypes.semi:
7307
+ level.suppressed = undefined;
7308
+ break;
7309
+ }
7310
+ }
7311
+ /**
7312
+ * Refuses a colon name as an object key, in a literal or a pattern alike
7313
+ * (§ 3.4, 2): `{Q1:1}` is `{Q1: 1}` to JavaScript and a shorthand to the
7314
+ * grammar, and keeping either would answer some author wrongly. Only a
7315
+ * joined token is a `name` holding a colon.
7316
+ */
7317
+ parsePropertyName(prop) {
7318
+ const name = this.value;
7319
+ if (this.type === tokTypes.name && typeof name === 'string' && name.includes(':')) {
7320
+ const first = name.slice(0, name.indexOf(':'));
7321
+ this.raise(this.start, `Colon-joined name '${name}' cannot be an object key: ` +
7322
+ `write '${first}: ...' with a space for a property, or quote the key`);
7323
+ }
7324
+ return super.parsePropertyName(prop);
7325
+ }
7326
+ /**
7327
+ * Forgets the name not joined at the level a statement starts at: the
7328
+ * statement boundary ended the conditional whose consequent lost it. A
7329
+ * semicolon acorn inserts at a line break is such a boundary, and no `;`
7330
+ * token marks it.
7331
+ */
7332
+ parseStatement(...args) {
7333
+ this.tokenLevel.suppressed = undefined;
7334
+ return super.parseStatement(...args);
7335
+ }
7336
+ /**
7337
+ * acorn's own error, with the hint of § 3.4, 1 when the unexpected token
7338
+ * is a `:` at a level that did not join a name since its last `,`, `;` or
7339
+ * statement start: the colon the name lost to the conditional. Any other
7340
+ * error is left as acorn words it.
7341
+ */
7342
+ unexpected(pos) {
7343
+ const suppressed = this.tokenLevel.suppressed;
7344
+ if (suppressed !== undefined && this.type === tokTypes.colon &&
7345
+ (pos === undefined || pos === this.start)) {
7346
+ return this.raise(this.start, 'Unexpected token: a colon-joined name in the ' +
7347
+ `consequent of a conditional needs parentheses: (${suppressed})`);
7348
+ }
7349
+ return super.unexpected(pos);
7350
+ }
7351
+ }
7352
+ return ColonParser;
7353
+ };
7354
+ /**
7355
+ * acorn's `Parser` with the grammar, built once, at module load. `extend`
7356
+ * returns a subclass, so acorn's own `Parser`, which `acorn.parse` uses, is
7357
+ * left as it was.
7358
+ */
7359
+ const ColonIdentifiersParser = Parser.extend(colonIdentifiers);
7360
+
7361
+ /**
7362
+ * @description
7363
+ * Parses expression and returns ES6/ES2020 AST.
7364
+ * With `colonIdentifiers` set the parser is the colon-joined name grammar's;
7365
+ * otherwise it is acorn's own `parse`.
7366
+ * @param expr expression to parse
7367
+ * @param options parser options
7368
+ */
7369
+ const parse = (expr, options) => {
7370
+ options = { ecmaVersion: 2020, ...options };
7371
+ const acornOptions = { ecmaVersion: 2020, ...options };
7372
+ const program = options.colonIdentifiers
7373
+ ? ColonIdentifiersParser.parse(expr, acornOptions)
7374
+ : parse$1(expr, acornOptions);
7375
+ if (!options.extractExpressions) {
7376
+ return program;
7377
+ }
7378
+ return extractExpression(program);
7379
+ };
7380
+ /**
7381
+ * @description
7382
+ * Walks through the AST and extracts first expression.
7383
+ * @param expr expression to parse
7384
+ */
7385
+ const extractExpression = (program) => {
7386
+ if (program.body.length === 1) {
7387
+ const expression = program.body[0];
7388
+ if (expression.type === 'ExpressionStatement') {
7389
+ return expression.expression;
7390
+ }
7391
+ }
7392
+ return undefined;
7393
+ };
7394
+
7395
+ /**
7396
+ * Compiles the given node and returns a function that can be used to evaluate it.
7397
+ *
7398
+ * @param node The node to compile.
7399
+ * @returns A function that takes an `EvalState` and returns the result of evaluating the node.
7400
+ */
7401
+ const compile = (node) => {
7402
+ return evaluate.bind(null, node);
7403
+ };
7404
+ /**
7405
+ * Compiles the given node asynchronously.
7406
+ *
7407
+ * @param node - The node to compile.
7408
+ * @returns A function that takes an `EvalState` object and returns a `Promise` that resolves to the compiled result.
7409
+ */
7410
+ const compileAsync = (node) => {
7411
+ return evaluateAsync.bind(null, node);
7412
+ };
7413
+ /**
7414
+ * Calls the provided function with the given state and returns the result.
7415
+ *
7416
+ * @param fn The function to be called.
7417
+ * @param state The state to be passed to the function.
7418
+ * @returns The result of calling the function.
7419
+ */
7420
+ const call = (fn, state) => {
7421
+ const value = fn(state);
7422
+ return value;
7423
+ };
7424
+ /**
7425
+ * Calls an asynchronous function with the given state and returns a promise that resolves to the result.
7426
+ * @param fn The asynchronous function to call.
7427
+ * @param state The state to pass to the function.
7428
+ * @returns A promise that resolves to the result of the function.
7429
+ */
7430
+ const callAsync = (fn, state) => {
7431
+ const promise = fn(state);
7432
+ return promise;
7433
+ };
7434
+
7435
+ /**
7436
+ * Finds all nodes of a specific type in the given AST.
7437
+ *
7438
+ * @param ast The AST to search in.
7439
+ * @param searchType The type of nodes to search for.
7440
+ * @returns An array of nodes of the specified type if found, otherwise undefined.
7441
+ */
7442
+ const extract = (node, searchType) => {
7443
+ if (node) {
7444
+ const state = [];
7445
+ const visitors = {
7446
+ [searchType]: (node) => { state.push(node); return; }
7447
+ };
7448
+ walk.simple(node, visitors);
7449
+ return state.length > 0 ? state : undefined;
7450
+ }
7451
+ return undefined;
7452
+ };
7453
+
7454
+ /**
7455
+ * Whether a node is a statement or a module declaration. Every member of
7456
+ * acorn's `Statement` and `ModuleDeclaration` unions is named `…Statement` or
7457
+ * `…Declaration`, and no other node type is: a declarator is a
7458
+ * `VariableDeclarator`.
7459
+ */
7460
+ const isStatement = (node) => /(?:Statement|Declaration)$/.test(node.type);
7461
+ /** The message evaluation throws for this statement, or `undefined`. */
7462
+ const refusalOf = (statement) => statementTypeRefusal(statement)
7463
+ ?? (statement.type === 'VariableDeclaration' ? declarationKindRefusal(statement) : undefined);
7464
+ /**
7465
+ * Finds the first statement in a tree that evaluation would refuse.
7466
+ *
7467
+ * Evaluation refuses a statement only when the walk reaches it, so one in an
7468
+ * arrow function's body that is never called, or in a branch not taken, throws
7469
+ * nothing. This reads the whole tree instead - function bodies, untaken
7470
+ * branches and class bodies included - against the same table the evaluator
7471
+ * uses, and returns the message evaluation throws for that statement.
7472
+ *
7473
+ * "First" is source order, the lowest `start`, so a refused statement inside
7474
+ * another refused one is reported after it, as evaluation would meet the outer
7475
+ * one first.
7476
+ *
7477
+ * @param node The AST to search, as `parse` returns it.
7478
+ * @returns The statement and its message, or `undefined` when the tree holds
7479
+ * none, or `node` is `undefined`.
7480
+ */
7481
+ const findUnsupportedStatement = (node) => {
7482
+ if (!node) {
7483
+ return undefined;
7484
+ }
7485
+ let first;
7486
+ // `walk.full` calls back in post-order, an enclosing statement after the
7487
+ // ones inside it, so the first one visited is not the first in the source.
7488
+ walk.full(node, (visited) => {
7489
+ if (!isStatement(visited)) {
7490
+ return;
7491
+ }
7492
+ const message = refusalOf(visited);
7493
+ if (message !== undefined && (first === undefined || visited.start < first.statement.start)) {
7494
+ first = { statement: visited, message };
7495
+ }
7496
+ });
7497
+ return first;
7498
+ };
7499
+
7280
7500
  /**
7281
7501
  * The options a cached AST cannot honour: acorn calls each callback as it
7282
7502
  * parses, and appends to a caller's `program` node. A parse carrying any of
@@ -7426,13 +7646,31 @@ function provideColonIdentifiers() {
7426
7646
  */
7427
7647
  class ParserService {
7428
7648
  /**
7429
- * Gets the parser options.
7649
+ * Gets the parser options: the constructor's, or the last value given to
7650
+ * the setter.
7430
7651
  */
7431
7652
  get parserOptions() {
7432
7653
  return this._parserOptions;
7433
7654
  }
7434
7655
  /**
7435
- * Sets the parser options.
7656
+ * Sets the parser options for direct `ParserService.parse` calls, which
7657
+ * merge the options they are given over this value, the call's key winning,
7658
+ * for every key but `cacheSize`.
7659
+ *
7660
+ * `EvalService`, `CompilerService` and `DiscoveryService` pass their own
7661
+ * options on every parse, and those carry every key of
7662
+ * `defaultParserOptions`, so for each of them the service's key wins over
7663
+ * this value, `cacheSize` again aside. Only `cacheSize` and a key
7664
+ * `defaultParserOptions` does not carry reach those services through the
7665
+ * setter: `colonIdentifiers` is the one the README relies on
7666
+ * (`docs/backlog-retired.md` A30).
7667
+ *
7668
+ * `cacheSize` is read from this value alone, never from a call's or a
7669
+ * service's options. It sizes the parse cache once, at construction, and a
7670
+ * later value does not resize it. Whether a parse uses the cache is read
7671
+ * from it on every parse, so a later falsy one stops every parse using the
7672
+ * cache, the services' included.
7673
+ *
7436
7674
  * @param value The parser options to set.
7437
7675
  */
7438
7676
  set parserOptions(value) {
@@ -8006,5 +8244,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.2.3", ngImpor
8006
8244
  * Generated bundle index. Do not edit.
8007
8245
  */
8008
8246
 
8009
- 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 };
8247
+ 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 };
8010
8248
  //# sourceMappingURL=zvenigora-ng-eval-core.mjs.map