@tslite/services 1.16.0 → 1.17.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 (123) hide show
  1. package/NOTICE +3 -1
  2. package/dist/_namespaces/edit.d.ts +1 -1
  3. package/dist/_namespaces/edit.js +10759 -11
  4. package/dist/_namespaces/ts.codefix.d.ts +0 -1
  5. package/dist/_namespaces/ts.js +10196 -19
  6. package/dist/classifier.d.ts +3 -1
  7. package/dist/codeFixProvider.d.ts +2 -1
  8. package/dist/codefixes/helpers.d.ts +3 -1
  9. package/dist/codefixes/importFixes.d.ts +3 -1
  10. package/dist/completions.d.ts +5 -2
  11. package/dist/documentHighlights.d.ts +3 -1
  12. package/dist/documentRegistry.d.ts +2 -1
  13. package/dist/findAllReferences.d.ts +3 -1
  14. package/dist/formatting/formatting.d.ts +3 -2
  15. package/dist/formatting/formattingContext.d.ts +2 -1
  16. package/dist/formatting/formattingScanner.d.ts +2 -2
  17. package/dist/formatting/rule.d.ts +1 -1
  18. package/dist/formatting/rulesMap.d.ts +1 -1
  19. package/dist/formatting/smartIndenter.d.ts +2 -1
  20. package/dist/getEditsForFileRename.d.ts +4 -1
  21. package/dist/goToDefinition.d.ts +3 -1
  22. package/dist/importTracker.d.ts +2 -1
  23. package/dist/navigationBar.d.ts +3 -1
  24. package/dist/organizeImports.d.ts +4 -2
  25. package/dist/outliningElementsCollector.d.ts +3 -1
  26. package/dist/refactorProvider.d.ts +1 -1
  27. package/dist/refactors/extractSymbol.d.ts +2 -1
  28. package/dist/rename.d.ts +3 -1
  29. package/dist/services.d.ts +5 -2
  30. package/dist/signatureHelp.d.ts +3 -1
  31. package/dist/smartSelection.d.ts +2 -1
  32. package/dist/stringCompletions.d.ts +3 -1
  33. package/dist/suggestionDiagnostics.d.ts +4 -3
  34. package/dist/symbolDisplay.d.ts +3 -1
  35. package/dist/textChanges.d.ts +4 -2
  36. package/dist/types.d.ts +3 -3
  37. package/dist/utilities.d.ts +7 -2
  38. package/package.json +7 -5
  39. package/dist/_namespaces/ts.Completions.StringCompletions.js +0 -2
  40. package/dist/_namespaces/ts.Completions.js +0 -3
  41. package/dist/_namespaces/ts.FindAllReferences.js +0 -3
  42. package/dist/_namespaces/ts.GoToDefinition.js +0 -2
  43. package/dist/_namespaces/ts.NavigationBar.js +0 -2
  44. package/dist/_namespaces/ts.OrganizeImports.js +0 -2
  45. package/dist/_namespaces/ts.OutliningElementsCollector.js +0 -2
  46. package/dist/_namespaces/ts.Rename.js +0 -2
  47. package/dist/_namespaces/ts.SignatureHelp.js +0 -2
  48. package/dist/_namespaces/ts.SmartSelectionRange.js +0 -2
  49. package/dist/_namespaces/ts.SymbolDisplay.js +0 -2
  50. package/dist/_namespaces/ts.codefix.js +0 -27
  51. package/dist/_namespaces/ts.formatting.js +0 -8
  52. package/dist/_namespaces/ts.refactor.addOrRemoveBracesToArrowFunction.js +0 -2
  53. package/dist/_namespaces/ts.refactor.convertParamsToDestructuredObject.js +0 -2
  54. package/dist/_namespaces/ts.refactor.convertStringOrTemplateLiteral.js +0 -2
  55. package/dist/_namespaces/ts.refactor.extractSymbol.js +0 -2
  56. package/dist/_namespaces/ts.refactor.js +0 -10
  57. package/dist/_namespaces/ts.textChanges.js +0 -2
  58. package/dist/classifier.js +0 -715
  59. package/dist/codeFixProvider.js +0 -84
  60. package/dist/codefixes/addConvertToUnknownForNonOverlappingTypes.d.ts +0 -1
  61. package/dist/codefixes/addConvertToUnknownForNonOverlappingTypes.js +0 -21
  62. package/dist/codefixes/addEmptyExportDeclaration.js +0 -17
  63. package/dist/codefixes/addMissingAsync.js +0 -75
  64. package/dist/codefixes/addMissingAwait.js +0 -236
  65. package/dist/codefixes/addMissingConst.js +0 -91
  66. package/dist/codefixes/addNameToNamelessParameter.js +0 -29
  67. package/dist/codefixes/convertConstToLet.js +0 -30
  68. package/dist/codefixes/convertToAsyncFunction.js +0 -495
  69. package/dist/codefixes/convertToMappedObjectType.js +0 -48
  70. package/dist/codefixes/correctQualifiedNameToIndexedAccessType.js +0 -33
  71. package/dist/codefixes/fixAddModuleReferTypeMissingTypeof.js +0 -27
  72. package/dist/codefixes/fixAwaitInSyncFunction.js +0 -69
  73. package/dist/codefixes/fixExpectedComma.js +0 -35
  74. package/dist/codefixes/fixInvalidJsxCharacters.js +0 -41
  75. package/dist/codefixes/fixMissingCallParentheses.js +0 -42
  76. package/dist/codefixes/fixSpelling.js +0 -94
  77. package/dist/codefixes/fixUnreachableCode.js +0 -65
  78. package/dist/codefixes/fixUnusedIdentifier.js +0 -224
  79. package/dist/codefixes/helpers.js +0 -53
  80. package/dist/codefixes/importFixes.js +0 -441
  81. package/dist/codefixes/inferFromUsage.js +0 -742
  82. package/dist/codefixes/removeUnnecessaryAwait.js +0 -41
  83. package/dist/codefixes/returnValueCorrect.js +0 -132
  84. package/dist/codefixes/splitTypeOnlyImport.js +0 -32
  85. package/dist/codefixes/useBigintLiteral.js +0 -29
  86. package/dist/completions.js +0 -1720
  87. package/dist/documentHighlights.js +0 -367
  88. package/dist/documentRegistry.js +0 -63
  89. package/dist/editingServices.js +0 -4
  90. package/dist/findAllReferences.js +0 -1366
  91. package/dist/formatting/formatting.js +0 -1021
  92. package/dist/formatting/formattingContext.js +0 -78
  93. package/dist/formatting/formattingScanner.js +0 -228
  94. package/dist/formatting/rule.js +0 -22
  95. package/dist/formatting/rules.js +0 -610
  96. package/dist/formatting/rulesMap.js +0 -127
  97. package/dist/formatting/smartIndenter.js +0 -518
  98. package/dist/getEditsForFileRename.js +0 -86
  99. package/dist/goToDefinition.js +0 -246
  100. package/dist/importTracker.js +0 -422
  101. package/dist/index.js +0 -3
  102. package/dist/navigationBar.js +0 -549
  103. package/dist/organizeImports.js +0 -290
  104. package/dist/outliningElementsCollector.js +0 -261
  105. package/dist/refactorProvider.js +0 -16
  106. package/dist/refactors/addOrRemoveBracesToArrowFunction.js +0 -86
  107. package/dist/refactors/convertExport.js +0 -126
  108. package/dist/refactors/convertImport.js +0 -116
  109. package/dist/refactors/convertParamsToDestructuredObject.js +0 -282
  110. package/dist/refactors/convertStringOrTemplateLiteral.js +0 -148
  111. package/dist/refactors/extractSymbol.js +0 -1281
  112. package/dist/refactors/extractType.js +0 -102
  113. package/dist/refactors/moveToNewFile.js +0 -477
  114. package/dist/rename.js +0 -100
  115. package/dist/services.js +0 -1480
  116. package/dist/signatureHelp.js +0 -414
  117. package/dist/smartSelection.js +0 -243
  118. package/dist/stringCompletions.js +0 -220
  119. package/dist/suggestionDiagnostics.js +0 -92
  120. package/dist/symbolDisplay.js +0 -400
  121. package/dist/textChanges.js +0 -1163
  122. package/dist/types.js +0 -263
  123. package/dist/utilities.js +0 -1981
