-
-
Notifications
You must be signed in to change notification settings - Fork 188
/
DiagnosticsProvider.ts
607 lines (538 loc) · 22.1 KB
/
DiagnosticsProvider.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
import ts from 'typescript';
import { CancellationToken, Diagnostic, DiagnosticSeverity, Range } from 'vscode-languageserver';
import {
Document,
getNodeIfIsInStartTag,
getTextInRange,
isRangeInTag,
mapRangeToOriginal
} from '../../../lib/documents';
import { DiagnosticsProvider } from '../../interfaces';
import { LSAndTSDocResolver } from '../LSAndTSDocResolver';
import { convertRange, getDiagnosticTag, hasNonZeroRange, mapSeverity } from '../utils';
import { SvelteDocumentSnapshot } from '../DocumentSnapshot';
import {
isInGeneratedCode,
isAfterSvelte2TsxPropsReturn,
findNodeAtSpan,
isReactiveStatement,
isInReactiveStatement,
gatherIdentifiers,
isStoreVariableIn$storeDeclaration,
get$storeOffsetOf$storeDeclaration
} from './utils';
import {
not,
flatten,
passMap,
swapRangeStartEndIfNecessary,
memoize,
traverseTypeString
} from '../../../utils';
import { LSConfigManager } from '../../../ls-config';
import { isAttributeName, isEventHandler } from '../svelte-ast-utils';
export enum DiagnosticCode {
MODIFIERS_CANNOT_APPEAR_HERE = 1184, // "Modifiers cannot appear here."
USED_BEFORE_ASSIGNED = 2454, // "Variable '{0}' is used before being assigned."
JSX_ELEMENT_DOES_NOT_SUPPORT_ATTRIBUTES = 2607, // "JSX element class does not support attributes because it does not have a '{0}' property."
CANNOT_BE_USED_AS_JSX_COMPONENT = 2786, // "'{0}' cannot be used as a JSX component."
NOOP_IN_COMMAS = 2695, // "Left side of comma operator is unused and has no side effects."
NEVER_READ = 6133, // "'{0}' is declared but its value is never read."
ALL_IMPORTS_UNUSED = 6192, // "All imports in import declaration are unused."
UNUSED_LABEL = 7028, // "Unused label."
DUPLICATED_JSX_ATTRIBUTES = 17001, // "JSX elements cannot have multiple attributes with the same name."
DUPLICATE_IDENTIFIER = 2300, // "Duplicate identifier 'xxx'"
MULTIPLE_PROPS_SAME_NAME = 1117, // "An object literal cannot have multiple properties with the same name in strict mode."
ARG_TYPE_X_NOT_ASSIGNABLE_TO_TYPE_Y = 2345, // "Argument of type '..' is not assignable to parameter of type '..'."
TYPE_X_NOT_ASSIGNABLE_TO_TYPE_Y = 2322, // "Type '..' is not assignable to type '..'."
TYPE_X_NOT_ASSIGNABLE_TO_TYPE_Y_DID_YOU_MEAN = 2820, // "Type '..' is not assignable to type '..'. Did you mean '...'?"
UNKNOWN_PROP = 2353, // "Object literal may only specify known properties, and '...' does not exist in type '...'"
MISSING_PROPS = 2739, // "Type '...' is missing the following properties from type '..': ..."
MISSING_PROP = 2741, // "Property '..' is missing in type '..' but required in type '..'."
NO_OVERLOAD_MATCHES_CALL = 2769, // "No overload matches this call"
CANNOT_FIND_NAME = 2304, // "Cannot find name 'xxx'"
EXPECTED_N_ARGUMENTS = 2554, // Expected {0} arguments, but got {1}.
DEPRECATED_SIGNATURE = 6387 // The signature '..' of '..' is deprecated
}
export class DiagnosticsProviderImpl implements DiagnosticsProvider {
constructor(
private readonly lsAndTsDocResolver: LSAndTSDocResolver,
private configManager: LSConfigManager
) {}
async getDiagnostics(
document: Document,
cancellationToken?: CancellationToken
): Promise<Diagnostic[]> {
const { lang, tsDoc } = await this.getLSAndTSDoc(document);
if (
['coffee', 'coffeescript'].includes(document.getLanguageAttribute('script')) ||
cancellationToken?.isCancellationRequested
) {
return [];
}
const isTypescript =
tsDoc.scriptKind === ts.ScriptKind.TSX || tsDoc.scriptKind === ts.ScriptKind.TS;
// Document preprocessing failed, show parser error instead
if (tsDoc.parserError) {
return [
{
range: tsDoc.parserError.range,
severity: DiagnosticSeverity.Error,
source: isTypescript ? 'ts' : 'js',
message: tsDoc.parserError.message,
code: tsDoc.parserError.code
}
];
}
let diagnostics: ts.Diagnostic[] = lang.getSyntacticDiagnostics(tsDoc.filePath);
const checkers = [lang.getSuggestionDiagnostics, lang.getSemanticDiagnostics];
for (const checker of checkers) {
if (cancellationToken) {
// wait a bit so the event loop can check for cancellation
// or let completion go first
await new Promise((resolve) => setTimeout(resolve, 10));
if (cancellationToken.isCancellationRequested) {
return [];
}
}
diagnostics.push(...checker.call(lang, tsDoc.filePath));
}
const additionalStoreDiagnostics: ts.Diagnostic[] = [];
const notGenerated = isNotGenerated(tsDoc.getFullText());
for (const diagnostic of diagnostics) {
if (
(diagnostic.code === DiagnosticCode.NO_OVERLOAD_MATCHES_CALL ||
diagnostic.code === DiagnosticCode.ARG_TYPE_X_NOT_ASSIGNABLE_TO_TYPE_Y) &&
!notGenerated(diagnostic)
) {
if (isStoreVariableIn$storeDeclaration(tsDoc.getFullText(), diagnostic.start!)) {
const storeName = tsDoc
.getFullText()
.substring(diagnostic.start!, diagnostic.start! + diagnostic.length!);
const storeUsages = lang.findReferences(
tsDoc.filePath,
get$storeOffsetOf$storeDeclaration(tsDoc.getFullText(), diagnostic.start!)
)![0].references;
for (const storeUsage of storeUsages) {
additionalStoreDiagnostics.push({
...diagnostic,
messageText: `Cannot use '${storeName}' as a store. '${storeName}' needs to be an object with a subscribe method on it.\n\n${ts.flattenDiagnosticMessageText(
diagnostic.messageText,
'\n'
)}`,
start: storeUsage.textSpan.start,
length: storeUsage.textSpan.length
});
}
}
}
}
diagnostics.push(...additionalStoreDiagnostics);
diagnostics = diagnostics
.filter(notGenerated)
.filter(not(isUnusedReactiveStatementLabel))
.filter((diagnostics) => !expectedTransitionThirdArgument(diagnostics, tsDoc, lang));
diagnostics = resolveNoopsInReactiveStatements(lang, diagnostics);
return diagnostics
.map<Diagnostic>((diagnostic) => ({
range: convertRange(tsDoc, diagnostic),
severity: mapSeverity(diagnostic.category),
source: isTypescript ? 'ts' : 'js',
message: ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'),
code: diagnostic.code,
tags: getDiagnosticTag(diagnostic)
}))
.map(mapRange(tsDoc, document, lang))
.filter(hasNoNegativeLines)
.filter(isNoFalsePositive(document, tsDoc))
.map(adjustIfNecessary)
.map(swapDiagRangeStartEndIfNecessary);
}
private async getLSAndTSDoc(document: Document) {
return this.lsAndTsDocResolver.getLSAndTSDoc(document);
}
}
function mapRange(
snapshot: SvelteDocumentSnapshot,
document: Document,
lang: ts.LanguageService
): (value: Diagnostic) => Diagnostic {
const get$$PropsDefWithCache = memoize(() => get$$PropsDef(lang, snapshot));
const get$$PropsAliasInfoWithCache = memoize(() =>
get$$PropsAliasForInfo(get$$PropsDefWithCache, lang, document)
);
return (diagnostic) => {
let range = mapRangeToOriginal(snapshot, diagnostic.range);
if (range.start.line < 0) {
range =
movePropsErrorRangeBackIfNecessary(
diagnostic,
snapshot,
get$$PropsDefWithCache,
get$$PropsAliasInfoWithCache
) ?? range;
}
if (
([DiagnosticCode.MISSING_PROP, DiagnosticCode.MISSING_PROPS].includes(
diagnostic.code as number
) ||
(DiagnosticCode.TYPE_X_NOT_ASSIGNABLE_TO_TYPE_Y &&
diagnostic.message.includes("'PropsWithChildren<"))) &&
!hasNonZeroRange({ range })
) {
const node = getNodeIfIsInStartTag(document.html, document.offsetAt(range.start));
if (node) {
// This is a "some prop missing" error on a component -> remap
range.start = document.positionAt(node.start + 1);
range.end = document.positionAt(node.start + 1 + (node.tag?.length || 1));
}
}
return { ...diagnostic, range };
};
}
function findDiagnosticNode(diagnostic: ts.Diagnostic) {
const { file, start, length } = diagnostic;
if (!file || !start || !length) {
return;
}
const span = { start, length };
return findNodeAtSpan(file, span);
}
function copyDiagnosticAndChangeNode(diagnostic: ts.Diagnostic) {
return (node: ts.Node) => ({
...diagnostic,
start: node.getStart(),
length: node.getWidth()
});
}
/**
* In some rare cases mapping of diagnostics does not work and produces negative lines.
* We filter out these diagnostics with negative lines because else the LSP
* apparently has a hickup and does not show any diagnostics at all.
*/
function hasNoNegativeLines(diagnostic: Diagnostic): boolean {
return diagnostic.range.start.line >= 0 && diagnostic.range.end.line >= 0;
}
const generatedVarRegex = /'\$\$_\w+(\.\$on)?'/;
function isNoFalsePositive(document: Document, tsDoc: SvelteDocumentSnapshot) {
const text = document.getText();
const usesPug = document.getLanguageAttribute('template') === 'pug';
return (diagnostic: Diagnostic) => {
if (
[DiagnosticCode.MULTIPLE_PROPS_SAME_NAME, DiagnosticCode.DUPLICATE_IDENTIFIER].includes(
diagnostic.code as number
)
) {
const node = tsDoc.svelteNodeAt(diagnostic.range.start);
if (isAttributeName(node, 'Element') || isEventHandler(node, 'Element')) {
return false;
}
}
if (
diagnostic.code === DiagnosticCode.DEPRECATED_SIGNATURE &&
generatedVarRegex.test(diagnostic.message)
) {
// Svelte 5: $on and constructor is deprecated, but we don't want to show this warning for generated code
return false;
}
return (
isNoUsedBeforeAssigned(diagnostic, text, tsDoc) &&
(!usesPug || isNoPugFalsePositive(diagnostic, document))
);
};
}
/**
* All diagnostics inside the template tag and the unused import/variable diagnostics
* are marked as false positive.
*/
function isNoPugFalsePositive(diagnostic: Diagnostic, document: Document): boolean {
return (
!isRangeInTag(diagnostic.range, document.templateInfo) &&
diagnostic.code !== DiagnosticCode.NEVER_READ &&
diagnostic.code !== DiagnosticCode.ALL_IMPORTS_UNUSED
);
}
/**
* Variable used before being assigned, can happen when you do `export let x`
* without assigning a value in strict mode. Should not throw an error here
* but on the component-user-side ("you did not set a required prop").
*/
function isNoUsedBeforeAssigned(
diagnostic: Diagnostic,
text: string,
tsDoc: SvelteDocumentSnapshot
): boolean {
if (diagnostic.code !== DiagnosticCode.USED_BEFORE_ASSIGNED) {
return true;
}
return !tsDoc.hasProp(getTextInRange(diagnostic.range, text));
}
/**
* Some diagnostics have JSX-specific or confusing nomenclature. Enhance/adjust them for more clarity.
*/
function adjustIfNecessary(diagnostic: Diagnostic): Diagnostic {
if (
diagnostic.code === DiagnosticCode.ARG_TYPE_X_NOT_ASSIGNABLE_TO_TYPE_Y &&
diagnostic.message.includes('ConstructorOfATypedSvelteComponent')
) {
return {
...diagnostic,
message:
diagnostic.message +
'\n\nPossible causes:\n' +
'- You use the instance type of a component where you should use the constructor type\n' +
'- Type definitions are missing for this Svelte Component. ' +
'If you are using Svelte 3.31+, use SvelteComponentTyped to add a definition:\n' +
' import type { SvelteComponentTyped } from "svelte";\n' +
' class ComponentName extends SvelteComponentTyped<{propertyName: string;}> {}'
};
}
if (diagnostic.code === DiagnosticCode.MODIFIERS_CANNOT_APPEAR_HERE) {
return {
...diagnostic,
message:
diagnostic.message +
'\nIf this is a declare statement, move it into <script context="module">..</script>'
};
}
if (
(diagnostic.code === DiagnosticCode.TYPE_X_NOT_ASSIGNABLE_TO_TYPE_Y ||
diagnostic.code === DiagnosticCode.TYPE_X_NOT_ASSIGNABLE_TO_TYPE_Y_DID_YOU_MEAN) &&
diagnostic.message.includes("'Bindable<")
) {
const countBindable = (diagnostic.message.match(/'Bindable\</g) || []).length;
const countBinding = (diagnostic.message.match(/'Binding\</g) || []).length;
if (countBindable === 1 && countBinding === 0) {
// Remove distracting Bindable<...> from diagnostic message
const start = diagnostic.message.indexOf("'Bindable<");
const startType = start + "'Bindable".length;
const end = traverseTypeString(diagnostic.message, startType, '>');
diagnostic.message =
diagnostic.message.substring(0, start + 1) +
diagnostic.message.substring(startType + 1, end) +
diagnostic.message.substring(end + 1);
} else if (countBinding === 3 && countBindable === 1) {
// Only keep Type '...' is not assignable to type '...' in
// Type Bindings<...> is not assignable to type Bindable<...>, Type Binding<...> is not assignable to type Bindable<...>, Type '...' is not assignable to type '...'
const lines = diagnostic.message.split('\n');
if (lines.length === 3) {
diagnostic.message = lines[2].trimStart();
}
}
return {
...diagnostic,
message: diagnostic.message
};
}
return diagnostic;
}
/**
* Due to source mapping, some ranges may be swapped: Start is end. Swap back in this case.
*/
function swapDiagRangeStartEndIfNecessary(diag: Diagnostic): Diagnostic {
diag.range = swapRangeStartEndIfNecessary(diag.range);
return diag;
}
/**
* Checks if diagnostic is not within a section that should be completely ignored
* because it's purely generated.
*/
function isNotGenerated(text: string) {
return (diagnostic: ts.Diagnostic) => {
if (diagnostic.start === undefined || diagnostic.length === undefined) {
return true;
}
return !isInGeneratedCode(text, diagnostic.start, diagnostic.start + diagnostic.length);
};
}
function isUnusedReactiveStatementLabel(diagnostic: ts.Diagnostic) {
if (diagnostic.code !== DiagnosticCode.UNUSED_LABEL) {
return false;
}
const diagNode = findDiagnosticNode(diagnostic);
if (!diagNode) {
return false;
}
// TS warning targets the identifier
if (!ts.isIdentifier(diagNode)) {
return false;
}
if (!diagNode.parent) {
return false;
}
return isReactiveStatement(diagNode.parent);
}
/**
* Checks if diagnostics should be ignored because they report an unused expression* in
* a reactive statement, and those actually have side effects in Svelte (hinting deps).
*
* $: x, update()
*
* Only `let` (i.e. reactive) variables are ignored. For the others, new diagnostics are
* emitted, centered on the (non reactive) identifiers in the initial warning.
*/
function resolveNoopsInReactiveStatements(lang: ts.LanguageService, diagnostics: ts.Diagnostic[]) {
const isLet = (file: ts.SourceFile) => (node: ts.Node) => {
const defs = lang.getDefinitionAtPosition(file.fileName, node.getStart());
return !!defs && defs.some((def) => def.fileName === file.fileName && def.kind === 'let');
};
const expandRemainingNoopWarnings = (diagnostic: ts.Diagnostic): void | ts.Diagnostic[] => {
const { code, file } = diagnostic;
// guard: missing info
if (!file) {
return;
}
// guard: not target error
const isNoopDiag = code === DiagnosticCode.NOOP_IN_COMMAS;
if (!isNoopDiag) {
return;
}
const diagNode = findDiagnosticNode(diagnostic);
if (!diagNode) {
return;
}
if (!isInReactiveStatement(diagNode)) {
return;
}
return (
// for all identifiers in diagnostic node
gatherIdentifiers(diagNode)
// ignore `let` (i.e. reactive) variables
.filter(not(isLet(file)))
// and create targeted diagnostics just for the remaining ids
.map(copyDiagnosticAndChangeNode(diagnostic))
);
};
const expandedDiagnostics = flatten(passMap(diagnostics, expandRemainingNoopWarnings));
return expandedDiagnostics.length === diagnostics.length
? expandedDiagnostics
: // This can generate duplicate diagnostics
expandedDiagnostics.filter(dedupDiagnostics());
}
function dedupDiagnostics() {
const hashDiagnostic = (diag: ts.Diagnostic) =>
[diag.start, diag.length, diag.category, diag.source, diag.code]
.map((x) => JSON.stringify(x))
.join(':');
const known = new Set();
return (diag: ts.Diagnostic) => {
const key = hashDiagnostic(diag);
if (known.has(key)) {
return false;
} else {
known.add(key);
return true;
}
};
}
function get$$PropsAliasForInfo(
get$$PropsDefWithCache: () => ReturnType<typeof get$$PropsDef>,
lang: ts.LanguageService,
document: Document
) {
if (!/type\s+\$\$Props[\s\n]+=/.test(document.getText())) {
return;
}
const propsDef = get$$PropsDefWithCache();
if (!propsDef || !ts.isTypeAliasDeclaration(propsDef)) {
return;
}
const type = lang.getProgram()?.getTypeChecker()?.getTypeAtLocation(propsDef.name);
if (!type) {
return;
}
// TS says symbol is always defined but it's not
const rootSymbolName = (type.aliasSymbol ?? type.symbol)?.name;
if (!rootSymbolName) {
return;
}
return [rootSymbolName, propsDef] as const;
}
function get$$PropsDef(lang: ts.LanguageService, snapshot: SvelteDocumentSnapshot) {
const program = lang.getProgram();
const sourceFile = program?.getSourceFile(snapshot.filePath);
if (!program || !sourceFile) {
return undefined;
}
const renderFunction = sourceFile.statements.find(
(statement): statement is ts.FunctionDeclaration =>
ts.isFunctionDeclaration(statement) && statement.name?.getText() === 'render'
);
return renderFunction?.body?.statements.find(
(node): node is ts.TypeAliasDeclaration | ts.InterfaceDeclaration =>
(ts.isTypeAliasDeclaration(node) || ts.isInterfaceDeclaration(node)) &&
node.name.getText() === '$$Props'
);
}
function movePropsErrorRangeBackIfNecessary(
diagnostic: Diagnostic,
snapshot: SvelteDocumentSnapshot,
get$$PropsDefWithCache: () => ReturnType<typeof get$$PropsDef>,
get$$PropsAliasForWithCache: () => ReturnType<typeof get$$PropsAliasForInfo>
): Range | undefined {
const possibly$$PropsError = isAfterSvelte2TsxPropsReturn(
snapshot.getFullText(),
snapshot.offsetAt(diagnostic.range.start)
);
if (!possibly$$PropsError) {
return;
}
if (diagnostic.message.includes('$$Props')) {
const propsDef = get$$PropsDefWithCache();
const generatedPropsStart = propsDef?.name.getStart();
const propsStart =
generatedPropsStart != null &&
snapshot.getOriginalPosition(snapshot.positionAt(generatedPropsStart));
if (propsStart) {
return {
start: propsStart,
end: { ...propsStart, character: propsStart.character + '$$Props'.length }
};
}
return;
}
const aliasForInfo = get$$PropsAliasForWithCache();
if (!aliasForInfo) {
return;
}
const [aliasFor, propsDef] = aliasForInfo;
if (diagnostic.message.includes(aliasFor)) {
return mapRangeToOriginal(snapshot, {
start: snapshot.positionAt(propsDef.name.getStart()),
end: snapshot.positionAt(propsDef.name.getEnd())
});
}
}
function expectedTransitionThirdArgument(
diagnostic: ts.Diagnostic,
tsDoc: SvelteDocumentSnapshot,
lang: ts.LanguageService
) {
if (
diagnostic.code !== DiagnosticCode.EXPECTED_N_ARGUMENTS ||
!diagnostic.start ||
!tsDoc.getText(0, diagnostic.start).endsWith('__sveltets_2_ensureTransition(')
) {
return false;
}
const node = findDiagnosticNode(diagnostic);
if (!node) {
return false;
}
// in TypeScript 5.4 the error is on the function name
// in earlier versions it's on the whole call expression
const callExpression =
ts.isIdentifier(node) && ts.isCallExpression(node.parent)
? node.parent
: findNodeAtSpan(
node,
{ start: node.getStart(), length: node.getWidth() },
ts.isCallExpression
);
const signature =
callExpression && lang.getProgram()?.getTypeChecker().getResolvedSignature(callExpression);
return (
signature?.parameters.filter((parameter) => !(parameter.flags & ts.SymbolFlags.Optional))
.length === 3
);
}