@tslite/services 1.13.0 → 1.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,9 @@
1
- import type { CancellationToken, Classifications, ClassifiedSpan, SourceFile, TextSpan, TypeChecker, UnderscoreEscapedMap } from "./_namespaces/ts.js";
1
+ import type { CancellationToken, Classifications, ClassifiedSpan, Classifier, SourceFile, TextSpan, TypeChecker, UnderscoreEscapedMap } from "./_namespaces/ts.js";
2
+ /**
3
+ * O classificador léxico: a classe de cada token de um trecho, só pelo scanner, sem árvore nem programa. É o que
4
+ * classifica um trecho solto, como o bloco de código de um hover, que não é arquivo de programa nenhum.
5
+ */
6
+ export declare function createClassifier(): Classifier;
2
7
  export declare function getSemanticClassifications(typeChecker: TypeChecker, cancellationToken: CancellationToken, sourceFile: SourceFile, classifiableNames: UnderscoreEscapedMap<true>, span: TextSpan): ClassifiedSpan[];
3
8
  export declare function getEncodedSemanticClassifications(typeChecker: TypeChecker, cancellationToken: CancellationToken, sourceFile: SourceFile, classifiableNames: UnderscoreEscapedMap<true>, span: TextSpan): Classifications;
4
9
  export declare function getSyntacticClassifications(cancellationToken: CancellationToken, sourceFile: SourceFile, span: TextSpan): ClassifiedSpan[];
@@ -1,7 +1,283 @@
1
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 que os serviços que já vieram usam (a classificação sintática e a semântica); o classificador
3
- // léxico (o `createClassifier`) vem com o grupo que o usar (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, nodeIsMissing, some, textSpanIntersectsWith, } from "./_namespaces/ts.js";
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
+ }
5
281
  export function getSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) {
6
282
  return convertClassificationsToSpans(getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span));
7
283
  }
package/dist/types.d.ts CHANGED
@@ -719,6 +719,20 @@ export declare enum OutliningSpanKind {
719
719
  /** Contiguous blocks of import declarations */
720
720
  Imports = "imports"
721
721
  }
722
+ export interface Classifier {
723
+ /**
724
+ * A classe de cada token de um texto, só pelo scanner, sem contexto sintático: `string` pode ser um identificador ou
725
+ * a palavra-chave, e o classificador decide por heurística. É o que classifica um trecho que não é arquivo de
726
+ * programa; para a precisão, o classificador sintático.
727
+ *
728
+ * @param text O texto a classificar (uma linha, ou um trecho).
729
+ * @param endOfLineState O estado do classificador no fim da linha anterior.
730
+ * @param syntacticClassifierAbsent Se quem pede **não** usa o classificador sintático. Com ele presente (`false`),
731
+ * o que pode ser classificado errado (a palavra de tipo dentro do que pode ser um
732
+ * genérico) sai como identificador, para o sintático decidir.
733
+ */
734
+ getEncodedLexicalClassifications(text: string, endOfLineState: EndOfLineState, syntacticClassifierAbsent: boolean): Classifications;
735
+ }
722
736
  export declare enum ScriptElementKind {
723
737
  unknown = "",
724
738
  warning = "warning",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tslite/services",
3
- "version": "1.13.0",
3
+ "version": "1.15.0",
4
4
  "description": "The tsc 3.9.10 language service, copied from the tag and cut down to the TSLite Language, over the copy of the tsc checker",
5
5
  "author": "Anderson D. Rosa <andersondrosa@outlook.com>",
6
6
  "license": "Apache-2.0",
@@ -24,8 +24,8 @@
24
24
  "NOTICE"
25
25
  ],
26
26
  "dependencies": {
27
- "@tslite/checker": "1.13.0",
28
- "@tslite/parser": "1.13.0"
27
+ "@tslite/checker": "1.15.0",
28
+ "@tslite/parser": "1.15.0"
29
29
  },
30
30
  "devDependencies": {
31
31
  "@tslite/oracle": "0.1.1"