@@ -1,715 +0,0 @@
1
- // Modificado de microsoft/TypeScript v3.9.10, src/services/classifier.ts: o namespace virou módulo ES, com os imports explícitos.
2
- // O arquivo entra com o classificador léxico (o `createClassifier`, sem o `getClassificationsForLine`, obsoleto na tag) e
3
- // com a classificação sintática e a semântica (o docs/ARCHITECTURE.md do pacote).
4
- import { CharacterCodes, Debug, ModuleInstanceState, ScriptTarget, SymbolFlags, SyntaxKind, commentPragmas, couldStartTrivia, createScanner, createTextSpan, decodedTextSpanIntersectsWith, getMeaningFromLocation, getModuleInstanceState, getTypeArgumentOrTypeParameterList, isIdentifier, isKeyword, isLineBreak, isModuleDeclaration, isPunctuation, isTemplateLiteralKind, isToken, isTrivia, lastOrUndefined, nodeIsMissing, some, textSpanIntersectsWith, } from "./_namespaces/ts.js";
5
- /**
6
- * O classificador léxico: a classe de cada token de um trecho, só pelo scanner, sem árvore nem programa. É o que
7
- * classifica um trecho solto, como o bloco de código de um hover, que não é arquivo de programa nenhum.
8
- */
9
- export function createClassifier() {
10
- const scanner = createScanner(ScriptTarget.Latest, /*skipTrivia*/ false);
11
- // Com um classificador sintático ao lado (`syntacticClassifierAbsent` falso), o léxico é mais conservador, para não
12
- // brigar com ele.
13
- function getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent) {
14
- let token = SyntaxKind.Unknown;
15
- let lastNonTriviaToken = SyntaxKind.Unknown;
16
- // Uma pilha de TemplateHeads e de `{`, para classificar o template de forma aproximada. A classificação exata
17
- // pediria levar a pilha de uma linha para a outra, como o estado de fim de linha; em vez disso, o aninhamento se
18
- // achata quando a pilha não está vazia, e vai no estado de fim de linha. Falha em dois casos: o template aninhado
19
- // que atravessa linhas, e o `{` de uma substituição que fecha na linha seguinte. O classificador sintático cobre
20
- // os dois.
21
- const templateStack = [];
22
- const { prefix, pushTemplate } = getPrefixFromLexState(lexState);
23
- text = prefix + text;
24
- const offset = prefix.length;
25
- if (pushTemplate) {
26
- templateStack.push(SyntaxKind.TemplateHead);
27
- }
28
- scanner.setText(text);
29
- let endOfLineState = 0 /* EndOfLineState.None */;
30
- const spans = [];
31
- // Enquanto se digita um genérico (`Foo<number`), o léxico vê `number` como palavra-chave, e o sintático como um
32
- // identificador à direita de um `<`: a cor trocaria a cada tecla. Por isso, quando pode ser um genérico (a
33
- // heurística conta os `<` e os `>` depois de um identificador), a palavra de tipo não vira palavra-chave, e a
34
- // decisão fica com o sintático.
35
- let angleBracketStack = 0;
36
- do {
37
- token = scanner.scan();
38
- if (!isTrivia(token)) {
39
- handleToken();
40
- lastNonTriviaToken = token;
41
- }
42
- const end = scanner.getTextPos();
43
- pushEncodedClassification(scanner.getTokenPos(), end, offset, classFromKind(token), spans);
44
- if (end >= text.length) {
45
- const end = getNewEndOfLineState(scanner, token, lastOrUndefined(templateStack));
46
- if (end !== undefined) {
47
- endOfLineState = end;
48
- }
49
- }
50
- } while (token !== SyntaxKind.EndOfFileToken);
51
- function handleToken() {
52
- switch (token) {
53
- case SyntaxKind.LessThanToken:
54
- if (lastNonTriviaToken === SyntaxKind.Identifier) {
55
- // Pode ser o começo de um genérico.
56
- angleBracketStack++;
57
- }
58
- break;
59
- case SyntaxKind.GreaterThanToken:
60
- if (angleBracketStack > 0) {
61
- // O genérico em que se estava fechou.
62
- angleBracketStack--;
63
- }
64
- break;
65
- case SyntaxKind.AnyKeyword:
66
- case SyntaxKind.StringKeyword:
67
- case SyntaxKind.NumberKeyword:
68
- case SyntaxKind.BooleanKeyword:
69
- case SyntaxKind.SymbolKeyword:
70
- if (angleBracketStack > 0 && !syntacticClassifierAbsent) {
71
- // Dentro do que pode ser um genérico, a palavra de tipo fica como identificador: o sintático
72
- // decide, e a cor não pisca.
73
- token = SyntaxKind.Identifier;
74
- }
75
- break;
76
- case SyntaxKind.TemplateHead:
77
- templateStack.push(token);
78
- break;
79
- case SyntaxKind.OpenBraceToken:
80
- // Só se acompanha o `{` quando há um TemplateHead na pilha.
81
- if (templateStack.length > 0) {
82
- templateStack.push(token);
83
- }
84
- break;
85
- case SyntaxKind.CloseBraceToken:
86
- // Só se acompanha o `}` quando há um TemplateHead na pilha.
87
- if (templateStack.length > 0) {
88
- const lastTemplateStackToken = lastOrUndefined(templateStack);
89
- if (lastTemplateStackToken === SyntaxKind.TemplateHead) {
90
- token = scanner.reScanTemplateToken();
91
- // Só o TemplateTail desempilha; o TemplateMiddle diz que o template continua.
92
- if (token === SyntaxKind.TemplateTail) {
93
- templateStack.pop();
94
- }
95
- else {
96
- Debug.assertEqual(token, SyntaxKind.TemplateMiddle, "Should have been a template middle.");
97
- }
98
- }
99
- else {
100
- Debug.assertEqual(lastTemplateStackToken, SyntaxKind.OpenBraceToken, "Should have been an open brace");
101
- templateStack.pop();
102
- }
103
- }
104
- break;
105
- default:
106
- if (!isKeyword(token)) {
107
- break;
108
- }
109
- // Depois de um `.`, uma palavra é o nome de um membro.
110
- if (lastNonTriviaToken === SyntaxKind.DotToken) {
111
- token = SyntaxKind.Identifier;
112
- }
113
- }
114
- }
115
- return { endOfLineState, spans };
116
- }
117
- return { getEncodedLexicalClassifications };
118
- }
119
- function getNewEndOfLineState(scanner, token, lastOnTemplateStack) {
120
- switch (token) {
121
- case SyntaxKind.StringLiteral: {
122
- // A linha terminou numa string que continua na seguinte?
123
- if (!scanner.isUnterminated())
124
- return undefined;
125
- const tokenText = scanner.getTokenText();
126
- const lastCharIndex = tokenText.length - 1;
127
- let numBackslashes = 0;
128
- while (tokenText.charCodeAt(lastCharIndex - numBackslashes) === CharacterCodes.backslash) {
129
- numBackslashes++;
130
- }
131
- // Com um número ímpar de barras invertidas, a string continua aberta.
132
- if ((numBackslashes & 1) === 0)
133
- return undefined;
134
- return tokenText.charCodeAt(0) === CharacterCodes.doubleQuote ? 3 /* EndOfLineState.InDoubleQuoteStringLiteral */ : 2 /* EndOfLineState.InSingleQuoteStringLiteral */;
135
- }
136
- case SyntaxKind.MultiLineCommentTrivia:
137
- // O comentário de várias linhas ficou aberto?
138
- return scanner.isUnterminated() ? 1 /* EndOfLineState.InMultiLineCommentTrivia */ : undefined;
139
- default:
140
- if (isTemplateLiteralKind(token)) {
141
- if (!scanner.isUnterminated()) {
142
- return undefined;
143
- }
144
- switch (token) {
145
- case SyntaxKind.TemplateTail:
146
- return 5 /* EndOfLineState.InTemplateMiddleOrTail */;
147
- case SyntaxKind.NoSubstitutionTemplateLiteral:
148
- return 4 /* EndOfLineState.InTemplateHeadOrNoSubstitutionTemplate */;
149
- default:
150
- return Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token);
151
- }
152
- }
153
- return lastOnTemplateStack === SyntaxKind.TemplateHead ? 6 /* EndOfLineState.InTemplateSubstitutionPosition */ : undefined;
154
- }
155
- }
156
- function pushEncodedClassification(start, end, offset, classification, result) {
157
- if (classification === 8 /* ClassificationType.whiteSpace */) {
158
- // O espaço em branco não se classifica.
159
- return;
160
- }
161
- if (start === 0 && offset > 0) {
162
- // O primeiro token, quando se pôs um prefixo no texto: ele começa no começo do texto original.
163
- start += offset;
164
- }
165
- const length = end - start;
166
- if (length > 0) {
167
- // As posições são as do texto com o prefixo; voltam a ser as do texto original.
168
- result.push(start - offset, length, classification);
169
- }
170
- }
171
- function getPrefixFromLexState(lexState) {
172
- // Na string ou no comentário que vem da linha anterior, um prefixo põe o scanner dentro dele.
173
- switch (lexState) {
174
- case 3 /* EndOfLineState.InDoubleQuoteStringLiteral */:
175
- return { prefix: "\"\\\n" };
176
- case 2 /* EndOfLineState.InSingleQuoteStringLiteral */:
177
- return { prefix: "'\\\n" };
178
- case 1 /* EndOfLineState.InMultiLineCommentTrivia */:
179
- return { prefix: "/*\n" };
180
- case 4 /* EndOfLineState.InTemplateHeadOrNoSubstitutionTemplate */:
181
- return { prefix: "`\n" };
182
- case 5 /* EndOfLineState.InTemplateMiddleOrTail */:
183
- return { prefix: "}\n", pushTemplate: true };
184
- case 6 /* EndOfLineState.InTemplateSubstitutionPosition */:
185
- return { prefix: "", pushTemplate: true };
186
- case 0 /* EndOfLineState.None */:
187
- return { prefix: "" };
188
- default:
189
- return Debug.assertNever(lexState);
190
- }
191
- }
192
- function isBinaryExpressionOperatorToken(token) {
193
- switch (token) {
194
- case SyntaxKind.AsteriskToken:
195
- case SyntaxKind.SlashToken:
196
- case SyntaxKind.PercentToken:
197
- case SyntaxKind.PlusToken:
198
- case SyntaxKind.MinusToken:
199
- case SyntaxKind.LessThanLessThanToken:
200
- case SyntaxKind.GreaterThanGreaterThanToken:
201
- case SyntaxKind.GreaterThanGreaterThanGreaterThanToken:
202
- case SyntaxKind.LessThanToken:
203
- case SyntaxKind.GreaterThanToken:
204
- case SyntaxKind.LessThanEqualsToken:
205
- case SyntaxKind.GreaterThanEqualsToken:
206
- case SyntaxKind.InKeyword:
207
- case SyntaxKind.AsKeyword:
208
- case SyntaxKind.EqualsEqualsToken:
209
- case SyntaxKind.ExclamationEqualsToken:
210
- case SyntaxKind.EqualsEqualsEqualsToken:
211
- case SyntaxKind.ExclamationEqualsEqualsToken:
212
- case SyntaxKind.AmpersandToken:
213
- case SyntaxKind.CaretToken:
214
- case SyntaxKind.BarToken:
215
- case SyntaxKind.AmpersandAmpersandToken:
216
- case SyntaxKind.BarBarToken:
217
- case SyntaxKind.BarEqualsToken:
218
- case SyntaxKind.AmpersandEqualsToken:
219
- case SyntaxKind.CaretEqualsToken:
220
- case SyntaxKind.LessThanLessThanEqualsToken:
221
- case SyntaxKind.GreaterThanGreaterThanEqualsToken:
222
- case SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken:
223
- case SyntaxKind.PlusEqualsToken:
224
- case SyntaxKind.MinusEqualsToken:
225
- case SyntaxKind.AsteriskEqualsToken:
226
- case SyntaxKind.SlashEqualsToken:
227
- case SyntaxKind.PercentEqualsToken:
228
- case SyntaxKind.EqualsToken:
229
- case SyntaxKind.CommaToken:
230
- case SyntaxKind.QuestionQuestionToken:
231
- return true;
232
- default:
233
- return false;
234
- }
235
- }
236
- function isPrefixUnaryExpressionOperatorToken(token) {
237
- switch (token) {
238
- case SyntaxKind.PlusToken:
239
- case SyntaxKind.MinusToken:
240
- case SyntaxKind.TildeToken:
241
- case SyntaxKind.ExclamationToken:
242
- case SyntaxKind.PlusPlusToken:
243
- case SyntaxKind.MinusMinusToken:
244
- return true;
245
- default:
246
- return false;
247
- }
248
- }
249
- function classFromKind(token) {
250
- if (isKeyword(token)) {
251
- return 3 /* ClassificationType.keyword */;
252
- }
253
- else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) {
254
- return 5 /* ClassificationType.operator */;
255
- }
256
- else if (token >= SyntaxKind.FirstPunctuation && token <= SyntaxKind.LastPunctuation) {
257
- return 10 /* ClassificationType.punctuation */;
258
- }
259
- switch (token) {
260
- case SyntaxKind.NumericLiteral:
261
- return 4 /* ClassificationType.numericLiteral */;
262
- case SyntaxKind.BigIntLiteral:
263
- return 25 /* ClassificationType.bigintLiteral */;
264
- case SyntaxKind.StringLiteral:
265
- return 6 /* ClassificationType.stringLiteral */;
266
- case SyntaxKind.ConflictMarkerTrivia:
267
- case SyntaxKind.MultiLineCommentTrivia:
268
- case SyntaxKind.SingleLineCommentTrivia:
269
- return 1 /* ClassificationType.comment */;
270
- case SyntaxKind.WhitespaceTrivia:
271
- case SyntaxKind.NewLineTrivia:
272
- return 8 /* ClassificationType.whiteSpace */;
273
- case SyntaxKind.Identifier:
274
- default:
275
- if (isTemplateLiteralKind(token)) {
276
- return 6 /* ClassificationType.stringLiteral */;
277
- }
278
- return 2 /* ClassificationType.identifier */;
279
- }
280
- }
281
- export function getSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) {
282
- return convertClassificationsToSpans(getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span));
283
- }
284
- function checkForClassificationCancellation(cancellationToken, kind) {
285
- // We don't want to actually call back into our host on every node to find out if we've
286
- // been canceled. That would be an enormous amount of chattyness, along with the all
287
- // the overhead of marshalling the data to/from the host. So instead we pick a few
288
- // reasonable node kinds to bother checking on. These node kinds represent high level
289
- // constructs that we would expect to see commonly, but just at a far less frequent
290
- // interval.
291
- //
292
- // For example, in checker.ts (around 750k) we only have around 600 of these constructs.
293
- // That means we're calling back into the host around every 1.2k of the file we process.
294
- // Lib.d.ts has similar numbers.
295
- // Na tag, também a classe, a interface e a `function` declaradas (CK-02).
296
- switch (kind) {
297
- case SyntaxKind.ModuleDeclaration:
298
- cancellationToken.throwIfCancellationRequested();
299
- }
300
- }
301
- export function getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) {
302
- const spans = [];
303
- sourceFile.forEachChild(function cb(node) {
304
- // Only walk into nodes that intersect the requested span.
305
- if (!node || !textSpanIntersectsWith(span, node.pos, node.getFullWidth())) {
306
- return;
307
- }
308
- checkForClassificationCancellation(cancellationToken, node.kind);
309
- // Only bother calling into the typechecker if this is an identifier that
310
- // could possibly resolve to a type name. This makes classification run
311
- // in a third of the time it would normally take.
312
- if (isIdentifier(node) && !nodeIsMissing(node) && classifiableNames.has(node.escapedText)) {
313
- const symbol = typeChecker.getSymbolAtLocation(node);
314
- const type = symbol && classifySymbol(symbol, getMeaningFromLocation(node), typeChecker);
315
- if (type) {
316
- pushClassification(node.getStart(sourceFile), node.getEnd(), type);
317
- }
318
- }
319
- node.forEachChild(cb);
320
- });
321
- return { spans, endOfLineState: 0 /* EndOfLineState.None */ };
322
- function pushClassification(start, end, type) {
323
- const length = end - start;
324
- Debug.assert(length > 0, `Classification had non-positive length of ${length}`);
325
- spans.push(start);
326
- spans.push(length);
327
- spans.push(type);
328
- }
329
- }
330
- function classifySymbol(symbol, meaningAtPosition, checker) {
331
- const flags = symbol.getFlags();
332
- // Na tag, também a classe e o enum (CK-02). A interface que fica é a do embutido (CK-48).
333
- if ((flags & SymbolFlags.Classifiable) === SymbolFlags.None) {
334
- return undefined;
335
- }
336
- else if (flags & SymbolFlags.TypeAlias) {
337
- return 16 /* ClassificationType.typeAliasName */;
338
- }
339
- else if (flags & SymbolFlags.Module) {
340
- // Only classify a module as such if
341
- // - It appears in a namespace context.
342
- // - There exists a module declaration which actually impacts the value side.
343
- return meaningAtPosition & 4 /* SemanticMeaning.Namespace */ || meaningAtPosition & 1 /* SemanticMeaning.Value */ && hasValueSideModule(symbol) ? 14 /* ClassificationType.moduleName */ : undefined;
344
- }
345
- else if (flags & SymbolFlags.Alias) {
346
- return classifySymbol(checker.getAliasedSymbol(symbol), meaningAtPosition, checker);
347
- }
348
- else if (meaningAtPosition & 2 /* SemanticMeaning.Type */) {
349
- return flags & SymbolFlags.Interface ? 13 /* ClassificationType.interfaceName */ : flags & SymbolFlags.TypeParameter ? 15 /* ClassificationType.typeParameterName */ : undefined;
350
- }
351
- else {
352
- return undefined;
353
- }
354
- }
355
- /** Returns true if there exists a module that introduces entities on the value side. */
356
- function hasValueSideModule(symbol) {
357
- return some(symbol.declarations, declaration => isModuleDeclaration(declaration) && getModuleInstanceState(declaration) === ModuleInstanceState.Instantiated);
358
- }
359
- function getClassificationTypeName(type) {
360
- switch (type) {
361
- case 1 /* ClassificationType.comment */: return "comment" /* ClassificationTypeNames.comment */;
362
- case 2 /* ClassificationType.identifier */: return "identifier" /* ClassificationTypeNames.identifier */;
363
- case 3 /* ClassificationType.keyword */: return "keyword" /* ClassificationTypeNames.keyword */;
364
- case 4 /* ClassificationType.numericLiteral */: return "number" /* ClassificationTypeNames.numericLiteral */;
365
- case 25 /* ClassificationType.bigintLiteral */: return "bigint" /* ClassificationTypeNames.bigintLiteral */;
366
- case 5 /* ClassificationType.operator */: return "operator" /* ClassificationTypeNames.operator */;
367
- case 6 /* ClassificationType.stringLiteral */: return "string" /* ClassificationTypeNames.stringLiteral */;
368
- case 8 /* ClassificationType.whiteSpace */: return "whitespace" /* ClassificationTypeNames.whiteSpace */;
369
- case 9 /* ClassificationType.text */: return "text" /* ClassificationTypeNames.text */;
370
- case 10 /* ClassificationType.punctuation */: return "punctuation" /* ClassificationTypeNames.punctuation */;
371
- case 11 /* ClassificationType.className */: return "class name" /* ClassificationTypeNames.className */;
372
- case 12 /* ClassificationType.enumName */: return "enum name" /* ClassificationTypeNames.enumName */;
373
- case 13 /* ClassificationType.interfaceName */: return "interface name" /* ClassificationTypeNames.interfaceName */;
374
- case 14 /* ClassificationType.moduleName */: return "module name" /* ClassificationTypeNames.moduleName */;
375
- case 15 /* ClassificationType.typeParameterName */: return "type parameter name" /* ClassificationTypeNames.typeParameterName */;
376
- case 16 /* ClassificationType.typeAliasName */: return "type alias name" /* ClassificationTypeNames.typeAliasName */;
377
- case 17 /* ClassificationType.parameterName */: return "parameter name" /* ClassificationTypeNames.parameterName */;
378
- case 18 /* ClassificationType.docCommentTagName */: return "doc comment tag name" /* ClassificationTypeNames.docCommentTagName */;
379
- case 19 /* ClassificationType.jsxOpenTagName */: return "jsx open tag name" /* ClassificationTypeNames.jsxOpenTagName */;
380
- case 20 /* ClassificationType.jsxCloseTagName */: return "jsx close tag name" /* ClassificationTypeNames.jsxCloseTagName */;
381
- case 21 /* ClassificationType.jsxSelfClosingTagName */: return "jsx self closing tag name" /* ClassificationTypeNames.jsxSelfClosingTagName */;
382
- case 22 /* ClassificationType.jsxAttribute */: return "jsx attribute" /* ClassificationTypeNames.jsxAttribute */;
383
- case 23 /* ClassificationType.jsxText */: return "jsx text" /* ClassificationTypeNames.jsxText */;
384
- case 24 /* ClassificationType.jsxAttributeStringLiteralValue */: return "jsx attribute string literal value" /* ClassificationTypeNames.jsxAttributeStringLiteralValue */;
385
- default: return undefined;
386
- }
387
- }
388
- function convertClassificationsToSpans(classifications) {
389
- Debug.assert(classifications.spans.length % 3 === 0);
390
- const dense = classifications.spans;
391
- const result = [];
392
- for (let i = 0; i < dense.length; i += 3) {
393
- result.push({
394
- textSpan: createTextSpan(dense[i], dense[i + 1]),
395
- classificationType: getClassificationTypeName(dense[i + 2])
396
- });
397
- }
398
- return result;
399
- }
400
- export function getSyntacticClassifications(cancellationToken, sourceFile, span) {
401
- return convertClassificationsToSpans(getEncodedSyntacticClassifications(cancellationToken, sourceFile, span));
402
- }
403
- export function getEncodedSyntacticClassifications(cancellationToken, sourceFile, span) {
404
- const spanStart = span.start;
405
- const spanLength = span.length;
406
- // Make a scanner we can get trivia from.
407
- const triviaScanner = createScanner(ScriptTarget.Latest, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text);
408
- const mergeConflictScanner = createScanner(ScriptTarget.Latest, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text);
409
- const result = [];
410
- processElement(sourceFile);
411
- return { spans: result, endOfLineState: 0 /* EndOfLineState.None */ };
412
- function pushClassification(start, length, type) {
413
- result.push(start);
414
- result.push(length);
415
- result.push(type);
416
- }
417
- function classifyLeadingTriviaAndGetTokenStart(token) {
418
- triviaScanner.setTextPos(token.pos);
419
- while (true) {
420
- const start = triviaScanner.getTextPos();
421
- // only bother scanning if we have something that could be trivia.
422
- if (!couldStartTrivia(sourceFile.text, start)) {
423
- return start;
424
- }
425
- const kind = triviaScanner.scan();
426
- const end = triviaScanner.getTextPos();
427
- const width = end - start;
428
- // The moment we get something that isn't trivia, then stop processing.
429
- if (!isTrivia(kind)) {
430
- return start;
431
- }
432
- switch (kind) {
433
- case SyntaxKind.NewLineTrivia:
434
- case SyntaxKind.WhitespaceTrivia:
435
- // Don't bother with newlines/whitespace.
436
- continue;
437
- case SyntaxKind.SingleLineCommentTrivia:
438
- case SyntaxKind.MultiLineCommentTrivia:
439
- // Only bother with the trivia if it at least intersects the span of interest.
440
- classifyComment(kind, start, width);
441
- // Classifying a comment might cause us to reuse the trivia scanner
442
- // (because of jsdoc comments). So after we classify the comment make
443
- // sure we set the scanner position back to where it needs to be.
444
- triviaScanner.setTextPos(end);
445
- continue;
446
- case SyntaxKind.ConflictMarkerTrivia:
447
- const text = sourceFile.text;
448
- const ch = text.charCodeAt(start);
449
- // for the <<<<<<< and >>>>>>> markers, we just add them in as comments
450
- // in the classification stream.
451
- if (ch === CharacterCodes.lessThan || ch === CharacterCodes.greaterThan) {
452
- pushClassification(start, width, 1 /* ClassificationType.comment */);
453
- continue;
454
- }
455
- // for the ||||||| and ======== markers, add a comment for the first line,
456
- // and then lex all subsequent lines up until the end of the conflict marker.
457
- Debug.assert(ch === CharacterCodes.bar || ch === CharacterCodes.equals);
458
- classifyDisabledMergeCode(text, start, end);
459
- break;
460
- case SyntaxKind.ShebangTrivia:
461
- // TODO: Maybe we should classify these.
462
- break;
463
- default:
464
- Debug.assertNever(kind);
465
- }
466
- }
467
- }
468
- /**
469
- * Na tag, o comentário JSDoc se classificava por partes (a tag, o nome do parâmetro, o tipo), pelo nó que o parser do
470
- * JSDoc montava, e o nó que o comentário documenta era o `token`; sem o JSDoc (CK-03), ele é um comentário como os
471
- * outros.
472
- */
473
- function classifyComment(kind, start, width) {
474
- if (kind === SyntaxKind.SingleLineCommentTrivia) {
475
- if (tryClassifyTripleSlashComment(start, width)) {
476
- return;
477
- }
478
- }
479
- // Simple comment. Just add as is.
480
- pushCommentRange(start, width);
481
- }
482
- function pushCommentRange(start, width) {
483
- pushClassification(start, width, 1 /* ClassificationType.comment */);
484
- }
485
- function tryClassifyTripleSlashComment(start, width) {
486
- const tripleSlashXMLCommentRegEx = /^(\/\/\/\s*)(<)(?:(\S+)((?:[^/]|\/[^>])*)(\/>)?)?/im;
487
- const attributeRegex = /(\S+)(\s*)(=)(\s*)('[^']+'|"[^"]+")/img;
488
- const text = sourceFile.text.substr(start, width);
489
- const match = tripleSlashXMLCommentRegEx.exec(text);
490
- if (!match) {
491
- return false;
492
- }
493
- // Limiting classification to exactly the elements and attributes
494
- // defined in `ts.commentPragmas` would be excessive, but we can avoid
495
- // some obvious false positives (e.g. in XML-like doc comments) by
496
- // checking the element name.
497
- // eslint-disable-next-line no-in-operator
498
- if (!match[3] || !(match[3] in commentPragmas)) {
499
- return false;
500
- }
501
- let pos = start;
502
- pushCommentRange(pos, match[1].length); // ///
503
- pos += match[1].length;
504
- pushClassification(pos, match[2].length, 10 /* ClassificationType.punctuation */); // <
505
- pos += match[2].length;
506
- pushClassification(pos, match[3].length, 21 /* ClassificationType.jsxSelfClosingTagName */); // element name
507
- pos += match[3].length;
508
- const attrText = match[4];
509
- let attrPos = pos;
510
- while (true) {
511
- const attrMatch = attributeRegex.exec(attrText);
512
- if (!attrMatch) {
513
- break;
514
- }
515
- const newAttrPos = pos + attrMatch.index;
516
- if (newAttrPos > attrPos) {
517
- pushCommentRange(attrPos, newAttrPos - attrPos);
518
- attrPos = newAttrPos;
519
- }
520
- pushClassification(attrPos, attrMatch[1].length, 22 /* ClassificationType.jsxAttribute */); // attribute name
521
- attrPos += attrMatch[1].length;
522
- if (attrMatch[2].length) {
523
- pushCommentRange(attrPos, attrMatch[2].length); // whitespace
524
- attrPos += attrMatch[2].length;
525
- }
526
- pushClassification(attrPos, attrMatch[3].length, 5 /* ClassificationType.operator */); // =
527
- attrPos += attrMatch[3].length;
528
- if (attrMatch[4].length) {
529
- pushCommentRange(attrPos, attrMatch[4].length); // whitespace
530
- attrPos += attrMatch[4].length;
531
- }
532
- pushClassification(attrPos, attrMatch[5].length, 24 /* ClassificationType.jsxAttributeStringLiteralValue */); // attribute value
533
- attrPos += attrMatch[5].length;
534
- }
535
- pos += match[4].length;
536
- if (pos > attrPos) {
537
- pushCommentRange(attrPos, pos - attrPos);
538
- }
539
- if (match[5]) {
540
- pushClassification(pos, match[5].length, 10 /* ClassificationType.punctuation */); // />
541
- pos += match[5].length;
542
- }
543
- const end = start + width;
544
- if (pos < end) {
545
- pushCommentRange(pos, end - pos);
546
- }
547
- return true;
548
- }
549
- function classifyDisabledMergeCode(text, start, end) {
550
- // Classify the line that the ||||||| or ======= marker is on as a comment.
551
- // Then just lex all further tokens and add them to the result.
552
- let i;
553
- for (i = start; i < end; i++) {
554
- if (isLineBreak(text.charCodeAt(i))) {
555
- break;
556
- }
557
- }
558
- pushClassification(start, i - start, 1 /* ClassificationType.comment */);
559
- mergeConflictScanner.setTextPos(i);
560
- while (mergeConflictScanner.getTextPos() < end) {
561
- classifyDisabledCodeToken();
562
- }
563
- }
564
- function classifyDisabledCodeToken() {
565
- const start = mergeConflictScanner.getTextPos();
566
- const tokenKind = mergeConflictScanner.scan();
567
- const end = mergeConflictScanner.getTextPos();
568
- const type = classifyTokenType(tokenKind);
569
- if (type) {
570
- pushClassification(start, end - start, type);
571
- }
572
- }
573
- /**
574
- * Returns true if node should be treated as classified and no further processing is required.
575
- * False will mean that node is not classified and traverse routine should recurse into node contents.
576
- * Na tag, também o nó de JSDoc, que a parse tree da cópia não tem (CK-03).
577
- */
578
- function tryClassifyNode(node) {
579
- if (nodeIsMissing(node)) {
580
- return true;
581
- }
582
- const classifiedElementName = tryClassifyJsxElementName(node);
583
- if (!isToken(node) && node.kind !== SyntaxKind.JsxText && classifiedElementName === undefined) {
584
- return false;
585
- }
586
- const tokenStart = node.kind === SyntaxKind.JsxText ? node.pos : classifyLeadingTriviaAndGetTokenStart(node);
587
- const tokenWidth = node.end - tokenStart;
588
- Debug.assert(tokenWidth >= 0);
589
- if (tokenWidth > 0) {
590
- const type = classifiedElementName || classifyTokenType(node.kind, node);
591
- if (type) {
592
- pushClassification(tokenStart, tokenWidth, type);
593
- }
594
- }
595
- return true;
596
- }
597
- function tryClassifyJsxElementName(token) {
598
- switch (token.parent && token.parent.kind) {
599
- case SyntaxKind.JsxOpeningElement:
600
- if (token.parent.tagName === token) {
601
- return 19 /* ClassificationType.jsxOpenTagName */;
602
- }
603
- break;
604
- case SyntaxKind.JsxClosingElement:
605
- if (token.parent.tagName === token) {
606
- return 20 /* ClassificationType.jsxCloseTagName */;
607
- }
608
- break;
609
- case SyntaxKind.JsxSelfClosingElement:
610
- if (token.parent.tagName === token) {
611
- return 21 /* ClassificationType.jsxSelfClosingTagName */;
612
- }
613
- break;
614
- case SyntaxKind.JsxAttribute:
615
- if (token.parent.name === token) {
616
- return 22 /* ClassificationType.jsxAttribute */;
617
- }
618
- break;
619
- }
620
- return undefined;
621
- }
622
- // for accurate classification, the actual token should be passed in. however, for
623
- // cases like 'disabled merge code' classification, we just get the token kind and
624
- // classify based on that instead.
625
- function classifyTokenType(tokenKind, token) {
626
- if (isKeyword(tokenKind)) {
627
- return 3 /* ClassificationType.keyword */;
628
- }
629
- // Special case `<` and `>`: If they appear in a generic context they are punctuation,
630
- // not operators.
631
- if (tokenKind === SyntaxKind.LessThanToken || tokenKind === SyntaxKind.GreaterThanToken) {
632
- // If the node owning the token has a type argument list or type parameter list, then
633
- // we can effectively assume that a '<' and '>' belong to those lists.
634
- if (token && getTypeArgumentOrTypeParameterList(token.parent)) {
635
- return 10 /* ClassificationType.punctuation */;
636
- }
637
- }
638
- if (isPunctuation(tokenKind)) {
639
- if (token) {
640
- const parent = token.parent;
641
- if (tokenKind === SyntaxKind.EqualsToken) {
642
- // the '=' in a variable declaration is special cased here.
643
- // Na tag, também o de uma propriedade de classe (CK-02).
644
- if (parent.kind === SyntaxKind.VariableDeclaration ||
645
- parent.kind === SyntaxKind.Parameter ||
646
- parent.kind === SyntaxKind.JsxAttribute) {
647
- return 5 /* ClassificationType.operator */;
648
- }
649
- }
650
- if (parent.kind === SyntaxKind.BinaryExpression ||
651
- parent.kind === SyntaxKind.PrefixUnaryExpression ||
652
- parent.kind === SyntaxKind.PostfixUnaryExpression ||
653
- parent.kind === SyntaxKind.ConditionalExpression) {
654
- return 5 /* ClassificationType.operator */;
655
- }
656
- }
657
- return 10 /* ClassificationType.punctuation */;
658
- }
659
- else if (tokenKind === SyntaxKind.NumericLiteral) {
660
- return 4 /* ClassificationType.numericLiteral */;
661
- }
662
- else if (tokenKind === SyntaxKind.BigIntLiteral) {
663
- return 25 /* ClassificationType.bigintLiteral */;
664
- }
665
- else if (tokenKind === SyntaxKind.StringLiteral) {
666
- return token && token.parent.kind === SyntaxKind.JsxAttribute ? 24 /* ClassificationType.jsxAttributeStringLiteralValue */ : 6 /* ClassificationType.stringLiteral */;
667
- }
668
- // Na tag, também o literal de regex, como string (CK-02).
669
- else if (isTemplateLiteralKind(tokenKind)) {
670
- return 6 /* ClassificationType.stringLiteral */;
671
- }
672
- else if (tokenKind === SyntaxKind.JsxText) {
673
- return 23 /* ClassificationType.jsxText */;
674
- }
675
- else if (tokenKind === SyntaxKind.Identifier) {
676
- if (token) {
677
- // Na tag, também o nome de uma classe, de uma interface e de um enum declarados, e o parâmetro `this`, que
678
- // era palavra-chave (CK-02).
679
- switch (token.parent.kind) {
680
- case SyntaxKind.TypeParameter:
681
- if (token.parent.name === token) {
682
- return 15 /* ClassificationType.typeParameterName */;
683
- }
684
- return;
685
- case SyntaxKind.ModuleDeclaration:
686
- if (token.parent.name === token) {
687
- return 14 /* ClassificationType.moduleName */;
688
- }
689
- return;
690
- case SyntaxKind.Parameter:
691
- if (token.parent.name === token) {
692
- return 17 /* ClassificationType.parameterName */;
693
- }
694
- return;
695
- }
696
- }
697
- return 2 /* ClassificationType.identifier */;
698
- }
699
- }
700
- function processElement(element) {
701
- if (!element) {
702
- return;
703
- }
704
- // Ignore nodes that don't intersect the original span to classify.
705
- if (decodedTextSpanIntersectsWith(spanStart, spanLength, element.pos, element.getFullWidth())) {
706
- checkForClassificationCancellation(cancellationToken, element.kind);
707
- for (const child of element.getChildren(sourceFile)) {
708
- if (!tryClassifyNode(child)) {
709
- // Recurse into our child nodes.
710
- processElement(child);
711
- }
712
- }
713
- }
714
- }
715
- }