targeted-mutation 0.0.0-stage → 0.1.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.
Files changed (63) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +21 -0
  3. package/README.md +111 -2
  4. package/bin/tmt-compile.mjs +46 -0
  5. package/bin/tmt.mjs +117 -0
  6. package/build/typescript-syntax/LICENSE.txt +55 -0
  7. package/build/typescript-syntax/ThirdPartyNoticeText.txt +193 -0
  8. package/build/typescript-syntax/typescript-syntax.cjs +43 -0
  9. package/docs/analysis.md +218 -0
  10. package/docs/compiler.md +462 -0
  11. package/docs/development.md +61 -0
  12. package/docs/how-it-works.svg +188 -0
  13. package/docs/l1.md +94 -0
  14. package/docs/performance.md +647 -0
  15. package/docs/releasing.md +48 -0
  16. package/package.json +49 -4
  17. package/src/analysis.mjs +689 -0
  18. package/src/assertion-session.mjs +93 -0
  19. package/src/assertion-strength.mjs +795 -0
  20. package/src/builtin-mutations.mjs +755 -0
  21. package/src/builtin-switches.mjs +642 -0
  22. package/src/change-undone.mjs +524 -0
  23. package/src/cli-output.mjs +166 -0
  24. package/src/compiler-compat.cjs +108 -0
  25. package/src/compiler-maps.cjs +60 -0
  26. package/src/compiler-routes.cjs +391 -0
  27. package/src/compiler.cjs +98 -0
  28. package/src/compiler.mjs +1 -0
  29. package/src/conventional.mjs +172 -0
  30. package/src/displacement.mjs +19 -0
  31. package/src/extract.mjs +135 -0
  32. package/src/fallback-process.mjs +14 -0
  33. package/src/in-parallel.mjs +20 -0
  34. package/src/lean-replay.mjs +39 -0
  35. package/src/operator-analysis.mjs +123 -0
  36. package/src/playwright.mjs +139 -0
  37. package/src/probe-runtime.mjs +50 -0
  38. package/src/probe.mjs +170 -0
  39. package/src/prototype.mjs +230 -0
  40. package/src/regex-mutations.mjs +102 -0
  41. package/src/runner-process.mjs +59 -0
  42. package/src/runtime-binaries.mjs +50 -0
  43. package/src/scope.mjs +202 -0
  44. package/src/source-text.mjs +49 -0
  45. package/src/standard-plan.mjs +308 -0
  46. package/src/standard-runner.mjs +185 -0
  47. package/src/standard-session.mjs +362 -0
  48. package/src/standard-setup.mjs +20 -0
  49. package/src/targeted-gaps.mjs +85 -0
  50. package/src/threshold.mjs +185 -0
  51. package/src/trace-buffer.mjs +126 -0
  52. package/src/typescript-bindings.mjs +243 -0
  53. package/src/typescript-compiler.mjs +59 -0
  54. package/src/typescript-extraction.mjs +354 -0
  55. package/src/typescript-grammar.mjs +923 -0
  56. package/src/vitest-reporter.mjs +64 -0
  57. package/src/vitest.mjs +262 -0
  58. package/src/witness-analysis.mjs +234 -0
  59. package/src/witness-contracts.mjs +110 -0
  60. package/src/witness-discovery.mjs +239 -0
  61. package/src/witness-fixtures.mjs +148 -0
  62. package/src/witness-order.mjs +83 -0
  63. package/src/witness-rules.mjs +254 -0
