fallow-type-aware 3.41.0 → 3.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/cli.mjs CHANGED
@@ -2,6 +2,7 @@ import path from "node:path";
2
2
  import { createInterface } from "node:readline";
3
3
 
4
4
  import {
5
+ CALL_EVIDENCE_OPERATION,
5
6
  MUTANT_TYPECHECK_OPERATION,
6
7
  SESSION_ENVELOPE_TYPES,
7
8
  STATUS_OPERATION,
@@ -9,7 +10,9 @@ import {
9
10
  } from "./generated-protocol.mjs";
10
11
  import { analyzeSemanticQueries, createSemanticSession } from "./semantic.mjs";
11
12
  import { checkMutants } from "./mutant-typecheck.mjs";
13
+ import { collectCallEvidence } from "./call-evidence.mjs";
12
14
  import {
15
+ createCallEvidenceResponse,
13
16
  createMutantTypecheckResponse,
14
17
  createSemanticResponse,
15
18
  createStatusResponse,
@@ -98,8 +101,11 @@ const runSession = async (input, output) => {
98
101
  throw new Error("invalid semantic session envelope");
99
102
  }
100
103
  const request = parseRequest(envelope.request);
101
- if (request.operation === MUTANT_TYPECHECK_OPERATION) {
102
- throw new Error("a semantic session does not accept a mutant-typecheck request");
104
+ if (
105
+ request.operation === MUTANT_TYPECHECK_OPERATION ||
106
+ request.operation === CALL_EVIDENCE_OPERATION
107
+ ) {
108
+ throw new Error(`a semantic session does not accept a ${request.operation} request`);
103
109
  }
104
110
  if (!session) {
105
111
  root = request.root;
@@ -163,6 +169,14 @@ export const run = async ({ input, output, args = [] }) => {
163
169
  );
164
170
  return;
165
171
  }
172
+ if (request.operation === CALL_EVIDENCE_OPERATION) {
173
+ const evidence = collectCallEvidence(request);
174
+ writeJson(
175
+ output,
176
+ createCallEvidenceResponse({ ...evidence, elapsedMs: performance.now() - startedAt }),
177
+ );
178
+ return;
179
+ }
166
180
  const result = analyzeSemanticQueries(request);
167
181
  writeJson(output, responseFor(result, performance.now() - startedAt));
168
182
  };
@@ -0,0 +1,27 @@
1
+ // Syntactic facts about a declaration that the type proofs share.
2
+
3
+ import { SyntaxKind } from "./backend.mjs";
4
+
5
+ const hasModifier = (node, kind) => node.modifiers?.some((modifier) => modifier.kind === kind);
6
+
7
+ /** True when a direct child of `node` is a token of `kind`, such as `!`. */
8
+ export const hasToken = (node, kind) => {
9
+ let found = false;
10
+ node.forEachChild((child) => {
11
+ found = found || child.kind === kind;
12
+ return found ? true : undefined;
13
+ });
14
+ return found;
15
+ };
16
+
17
+ /**
18
+ * True for a `declare` declaration, a member of one, or anything in a
19
+ * declaration file: their types are claims that no code in the project checks.
20
+ */
21
+ export const isAmbient = (node) => {
22
+ for (let current = node; current; current = current.parent) {
23
+ if (current.isDeclarationFile === true) return true;
24
+ if (hasModifier(current, SyntaxKind.DeclareKeyword)) return true;
25
+ }
26
+ return false;
27
+ };
@@ -1,11 +1,27 @@
1
1
  import { realpathSync } from "node:fs";
2
2
  import path from "node:path";
3
3
 
4
- export const canonicalFileIdentity = (fileName) => {
5
- const absolutePath = path.normalize(path.resolve(fileName));
4
+ // One request resolves the same file many times, and each resolution is a
5
+ // system call. The cache lives for one request, so a symlink that changes
6
+ // between session requests resolves again.
7
+ const identities = new Map();
8
+
9
+ /** Forgets the resolved file identities. Each semantic analysis calls it at its start. */
10
+ export const resetFileIdentityCache = () => identities.clear();
11
+
12
+ const resolveIdentity = (absolutePath) => {
6
13
  try {
7
14
  return path.normalize(realpathSync.native(absolutePath));
8
15
  } catch {
9
16
  return absolutePath;
10
17
  }
11
18
  };
19
+
20
+ export const canonicalFileIdentity = (fileName) => {
21
+ const absolutePath = path.normalize(path.resolve(fileName));
22
+ const cached = identities.get(absolutePath);
23
+ if (cached !== undefined) return cached;
24
+ const identity = resolveIdentity(absolutePath);
25
+ identities.set(absolutePath, identity);
26
+ return identity;
27
+ };
@@ -6,6 +6,7 @@ export const TYPE_AWARE_PROTOCOL = Object.freeze({
6
6
  analysis_operation: "semantic-queries",
7
7
  status_operation: "status",
8
8
  mutant_typecheck_operation: "mutant-typecheck",
9
+ call_evidence_operation: "call-evidence",
9
10
  query_operations: ["symbol-use", "symbol-trace", "api-surface", "symbol-impact", "type-coupling"],
10
11
  session_envelope_types: ["analyze", "shutdown"],
11
12
  backend: {
@@ -34,6 +35,7 @@ export const SEMANTIC_SCHEMA_VERSION = TYPE_AWARE_PROTOCOL.semantic_schema_versi
34
35
  export const ANALYSIS_OPERATION = TYPE_AWARE_PROTOCOL.analysis_operation;
35
36
  export const STATUS_OPERATION = TYPE_AWARE_PROTOCOL.status_operation;
36
37
  export const MUTANT_TYPECHECK_OPERATION = TYPE_AWARE_PROTOCOL.mutant_typecheck_operation;
38
+ export const CALL_EVIDENCE_OPERATION = TYPE_AWARE_PROTOCOL.call_evidence_operation;
37
39
  export const QUERY_OPERATIONS = Object.freeze(TYPE_AWARE_PROTOCOL.query_operations);
38
40
  export const SESSION_ENVELOPE_TYPES = Object.freeze(TYPE_AWARE_PROTOCOL.session_envelope_types);
39
41
  export const BACKEND_FAMILY = TYPE_AWARE_PROTOCOL.backend.family;
@@ -19,6 +19,7 @@ import {
19
19
  } from "./backend.mjs";
20
20
 
21
21
  import { canonicalFileIdentity } from "./file-identity.mjs";
22
+ import { NON_NULLISH_HINT, nonNullishMutants } from "./optional-chain-proof.mjs";
22
23
 
23
24
  const { DiagnosticCategory } = sync;
24
25
 
@@ -131,8 +132,9 @@ const checkMutant = (context, check, mutant) => {
131
132
  check.snapshot = next;
132
133
  const errors = fileErrors(next.getProject(check.config), check.file.absolutePath);
133
134
  const codes = newErrorCodes(check.baseline, errors);
134
- return codes.length > 0
135
- ? { id: mutant.id, outcome: "compile-error", codes }
135
+ if (codes.length > 0) return { id: mutant.id, outcome: "compile-error", codes };
136
+ return check.hinted.has(mutant.id)
137
+ ? { id: mutant.id, outcome: "compiles", hint: NON_NULLISH_HINT }
136
138
  : { id: mutant.id, outcome: "compiles" };
137
139
  };
138
140
 
@@ -145,12 +147,14 @@ const checkInProject = (context, file, original, config) => {
145
147
  changes: { fileChanges: { changed: [file.absolutePath] } },
146
148
  snapshot: context.api.updateSnapshot({ openProjects: [config] }),
147
149
  baseline: null,
150
+ hinted: new Set(),
148
151
  };
149
152
  try {
150
153
  const project = check.snapshot.getProject(config);
151
154
  const reason = projectSkipReason(project, file, original);
152
155
  if (reason !== null) return unchecked(file, reason);
153
156
  check.baseline = countKeys(fileErrors(project, file.absolutePath));
157
+ check.hinted = nonNullishMutants(project, file, original);
154
158
  return file.mutants.map((mutant) => checkMutant(context, check, mutant));
155
159
  } finally {
156
160
  context.overlay.delete(check.identity);
@@ -0,0 +1,458 @@
1
+ // Finds optional-chaining and nullish-fallback mutants that the types suggest
2
+ // are equivalent to the original code. The result is an advisory hint, never a
3
+ // verdict: the mutant keeps the status `survived`, because a type does not
4
+ // prove a run-time value.
5
+ //
6
+ // The mutants `a?.b` -> `a.b`, `a?.()` -> `a()`, `a?.[k]` -> `a[k]` and
7
+ // `a ?? b` -> `a` change nothing when the receiver `a` is never `null` or
8
+ // `undefined` at run time.
9
+ // The proof trusts declarations and never trusts flow analysis or assertions:
10
+ //
11
+ // - It reads the declared type of the root binding or property, not the type
12
+ // that control flow narrows at the use. A call can invalidate a narrowing
13
+ // that the checker keeps.
14
+ // - It rejects an assertion (`as`, `<T>x`, `x!`) anywhere in the receiver, and
15
+ // in the initializer of each local binding that the receiver reads.
16
+ // - It rejects bindings and properties that the language does not force to
17
+ // hold a value: `declare` and `.d.ts` variables, bindings without an
18
+ // initializer, `!` and `declare` properties, and class properties that no
19
+ // initializer or constructor assignment sets.
20
+ // - It rejects a `let`, `var` or parameter binding that any code assigns after
21
+ // its declaration, in a closure or through a destructuring target too.
22
+ // - It needs `strictNullChecks` (a type excludes nullish values only then) and
23
+ // `noUncheckedIndexedAccess` (otherwise `xs[0]` has a non-nullable type and
24
+ // is `undefined` for an empty array).
25
+ //
26
+ // When the provenance of the type is unclear, the proof says nothing and the
27
+ // mutant keeps its normal check.
28
+
29
+ import path from "node:path";
30
+
31
+ import { ast, NodeFlags, projectCompilerOptions, sync, SyntaxKind } from "./backend.mjs";
32
+ import { targetDirection } from "./accessor-direction.mjs";
33
+ import { hasToken, isAmbient } from "./declaration-facts.mjs";
34
+ import { declarationsForSymbol } from "./semantic-identity.mjs";
35
+
36
+ const { TypeFlags, SymbolFlags } = sync;
37
+ const {
38
+ isArrayLiteralExpression,
39
+ isArrowFunction,
40
+ isAsExpression,
41
+ isBinaryExpression,
42
+ isCallExpression,
43
+ isClassDeclaration,
44
+ isClassExpression,
45
+ isConstructorDeclaration,
46
+ isElementAccessExpression,
47
+ isExpressionStatement,
48
+ isFunctionExpression,
49
+ isIdentifier,
50
+ isLiteralExpression,
51
+ isNewExpression,
52
+ isNonNullExpression,
53
+ isObjectLiteralExpression,
54
+ isParenthesizedExpression,
55
+ isPropertyAccessExpression,
56
+ isPropertyDeclaration,
57
+ isSatisfiesExpression,
58
+ isTemplateExpression,
59
+ isThisExpression,
60
+ isTypeAssertion,
61
+ isVariableDeclaration,
62
+ } = ast;
63
+
64
+ /** The hint that the response gives for a mutant whose receiver type excludes nullish values. */
65
+ export const NON_NULLISH_HINT = "type-non-nullish";
66
+
67
+ const OPTIONAL_TOKEN = "?.";
68
+ const COALESCE_TOKEN = "??";
69
+ const TYPESCRIPT_EXTENSIONS = new Set([".ts", ".tsx", ".mts", ".cts"]);
70
+ const MAX_UNION_DEPTH = 8;
71
+ const MAX_BINDING_DEPTH = 8;
72
+ const NON_NULLABLE_FLAGS = TypeFlags.DefinitelyNonNullable;
73
+ const UNION_OR_INTERSECTION = TypeFlags.Union | TypeFlags.Intersection;
74
+
75
+ const strictNullChecks = (options) =>
76
+ options.strictNullChecks === true ||
77
+ (options.strictNullChecks === undefined && options.strict === true);
78
+
79
+ const allowsTypeProof = (project, absolutePath) => {
80
+ const options = projectCompilerOptions(project);
81
+ return (
82
+ TYPESCRIPT_EXTENSIONS.has(path.extname(absolutePath).toLowerCase()) &&
83
+ strictNullChecks(options) &&
84
+ options.noUncheckedIndexedAccess === true
85
+ );
86
+ };
87
+
88
+ const neverNullish = (type, depth) => {
89
+ if (depth > MAX_UNION_DEPTH) return false;
90
+ if ((type.flags & UNION_OR_INTERSECTION) !== 0) {
91
+ const members = type.getTypes?.() ?? [];
92
+ return members.length > 0 && members.every((member) => neverNullish(member, depth + 1));
93
+ }
94
+ return type.flags !== 0 && (type.flags & ~NON_NULLABLE_FLAGS) === 0;
95
+ };
96
+
97
+ const isParameter = (node) => node.kind === SyntaxKind.Parameter;
98
+ const isPropertySignature = (node) => node.kind === SyntaxKind.PropertySignature;
99
+
100
+ // True for an optional chain: `a?.b`, `a?.()`, `a?.[k]`, or a longer chain
101
+ // after such a link, such as `a?.b.c()`. A chain gives `undefined` when a link
102
+ // short-circuits, whatever the declared type of its last link. A later link
103
+ // of the same chain is skipped too, so the receiver of an optional link can
104
+ // be a chain. The left operand of `??` is a value outside the chain.
105
+ const isOptionalChain = (node) => {
106
+ for (let current = node; current !== undefined; current = current.expression) {
107
+ const isLink =
108
+ isPropertyAccessExpression(current) ||
109
+ isElementAccessExpression(current) ||
110
+ isCallExpression(current) ||
111
+ isNonNullExpression(current);
112
+ if (!isLink) return false;
113
+ if (current.questionDotToken !== undefined) return true;
114
+ }
115
+ return false;
116
+ };
117
+
118
+ const withoutParentheses = (node) => {
119
+ let current = node;
120
+ while (isParenthesizedExpression(current) || isSatisfiesExpression(current)) {
121
+ current = current.expression;
122
+ }
123
+ return current;
124
+ };
125
+
126
+ // The declared type of a value outside its chain. An optional chain can give
127
+ // `undefined` there, so it has no proven type.
128
+ const settledType = (project, expression, context) =>
129
+ isOptionalChain(withoutParentheses(expression))
130
+ ? null
131
+ : declaredType(project, expression, context);
132
+
133
+ const isAssertion = (node) =>
134
+ isAsExpression(node) || isTypeAssertion(node) || isNonNullExpression(node);
135
+
136
+ const containsAssertion = (node) => {
137
+ if (isAssertion(node)) return true;
138
+ let found = false;
139
+ node.forEachChild((child) => {
140
+ found = found || containsAssertion(child);
141
+ return found ? true : undefined;
142
+ });
143
+ return found;
144
+ };
145
+
146
+ const hasModifier = (node, kind) => node.modifiers?.some((modifier) => modifier.kind === kind);
147
+
148
+ const typeAt = (project, declaration, symbol) =>
149
+ project.checker.getTypeOfSymbolAtLocation(symbol, declaration);
150
+
151
+ // A constructor statement `this.name = value;` at the top level of the body.
152
+ const constructorAssigns = (classNode, name) =>
153
+ classNode.members.some(
154
+ (member) =>
155
+ isConstructorDeclaration(member) &&
156
+ member.body !== undefined &&
157
+ member.body.statements.some((statement) => {
158
+ if (!isExpressionStatement(statement)) return false;
159
+ const { expression } = statement;
160
+ return (
161
+ isBinaryExpression(expression) &&
162
+ expression.operatorToken.kind === SyntaxKind.EqualsToken &&
163
+ isPropertyAccessExpression(expression.left) &&
164
+ isThisExpression(expression.left.expression) &&
165
+ expression.left.name.text === name &&
166
+ !containsAssertion(expression.right)
167
+ );
168
+ }),
169
+ );
170
+
171
+ const isParameterProperty = (declaration) =>
172
+ isParameter(declaration) && isConstructorDeclaration(declaration.parent);
173
+
174
+ const classPropertyIsSet = (project, declaration, context) => {
175
+ if (
176
+ hasModifier(declaration, SyntaxKind.DeclareKeyword) ||
177
+ hasToken(declaration, SyntaxKind.ExclamationToken)
178
+ ) {
179
+ return false;
180
+ }
181
+ if (declaration.initializer !== undefined) {
182
+ return initializerIsSafe(project, declaration.initializer, context);
183
+ }
184
+ if (hasModifier(declaration, SyntaxKind.StaticKeyword)) return false;
185
+ const owner = declaration.parent;
186
+ return (
187
+ (isClassDeclaration(owner) || isClassExpression(owner)) &&
188
+ constructorAssigns(owner, declaration.name.text)
189
+ );
190
+ };
191
+
192
+ const propertyIsSafe = (project, declaration, context) => {
193
+ if (isPropertySignature(declaration)) return true;
194
+ if (isParameterProperty(declaration)) return !isAmbient(declaration);
195
+ if (!isPropertyDeclaration(declaration) || isAmbient(declaration)) return false;
196
+ return classPropertyIsSet(project, declaration, context);
197
+ };
198
+
199
+ // The initializer must itself be non-nullish by declaration. Otherwise a
200
+ // stale narrowing in the initializer would give the binding a type that the
201
+ // value does not have.
202
+ const initializerIsSafe = (project, initializer, context) => {
203
+ if (containsAssertion(initializer)) return false;
204
+ const type = declaredType(project, initializer, context);
205
+ return type !== null && neverNullish(type, 0);
206
+ };
207
+
208
+ const uniqueDeclaration = (project, symbol) => {
209
+ const declarations = declarationsForSymbol(project, symbol);
210
+ return declarations.length === 1 ? declarations[0] : null;
211
+ };
212
+
213
+ const isWriteTarget = (identifier) => targetDirection(identifier) !== "read";
214
+
215
+ const writtenSymbolId = (project, identifier) => {
216
+ const symbol = isShorthandName(identifier)
217
+ ? project.checker.getShorthandAssignmentValueSymbol(identifier.parent)
218
+ : project.checker.getSymbolAtLocation(identifier);
219
+ return symbol?.id;
220
+ };
221
+
222
+ const isShorthandName = (identifier) =>
223
+ identifier.parent?.kind === SyntaxKind.ShorthandPropertyAssignment &&
224
+ identifier.parent.name === identifier;
225
+
226
+ // The ids of the symbols that code in `sourceFile` assigns, found once for
227
+ // each file. An unresolved write target is not recorded, so the scan also
228
+ // keeps a flag for a file where a write could not be resolved.
229
+ const writesOf = (project, sourceFile, cache) => {
230
+ const cached = cache.get(sourceFile);
231
+ if (cached) return cached;
232
+ const writes = { ids: new Set(), unresolved: false };
233
+ const visit = (node) => {
234
+ if (isIdentifier(node) && isWriteTarget(node)) {
235
+ const id = writtenSymbolId(project, node);
236
+ if (id === undefined) writes.unresolved = true;
237
+ else writes.ids.add(id);
238
+ }
239
+ node.forEachChild((child) => {
240
+ visit(child);
241
+ return undefined;
242
+ });
243
+ };
244
+ visit(sourceFile);
245
+ cache.set(sourceFile, writes);
246
+ return writes;
247
+ };
248
+
249
+ const isConstBinding = (declaration) =>
250
+ isVariableDeclaration(declaration) && (declaration.parent.flags & NodeFlags.Const) !== 0;
251
+
252
+ // A top-level `let` or `var` of a script file is global: code in another file
253
+ // can assign it, and the scan reads one file only.
254
+ const isGlobalScriptBinding = (declaration, sourceFile) =>
255
+ isVariableDeclaration(declaration) &&
256
+ sourceFile.externalModuleIndicator === undefined &&
257
+ declaration.parent.parent.parent === sourceFile;
258
+
259
+ // True when the binding can change after its declaration: a `let`, `var` or
260
+ // parameter that some code assigns. Only the module that declares a binding
261
+ // can assign it, so the scan reads the declaring file.
262
+ const isReassigned = (project, declaration, symbol, context) => {
263
+ if (isConstBinding(declaration)) return false;
264
+ const sourceFile = declaration.getSourceFile();
265
+ if (isGlobalScriptBinding(declaration, sourceFile)) return true;
266
+ const writes = writesOf(project, sourceFile, context.writes);
267
+ return writes.unresolved || writes.ids.has(symbol.id);
268
+ };
269
+
270
+ const bindingType = (project, identifier, context) => {
271
+ if (context.depth > MAX_BINDING_DEPTH) return null;
272
+ let symbol = project.checker.getSymbolAtLocation(identifier);
273
+ if (!symbol) return null;
274
+ if ((symbol.flags & SymbolFlags.Alias) !== 0) {
275
+ symbol = project.checker.getAliasedSymbol(symbol);
276
+ if (project.checker.isUnknownSymbol(symbol)) return null;
277
+ }
278
+ const declaration = uniqueDeclaration(project, symbol);
279
+ if (declaration === null || context.visited.has(declaration) || isAmbient(declaration)) {
280
+ return null;
281
+ }
282
+ context.visited.add(declaration);
283
+ if (isReassigned(project, declaration, symbol, context)) return null;
284
+ const inner = { ...context, depth: context.depth + 1 };
285
+ if (isParameter(declaration) && isIdentifier(declaration.name)) {
286
+ return typeAt(project, declaration, symbol);
287
+ }
288
+ if (
289
+ isVariableDeclaration(declaration) &&
290
+ isIdentifier(declaration.name) &&
291
+ declaration.initializer !== undefined &&
292
+ initializerIsSafe(project, declaration.initializer, inner)
293
+ ) {
294
+ return typeAt(project, declaration, symbol);
295
+ }
296
+ return null;
297
+ };
298
+
299
+ const propertyType = (project, access, context) => {
300
+ const objectType = declaredType(project, access.expression, context);
301
+ if (objectType === null) return null;
302
+ const property = project.checker.getPropertyOfType(objectType, access.name.text);
303
+ if (!property) return null;
304
+ const declaration = uniqueDeclaration(project, property);
305
+ if (declaration === null || !propertyIsSafe(project, declaration, context)) return null;
306
+ return typeAt(project, declaration, property);
307
+ };
308
+
309
+ const callType = (project, call) => {
310
+ const signature = project.checker.getResolvedSignature(call);
311
+ const declaration = signature?.declaration?.resolve(project);
312
+ if (!declaration?.type) return null;
313
+ return project.checker.getTypeAtLocation(declaration.type) ?? null;
314
+ };
315
+
316
+ const isFreshValue = (node) =>
317
+ isObjectLiteralExpression(node) ||
318
+ isArrayLiteralExpression(node) ||
319
+ isArrowFunction(node) ||
320
+ isFunctionExpression(node) ||
321
+ isClassExpression(node) ||
322
+ isNewExpression(node) ||
323
+ isTemplateExpression(node) ||
324
+ isLiteralExpression(node);
325
+
326
+ // The type that declarations give to `expression`, or null when the
327
+ // expression is not a form whose type the proof trusts. The checker's own
328
+ // type at the use is never read for a reference, because it reflects control
329
+ // flow narrowing.
330
+ const declaredType = (project, expression, context) => {
331
+ if (isParenthesizedExpression(expression) || isSatisfiesExpression(expression)) {
332
+ return declaredType(project, expression.expression, context);
333
+ }
334
+ if (isIdentifier(expression)) return bindingType(project, expression, context);
335
+ if (isThisExpression(expression)) {
336
+ const type = project.checker.getTypeAtLocation(expression);
337
+ return type ? (project.checker.getBaseConstraintOfType(type) ?? type) : null;
338
+ }
339
+ if (isPropertyAccessExpression(expression)) return propertyType(project, expression, context);
340
+ if (isCallExpression(expression) && expression.questionDotToken === undefined) {
341
+ return callType(project, expression);
342
+ }
343
+ if (isFreshValue(expression)) return project.checker.getTypeAtLocation(expression) ?? null;
344
+ return null;
345
+ };
346
+
347
+ const optionalLinkReceiver = (node) => {
348
+ if (node.questionDotToken === undefined) return null;
349
+ const hasReceiver =
350
+ isPropertyAccessExpression(node) || isElementAccessExpression(node) || isCallExpression(node);
351
+ return hasReceiver ? node.expression : null;
352
+ };
353
+
354
+ // Maps the UTF-16 end offset of each `?.` token to the receiver it follows.
355
+ const receiversByLinkEnd = (sourceFile) => {
356
+ const receivers = new Map();
357
+ const visit = (node) => {
358
+ const receiver = optionalLinkReceiver(node);
359
+ if (receiver !== null) receivers.set(node.questionDotToken.end, receiver);
360
+ node.forEachChild((child) => {
361
+ visit(child);
362
+ return undefined;
363
+ });
364
+ };
365
+ visit(sourceFile);
366
+ return receivers;
367
+ };
368
+
369
+ // Maps the UTF-16 start offset of each `??` token to its left operand and
370
+ // the end of its right operand.
371
+ const fallbacksByTokenStart = (sourceFile) => {
372
+ const fallbacks = new Map();
373
+ const visit = (node) => {
374
+ if (isBinaryExpression(node) && node.operatorToken.kind === SyntaxKind.QuestionQuestionToken) {
375
+ fallbacks.set(node.operatorToken.end - COALESCE_TOKEN.length, {
376
+ left: node.left,
377
+ rightEnd: node.right.end,
378
+ });
379
+ }
380
+ node.forEachChild((child) => {
381
+ visit(child);
382
+ return undefined;
383
+ });
384
+ };
385
+ visit(sourceFile);
386
+ return fallbacks;
387
+ };
388
+
389
+ const isOptionalLink = (original, mutant) =>
390
+ original.subarray(mutant.start, mutant.end).toString("utf8") === OPTIONAL_TOKEN;
391
+
392
+ // The `nullish-fallback` mutant removes the `??` token and the right operand.
393
+ const isFallbackRemoval = (original, mutant) =>
394
+ mutant.replacement === "" &&
395
+ original.subarray(mutant.start, mutant.start + COALESCE_TOKEN.length).toString("utf8") ===
396
+ COALESCE_TOKEN;
397
+
398
+ const utf16Offset = (original, byteOffset) =>
399
+ original.subarray(0, byteOffset).toString("utf8").length;
400
+
401
+ // `receiver.node` is the receiver expression. `receiver.settled` is true
402
+ // when the value has left its chain, as the left operand of `??` has.
403
+ const receiverIsNeverNullish = (project, receiver, writes) => {
404
+ if (containsAssertion(receiver.node)) return false;
405
+ try {
406
+ const type = receiver.settled
407
+ ? settledType(project, receiver.node, { visited: new Set(), depth: 0, writes })
408
+ : declaredType(project, receiver.node, { visited: new Set(), depth: 0, writes });
409
+ return type !== null && neverNullish(type, 0);
410
+ } catch {
411
+ return false;
412
+ }
413
+ };
414
+
415
+ // The receiver of a mutant whose equivalence depends on a never-nullish
416
+ // value, or undefined when the mutant is not such a form.
417
+ const receiverOf = (original, mutant, sites) => {
418
+ if (isOptionalLink(original, mutant)) {
419
+ const node = sites.receivers.get(utf16Offset(original, mutant.end));
420
+ return node === undefined ? undefined : { node, settled: false };
421
+ }
422
+ if (!isFallbackRemoval(original, mutant)) return undefined;
423
+ const fallback = sites.fallbacks.get(utf16Offset(original, mutant.start));
424
+ return fallback?.rightEnd === utf16Offset(original, mutant.end)
425
+ ? { node: fallback.left, settled: true }
426
+ : undefined;
427
+ };
428
+
429
+ const mayNeedProof = (original, mutant) =>
430
+ isOptionalLink(original, mutant) || isFallbackRemoval(original, mutant);
431
+
432
+ /**
433
+ * Returns the ids of the mutants of `file` whose change has no effect when a
434
+ * receiver is never nullish, and whose receiver the declarations prove never
435
+ * nullish: the removal of an optional link (`a?.b` to `a.b`) and the removal
436
+ * of a nullish fallback (`a ?? b` to `a`). `project` is the project of the
437
+ * original file, before any mutant is applied.
438
+ */
439
+ export const nonNullishMutants = (project, file, original) => {
440
+ const candidates = file.mutants.filter((mutant) => mayNeedProof(original, mutant));
441
+ if (candidates.length === 0 || !allowsTypeProof(project, file.absolutePath)) return new Set();
442
+ const sourceFile = project.program.getSourceFile(file.absolutePath);
443
+ if (!sourceFile) return new Set();
444
+ try {
445
+ const sites = {
446
+ receivers: receiversByLinkEnd(sourceFile),
447
+ fallbacks: fallbacksByTokenStart(sourceFile),
448
+ };
449
+ const writes = new Map();
450
+ const proven = candidates.filter((mutant) => {
451
+ const receiver = receiverOf(original, mutant, sites);
452
+ return receiver !== undefined && receiverIsNeverNullish(project, receiver, writes);
453
+ });
454
+ return new Set(proven.map((mutant) => mutant.id));
455
+ } catch {
456
+ return new Set();
457
+ }
458
+ };
@@ -20,11 +20,38 @@ const INFERRED_PROJECT = "<inferred>";
20
20
  const compareText = (left, right) => Buffer.compare(Buffer.from(left), Buffer.from(right));
21
21
  const slash = (value) => value.split(path.sep).join("/");
22
22
 
23
+ const DIRECTIVE_LINE = /^(?:\/\/\/?|\/\*+)\s*@ts-(?:ignore|expect-error)\b/u;
24
+ const BLANK_OR_LINE_COMMENT = /^(?:$|\/\/)/u;
25
+
26
+ // Strict-mode name errors, such as `arguments` used as a declaration name.
27
+ // They do not change which symbol a name resolves to. Other binding errors,
28
+ // such as a duplicate declaration, do, so they stay blocking under a directive.
29
+ const NAME_ONLY_BINDING_CODES = new Set([1100, 1101, 1102, 1212, 1213, 1214, 1215]);
30
+
31
+ // The compiler drops a binding or semantic diagnostic when an `@ts-ignore` or
32
+ // `@ts-expect-error` comment precedes its line, with only blank lines and `//`
33
+ // comment lines in between. Svelte, for example, declares
34
+ // `export const arguments` under `// @ts-ignore` in an ambient file.
35
+ const isSuppressedByDirective = (project, diagnostic) => {
36
+ if (!NAME_ONLY_BINDING_CODES.has(diagnostic.code)) return false;
37
+ const text = project.program.getSourceFile(diagnostic.fileName)?.text;
38
+ if (typeof text !== "string" || !Number.isInteger(diagnostic.pos)) return false;
39
+ const lines = text.slice(0, diagnostic.pos).split(/\r?\n/u);
40
+ for (let index = lines.length - 2; index >= 0; index -= 1) {
41
+ const line = lines[index].trim();
42
+ if (DIRECTIVE_LINE.test(line)) return true;
43
+ if (!BLANK_OR_LINE_COMMENT.test(line)) return false;
44
+ }
45
+ return false;
46
+ };
47
+
23
48
  const structuralDiagnostics = (project) => [
24
49
  ...project.program.getConfigFileParsingDiagnostics(),
25
50
  ...project.program.getProgramDiagnostics(),
26
51
  ...project.program.getSyntacticDiagnostics(),
27
- ...project.program.getBindDiagnostics(),
52
+ ...project.program
53
+ .getBindDiagnostics()
54
+ .filter((diagnostic) => !isSuppressedByDirective(project, diagnostic)),
28
55
  ];
29
56
 
30
57
  const isProjectLocalDiagnostic = (project, diagnostic) => {