@@ -0,0 +1,923 @@
1
+ export function createTypeScriptGrammar(ts, bindings) {
2
+ const {
3
+ NodeFlags, ScriptTarget, SyntaxKind, TokenFlags, canHaveModifiers, createScanner, forEachChild, getModifiers,
4
+ isAccessor, isArrayBindingPattern, isArrayLiteralExpression, isArrowFunction, isAsExpression,
5
+ isAwaitExpression, isBigIntLiteral, isBinaryExpression, isBindingElement, isBlock, isBreakStatement,
6
+ isCallExpression, isCaseBlock, isCatchClause, isClassDeclaration, isClassLike, isClassStaticBlockDeclaration,
7
+ isComputedPropertyName, isConstructorDeclaration, isContinueStatement, isDefaultClause, isDeleteExpression,
8
+ isElementAccessExpression, isEnumDeclaration, isEnumMember, isExportAssignment, isExportDeclaration,
9
+ isExpressionStatement, isForInOrOfStatement, isForInStatement, isForOfStatement, isForStatement,
10
+ isFunctionDeclaration, isFunctionExpression, isFunctionLike, isFunctionTypeNode, isGetAccessorDeclaration,
11
+ isIdentifier, isIfStatement, isImportAttribute, isImportClause, isImportDeclaration, isImportEqualsDeclaration,
12
+ isImportSpecifier, isImportTypeNode, isIndexSignatureDeclaration, isInterfaceDeclaration, isIterationStatement,
13
+ isJsxAttribute, isJsxAttributes, isJsxExpression, isJsxFragment, isLabeledStatement, isLiteralTypeNode,
14
+ isMappedTypeNode, isMetaProperty, isMethodDeclaration, isMethodSignature, isModuleBlock, isModuleDeclaration,
15
+ isNamedTupleMember, isNamespaceImport, isNewExpression, isNonNullExpression, isNumericLiteral,
16
+ isObjectBindingPattern, isObjectLiteralExpression, isOmittedExpression, isOptionalChain, isOptionalTypeNode,
17
+ isParameter, isParenthesizedExpression, isPostfixUnaryExpression, isPrefixUnaryExpression, isPrivateIdentifier,
18
+ isPropertyAccessExpression, isPropertyAssignment, isPropertyDeclaration, isPropertySignature, isQualifiedName,
19
+ isRegularExpressionLiteral, isRestTypeNode, isReturnStatement, isSatisfiesExpression, isSetAccessorDeclaration,
20
+ isShorthandPropertyAssignment, isSourceFile, isSpreadAssignment, isSpreadElement, isStatement, isStringLiteral,
21
+ isSwitchStatement, isTaggedTemplateExpression, isTemplateLiteralTypeNode, isTemplateLiteralTypeSpan,
22
+ isThrowStatement, isTupleTypeNode, isTypeAliasDeclaration, isTypeAssertionExpression, isTypeLiteralNode,
23
+ isTypeNode, isTypeOperatorNode, isTypeParameterDeclaration, isVariableDeclaration, isVariableDeclarationList,
24
+ isVariableStatement, isWithStatement, isYieldExpression, stringToToken,
25
+ } = ts;
26
+ const strictReservedBindings = new Set(['implements', 'interface', 'let', 'package', 'private', 'protected', 'public', 'static', 'yield']);
27
+ const strictRestrictedBindings = new Set(['eval', 'arguments']);
28
+ const accessModifiers = new Set([SyntaxKind.PublicKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.PrivateKeyword]);
29
+ const exclusiveModifiers = new Set([SyntaxKind.PublicKeyword, SyntaxKind.StaticKeyword, SyntaxKind.ReadonlyKeyword, SyntaxKind.OverrideKeyword]);
30
+ const isInstanceConstructor = node => isConstructorDeclaration(node) &&
31
+ !node.modifiers?.some(modifier => modifier.kind === SyntaxKind.StaticKeyword);
32
+
33
+ function checkStatement(node, parent, module, ambient, strict, async, frame, emit) {
34
+ const { functionContext, runtimeParameters, forHead, declarationScope } = frame;
35
+ const report = (message, at = node) => emit(at, message);
36
+ let binding;
37
+ if (
38
+ isVariableDeclaration(node) || isBindingElement(node) || isClassLike(node) ||
39
+ isEnumDeclaration(node) || isTypeAliasDeclaration(node) || isInterfaceDeclaration(node) ||
40
+ isModuleDeclaration(node) || isImportClause(node) || isNamespaceImport(node) ||
41
+ isImportSpecifier(node) || isImportEqualsDeclaration(node) ||
42
+ ((isFunctionDeclaration(node) || isFunctionExpression(node)) && node.body) ||
43
+ ((isTypeParameterDeclaration(node) || isParameter(node)) && runtimeParameters)
44
+ ) binding = node.name;
45
+ if (binding && isIdentifier(binding)) {
46
+ const name = binding.text;
47
+ if (!ambient && strict && strictReservedBindings.has(name)) report(`'${name}' is reserved in strict mode and cannot be used as a binding identifier`, binding);
48
+ else if (!ambient && strict && strictRestrictedBindings.has(name)) report(`'${name}' is not allowed as a binding identifier in strict mode`, binding);
49
+ else if (name === 'await' && (module || async) && (!ambient || isInterfaceDeclaration(node))) {
50
+ report("'await' is reserved in an async/module context and cannot be used as a binding identifier", binding);
51
+ }
52
+ }
53
+
54
+ if (isVariableDeclaration(node) && isVariableDeclarationList(parent) &&
55
+ !ambient && !declarationScope && !node.initializer && forHead !== 'iteration') {
56
+ const destructured = isObjectBindingPattern(node.name) || isArrayBindingPattern(node.name);
57
+ if (forHead === 'classic') {
58
+ if (destructured) report('Destructuring declaration in for loop initializer must be initialized');
59
+ else if ((parent.flags & NodeFlags.Const) !== 0) report("'const' declarations in for loop initializer must be initialized");
60
+ } else if (destructured) report('Destructuring declaration must have an initializer');
61
+ else if ((parent.flags & NodeFlags.Const) !== 0) report("'const' declarations must be initialized");
62
+ }
63
+
64
+ if (strict && isWithStatement(node)) report("'with' statements are not allowed in strict mode");
65
+ if (isReturnStatement(node) && !functionContext) report("'return' statement is only valid inside a function");
66
+ const single = parent && (
67
+ (isIfStatement(parent) && (parent.thenStatement === node || parent.elseStatement === node)) ||
68
+ ((isIterationStatement(parent, true) || isWithStatement(parent) || isLabeledStatement(parent)) && parent.statement === node)
69
+ );
70
+ if (single) {
71
+ if (isClassDeclaration(node)) report('Class declarations are not allowed in single-statement contexts');
72
+ if (isFunctionDeclaration(node) && node.body && (strict || !isIfStatement(parent) && !isLabeledStatement(parent))) {
73
+ report(strict ? 'In strict mode code, functions can only be declared at top level or inside a block' :
74
+ 'In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement');
75
+ }
76
+ if (isVariableStatement(node) && (node.declarationList.flags & NodeFlags.BlockScoped) !== 0) {
77
+ report('Lexical declaration cannot appear in a single-statement context');
78
+ }
79
+ }
80
+ }
81
+
82
+ function checkContexts(file, module, strictRoot, emit, hasVarBindings) {
83
+ const pending = [{
84
+ node: file, parent: undefined, loop: false, switch_: false, super_: 'none', labels: [],
85
+ outerLabels: [], ambient: false, strict: strictRoot,
86
+ async: false, functionContext: false, runtimeParameters: false, forHead: '', declarationScope: file.isDeclarationFile,
87
+ }];
88
+ const statementDiagnostics = [];
89
+ const recordStatement = (node, message) => { statementDiagnostics.push([node, message]); };
90
+ function duplicates(names) {
91
+ const seen = new Map();
92
+ for (const name of names) {
93
+ const first = seen.get(name.text);
94
+ if (first) emit(name, `Identifier '${name.text}' has already been declared`, first);
95
+ else seen.set(name.text, name);
96
+ }
97
+ }
98
+ function nestedAliases(statements) {
99
+ const aliases = [];
100
+ const pending = [...statements];
101
+ while (pending.length) {
102
+ const node = pending.pop();
103
+ const add = child => {
104
+ if (child && isTypeAliasDeclaration(child)) aliases.push(child);
105
+ else if (child && !isBlock(child)) pending.push(child);
106
+ };
107
+ if (isIfStatement(node)) { add(node.thenStatement); add(node.elseStatement); }
108
+ else if (isIterationStatement(node, false)) add(node.statement);
109
+ }
110
+ return aliases;
111
+ }
112
+ const isIteration = node => isIterationStatement(node, false);
113
+ const modifiersOf = node => canHaveModifiers(node) ? getModifiers(node) : undefined;
114
+ const lexicalListNames = list => list?.declarations.flatMap(decl => bindings.namesIn(decl.name)) ?? [];
115
+ while (pending.length) {
116
+ const frame = pending.pop();
117
+ const { node, parent, loop, switch_, super_, labels, outerLabels, ambient: parentAmbient,
118
+ strict: parentStrict, async: parentAsync, functionContext, runtimeParameters, forHead, declarationScope } = frame;
119
+ const report = (message, at = node) => emit(at, message);
120
+ const strict = strictScope(node, file, parentStrict);
121
+ const ambient = parentAmbient || modifiersOf(node)?.some(modifier => modifier.kind === SyntaxKind.DeclareKeyword);
122
+ const functionLike = isFunctionLike(node);
123
+ const async = functionLike ? node.modifiers?.some(modifier => modifier.kind === SyntaxKind.AsyncKeyword) : parentAsync;
124
+ if (node.kind !== SyntaxKind.SuperKeyword) checkStatement(node, parent, module, ambient, strict, async, frame, recordStatement);
125
+ if (functionLike) {
126
+ const ordinary = isFunctionDeclaration(node) || isFunctionExpression(node);
127
+ if (strict || !ordinary || node.parameters.some(nonSimpleParameter)) {
128
+ duplicates(node.parameters.flatMap(param => bindings.namesIn(param.name)));
129
+ }
130
+ }
131
+ if (isBlock(node) || isModuleBlock(node) || isCaseBlock(node)) {
132
+ const statements = isCaseBlock(node) ? node.clauses.flatMap(clause => [...clause.statements]) : [...node.statements];
133
+ const params = parent && isFunctionLike(parent) ? parent.parameters.flatMap(param => bindings.namesIn(param.name))
134
+ : parent && isCatchClause(parent) && parent.variableDeclaration ? bindings.namesIn(parent.variableDeclaration.name)
135
+ : [];
136
+ const catchPattern = parent && isCatchClause(parent) && parent.variableDeclaration && !isIdentifier(parent.variableDeclaration.name);
137
+ const deep = hasVarBindings ? statements.filter(statement => !isVariableStatement(statement)).flatMap(bindings.nestedVarsIn) : [];
138
+ const parameters = catchPattern ? params : [...new Map(params.map(name => [name.text, name])).values()];
139
+ bindings.checkScope([...statements, ...nestedAliases(statements)], emit, {
140
+ parameters, catchPattern, nestedVars: deep, ambient,
141
+ });
142
+ }
143
+ if (isIteration(node) && node.initializer && isVariableDeclarationList(node.initializer) &&
144
+ (node.initializer.flags & NodeFlags.BlockScoped) !== 0) {
145
+ const names = lexicalListNames(node.initializer);
146
+ duplicates(names);
147
+ const lexical = new Map(names.map(name => [name.text, name]));
148
+ const nested = hasVarBindings ? bindings.nestedVarsIn(node.statement) : [];
149
+ for (const name of nested) {
150
+ const earlier = lexical.get(name.text);
151
+ if (earlier) emit(name, `Identifier '${name.text}' has already been declared`, earlier);
152
+ }
153
+ }
154
+ if (isLabeledStatement(node)) {
155
+ const name = node.label.text;
156
+ if (strict && strictReservedBindings.has(name)) report(`'${name}' is reserved in strict mode and cannot be used as a label`, node.label);
157
+ if (labels.some(label => label.name === name)) report(`Duplicate label '${name}'`);
158
+ }
159
+ if (isBreakStatement(node) || isContinueStatement(node)) {
160
+ if (node.label) {
161
+ const name = node.label.text;
162
+ if (strict && strictReservedBindings.has(name)) report(`'${name}' is reserved in strict mode and cannot be used as a label`, node.label);
163
+ const target = labels.find(label => label.name === name);
164
+ if (!target) {
165
+ if (outerLabels.some(label => label.name === name)) {
166
+ report(`Cannot ${isBreakStatement(node) ? 'break' : 'continue'} to label '${name}' across function boundaries`);
167
+ } else report(`Use of undefined label '${name}'`);
168
+ }
169
+ else if (!isBreakStatement(node) && !target.iteration) report(`Label '${name}' does not denote an iteration statement`);
170
+ } else if (!loop && (!isBreakStatement(node) || !switch_)) {
171
+ report(isBreakStatement(node) ? 'Illegal break statement' : 'Illegal continue statement');
172
+ }
173
+ }
174
+ if (isImportDeclaration(node) && modifiersOf(node)?.some(modifier => modifier.kind === SyntaxKind.ExportKeyword)) {
175
+ report('An import declaration cannot have modifiers');
176
+ }
177
+ if (node.kind === SyntaxKind.SuperKeyword && parent) {
178
+ if (isCallExpression(parent) && parent.expression === node && super_ !== 'constructor') {
179
+ report("'super()' is only valid in a constructor of a derived class");
180
+ } else if ((isPropertyAccessExpression(parent) || isElementAccessExpression(parent)) &&
181
+ parent.expression === node && super_ === 'none') {
182
+ report("'super' property access is only valid inside a method or class body");
183
+ }
184
+ }
185
+ const staticBlock = isClassStaticBlockDeclaration(node);
186
+ const boundary = functionLike || staticBlock;
187
+ const childParameters = functionLike ? !!node.body : runtimeParameters || isClassLike(node) ||
188
+ isInterfaceDeclaration(node) || isTypeAliasDeclaration(node);
189
+ const childDeclarationScope = declarationScope && (isSourceFile(node) || isModuleDeclaration(node) ||
190
+ isModuleBlock(node) || isVariableStatement(node) || isVariableDeclarationList(node));
191
+ const childOuterLabels = boundary && labels.length ? [...labels, ...outerLabels] : outerLabels;
192
+ forEachChild(node, child => {
193
+ if (child.kind <= SyntaxKind.LastToken && child.kind !== SyntaxKind.SuperKeyword) return;
194
+ const childLoop = boundary ? false : isIteration(node) && node.statement === child ? true : loop;
195
+ const childSwitch = boundary ? false : isSwitchStatement(node) && node.caseBlock === child ? true : switch_;
196
+ let childLabels = boundary ? [] : labels;
197
+ if (isLabeledStatement(node) && node.statement === child) {
198
+ childLabels = [{ name: node.label.text, iteration: isIterationStatement(child, true) }, ...labels];
199
+ }
200
+ let childSuper = super_;
201
+ const usesMethodContext = child !== node.name && child.kind !== SyntaxKind.Decorator;
202
+ if (isConstructorDeclaration(node) && usesMethodContext) {
203
+ const derived = isInstanceConstructor(node) && parent && isClassLike(parent) &&
204
+ parent.heritageClauses?.some(c => c.token === SyntaxKind.ExtendsKeyword);
205
+ childSuper = derived ? 'constructor' : 'property';
206
+ } else if ((isMethodDeclaration(node) || isAccessor(node)) && usesMethodContext) childSuper = 'property';
207
+ else if (isFunctionDeclaration(node) || isFunctionExpression(node)) childSuper = 'none';
208
+ else if (staticBlock || (isPropertyDeclaration(node) && child === node.initializer)) childSuper = 'property';
209
+ const loopHead = isVariableDeclarationList(child) && node.initializer === child
210
+ ? (isForInOrOfStatement(node) ? 'iteration' : isForStatement(node) ? 'classic' : '')
211
+ : isVariableDeclarationList(node) ? forHead : '';
212
+ pending.push({ node: child, parent: node, loop: childLoop, switch_: childSwitch, super_: childSuper, labels: childLabels,
213
+ outerLabels: childOuterLabels, ambient, strict, async,
214
+ functionContext: !staticBlock && (functionLike && node.body === child || functionContext),
215
+ runtimeParameters: childParameters, forHead: loopHead, declarationScope: childDeclarationScope });
216
+ });
217
+ }
218
+ // Keep context diagnostics before statement diagnostics at the same byte offset.
219
+ for (const [node, message] of statementDiagnostics) emit(node, message);
220
+ }
221
+
222
+ // The remaining type checks use empty lists, template flags, multiple modifiers, or the parent kind.
223
+ const typeCheckKind = new Uint8Array(SyntaxKind.Count);
224
+ for (const kind of [
225
+ SyntaxKind.IndexSignature, SyntaxKind.CatchClause, SyntaxKind.EnumMember, SyntaxKind.TupleType,
226
+ SyntaxKind.Parameter, SyntaxKind.FunctionDeclaration, SyntaxKind.ClassDeclaration, SyntaxKind.ClassExpression,
227
+ SyntaxKind.InterfaceDeclaration, SyntaxKind.Constructor, SyntaxKind.MethodDeclaration, SyntaxKind.MethodSignature,
228
+ SyntaxKind.GetAccessor, SyntaxKind.SetAccessor, SyntaxKind.MappedType, SyntaxKind.PropertyDeclaration,
229
+ SyntaxKind.VariableDeclaration, SyntaxKind.PropertySignature, SyntaxKind.ArrowFunction, SyntaxKind.ThrowStatement,
230
+ SyntaxKind.NewExpression, SyntaxKind.BindingElement, SyntaxKind.ExportDeclaration, SyntaxKind.SwitchStatement,
231
+ SyntaxKind.JsxAttribute, SyntaxKind.JsxExpression, SyntaxKind.MetaProperty, SyntaxKind.RegularExpressionLiteral,
232
+ SyntaxKind.ImportType, SyntaxKind.ImportClause, SyntaxKind.ImportAttribute, SyntaxKind.ImportAttributes, SyntaxKind.ImportDeclaration,
233
+ ]) typeCheckKind[kind] = 1;
234
+
235
+ function createTypeSyntaxVisitor(file, module, emit) {
236
+ const scanner = createScanner(ScriptTarget.Latest, true, file.languageVariant, file.text);
237
+ function tokenAt(at) {
238
+ scanner.setTextPos(at);
239
+ return scanner.scan() === SyntaxKind.EndOfFileToken ? 'end of file' : scanner.getTokenText();
240
+ }
241
+ const modifiers = node => node.modifiers?.filter(modifier => modifier.kind !== SyntaxKind.Decorator) ?? [];
242
+ const propertyModifier = modifier => [
243
+ SyntaxKind.PublicKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.PrivateKeyword,
244
+ SyntaxKind.ReadonlyKeyword, SyntaxKind.OverrideKeyword,
245
+ ].includes(modifier.kind);
246
+ return function visitType(node, parent) {
247
+ if (!typeCheckKind[node.kind] && node.typeParameters?.length !== 0 && node.typeArguments?.length !== 0 &&
248
+ !node.templateFlags && !(node.modifiers?.length > 1) && parent?.kind !== SyntaxKind.ObjectLiteralExpression) return;
249
+ const add = (message, at = node) => emit(at, message);
250
+ if (node.typeParameters?.length === 0) add('A type parameter list cannot be empty');
251
+ if (node.typeArguments?.length === 0) add('A type argument list cannot be empty');
252
+ if (isIndexSignatureDeclaration(node)) {
253
+ if (module && node.parameters.some(param => isIdentifier(param.name) && param.name.text === 'await')) {
254
+ add("'await' is reserved in an async/module context and cannot be used as a binding identifier");
255
+ }
256
+ const key = node.parameters[0];
257
+ if (modifiers(node).some(modifier => modifier.kind !== SyntaxKind.ReadonlyKeyword) && parent && (isInterfaceDeclaration(parent) || isTypeLiteralNode(parent))) {
258
+ add("Expected ';', ',', or newline between type members, but found '['");
259
+ }
260
+ if (key?.dotDotDotToken) add("Unexpected token '...'");
261
+ else if (key?.questionToken) add("Unexpected token ':'");
262
+ else if (key && modifiers(key).length) add(`Expected ']' to close a computed property key, but found '${key.name.getText(file)}'`);
263
+ else if (key?.initializer) add("Expected ']' to close an index signature parameter list, but found '='");
264
+ else if (node.parameters.length === 0) add("Unexpected token ']'");
265
+ else if (node.parameters.length !== 1 || node.parameters.hasTrailingComma) add('An index signature must have exactly one parameter');
266
+ else if (!node.type) {
267
+ scanner.setTextPos(node.parameters.end);
268
+ let kind = scanner.scan();
269
+ if (kind === SyntaxKind.CloseBracketToken) kind = scanner.scan();
270
+ const token = kind === SyntaxKind.EndOfFileToken ? 'end of file' : scanner.getTokenText();
271
+ add(`Expected ':' after index signature parameters, but found '${token}'`);
272
+ }
273
+ }
274
+ const nodeModifiers = modifiers(node);
275
+ if (nodeModifiers.filter(flag => flag.kind === SyntaxKind.ExportKeyword).length > 1) {
276
+ add("Expected declaration after 'export', but found 'export'");
277
+ }
278
+ if (nodeModifiers.filter(flag => flag.kind === SyntaxKind.DeclareKeyword).length > 1) {
279
+ add("Expected a semicolon or an implicit semicolon after a statement, but found 'declare'");
280
+ }
281
+ if (nodeModifiers.length > 1 && parent && isClassLike(parent)) {
282
+ const seen = new Set();
283
+ for (const modifier of nodeModifiers) {
284
+ const group = accessModifiers.has(modifier.kind) ? SyntaxKind.PublicKeyword : modifier.kind;
285
+ if (!exclusiveModifiers.has(group)) continue;
286
+ if (seen.has(group)) {
287
+ add(`Expected ';' after class field, but found '${tokenAt(modifier.end)}'`);
288
+ break;
289
+ }
290
+ seen.add(group);
291
+ }
292
+ }
293
+ if (isCatchClause(node) && node.variableDeclaration?.initializer) {
294
+ add("Expected ')' after catch parameter, but found '='");
295
+ }
296
+ if (isEnumMember(node) && isComputedPropertyName(node.name)) {
297
+ add('Computed property names are not allowed in enums', node.name);
298
+ }
299
+ if (isTupleTypeNode(node)) {
300
+ let optional = false;
301
+ for (const element of node.elements) {
302
+ const currentOptional = isOptionalTypeNode(element) || isNamedTupleMember(element) && !!element.questionToken;
303
+ const rest = isRestTypeNode(element) || isNamedTupleMember(element) && !!element.dotDotDotToken;
304
+ if (optional && !currentOptional && !rest) add('A required element cannot follow an optional element');
305
+ optional ||= currentOptional;
306
+ }
307
+ }
308
+ if (isParameter(node) && !isIndexSignatureDeclaration(parent)) {
309
+ const flags = modifiers(node);
310
+ const constructor = isInstanceConstructor(parent);
311
+ const isProperty = constructor && flags.length && flags.every(propertyModifier);
312
+ if (isProperty && !isIdentifier(node.name)) {
313
+ add('A parameter property may not be declared using a binding pattern');
314
+ }
315
+ if (flags.length && node.dotDotDotToken) add("Unexpected token '...' in binding pattern");
316
+ if (node.dotDotDotToken && parent.parameters.at(-1) !== node) add('Rest parameter must be the last parameter');
317
+ if (node.dotDotDotToken && node.initializer) add("Expected ')' to close parameter list, but found '='");
318
+ if (node.dotDotDotToken && parent.parameters.hasTrailingComma) add('Rest parameter may not have a trailing comma');
319
+ if (node.dotDotDotToken && node.questionToken) add("Expected ')' to close parameter list, but found '?'");
320
+ const invalid = flags.find(flag => !constructor || !propertyModifier(flag));
321
+ if (invalid) {
322
+ const token = tokenAt(invalid.end);
323
+ if (isArrowFunction(parent)) add(`Expected ',' or ')' in parenthesized expression, but found '${token}'`);
324
+ else if (isFunctionTypeNode(parent)) add(`Expected ')' to close a parenthesized type, but found '${token}'`);
325
+ else add(`Expected ')' to close parameter list, but found '${token}'`);
326
+ }
327
+ }
328
+ if (isFunctionDeclaration(node)) {
329
+ const firstAsync = nodeModifiers.findIndex(flag => flag.kind === SyntaxKind.AsyncKeyword);
330
+ const firstDeclare = nodeModifiers.findIndex(flag => flag.kind === SyntaxKind.DeclareKeyword);
331
+ if (firstAsync >= 0 && firstDeclare > firstAsync) {
332
+ add(nodeModifiers.some(flag=>flag.kind === SyntaxKind.ExportKeyword) ?
333
+ "Expected 'function' keyword, but found 'declare'" :
334
+ "Expected a semicolon or an implicit semicolon after a statement, but found 'declare'");
335
+ }
336
+ }
337
+ if (node.templateFlags & TokenFlags.ContainsInvalidEscape && parent && (isTemplateLiteralTypeNode(parent) || isLiteralTypeNode(parent) || isTemplateLiteralTypeSpan(parent))) {
338
+ add('Bad escape sequence in untagged template literal');
339
+ }
340
+ if (isClassLike(node)) {
341
+ const flags = modifiers(node);
342
+ if (flags.some(m => m.kind === SyntaxKind.DefaultKeyword) && !flags.some(m => m.kind === SyntaxKind.ExportKeyword)) {
343
+ add("Expected 'class' keyword, but found 'default'");
344
+ }
345
+ const constructors = node.members.filter(member => isConstructorDeclaration(member) && member.body && !modifiers(member).some(m => m.kind === SyntaxKind.StaticKeyword));
346
+ for (const duplicate of constructors.slice(1)) {
347
+ add('A class can only have one constructor', duplicate.getFirstToken(file));
348
+ }
349
+ if (isClassDeclaration(node) && !node.name && !modifiers(node).some(m => m.kind === SyntaxKind.DefaultKeyword)) {
350
+ add('Class declaration requires a name');
351
+ }
352
+ let extendsSeen = false;
353
+ let implementsSeen = false;
354
+ for (const clause of node.heritageClauses ?? []) {
355
+ if (clause.token === SyntaxKind.ExtendsKeyword) {
356
+ if (extendsSeen || implementsSeen) add("Expected '{' to start class body, but found 'extends'");
357
+ if (!clause.types.length) {
358
+ add(`Expected '{' to start class body, but found '${tokenAt(node.end)}'`, clause);
359
+ }
360
+ if (clause.types.length > 1 || clause.types.hasTrailingComma) add("Expected '{' to start class body, but found ','");
361
+ extendsSeen = true;
362
+ } else {
363
+ if (implementsSeen) add("Expected '{' to start class body, but found 'implements'");
364
+ implementsSeen = true;
365
+ for (const type of clause.types) {
366
+ let expression = type.expression;
367
+ while (isPropertyAccessExpression(expression)) expression = expression.expression;
368
+ if (expression.kind === SyntaxKind.NullKeyword) {
369
+ add("'null' is reserved and cannot be used as an identifier", expression);
370
+ }
371
+ }
372
+ }
373
+ }
374
+ }
375
+ if (isInterfaceDeclaration(node)) {
376
+ for (const clause of node.heritageClauses ?? []) {
377
+ if (clause.token === SyntaxKind.ImplementsKeyword) add("Expected '{' to start an interface body, but found 'implements'");
378
+ for (const type of clause.types) {
379
+ if (isCallExpression(type.expression)) add("Expected '{' to start an interface body, but found '('");
380
+ if (isParenthesizedExpression(type.expression)) add("Expected an identifier, but found '('");
381
+ }
382
+ }
383
+ }
384
+ if (isConstructorDeclaration(node)) {
385
+ if (isInstanceConstructor(node)) {
386
+ if (node.typeParameters?.length) add('Type parameters cannot appear on a constructor declaration');
387
+ if (nodeModifiers.some(modifier => modifier.kind === SyntaxKind.AsyncKeyword)) add('Constructor cannot be async');
388
+ }
389
+ if (nodeModifiers.some(modifier => modifier.kind === SyntaxKind.DeclareKeyword)) {
390
+ add("A 'declare' modifier cannot appear on a class element of this kind");
391
+ }
392
+ const field = nodeModifiers.find(flag => [SyntaxKind.ConstKeyword, SyntaxKind.InKeyword, SyntaxKind.OutKeyword].includes(flag.kind));
393
+ if (field) add(`Expected ';' after class field, but found '${tokenAt(field.end)}'`, field);
394
+ }
395
+ if ((isMethodDeclaration(node) || isMethodSignature(node) || isAccessor(node) || isConstructorDeclaration(node)) &&
396
+ nodeModifiers.some(m => m.kind === SyntaxKind.ReadonlyKeyword)) {
397
+ add("A 'readonly' modifier can only appear on a property declaration or index signature");
398
+ }
399
+ if (isMethodDeclaration(node) && parent && isClassLike(parent)) {
400
+ if (nodeModifiers.some(modifier => modifier.kind === SyntaxKind.DeclareKeyword)) {
401
+ add("A 'declare' modifier cannot appear on a class element of this kind");
402
+ }
403
+ if (node.body && nodeModifiers.some(modifier => modifier.kind === SyntaxKind.AbstractKeyword)) {
404
+ add('An abstract method cannot have an implementation');
405
+ }
406
+ }
407
+ if (isMappedTypeNode(node) && node.members?.length) {
408
+ add(`Expected '}' to close a mapped type, but found '${node.members[0].name?.getText(file) ?? tokenAt(node.members.pos)}'`);
409
+ }
410
+ if ((isPropertyDeclaration(node) || isVariableDeclaration(node)) && node.exclamationToken) {
411
+ if (node.initializer) add('A declaration with an initializer cannot also have a definite assignment assertion');
412
+ else if (!node.type) add('A declaration with a definite assignment assertion must also have a type annotation');
413
+ }
414
+ if (isAccessor(node)) {
415
+ const params = node.parameters.filter(param => param.name.getText(file) !== 'this');
416
+ const static_ = nodeModifiers.some(modifier => modifier.kind === SyntaxKind.StaticKeyword);
417
+ if (nodeModifiers.some(modifier => modifier.kind === SyntaxKind.AsyncKeyword)) {
418
+ add(`Expected '(' for method definition, but found '${node.name.getText(file)}'`, node.name);
419
+ }
420
+ if (nodeModifiers.some(modifier => modifier.kind === SyntaxKind.DeclareKeyword)) {
421
+ add("A 'declare' modifier cannot appear on a class element of this kind", node.name);
422
+ }
423
+ if (node.body && nodeModifiers.some(modifier => modifier.kind === SyntaxKind.AbstractKeyword)) {
424
+ add('An abstract accessor cannot have an implementation', node.name);
425
+ }
426
+ if (parent && isClassLike(parent) && !static_ &&
427
+ (isIdentifier(node.name) || isStringLiteral(node.name)) && node.name.text === 'constructor') {
428
+ add("Constructor can't have get/set modifier", node.name);
429
+ }
430
+ if (isGetAccessorDeclaration(node) && params.length) add('Getter must have no parameters');
431
+ if (isSetAccessorDeclaration(node) && (params.length !== 1 || params[0].dotDotDotToken)) {
432
+ add('Setter must have exactly one parameter');
433
+ }
434
+ if ((isInterfaceDeclaration(parent) || isTypeLiteralNode(parent)) && node.body) {
435
+ add("Expected ';', ',', or newline between type members, but found '{'");
436
+ }
437
+ }
438
+ if (isPropertyDeclaration(node)) {
439
+ if ((isIdentifier(node.name) || isStringLiteral(node.name)) && node.name.text === 'constructor' &&
440
+ nodeModifiers.some(m => m.kind === SyntaxKind.StaticKeyword)) {
441
+ add("Classes may not have a static field named 'constructor'", node.name);
442
+ }
443
+ if (node.initializer && nodeModifiers.some(modifier => modifier.kind === SyntaxKind.AbstractKeyword)) {
444
+ add('An abstract property cannot have an initializer');
445
+ }
446
+ const unusual = nodeModifiers.find(flag => [SyntaxKind.ConstKeyword, SyntaxKind.ExportKeyword].includes(flag.kind));
447
+ if (unusual) add(`Expected ';' after class field, but found '${tokenAt(unusual.end)}'`);
448
+ }
449
+ if (isPropertySignature(node) && node.initializer) add("Expected ';', ',', or newline between type members, but found '='");
450
+ if (parent && isObjectLiteralExpression(parent)) {
451
+ const firstModifier = modifiers(node).find(modifier =>
452
+ modifier.kind !== SyntaxKind.AsyncKeyword || !isMethodDeclaration(node));
453
+ if (firstModifier) add(`Expected ',' or '}' in object, but found '${tokenAt(firstModifier.end)}'`);
454
+ if (node.questionToken) add("Expected ',' or '}' in object, but found '?'");
455
+ if ((isMethodDeclaration(node) || isAccessor(node)) && !node.body) {
456
+ scanner.setTextPos(node.getEnd());
457
+ const last = file.text[node.getEnd() - 1];
458
+ const unexpected = last === ';' ? ';' : tokenAt(node.getEnd());
459
+ add(`Expected '{' to start function body, but found '${unexpected}'`);
460
+ }
461
+ }
462
+ if (isPropertyDeclaration(node) || isMethodDeclaration(node) || isAccessor(node)) {
463
+ const static_ = modifiers(node).some(m => m.kind === SyntaxKind.StaticKeyword);
464
+ if (static_ && (isIdentifier(node.name) || isStringLiteral(node.name)) && node.name.text === 'prototype') {
465
+ add("Classes may not have a static property named 'prototype'", node.name);
466
+ }
467
+ if (isPropertyDeclaration(node) && node.exclamationToken && !node.type) {
468
+ add('A declaration with a definite assignment assertion must also have a type annotation');
469
+ }
470
+ }
471
+ if (isArrowFunction(node)) {
472
+ const beforeArrow = file.text.slice(node.parameters.end, node.equalsGreaterThanToken.pos);
473
+ const safe = node.type ? file.text.slice(node.type.getEnd(), node.equalsGreaterThanToken.getStart(file)) :
474
+ beforeArrow.slice(beforeArrow.lastIndexOf(')') + 1) + file.text.slice(node.equalsGreaterThanToken.pos, node.equalsGreaterThanToken.getStart(file));
475
+ if (/[\r\n\u2028\u2029]/.test(safe)) {
476
+ add("Expected '=>' on the same line after the arrow function parameters, but found '=>'");
477
+ }
478
+ }
479
+ if (isThrowStatement(node) && (!node.expression || node.expression.getWidth(file) === 0)) add('Illegal newline after throw');
480
+ if (isNewExpression(node) && node.expression.kind === SyntaxKind.SuperKeyword) {
481
+ add("'super' cannot be used as the target of 'new'");
482
+ }
483
+ if (isBindingElement(node) && node.dotDotDotToken && node.propertyName && isObjectBindingPattern(parent)) {
484
+ add("Expected ',' or '}' in object, but found ':'");
485
+ }
486
+ if (isBindingElement(node) && node.dotDotDotToken && node.initializer) add('A rest element cannot have an initializer');
487
+ if (isExportDeclaration(node) && node.moduleSpecifier && !isStringLiteral(node.moduleSpecifier)) {
488
+ add(`Expected module specifier, but found '${node.moduleSpecifier.getText(file)}'`);
489
+ }
490
+ if (isExportDeclaration(node) && !node.moduleSpecifier && node.exportClause?.kind === SyntaxKind.NamedExports) {
491
+ for (const element of node.exportClause.elements) {
492
+ const local = element.propertyName ?? element.name;
493
+ if (isStringLiteral(local)) {
494
+ add("A string literal cannot be used as an exported binding without 'from'", local);
495
+ } else if (isIdentifier(local)) {
496
+ const token = stringToToken(local.text);
497
+ if (token >= SyntaxKind.FirstReservedWord && token <= SyntaxKind.LastFutureReservedWord) {
498
+ add("A reserved word cannot be used as an exported binding without 'from'", local);
499
+ }
500
+ }
501
+ }
502
+ }
503
+ if (isSwitchStatement(node) && node.caseBlock.clauses.filter(isDefaultClause).length > 1) {
504
+ add('A switch statement can only have one default clause');
505
+ }
506
+ if (isJsxAttribute(node) && node.initializer && isJsxFragment(node.initializer) && parent && isJsxAttributes(parent)) {
507
+ const next = parent.properties[parent.properties.indexOf(node) + 1];
508
+ if (next) add(`Expected '>' to close JSX opening element, but found '${next.name?.getText(file) ?? tokenAt(next.getStart(file))}'`);
509
+ }
510
+ if (isJsxExpression(node) && isJsxAttribute(parent) && !node.expression) add('JSX attribute value cannot be an empty expression');
511
+ if (isMetaProperty(node) && node.keywordToken === SyntaxKind.NewKeyword && node.name.text !== 'target') {
512
+ add("The only valid meta property for 'new' is 'new.target'");
513
+ }
514
+ if (isEnumMember(node) && (isNumericLiteral(node.name) || isBigIntLiteral(node.name))) {
515
+ add(`Unexpected token '${node.name.getText(file)}' as enum member name`);
516
+ }
517
+ if (isRegularExpressionLiteral(node)) {
518
+ const raw = node.getText(file);
519
+ const flags = raw.slice(raw.lastIndexOf('/') + 1);
520
+ const nonAscii = flags.search(/[^\x00-\x7F]/);
521
+ if (nonAscii >= 0) {
522
+ add(`Expected a semicolon or an implicit semicolon after a statement, but found '${flags.slice(nonAscii)}'`);
523
+ }
524
+ const ascii = nonAscii < 0 ? flags : flags.slice(0, nonAscii);
525
+ if (/[^dgimsuvy]/.test(ascii)) add('Invalid regular expression flag');
526
+ if (new Set(ascii).size !== ascii.length) add('Duplicate regular expression flag');
527
+ if (ascii.includes('u') && ascii.includes('v')) add("The 'u' and 'v' regular expression flags cannot be used together");
528
+ }
529
+ if (isImportTypeNode(node) && (!isLiteralTypeNode(node.argument) || !isStringLiteral(node.argument.literal))) {
530
+ add(`Expected a string literal, but found '${node.argument.getText(file)}'`);
531
+ }
532
+ if (isImportClause(node) && node.isTypeOnly && node.name && node.namedBindings) {
533
+ add('A type-only import can specify a default import or named bindings, but not both');
534
+ }
535
+ if (node.kind === SyntaxKind.ImportAttributes && parent && (isImportDeclaration(parent) || isExportDeclaration(parent))) {
536
+ const seen = new Set();
537
+ for (const { name } of node.elements) {
538
+ if (seen.has(name.text)) add(`Duplicate import attribute key '${name.text}'`, name);
539
+ else seen.add(name.text);
540
+ }
541
+ }
542
+ if (isImportAttribute(node) && !isStringLiteral(node.value)) add('Import attribute value must be a string literal');
543
+ if (isImportDeclaration(node) && !isSourceFile(parent) && !isModuleBlock(parent)) {
544
+ add("'import' declaration may only appear at the top level");
545
+ }
546
+ };
547
+ }
548
+
549
+
550
+ function checkPrivateNames(file, emit) {
551
+ const pending = [{ node: file, parent: undefined, visible: new Set() }];
552
+ while (pending.length) {
553
+ const { node, parent, visible } = pending.pop();
554
+ if (isPrivateIdentifier(node) && parent && !visible.has(node.text)) {
555
+ const access = isPropertyAccessExpression(parent);
556
+ const membership = isBinaryExpression(parent) && parent.operatorToken.kind === SyntaxKind.InKeyword;
557
+ if (access || membership) emit(node, `Private field '${node.text}' must be declared in an enclosing class`);
558
+ }
559
+ const members = isClassLike(node) ? new Set(node.members) : undefined;
560
+ let inside = visible;
561
+ if (members) {
562
+ const privateMembers = new Map();
563
+ for (const member of members) {
564
+ if (!member.name || !isPrivateIdentifier(member.name)) continue;
565
+ const token = member.name;
566
+ const accessor = isGetAccessorDeclaration(member) ? 1 : isSetAccessorDeclaration(member) ? 2 : 0;
567
+ const isStatic = member.modifiers?.some(modifier => modifier.kind === SyntaxKind.StaticKeyword) ?? false;
568
+ const previous = privateMembers.get(token.text);
569
+ if (token.text === '#constructor') emit(token, "Classes can't have a private field named '#constructor'");
570
+ if (previous) {
571
+ const pair = accessor !== 0 && previous.accessor !== 0 && (accessor & previous.accessor) === 0 &&
572
+ previous.isStatic === isStatic;
573
+ if (pair) previous.accessor |= accessor;
574
+ else emit(token, `Duplicate private name '${token.text}'`, previous.token);
575
+ } else privateMembers.set(token.text, { accessor, isStatic, token });
576
+ }
577
+ if (privateMembers.size) inside = new Set([...visible, ...privateMembers.keys()]);
578
+ }
579
+ forEachChild(node, child => {
580
+ pending.push({ node: child, parent: node, visible: members?.has(child) ? inside : visible });
581
+ });
582
+ }
583
+ }
584
+
585
+ function checkExpressionSyntax(file, module, strictRoot, emit, visitType, visitBinary) {
586
+ const pending = [{ node: file, parent: undefined, canAwait: module, field: false, formal: false,
587
+ canYield: false, ambient: false, assignmentPattern: false, forInitializer: false, strict: strictRoot,
588
+ newTarget: false, jsxAttribute: undefined }];
589
+ let hasVarBindings = false;
590
+ let hasPrivateNames = false;
591
+ const hasModifier = (node, kind) => node.modifiers?.some(modifier => modifier.kind === kind);
592
+ const tokenAt = at => {
593
+ scanner.setTextPos(at);
594
+ return scanner.scan() === SyntaxKind.EndOfFileToken ? 'end of file' : scanner.getTokenText();
595
+ };
596
+ const scanner = createScanner(ScriptTarget.Latest, true, file.languageVariant, file.text);
597
+ const isPlainAssignment = node => isBinaryExpression(node) && node.operatorToken.kind === SyntaxKind.EqualsToken;
598
+ const isAssignmentTarget = node => isIdentifier(node) || isPropertyAccessExpression(node) || isElementAccessExpression(node);
599
+ const peelTarget = node => {
600
+ while (isParenthesizedExpression(node) || isNonNullExpression(node) || isAsExpression(node) ||
601
+ isSatisfiesExpression(node) || isTypeAssertionExpression(node)) {
602
+ node = node.expression;
603
+ }
604
+ return node;
605
+ };
606
+ const isUpdateKind = kind => kind === SyntaxKind.PlusPlusToken || kind === SyntaxKind.MinusMinusToken;
607
+ const isTypeLevel = parent => parent && (isTypeNode(parent) || isTypeParameterDeclaration(parent));
608
+ const logical = new Set([SyntaxKind.BarBarToken, SyntaxKind.AmpersandAmpersandToken]);
609
+ const awaitMessage = "'await' is reserved in an async/module context and cannot be used as an identifier";
610
+ const valueUse = (node, parent) => !isTypeLevel(parent) && !isQualifiedName(parent) && (
611
+ parent.expression === node || parent.left === node || parent.right === node || parent.operand === node ||
612
+ parent.initializer === node || parent.condition === node || parent.whenTrue === node || parent.whenFalse === node ||
613
+ parent.arguments?.includes(node) || isArrayLiteralExpression(parent) ||
614
+ isArrowFunction(parent) && parent.body === node ||
615
+ isShorthandPropertyAssignment(parent) && parent.name === node
616
+ );
617
+ function checkTarget(root, patterns, strict) {
618
+ const targets = [{ node: root, patterns }];
619
+ while (targets.length) {
620
+ const { node, patterns } = targets.pop();
621
+ const target = peelTarget(node);
622
+ if (isOptionalChain(target)) {
623
+ emit(target, 'Optional chaining is not allowed in assignment pattern');
624
+ continue;
625
+ }
626
+ if (isAssignmentTarget(target)) {
627
+ let unparenthesized = node;
628
+ while (isParenthesizedExpression(unparenthesized)) unparenthesized = unparenthesized.expression;
629
+ if (strict && isIdentifier(unparenthesized) && strictRestrictedBindings.has(unparenthesized.text)) {
630
+ emit(unparenthesized, "Cannot assign to 'eval' or 'arguments' in strict mode");
631
+ }
632
+ continue;
633
+ }
634
+ const array = isArrayLiteralExpression(target);
635
+ const object = isObjectLiteralExpression(target);
636
+ if (isParenthesizedExpression(node)) {
637
+ emit(node, 'Parenthesized expression in assignment pattern must be a simple assignment target');
638
+ continue;
639
+ }
640
+ if (!patterns || (!array && !object)) {
641
+ emit(target, 'Invalid element in assignment pattern');
642
+ continue;
643
+ }
644
+ const children = array ? target.elements : target.properties;
645
+ for (const [index, child] of children.entries()) {
646
+ if (isOmittedExpression(child)) continue;
647
+ if (isSpreadElement(child) || isSpreadAssignment(child)) {
648
+ if (index !== children.length - 1) {
649
+ emit(child, array ? 'Rest element must be the last element' : 'Rest element must be the last property');
650
+ } else if (children.hasTrailingComma) {
651
+ emit(child, `Rest element cannot have a trailing comma in ${array ? 'array' : 'object'} destructuring.`);
652
+ }
653
+ targets.push({ node: child.expression, patterns: array });
654
+ } else if (array || isPropertyAssignment(child) || isShorthandPropertyAssignment(child)) {
655
+ const value = array ? child : isShorthandPropertyAssignment(child) ? child.name : child.initializer;
656
+ targets.push({ node: isPlainAssignment(value) ? value.left : value, patterns: true });
657
+ } else {
658
+ emit(child, 'Invalid element in assignment pattern');
659
+ }
660
+ }
661
+ }
662
+ }
663
+ while (pending.length) {
664
+ const { node, parent, canAwait, field, formal, canYield, ambient: inheritedAmbient,
665
+ assignmentPattern, forInitializer, strict: inheritedStrict, newTarget, jsxAttribute } = pending.pop();
666
+ if (node.kind === SyntaxKind.VariableDeclarationList && (node.flags & NodeFlags.BlockScoped) === 0) hasVarBindings = true;
667
+ visitType(node, parent);
668
+ if (node.kind <= SyntaxKind.LastToken) {
669
+ if (isIdentifier(node)) {
670
+ if (!strictReservedBindings.has(node.text) && node.text !== 'await' && node.text !== 'arguments') continue;
671
+ } else if (module || !isNumericLiteral(node) && !isStringLiteral(node)) continue;
672
+ }
673
+ const strict = strictScope(node, file, inheritedStrict);
674
+ const report = (message, at = node) => emit(at, message);
675
+ const ambient = inheritedAmbient || hasModifier(node, SyntaxKind.DeclareKeyword);
676
+ if (isAwaitExpression(node)) {
677
+ if (formal) report('Await expression is not allowed in formal parameters');
678
+ else if (!canAwait) {
679
+ report(module ? awaitMessage :
680
+ `Expected a semicolon or an implicit semicolon after a statement, but found '${tokenAt(node.expression.getStart(file))}'`);
681
+ }
682
+ }
683
+ if (isForOfStatement(node) && node.awaitModifier && !canAwait) {
684
+ report("'for await' is only valid in async functions or modules");
685
+ }
686
+ if (isYieldExpression(node) && formal) report('Yield expression is not allowed in formal parameters');
687
+ else if (isYieldExpression(node) && !canYield && node.expression) {
688
+ report(`Expected a semicolon or an implicit semicolon after a statement, but found '${node.expression.getText(file)}'`);
689
+ } else if (isYieldExpression(node) && node.asteriskToken && node.expression) {
690
+ const trivia = file.text.slice(node.asteriskToken.end, node.expression.getStart(file));
691
+ if (/[\r\n\u2028\u2029]/.test(trivia)) report("Expected expression after 'yield*'", node.asteriskToken);
692
+ }
693
+ if (isIdentifier(node) && parent && valueUse(node, parent)) {
694
+ const bare = isExpressionStatement(parent);
695
+ const call = isCallExpression(parent) && parent.expression === node;
696
+ if (strict && strictReservedBindings.has(node.text)) report(`'${node.text}' is reserved in strict mode and cannot be used as an identifier`);
697
+ if (module && (bare || call) && node.text === 'await' && !canAwait) report(awaitMessage);
698
+ if (field && node.text === 'arguments') {
699
+ report("'arguments' is not allowed in class field initializers or static blocks");
700
+ }
701
+ }
702
+ if (field && isClassLike(node)) {
703
+ const bases = node.heritageClauses?.find(clause => clause.token === SyntaxKind.ExtendsKeyword);
704
+ if (bases) {
705
+ for (const base of bases.types) {
706
+ let root = base.expression;
707
+ while (isPropertyAccessExpression(root)) root = root.expression;
708
+ if (isIdentifier(root) && root.text === 'arguments') {
709
+ report("'arguments' is not allowed in class field initializers or static blocks", root);
710
+ }
711
+ }
712
+ }
713
+ }
714
+ if (parent && isStatement(node) && (isExportDeclaration(node) || isExportAssignment(node) ||
715
+ hasModifier(node, SyntaxKind.ExportKeyword))) {
716
+ if (!isSourceFile(parent) && !isModuleBlock(parent)) report("'export' declaration may only appear at the top level");
717
+ else if (!module && isSourceFile(parent)) report("Cannot use 'export' declaration outside a module");
718
+ }
719
+ if (!module && isImportDeclaration(node) && isSourceFile(parent)) report("Cannot use 'import' declaration outside a module");
720
+ if (isMetaProperty(node) && node.keywordToken === SyntaxKind.NewKeyword && node.name.text === 'target' && !newTarget) {
721
+ report("'new.target' is only valid inside functions, class field initializers, or static blocks");
722
+ }
723
+ if (isMetaProperty(node) && node.keywordToken === SyntaxKind.ImportKeyword) {
724
+ if (!module && node.name.text === 'meta') report("'import.meta' is only valid in module code");
725
+ if (!['meta','source','defer'].includes(node.name.text)) {
726
+ report("The only valid meta properties for 'import' are 'import.meta', 'import.source()', or 'import.defer()'");
727
+ }
728
+ }
729
+ if (isForInOrOfStatement(node)) {
730
+ if (isVariableDeclarationList(node.initializer)) {
731
+ const { declarations } = node.initializer;
732
+ if (declarations.length !== 1) {
733
+ report('Only a single variable declaration is allowed in a for-in/of statement', node.initializer);
734
+ }
735
+ for (const declaration of declarations) {
736
+ if (declaration.initializer) {
737
+ report(`for-${isForInStatement(node) ? 'in' : 'of'} loop variable declaration may not have an initializer`, declaration);
738
+ }
739
+ }
740
+ } else {
741
+ checkTarget(node.initializer, true, strict);
742
+ }
743
+ }
744
+ if (isBinaryExpression(node)) {
745
+ visitBinary?.(node, jsxAttribute);
746
+ const op = node.operatorToken.kind;
747
+ const read = expression => isBinaryExpression(expression) ? expression.operatorToken.kind : undefined;
748
+ const nullish = SyntaxKind.QuestionQuestionToken;
749
+ if (op === SyntaxKind.LessThanLessThanToken && isAsExpression(node.left)) {
750
+ let type = node.left.type;
751
+ while (isTypeOperatorNode(type)) type = type.type;
752
+ if (isImportTypeNode(type) && !type.typeArguments) {
753
+ report("Expected '>' to close a type parameter list, but found ';'");
754
+ }
755
+ }
756
+ if (op === nullish && [node.left,node.right].some(side => logical.has(read(side))) ||
757
+ logical.has(op) && [node.left,node.right].some(side => read(side) === nullish)) {
758
+ report('Logical expressions and nullish coalescing cannot be mixed');
759
+ }
760
+ if (op >= SyntaxKind.FirstAssignment && op <= SyntaxKind.LastAssignment) {
761
+ checkTarget(node.left, op === SyntaxKind.EqualsToken, strict);
762
+ }
763
+ }
764
+ if ((isPostfixUnaryExpression(node) || isPrefixUnaryExpression(node)) && isUpdateKind(node.operator)) {
765
+ const operand = peelTarget(node.operand);
766
+ if (!isAssignmentTarget(operand) || isOptionalChain(operand)) report('Invalid operand for increment/decrement operator');
767
+ else if (strict && isIdentifier(operand) && strictRestrictedBindings.has(operand.text)) {
768
+ report("Cannot assign to 'eval' or 'arguments' in strict mode");
769
+ }
770
+ }
771
+ if (strict && isDeleteExpression(node)) {
772
+ let value = node.expression;
773
+ while (isParenthesizedExpression(value)) value = value.expression;
774
+ if (isIdentifier(value)) report('Deleting a variable in strict mode is not allowed');
775
+ }
776
+ if (!module && strict && isNumericLiteral(node)) {
777
+ const raw = node.getText(file);
778
+ if (/^0[0-7]+$/.test(raw)) report('Octal literals are not allowed in strict mode');
779
+ else if (/^0[0-9]+$/.test(raw)) report('Decimals with leading zeros are not allowed in strict mode');
780
+ }
781
+ if (!module && strict && isStringLiteral(node)) {
782
+ for (const [, legacy] of node.getText(file).matchAll(/\\(?:(0[0-9]|[1-9])|[\s\S])/g)) {
783
+ if (legacy) {
784
+ report('Legacy decimal and octal escape sequences are not allowed in strict mode');
785
+ break;
786
+ }
787
+ }
788
+ }
789
+ if (isVariableDeclarationList(node) && node.declarations.hasTrailingComma) {
790
+ report(`Unexpected token '${tokenAt(node.getEnd())}' in binding pattern`);
791
+ }
792
+ if (isCallExpression(node) && node.expression.kind === SyntaxKind.ImportKeyword) {
793
+ if (!node.arguments.length) report("Unexpected token ')'");
794
+ else if (isSpreadElement(node.arguments[0])) report("Unexpected token '...'");
795
+ else if (node.arguments.length > 2) report(`Expected ')' after import(), but found '${tokenAt(node.arguments[2].getStart(file))}'`);
796
+ }
797
+ if (isArrowFunction(node) && forInitializer && isBinaryExpression(node.body) &&
798
+ node.body.operatorToken.kind === SyntaxKind.InKeyword) {
799
+ report("Expected ',' or ')' in parenthesized expression, but found 'in'");
800
+ }
801
+ if (isTaggedTemplateExpression(node) && (node.questionDotToken || isOptionalChain(node.tag))) {
802
+ report('Tagged template expressions are not permitted in an optional chain');
803
+ }
804
+ if (isObjectLiteralExpression(node) && !assignmentPattern) {
805
+ const prototypes = node.properties.filter(p => isPropertyAssignment(p) &&
806
+ (isStringLiteral(p.name) || isIdentifier(p.name)) && p.name.text === '__proto__');
807
+ if (prototypes.length > 1) report("Duplicate '__proto__' property in object literal");
808
+ }
809
+ if (isObjectBindingPattern(node) || isArrayBindingPattern(node)) {
810
+ const rest = node.elements.findIndex(element => isBindingElement(element) && element.dotDotDotToken);
811
+ if (rest >= 0 && rest !== node.elements.length - 1 && isObjectBindingPattern(node)) {
812
+ report('Rest element must be the last property');
813
+ }
814
+ if (rest >= 0 && node.elements.hasTrailingComma && isArrayBindingPattern(node)) {
815
+ report('Rest element cannot have a trailing comma in array destructuring.');
816
+ }
817
+ if (rest >= 0 && rest !== node.elements.length - 1 && isArrayBindingPattern(node)) {
818
+ report('Rest element must be the last element', node.elements[rest]);
819
+ }
820
+ }
821
+ if (parent && isObjectLiteralExpression(parent) && node.name && isPrivateIdentifier(node.name)) {
822
+ report(`Expected ',' or '}' in object, but found '${node.name.text}'`, node.name);
823
+ }
824
+ if (isShorthandPropertyAssignment(node) && node.objectAssignmentInitializer && !assignmentPattern) {
825
+ report('Shorthand property cannot have a default value in object expression');
826
+ }
827
+ if (isVariableDeclarationList(node) && (node.flags & NodeFlags.Const) !== 0 && !node.declarations.length) {
828
+ report(`Unexpected token '${tokenAt(node.getEnd())}' in binding pattern`);
829
+ }
830
+ if (isFunctionLike(node) && node.body && ambient && isFunctionDeclaration(node)) {
831
+ report('An implementation cannot be declared in ambient contexts');
832
+ }
833
+ if (isFunctionLike(node) && node.body && isBlock(node.body) &&
834
+ node.parameters.some(nonSimpleParameter)) {
835
+ for (const statement of node.body.statements) {
836
+ if (!isExpressionStatement(statement) || !isStringLiteral(statement.expression)) break;
837
+ if (['"use strict"', "'use strict'"].includes(statement.expression.getText(file))) {
838
+ report("Illegal 'use strict' directive in function with non-simple parameter list", statement.expression);
839
+ break;
840
+ }
841
+ }
842
+ }
843
+ if (isStatement(node)) {
844
+ scanner.setTextPos(node.getStart(file));
845
+ const first = scanner.scan();
846
+ const second = first === SyntaxKind.DeclareKeyword || first === SyntaxKind.ExportKeyword ? scanner.scan() : undefined;
847
+ const third = second === SyntaxKind.DeclareKeyword ? scanner.scan() : undefined;
848
+ if (first === SyntaxKind.DeclareKeyword && second === SyntaxKind.ExportKeyword) {
849
+ report("Expected a semicolon or an implicit semicolon after a statement, but found 'export'");
850
+ }
851
+ if (first === SyntaxKind.ExportKeyword && second === SyntaxKind.DeclareKeyword && third === SyntaxKind.ExportKeyword) {
852
+ report("Expected declaration after 'export', but found 'declare'");
853
+ }
854
+ if (first === SyntaxKind.ExportKeyword && second === SyntaxKind.ExportKeyword) {
855
+ report("Expected declaration after 'export', but found 'export'");
856
+ }
857
+ }
858
+ const childAttribute = isJsxExpression(node) ? parent : undefined;
859
+ forEachChild(node, child => {
860
+ if (child.kind <= SyntaxKind.LastToken && !typeCheckKind[child.kind] && !child.templateFlags) {
861
+ if (child.kind === SyntaxKind.PrivateIdentifier) hasPrivateNames = true;
862
+ if (isIdentifier(child)) {
863
+ if (child.text !== 'await' && child.text !== 'arguments' && !strictReservedBindings.has(child.text)) return;
864
+ } else if (module || !isNumericLiteral(child) && !isStringLiteral(child)) return;
865
+ }
866
+ const inField = isClassStaticBlockDeclaration(node) || (isPropertyDeclaration(node) && node.initializer === child);
867
+ const fn = isFunctionLike(node);
868
+ const arrow = isArrowFunction(node);
869
+ const decorator = child.kind === SyntaxKind.Decorator;
870
+ const usesFunctionContext = fn && node.name !== child && !decorator;
871
+ const nextField = inField || (field && (!usesFunctionContext || arrow));
872
+ const nextAwait = inField ? false : usesFunctionContext ? hasModifier(node, SyntaxKind.AsyncKeyword) : canAwait;
873
+ const nextYield = inField ? false : usesFunctionContext ? !!node.asteriskToken : canYield;
874
+ const nextFormal = fn && !decorator ? node.parameters.includes(child) : formal;
875
+ const parentPattern = assignmentPattern && (isArrayLiteralExpression(node) || isObjectLiteralExpression(node) ||
876
+ isParenthesizedExpression(node) || isPropertyAssignment(node) && node.initializer === child ||
877
+ isSpreadAssignment(node) || isSpreadElement(node));
878
+ const nextPattern = parentPattern || (isPlainAssignment(node) && node.left === child) ||
879
+ (isForInOrOfStatement(node) && node.initializer === child);
880
+ pending.push({node: child, parent: node, canAwait: nextAwait, field: nextField, formal: nextFormal,
881
+ canYield: nextYield, ambient, assignmentPattern: nextPattern, strict, jsxAttribute: childAttribute,
882
+ newTarget: inField || newTarget || usesFunctionContext && !arrow,
883
+ forInitializer: forInitializer || isForStatement(node) && node.initializer === child});
884
+ });
885
+ }
886
+ return { hasVarBindings, hasPrivateNames };
887
+ }
888
+
889
+ function hasStrictDirective(statements, file) {
890
+ for (const statement of statements) {
891
+ if (!isExpressionStatement(statement) || !isStringLiteral(statement.expression)) return false;
892
+ const text = statement.expression.getText(file);
893
+ if (text === '"use strict"' || text === "'use strict'") return true;
894
+ }
895
+ return false;
896
+ }
897
+
898
+ function strictScope(node, file, inherited) {
899
+ return inherited || isClassLike(node) ||
900
+ (isFunctionLike(node) && node.body && isBlock(node.body) && hasStrictDirective(node.body.statements, file));
901
+ }
902
+
903
+ function nonSimpleParameter(parameter) {
904
+ return parameter.dotDotDotToken || parameter.initializer || !isIdentifier(parameter.name);
905
+ }
906
+
907
+ return function checkGrammar(file, mode, emit, visitBinary) {
908
+ const module = mode !== 'script';
909
+ const strict = module || hasStrictDirective(file.statements, file);
910
+ // Preserve the standalone type pass's emission order for diagnostics sharing a byte offset.
911
+ const typeDiagnostics = [];
912
+ const visitType = createTypeSyntaxVisitor(file, module, (node, message) => { typeDiagnostics.push([node, message]); });
913
+ // The expression walk visits declaration lists as well as expressions.
914
+ const { hasVarBindings, hasPrivateNames } = checkExpressionSyntax(file, module, strict, emit, visitType, visitBinary);
915
+ for (const [node, message] of typeDiagnostics) emit(node, message);
916
+ checkContexts(file, module, strict, emit, hasVarBindings);
917
+ if (hasPrivateNames) checkPrivateNames(file, emit);
918
+ const nestedVars = hasVarBindings ? file.statements.filter(statement => !isVariableStatement(statement)).flatMap(bindings.nestedVarsIn) : [];
919
+ bindings.checkScope(file.statements, emit, { nestedVars });
920
+ bindings.checkNamespaceExports(file, emit);
921
+ if (module) bindings.checkExports(file, emit, nestedVars);
922
+ };
923
+ }