@tslite/binder 1.16.0 → 1.16.1

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/dist/binder.js DELETED
@@ -1,1743 +0,0 @@
1
- // Modificado de microsoft/TypeScript v3.9.10, src/compiler/binder.ts: o namespace virou módulo ES, com os imports explícitos.
2
- import { Debug, DiagnosticCategory, Diagnostics, FlowFlags, InternalSymbolName, ModifierFlags, NodeFlags, SymbolFlags, SyntaxKind, TokenFlags, addRelatedInfo, append, appendIfUnique, concatenate, contains, createDiagnosticForNodeInSourceFile, createFileDiagnostic, createMap, createSymbolTable, createUnderscoreEscapedMap, declarationNameToString, escapeLeadingUnderscores, exportAssignmentIsAlias, findAncestor, forEach, forEachChild, getCombinedModifierFlags, getCombinedNodeFlags, getErrorSpanForNode, getEscapedTextOfIdentifierOrLiteral, getImmediatelyInvokedFunctionExpression, getNameOfDeclaration, getNodeId, getPropertyNameForKnownSymbolName, getRangesWhere, getSourceFileOfNode, getSpanOfTokenAtPosition, getTokenPosOfNode, hasDynamicName, hasModifier, idText, isAmbientModule, isAssignmentOperator, isAssignmentTarget, isBinaryExpression, isBindingPattern, isBlock, isBlockOrCatchScoped, isConditionalTypeNode, isDottedName, isElementAccessExpression, isExportAssignment, isExportDeclaration, isExportSpecifier, isExpression, isExpressionOfOptionalChainRoot, isExternalModule, isForInOrOfStatement, isFunctionLike, isIdentifier, isIdentifierName, isLeftHandSideExpression, isModuleAugmentationExternal, isModuleBlock, isNamedDeclaration, isNamespaceExport, isNullishCoalesce, isOmittedExpression, isOptionalChain, isOptionalChainRoot, isOutermostOptionalChain, isParameterDeclaration, isParenthesizedExpression, isPrefixUnaryExpression, isPropertyAccessExpression, isPropertyNameLiteral, isSignedNumericLiteral, isSourceFile, isStatement, isStatementButNotDeclaration, isStringLiteralLike, isStringOrNumericLiteralLike, isTypeAliasDeclaration, isVariableStatement, isTypeOfExpression, isWellKnownSymbolSyntactically, length, nodeHasName, nodeIsMissing, nodeIsPresent, objectAllocator, perfLogger, performance, removeFileExtension, setValueDeclaration, skipParentheses, sliceAfter, tokenToString, tryCast, unescapeLeadingUnderscores, unreachableCodeIsError, } from "./_namespaces/ts.js";
3
- export var ModuleInstanceState;
4
- (function (ModuleInstanceState) {
5
- ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated";
6
- ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated";
7
- })(ModuleInstanceState || (ModuleInstanceState = {}));
8
- export function getModuleInstanceState(node, visited) {
9
- if (node.body && !node.body.parent) {
10
- // o `getModuleInstanceStateForAliasTarget` sobe pelos pais, então eles têm de estar ligados já
11
- setParentPointers(node, node.body);
12
- }
13
- return node.body ? getModuleInstanceStateCached(node.body, visited) : 1 /* ModuleInstanceState.Instantiated */;
14
- }
15
- function getModuleInstanceStateCached(node, visited = createMap()) {
16
- const nodeId = "" + getNodeId(node);
17
- if (visited.has(nodeId)) {
18
- return visited.get(nodeId) || 0 /* ModuleInstanceState.NonInstantiated */;
19
- }
20
- visited.set(nodeId, undefined);
21
- const result = getModuleInstanceStateWorker(node, visited);
22
- visited.set(nodeId, result);
23
- return result;
24
- }
25
- /**
26
- * Um namespace não é instanciado — não vira valor em runtime — quando só tem interface e type alias, import não
27
- * exportado, `export { … }` de nomes que não são instanciados e outros namespaces não instanciados.
28
- */
29
- function getModuleInstanceStateWorker(node, visited) {
30
- switch (node.kind) {
31
- case SyntaxKind.TypeAliasDeclaration:
32
- return 0 /* ModuleInstanceState.NonInstantiated */;
33
- case SyntaxKind.ImportDeclaration:
34
- if (!(hasModifier(node, ModifierFlags.Export))) {
35
- return 0 /* ModuleInstanceState.NonInstantiated */;
36
- }
37
- break;
38
- case SyntaxKind.ExportDeclaration:
39
- const exportDeclaration = node;
40
- if (!exportDeclaration.moduleSpecifier && exportDeclaration.exportClause && exportDeclaration.exportClause.kind === SyntaxKind.NamedExports) {
41
- let state = 0 /* ModuleInstanceState.NonInstantiated */;
42
- for (const specifier of exportDeclaration.exportClause.elements) {
43
- const specifierState = getModuleInstanceStateForAliasTarget(specifier, visited);
44
- if (specifierState > state) {
45
- state = specifierState;
46
- }
47
- if (state === 1 /* ModuleInstanceState.Instantiated */) {
48
- return state;
49
- }
50
- }
51
- return state;
52
- }
53
- break;
54
- case SyntaxKind.ModuleBlock: {
55
- // o primeiro filho instanciado decide, e a busca para
56
- let state = 0 /* ModuleInstanceState.NonInstantiated */;
57
- forEachChild(node, n => {
58
- const childState = getModuleInstanceStateCached(n, visited);
59
- switch (childState) {
60
- case 0 /* ModuleInstanceState.NonInstantiated */:
61
- return;
62
- case 1 /* ModuleInstanceState.Instantiated */:
63
- state = 1 /* ModuleInstanceState.Instantiated */;
64
- return true;
65
- default:
66
- Debug.assertNever(childState);
67
- }
68
- });
69
- return state;
70
- }
71
- case SyntaxKind.ModuleDeclaration:
72
- return getModuleInstanceState(node, visited);
73
- }
74
- return 1 /* ModuleInstanceState.Instantiated */;
75
- }
76
- function getModuleInstanceStateForAliasTarget(specifier, visited) {
77
- const name = specifier.propertyName || specifier.name;
78
- let p = specifier.parent;
79
- while (p) {
80
- if (isBlock(p) || isModuleBlock(p) || isSourceFile(p)) {
81
- const statements = p.statements;
82
- let found;
83
- for (const statement of statements) {
84
- if (nodeHasName(statement, name)) {
85
- if (!statement.parent) {
86
- setParentPointers(p, statement);
87
- }
88
- const state = getModuleInstanceStateCached(statement, visited);
89
- if (found === undefined || state > found) {
90
- found = state;
91
- }
92
- if (found === 1 /* ModuleInstanceState.Instantiated */) {
93
- return found;
94
- }
95
- }
96
- }
97
- if (found !== undefined) {
98
- return found;
99
- }
100
- }
101
- p = p.parent;
102
- }
103
- return 1 /* ModuleInstanceState.Instantiated */; // sem achar o nome, ele pode ser um valor
104
- }
105
- var ContainerFlags;
106
- (function (ContainerFlags) {
107
- // o nó não é contêiner: nada muda antes de descer nele
108
- ContainerFlags[ContainerFlags["None"] = 0] = "None";
109
- // o nó é o contêiner corrente (e o de bloco) enquanto se desce nele, e não tem `locals`: o object literal, o tipo
110
- // literal, a interface
111
- ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer";
112
- // o nó é o contêiner de bloco corrente enquanto se desce nele: o bloco que não é corpo de função, o `catch`, os laços
113
- ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer";
114
- // o nó tem um caminho de fluxo próprio: o fluxo corrente se guarda, um novo começa dentro dele, e o guardado volta
115
- ContainerFlags[ContainerFlags["IsControlFlowContainer"] = 4] = "IsControlFlowContainer";
116
- ContainerFlags[ContainerFlags["IsFunctionLike"] = 8] = "IsFunctionLike";
117
- ContainerFlags[ContainerFlags["IsFunctionExpression"] = 16] = "IsFunctionExpression";
118
- ContainerFlags[ContainerFlags["HasLocals"] = 32] = "HasLocals";
119
- })(ContainerFlags || (ContainerFlags = {}));
120
- function initFlowNode(node) {
121
- Debug.attachFlowNodeDebugInfo(node);
122
- return node;
123
- }
124
- const binder = createBinder();
125
- export function bindSourceFile(file, options) {
126
- performance.mark("beforeBind");
127
- perfLogger.logStartBindFile("" + file.fileName);
128
- binder(file, options);
129
- perfLogger.logStopBindFile();
130
- performance.mark("afterBind");
131
- performance.measure("Bind", "beforeBind", "afterBind");
132
- }
133
- function createBinder() {
134
- let file;
135
- let options;
136
- let parent;
137
- let container;
138
- let blockScopeContainer;
139
- let lastContainer;
140
- // o estado da análise de fluxo
141
- let currentFlow;
142
- let currentBreakTarget;
143
- let currentContinueTarget;
144
- let currentReturnTarget;
145
- let currentTrueTarget;
146
- let currentFalseTarget;
147
- let currentExceptionTarget;
148
- let preSwitchCaseFlow;
149
- let hasExplicitReturn;
150
- // Um módulo é strict pelo ECMAScript; um script, pelo `alwaysStrict` da configuração fixa. Só a lib, que é
151
- // declaração, liga fora de strict mode.
152
- let inStrictMode;
153
- let Symbol;
154
- // Os nomes declarados com um significado classificável, para a classificação semântica do language service.
155
- let classifiableNames;
156
- const unreachableFlow = { flags: FlowFlags.Unreachable };
157
- const reportedUnreachableFlow = { flags: FlowFlags.Unreachable };
158
- /**
159
- * O diagnóstico de um nó que talvez ainda não tenha os pais ligados, e por isso não alcance o arquivo: se o binder
160
- * chegou nele, ele é do arquivo corrente.
161
- */
162
- function createDiagnosticForNode(node, message, arg0, arg1, arg2) {
163
- return createDiagnosticForNodeInSourceFile(getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2);
164
- }
165
- function bindSourceFile(f, opts) {
166
- file = f;
167
- options = opts;
168
- inStrictMode = bindInStrictMode(file);
169
- classifiableNames = createUnderscoreEscapedMap();
170
- Symbol = objectAllocator.getSymbolConstructor();
171
- Debug.attachFlowNodeDebugInfo(unreachableFlow);
172
- Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow);
173
- if (!file.locals) {
174
- bind(file);
175
- file.classifiableNames = classifiableNames;
176
- }
177
- file = undefined;
178
- options = undefined;
179
- parent = undefined;
180
- container = undefined;
181
- blockScopeContainer = undefined;
182
- lastContainer = undefined;
183
- currentFlow = undefined;
184
- currentBreakTarget = undefined;
185
- currentContinueTarget = undefined;
186
- currentReturnTarget = undefined;
187
- currentTrueTarget = undefined;
188
- currentFalseTarget = undefined;
189
- currentExceptionTarget = undefined;
190
- hasExplicitReturn = false;
191
- }
192
- return bindSourceFile;
193
- function bindInStrictMode(file) {
194
- return !file.isDeclarationFile || !!file.externalModuleIndicator;
195
- }
196
- function createSymbol(flags, name) {
197
- return new Symbol(flags, name);
198
- }
199
- function addDeclarationToSymbol(symbol, node, symbolFlags) {
200
- symbol.flags |= symbolFlags;
201
- node.symbol = symbol;
202
- symbol.declarations = appendIfUnique(symbol.declarations, node);
203
- if (symbolFlags & (SymbolFlags.Module | SymbolFlags.Variable) && !symbol.exports) {
204
- symbol.exports = createSymbolTable();
205
- }
206
- if (symbolFlags & (SymbolFlags.TypeLiteral | SymbolFlags.ObjectLiteral) && !symbol.members) {
207
- symbol.members = createSymbolTable();
208
- }
209
- if (symbolFlags & SymbolFlags.Value) {
210
- setValueDeclaration(symbol, node);
211
- }
212
- }
213
- /** O nome da declaração na tabela de símbolos. Um nome computado só vale aqui se for literal ou um `Symbol.x`. */
214
- function getDeclarationName(node) {
215
- if (node.kind === SyntaxKind.ExportAssignment) {
216
- return InternalSymbolName.Default;
217
- }
218
- const name = getNameOfDeclaration(node);
219
- if (name) {
220
- // O módulo ambiente é só o `declare global` (o `declare module "x"` saiu, CK-02).
221
- if (isAmbientModule(node)) {
222
- return "__global";
223
- }
224
- if (name.kind === SyntaxKind.ComputedPropertyName) {
225
- const nameExpression = name.expression;
226
- // `["a"]` e `[1]` valem como `a` e `1`
227
- if (isStringOrNumericLiteralLike(nameExpression)) {
228
- return escapeLeadingUnderscores(nameExpression.text);
229
- }
230
- if (isSignedNumericLiteral(nameExpression)) {
231
- return tokenToString(nameExpression.operator) + nameExpression.operand.text;
232
- }
233
- Debug.assert(isWellKnownSymbolSyntactically(nameExpression));
234
- return getPropertyNameForKnownSymbolName(idText(nameExpression.name));
235
- }
236
- if (isWellKnownSymbolSyntactically(name)) {
237
- return getPropertyNameForKnownSymbolName(idText(name.name));
238
- }
239
- return isPropertyNameLiteral(name) ? getEscapedTextOfIdentifierOrLiteral(name) : undefined;
240
- }
241
- switch (node.kind) {
242
- case SyntaxKind.FunctionType:
243
- case SyntaxKind.CallSignature:
244
- return InternalSymbolName.Call;
245
- case SyntaxKind.IndexSignature:
246
- return InternalSymbolName.Index;
247
- case SyntaxKind.ExportDeclaration:
248
- return InternalSymbolName.ExportStar;
249
- }
250
- }
251
- function getDisplayName(node) {
252
- return isNamedDeclaration(node) ? declarationNameToString(node.name) : unescapeLeadingUnderscores(Debug.checkDefined(getDeclarationName(node)));
253
- }
254
- /**
255
- * Declara o símbolo do nó na tabela, ou o funde com o que já está lá, e acusa o conflito de nomes.
256
- * @param parent o símbolo do contêiner
257
- * @param includes as flags do nó, além das da própria declaração (export, ambiente…)
258
- * @param excludes as flags com que o nó não pode dividir a tabela: um símbolo que as tenha é conflito
259
- */
260
- function declareSymbol(symbolTable, parent, node, includes, excludes) {
261
- Debug.assert(!hasDynamicName(node));
262
- const isDefaultExport = isExportSpecifier(node) && node.name.escapedText === "default";
263
- // o símbolo exportado de um `export default` se chama sempre `default`
264
- const name = isDefaultExport && parent ? InternalSymbolName.Default : getDeclarationName(node);
265
- let symbol;
266
- if (name === undefined) {
267
- symbol = createSymbol(SymbolFlags.None, InternalSymbolName.Missing);
268
- }
269
- else {
270
- // O símbolo novo nasce sem flags, para não conflitar com os `excludes` dele mesmo. Um símbolo que já está na
271
- // tabela com flags de `excludes` é conflito (um `let` e um `type` de mesmo nome não): cada declaração dele é
272
- // acusada, e a nova ganha um símbolo próprio. Sem conflito, a declaração se funde no símbolo que está lá (duas
273
- // declarações de um namespace, duas property signatures de mesmo nome num tipo).
274
- symbol = symbolTable.get(name);
275
- if (includes & SymbolFlags.Classifiable) {
276
- classifiableNames.set(name, true);
277
- }
278
- if (!symbol) {
279
- symbolTable.set(name, symbol = createSymbol(SymbolFlags.None, name));
280
- }
281
- else if (symbol.flags & excludes) {
282
- if (isNamedDeclaration(node)) {
283
- node.name.parent = node;
284
- }
285
- let message = symbol.flags & SymbolFlags.BlockScopedVariable
286
- ? Diagnostics.Cannot_redeclare_block_scoped_variable_0
287
- : Diagnostics.Duplicate_identifier_0;
288
- let messageNeedsName = true;
289
- let multipleDefaultExports = false;
290
- if (length(symbol.declarations)) {
291
- // Dois `export default` no mesmo módulo: o `export default` de declaração tem o modificador
292
- // `default`; o de expressão (`ExportAssignment`) não tem, e se reconhece pelo kind.
293
- if (isDefaultExport) {
294
- message = Diagnostics.A_module_cannot_have_multiple_default_exports;
295
- messageNeedsName = false;
296
- multipleDefaultExports = true;
297
- }
298
- else {
299
- if (symbol.declarations && symbol.declarations.length &&
300
- node.kind === SyntaxKind.ExportAssignment) {
301
- message = Diagnostics.A_module_cannot_have_multiple_default_exports;
302
- messageNeedsName = false;
303
- multipleDefaultExports = true;
304
- }
305
- }
306
- }
307
- const relatedInformation = [];
308
- if (isTypeAliasDeclaration(node) && nodeIsMissing(node.type) && hasModifier(node, ModifierFlags.Export) && symbol.flags & (SymbolFlags.Alias | SymbolFlags.Type | SymbolFlags.Namespace)) {
309
- // `export type T;` talvez quisesse dizer `export type { T }`
310
- relatedInformation.push(createDiagnosticForNode(node, Diagnostics.Did_you_mean_0, `export type { ${unescapeLeadingUnderscores(node.name.escapedText)} }`));
311
- }
312
- const declarationName = getNameOfDeclaration(node) || node;
313
- forEach(symbol.declarations, (declaration, index) => {
314
- const decl = getNameOfDeclaration(declaration) || declaration;
315
- const diag = createDiagnosticForNode(decl, message, messageNeedsName ? getDisplayName(declaration) : undefined);
316
- file.bindDiagnostics.push(multipleDefaultExports ? addRelatedInfo(diag, createDiagnosticForNode(declarationName, index === 0 ? Diagnostics.Another_export_default_is_here : Diagnostics.and_here)) : diag);
317
- if (multipleDefaultExports) {
318
- relatedInformation.push(createDiagnosticForNode(decl, Diagnostics.The_first_export_default_is_here));
319
- }
320
- });
321
- const diag = createDiagnosticForNode(declarationName, message, messageNeedsName ? getDisplayName(node) : undefined);
322
- file.bindDiagnostics.push(addRelatedInfo(diag, ...relatedInformation));
323
- symbol = createSymbol(SymbolFlags.None, name);
324
- }
325
- }
326
- addDeclarationToSymbol(symbol, node, includes);
327
- if (symbol.parent) {
328
- Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one");
329
- }
330
- else {
331
- symbol.parent = parent;
332
- }
333
- return symbol;
334
- }
335
- function declareModuleMember(node, symbolFlags, symbolExcludes) {
336
- const hasExportModifier = getCombinedModifierFlags(node) & ModifierFlags.Export;
337
- if (symbolFlags & SymbolFlags.Alias) {
338
- if (node.kind === SyntaxKind.ExportSpecifier) {
339
- return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
340
- }
341
- else {
342
- return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
343
- }
344
- }
345
- else {
346
- // O membro exportado ganha dois símbolos: um local, com a flag `ExportValue`, e o de exportação, com as flags
347
- // de verdade. Assim um local e um exportado de mesmo nome no mesmo contêiner conflitam, e o checker resolve o
348
- // nome para o local e devolve o exportado (`getExportSymbolOfValueSymbolIfExported`).
349
- //
350
- // O módulo ambiente aninhado vai sempre para os `locals`: o único lugar em que ele é permitido dentro de outro
351
- // módulo é a augmentation, que se funde só com o módulo original, e nunca na fusão global do checker.
352
- if (!isAmbientModule(node) && (hasExportModifier || container.flags & NodeFlags.ExportContext)) {
353
- if (!container.locals) {
354
- return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
355
- }
356
- const exportKind = symbolFlags & SymbolFlags.Value ? SymbolFlags.ExportValue : 0;
357
- const local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes);
358
- local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
359
- node.localSymbol = local;
360
- return local;
361
- }
362
- else {
363
- return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
364
- }
365
- }
366
- }
367
- /**
368
- * Desce num nó com o contêiner, o contêiner de bloco e o fluxo que ele pede, e devolve os de antes na saída. O
369
- * contêiner é também o contêiner de bloco, e ganha a tabela `locals` já na entrada quando quase sempre vai precisar
370
- * dela (parâmetros, variáveis); o contêiner de bloco só a ganha no primeiro `let` ou `const`, porque a maioria dos
371
- * blocos não declara nada, e perde a de uma compilação anterior, se o nó for reaproveitado.
372
- */
373
- function bindContainer(node, containerFlags) {
374
- const saveContainer = container;
375
- const savedBlockScopeContainer = blockScopeContainer;
376
- if (containerFlags & 1 /* ContainerFlags.IsContainer */) {
377
- container = blockScopeContainer = node;
378
- if (containerFlags & 32 /* ContainerFlags.HasLocals */) {
379
- container.locals = createSymbolTable();
380
- }
381
- addToContainerChain(container);
382
- }
383
- else if (containerFlags & 2 /* ContainerFlags.IsBlockScopedContainer */) {
384
- blockScopeContainer = node;
385
- blockScopeContainer.locals = undefined;
386
- }
387
- if (containerFlags & 4 /* ContainerFlags.IsControlFlowContainer */) {
388
- const saveCurrentFlow = currentFlow;
389
- const saveBreakTarget = currentBreakTarget;
390
- const saveContinueTarget = currentContinueTarget;
391
- const saveReturnTarget = currentReturnTarget;
392
- const saveExceptionTarget = currentExceptionTarget;
393
- const saveHasExplicitReturn = hasExplicitReturn;
394
- const isIIFE = containerFlags & 16 /* ContainerFlags.IsFunctionExpression */ && !hasModifier(node, ModifierFlags.Async) &&
395
- !!getImmediatelyInvokedFunctionExpression(node);
396
- // A IIFE que não é `async` faz parte do fluxo de quem a contém: o `return` dela é como um `break` para um
397
- // rótulo logo depois do corpo.
398
- if (!isIIFE) {
399
- currentFlow = initFlowNode({ flags: FlowFlags.Start });
400
- if (containerFlags & 16 /* ContainerFlags.IsFunctionExpression */) {
401
- currentFlow.node = node;
402
- }
403
- }
404
- currentReturnTarget = isIIFE ? createBranchLabel() : undefined;
405
- currentExceptionTarget = undefined;
406
- currentBreakTarget = undefined;
407
- currentContinueTarget = undefined;
408
- hasExplicitReturn = false;
409
- bindChildren(node);
410
- // as flags de alcançabilidade de uma compilação anterior, se o nó for reaproveitado
411
- node.flags &= ~NodeFlags.ReachabilityAndEmitFlags;
412
- if (!(currentFlow.flags & FlowFlags.Unreachable) && containerFlags & 8 /* ContainerFlags.IsFunctionLike */ && nodeIsPresent(node.body)) {
413
- node.flags |= NodeFlags.HasImplicitReturn;
414
- if (hasExplicitReturn)
415
- node.flags |= NodeFlags.HasExplicitReturn;
416
- node.endFlowNode = currentFlow;
417
- }
418
- if (currentReturnTarget) {
419
- addAntecedent(currentReturnTarget, currentFlow);
420
- currentFlow = finishFlowLabel(currentReturnTarget);
421
- }
422
- if (!isIIFE) {
423
- currentFlow = saveCurrentFlow;
424
- }
425
- currentBreakTarget = saveBreakTarget;
426
- currentContinueTarget = saveContinueTarget;
427
- currentReturnTarget = saveReturnTarget;
428
- currentExceptionTarget = saveExceptionTarget;
429
- hasExplicitReturn = saveHasExplicitReturn;
430
- }
431
- else {
432
- bindChildren(node);
433
- }
434
- container = saveContainer;
435
- blockScopeContainer = savedBlockScopeContainer;
436
- }
437
- function bindChildren(node) {
438
- bindChildrenWorker(node);
439
- }
440
- function bindEach(nodes, bindFunction = bind) {
441
- if (nodes === undefined) {
442
- return;
443
- }
444
- forEach(nodes, bindFunction);
445
- }
446
- function bindEachChild(node) {
447
- forEachChild(node, bind, bindEach);
448
- }
449
- function bindChildrenWorker(node) {
450
- if (checkUnreachable(node)) {
451
- bindEachChild(node);
452
- return;
453
- }
454
- if (node.kind >= SyntaxKind.FirstStatement && node.kind <= SyntaxKind.LastStatement && !options.allowUnreachableCode) {
455
- node.flowNode = currentFlow;
456
- }
457
- switch (node.kind) {
458
- case SyntaxKind.WhileStatement:
459
- bindWhileStatement(node);
460
- break;
461
- case SyntaxKind.DoStatement:
462
- bindDoStatement(node);
463
- break;
464
- case SyntaxKind.ForStatement:
465
- bindForStatement(node);
466
- break;
467
- case SyntaxKind.ForInStatement:
468
- case SyntaxKind.ForOfStatement:
469
- bindForInOrForOfStatement(node);
470
- break;
471
- case SyntaxKind.IfStatement:
472
- bindIfStatement(node);
473
- break;
474
- case SyntaxKind.ReturnStatement:
475
- case SyntaxKind.ThrowStatement:
476
- bindReturnOrThrow(node);
477
- break;
478
- case SyntaxKind.BreakStatement:
479
- case SyntaxKind.ContinueStatement:
480
- bindBreakOrContinueStatement(node);
481
- break;
482
- case SyntaxKind.TryStatement:
483
- bindTryStatement(node);
484
- break;
485
- case SyntaxKind.SwitchStatement:
486
- bindSwitchStatement(node);
487
- break;
488
- case SyntaxKind.CaseBlock:
489
- bindCaseBlock(node);
490
- break;
491
- case SyntaxKind.CaseClause:
492
- bindCaseClause(node);
493
- break;
494
- case SyntaxKind.ExpressionStatement:
495
- bindExpressionStatement(node);
496
- break;
497
- case SyntaxKind.PrefixUnaryExpression:
498
- bindPrefixUnaryExpressionFlow(node);
499
- break;
500
- case SyntaxKind.PostfixUnaryExpression:
501
- bindPostfixUnaryExpressionFlow(node);
502
- break;
503
- case SyntaxKind.BinaryExpression:
504
- bindBinaryExpressionFlow(node);
505
- break;
506
- case SyntaxKind.DeleteExpression:
507
- bindDeleteExpressionFlow(node);
508
- break;
509
- case SyntaxKind.ConditionalExpression:
510
- bindConditionalExpressionFlow(node);
511
- break;
512
- case SyntaxKind.VariableDeclaration:
513
- bindVariableDeclarationFlow(node);
514
- break;
515
- case SyntaxKind.PropertyAccessExpression:
516
- case SyntaxKind.ElementAccessExpression:
517
- bindAccessExpressionFlow(node);
518
- break;
519
- case SyntaxKind.CallExpression:
520
- bindCallExpressionFlow(node);
521
- break;
522
- default:
523
- bindEachChild(node);
524
- break;
525
- }
526
- }
527
- function isNarrowingExpression(expr) {
528
- switch (expr.kind) {
529
- case SyntaxKind.Identifier:
530
- case SyntaxKind.PropertyAccessExpression:
531
- case SyntaxKind.ElementAccessExpression:
532
- return containsNarrowableReference(expr);
533
- case SyntaxKind.CallExpression:
534
- return hasNarrowableArgument(expr);
535
- case SyntaxKind.ParenthesizedExpression:
536
- return isNarrowingExpression(expr.expression);
537
- case SyntaxKind.BinaryExpression:
538
- return isNarrowingBinaryExpression(expr);
539
- case SyntaxKind.PrefixUnaryExpression:
540
- return expr.operator === SyntaxKind.ExclamationToken && isNarrowingExpression(expr.operand);
541
- case SyntaxKind.TypeOfExpression:
542
- return isNarrowingExpression(expr.expression);
543
- }
544
- return false;
545
- }
546
- function isNarrowableReference(expr) {
547
- return expr.kind === SyntaxKind.Identifier ||
548
- (isPropertyAccessExpression(expr) || isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) ||
549
- isElementAccessExpression(expr) && isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression);
550
- }
551
- function containsNarrowableReference(expr) {
552
- return isNarrowableReference(expr) || isOptionalChain(expr) && containsNarrowableReference(expr.expression);
553
- }
554
- function hasNarrowableArgument(expr) {
555
- if (expr.arguments) {
556
- for (const argument of expr.arguments) {
557
- if (containsNarrowableReference(argument)) {
558
- return true;
559
- }
560
- }
561
- }
562
- if (expr.expression.kind === SyntaxKind.PropertyAccessExpression &&
563
- containsNarrowableReference(expr.expression.expression)) {
564
- return true;
565
- }
566
- return false;
567
- }
568
- function isNarrowingTypeofOperands(expr1, expr2) {
569
- return isTypeOfExpression(expr1) && isNarrowableOperand(expr1.expression) && isStringLiteralLike(expr2);
570
- }
571
- function isNarrowableInOperands(left, right) {
572
- return isStringLiteralLike(left) && isNarrowingExpression(right);
573
- }
574
- function isNarrowingBinaryExpression(expr) {
575
- switch (expr.operatorToken.kind) {
576
- case SyntaxKind.EqualsToken:
577
- return containsNarrowableReference(expr.left);
578
- case SyntaxKind.EqualsEqualsToken:
579
- case SyntaxKind.ExclamationEqualsToken:
580
- return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) ||
581
- isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right);
582
- case SyntaxKind.InKeyword:
583
- return isNarrowableInOperands(expr.left, expr.right);
584
- }
585
- return false;
586
- }
587
- function isNarrowableOperand(expr) {
588
- switch (expr.kind) {
589
- case SyntaxKind.ParenthesizedExpression:
590
- return isNarrowableOperand(expr.expression);
591
- case SyntaxKind.BinaryExpression:
592
- switch (expr.operatorToken.kind) {
593
- case SyntaxKind.EqualsToken:
594
- return isNarrowableOperand(expr.left);
595
- }
596
- }
597
- return containsNarrowableReference(expr);
598
- }
599
- function createBranchLabel() {
600
- return initFlowNode({ flags: FlowFlags.BranchLabel, antecedents: undefined });
601
- }
602
- function createLoopLabel() {
603
- return initFlowNode({ flags: FlowFlags.LoopLabel, antecedents: undefined });
604
- }
605
- function createReduceLabel(target, antecedents, antecedent) {
606
- return initFlowNode({ flags: FlowFlags.ReduceLabel, target, antecedents, antecedent });
607
- }
608
- function setFlowNodeReferenced(flow) {
609
- // a primeira referência marca `Referenced`; as seguintes, `Shared`
610
- flow.flags |= flow.flags & FlowFlags.Referenced ? FlowFlags.Shared : FlowFlags.Referenced;
611
- }
612
- function addAntecedent(label, antecedent) {
613
- if (!(antecedent.flags & FlowFlags.Unreachable) && !contains(label.antecedents, antecedent)) {
614
- (label.antecedents || (label.antecedents = [])).push(antecedent);
615
- setFlowNodeReferenced(antecedent);
616
- }
617
- }
618
- function createFlowCondition(flags, antecedent, expression) {
619
- if (antecedent.flags & FlowFlags.Unreachable) {
620
- return antecedent;
621
- }
622
- if (!expression) {
623
- return flags & FlowFlags.TrueCondition ? antecedent : unreachableFlow;
624
- }
625
- if ((expression.kind === SyntaxKind.TrueKeyword && flags & FlowFlags.FalseCondition ||
626
- expression.kind === SyntaxKind.FalseKeyword && flags & FlowFlags.TrueCondition) &&
627
- !isExpressionOfOptionalChainRoot(expression) && !isNullishCoalesce(expression.parent)) {
628
- return unreachableFlow;
629
- }
630
- if (!isNarrowingExpression(expression)) {
631
- return antecedent;
632
- }
633
- setFlowNodeReferenced(antecedent);
634
- return initFlowNode({ flags, antecedent, node: expression });
635
- }
636
- function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) {
637
- setFlowNodeReferenced(antecedent);
638
- return initFlowNode({ flags: FlowFlags.SwitchClause, antecedent, switchStatement, clauseStart, clauseEnd });
639
- }
640
- function createFlowMutation(flags, antecedent, node) {
641
- setFlowNodeReferenced(antecedent);
642
- const result = initFlowNode({ flags, antecedent, node });
643
- if (currentExceptionTarget) {
644
- addAntecedent(currentExceptionTarget, result);
645
- }
646
- return result;
647
- }
648
- function createFlowCall(antecedent, node) {
649
- setFlowNodeReferenced(antecedent);
650
- return initFlowNode({ flags: FlowFlags.Call, antecedent, node });
651
- }
652
- function finishFlowLabel(flow) {
653
- const antecedents = flow.antecedents;
654
- if (!antecedents) {
655
- return unreachableFlow;
656
- }
657
- if (antecedents.length === 1) {
658
- return antecedents[0];
659
- }
660
- return flow;
661
- }
662
- function isStatementCondition(node) {
663
- const parent = node.parent;
664
- switch (parent.kind) {
665
- case SyntaxKind.IfStatement:
666
- case SyntaxKind.WhileStatement:
667
- case SyntaxKind.DoStatement:
668
- return parent.expression === node;
669
- case SyntaxKind.ForStatement:
670
- case SyntaxKind.ConditionalExpression:
671
- return parent.condition === node;
672
- }
673
- return false;
674
- }
675
- function isLogicalExpression(node) {
676
- while (true) {
677
- if (node.kind === SyntaxKind.ParenthesizedExpression) {
678
- node = node.expression;
679
- }
680
- else if (node.kind === SyntaxKind.PrefixUnaryExpression && node.operator === SyntaxKind.ExclamationToken) {
681
- node = node.operand;
682
- }
683
- else {
684
- return node.kind === SyntaxKind.BinaryExpression && (node.operatorToken.kind === SyntaxKind.AmpersandAmpersandToken ||
685
- node.operatorToken.kind === SyntaxKind.BarBarToken ||
686
- node.operatorToken.kind === SyntaxKind.QuestionQuestionToken);
687
- }
688
- }
689
- }
690
- function isTopLevelLogicalExpression(node) {
691
- while (isParenthesizedExpression(node.parent) ||
692
- isPrefixUnaryExpression(node.parent) && node.parent.operator === SyntaxKind.ExclamationToken) {
693
- node = node.parent;
694
- }
695
- return !isStatementCondition(node) &&
696
- !isLogicalExpression(node.parent) &&
697
- !(isOptionalChain(node.parent) && node.parent.expression === node);
698
- }
699
- function doWithConditionalBranches(action, value, trueTarget, falseTarget) {
700
- const savedTrueTarget = currentTrueTarget;
701
- const savedFalseTarget = currentFalseTarget;
702
- currentTrueTarget = trueTarget;
703
- currentFalseTarget = falseTarget;
704
- action(value);
705
- currentTrueTarget = savedTrueTarget;
706
- currentFalseTarget = savedFalseTarget;
707
- }
708
- function bindCondition(node, trueTarget, falseTarget) {
709
- doWithConditionalBranches(bind, node, trueTarget, falseTarget);
710
- if (!node || !isLogicalExpression(node) && !(isOptionalChain(node) && isOutermostOptionalChain(node))) {
711
- addAntecedent(trueTarget, createFlowCondition(FlowFlags.TrueCondition, currentFlow, node));
712
- addAntecedent(falseTarget, createFlowCondition(FlowFlags.FalseCondition, currentFlow, node));
713
- }
714
- }
715
- function bindIterativeStatement(node, breakTarget, continueTarget) {
716
- const saveBreakTarget = currentBreakTarget;
717
- const saveContinueTarget = currentContinueTarget;
718
- currentBreakTarget = breakTarget;
719
- currentContinueTarget = continueTarget;
720
- bind(node);
721
- currentBreakTarget = saveBreakTarget;
722
- currentContinueTarget = saveContinueTarget;
723
- }
724
- function bindWhileStatement(node) {
725
- const preWhileLabel = createLoopLabel();
726
- const preBodyLabel = createBranchLabel();
727
- const postWhileLabel = createBranchLabel();
728
- addAntecedent(preWhileLabel, currentFlow);
729
- currentFlow = preWhileLabel;
730
- bindCondition(node.expression, preBodyLabel, postWhileLabel);
731
- currentFlow = finishFlowLabel(preBodyLabel);
732
- bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel);
733
- addAntecedent(preWhileLabel, currentFlow);
734
- currentFlow = finishFlowLabel(postWhileLabel);
735
- }
736
- function bindDoStatement(node) {
737
- const preDoLabel = createLoopLabel();
738
- const preConditionLabel = createBranchLabel();
739
- const postDoLabel = createBranchLabel();
740
- addAntecedent(preDoLabel, currentFlow);
741
- currentFlow = preDoLabel;
742
- bindIterativeStatement(node.statement, postDoLabel, preConditionLabel);
743
- addAntecedent(preConditionLabel, currentFlow);
744
- currentFlow = finishFlowLabel(preConditionLabel);
745
- bindCondition(node.expression, preDoLabel, postDoLabel);
746
- currentFlow = finishFlowLabel(postDoLabel);
747
- }
748
- function bindForStatement(node) {
749
- const preLoopLabel = createLoopLabel();
750
- const preBodyLabel = createBranchLabel();
751
- const postLoopLabel = createBranchLabel();
752
- bind(node.initializer);
753
- addAntecedent(preLoopLabel, currentFlow);
754
- currentFlow = preLoopLabel;
755
- bindCondition(node.condition, preBodyLabel, postLoopLabel);
756
- currentFlow = finishFlowLabel(preBodyLabel);
757
- bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
758
- bind(node.incrementor);
759
- addAntecedent(preLoopLabel, currentFlow);
760
- currentFlow = finishFlowLabel(postLoopLabel);
761
- }
762
- function bindForInOrForOfStatement(node) {
763
- const preLoopLabel = createLoopLabel();
764
- const postLoopLabel = createBranchLabel();
765
- bind(node.expression);
766
- addAntecedent(preLoopLabel, currentFlow);
767
- currentFlow = preLoopLabel;
768
- if (node.kind === SyntaxKind.ForOfStatement) {
769
- bind(node.awaitModifier);
770
- }
771
- addAntecedent(postLoopLabel, currentFlow);
772
- bind(node.initializer);
773
- if (node.initializer.kind !== SyntaxKind.VariableDeclarationList) {
774
- bindAssignmentTargetFlow(node.initializer);
775
- }
776
- bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
777
- addAntecedent(preLoopLabel, currentFlow);
778
- currentFlow = finishFlowLabel(postLoopLabel);
779
- }
780
- function bindIfStatement(node) {
781
- const thenLabel = createBranchLabel();
782
- const elseLabel = createBranchLabel();
783
- const postIfLabel = createBranchLabel();
784
- bindCondition(node.expression, thenLabel, elseLabel);
785
- currentFlow = finishFlowLabel(thenLabel);
786
- bind(node.thenStatement);
787
- addAntecedent(postIfLabel, currentFlow);
788
- currentFlow = finishFlowLabel(elseLabel);
789
- bind(node.elseStatement);
790
- addAntecedent(postIfLabel, currentFlow);
791
- currentFlow = finishFlowLabel(postIfLabel);
792
- }
793
- function bindReturnOrThrow(node) {
794
- bind(node.expression);
795
- if (node.kind === SyntaxKind.ReturnStatement) {
796
- hasExplicitReturn = true;
797
- if (currentReturnTarget) {
798
- addAntecedent(currentReturnTarget, currentFlow);
799
- }
800
- }
801
- currentFlow = unreachableFlow;
802
- }
803
- function bindBreakOrContinueFlow(node, breakTarget, continueTarget) {
804
- const flowLabel = node.kind === SyntaxKind.BreakStatement ? breakTarget : continueTarget;
805
- if (flowLabel) {
806
- addAntecedent(flowLabel, currentFlow);
807
- currentFlow = unreachableFlow;
808
- }
809
- }
810
- function bindBreakOrContinueStatement(node) {
811
- bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget);
812
- }
813
- function bindTryStatement(node) {
814
- // Qualquer ponto do `try` pode lançar, mas só as mutações interessam: só elas alargam o tipo de fluxo de uma
815
- // variável. Cada mutação vira antecedente do rótulo de exceção (`createFlowMutation`), que é o começo do `catch`
816
- // ou do `finally`; o fluxo de antes do `try` também entra, pela exceção que vem antes de qualquer mutação.
817
- const saveReturnTarget = currentReturnTarget;
818
- const saveExceptionTarget = currentExceptionTarget;
819
- const normalExitLabel = createBranchLabel();
820
- const returnLabel = createBranchLabel();
821
- let exceptionLabel = createBranchLabel();
822
- if (node.finallyBlock) {
823
- currentReturnTarget = returnLabel;
824
- }
825
- addAntecedent(exceptionLabel, currentFlow);
826
- currentExceptionTarget = exceptionLabel;
827
- bind(node.tryBlock);
828
- addAntecedent(normalExitLabel, currentFlow);
829
- if (node.catchClause) {
830
- // o `catch` começa nas exceções do `try`, e é um segundo `try` para o `finally`
831
- currentFlow = finishFlowLabel(exceptionLabel);
832
- exceptionLabel = createBranchLabel();
833
- addAntecedent(exceptionLabel, currentFlow);
834
- currentExceptionTarget = exceptionLabel;
835
- bind(node.catchClause);
836
- addAntecedent(normalExitLabel, currentFlow);
837
- }
838
- currentReturnTarget = saveReturnTarget;
839
- currentExceptionTarget = saveExceptionTarget;
840
- if (node.finallyBlock) {
841
- // O `finally` se alcança pelo fim normal do `try` ou do `catch`, por um `return` neles, ou por uma exceção
842
- // neles. Dentro do `finally` valem as cinco entradas; depois dele, só o fim normal (se passou do `finally`,
843
- // ele terminou); e, do `return` de uma IIFE, só o `return`. O `ReduceLabel` guarda esse conjunto menor de
844
- // antecedentes, e a análise de fluxo troca por ele o do `finally` enquanto passa.
845
- const finallyLabel = createBranchLabel();
846
- finallyLabel.antecedents = concatenate(concatenate(normalExitLabel.antecedents, exceptionLabel.antecedents), returnLabel.antecedents);
847
- currentFlow = finallyLabel;
848
- bind(node.finallyBlock);
849
- if (currentFlow.flags & FlowFlags.Unreachable) {
850
- // o fim do `finally` inalcançável deixa o `try` inteiro inalcançável
851
- currentFlow = unreachableFlow;
852
- }
853
- else {
854
- // o `return` de uma IIFE dentro do `try` ou do `catch` volta pelo `finally` e só pelos `return`
855
- if (currentReturnTarget && returnLabel.antecedents) {
856
- addAntecedent(currentReturnTarget, createReduceLabel(finallyLabel, returnLabel.antecedents, currentFlow));
857
- }
858
- // sem fim normal no `try` e no `catch` (`try { return 1; } finally { … }`), o que vem depois é inalcançável
859
- currentFlow = normalExitLabel.antecedents ? createReduceLabel(finallyLabel, normalExitLabel.antecedents, currentFlow) : unreachableFlow;
860
- }
861
- }
862
- else {
863
- currentFlow = finishFlowLabel(normalExitLabel);
864
- }
865
- }
866
- function bindSwitchStatement(node) {
867
- const postSwitchLabel = createBranchLabel();
868
- bind(node.expression);
869
- const saveBreakTarget = currentBreakTarget;
870
- const savePreSwitchCaseFlow = preSwitchCaseFlow;
871
- currentBreakTarget = postSwitchLabel;
872
- preSwitchCaseFlow = currentFlow;
873
- bind(node.caseBlock);
874
- addAntecedent(postSwitchLabel, currentFlow);
875
- const hasDefault = forEach(node.caseBlock.clauses, c => c.kind === SyntaxKind.DefaultClause);
876
- // Sem `default` e com todos os `case` terminando inalcançáveis, o `switch` talvez seja exaustivo. A análise de
877
- // fluxo não usa mais isso; a tag mantém por compatibilidade.
878
- node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents;
879
- if (!hasDefault) {
880
- addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0));
881
- }
882
- currentBreakTarget = saveBreakTarget;
883
- preSwitchCaseFlow = savePreSwitchCaseFlow;
884
- currentFlow = finishFlowLabel(postSwitchLabel);
885
- }
886
- function bindCaseBlock(node) {
887
- const clauses = node.clauses;
888
- const isNarrowingSwitch = isNarrowingExpression(node.parent.expression);
889
- let fallthroughFlow = unreachableFlow;
890
- for (let i = 0; i < clauses.length; i++) {
891
- const clauseStart = i;
892
- while (!clauses[i].statements.length && i + 1 < clauses.length) {
893
- bind(clauses[i]);
894
- i++;
895
- }
896
- const preCaseLabel = createBranchLabel();
897
- addAntecedent(preCaseLabel, isNarrowingSwitch ? createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1) : preSwitchCaseFlow);
898
- addAntecedent(preCaseLabel, fallthroughFlow);
899
- currentFlow = finishFlowLabel(preCaseLabel);
900
- const clause = clauses[i];
901
- bind(clause);
902
- fallthroughFlow = currentFlow;
903
- if (!(currentFlow.flags & FlowFlags.Unreachable) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) {
904
- clause.fallthroughFlowNode = currentFlow;
905
- }
906
- }
907
- }
908
- function bindCaseClause(node) {
909
- const saveCurrentFlow = currentFlow;
910
- currentFlow = preSwitchCaseFlow;
911
- bind(node.expression);
912
- currentFlow = saveCurrentFlow;
913
- bindEach(node.statements);
914
- }
915
- function bindExpressionStatement(node) {
916
- bind(node.expression);
917
- // Uma chamada solta a um nome pontuado pode ser uma assertion function, e entra no fluxo.
918
- if (node.expression.kind === SyntaxKind.CallExpression) {
919
- const call = node.expression;
920
- if (isDottedName(call.expression)) {
921
- currentFlow = createFlowCall(currentFlow, call);
922
- }
923
- }
924
- }
925
- function bindDestructuringTargetFlow(node) {
926
- if (node.kind === SyntaxKind.BinaryExpression && node.operatorToken.kind === SyntaxKind.EqualsToken) {
927
- bindAssignmentTargetFlow(node.left);
928
- }
929
- else {
930
- bindAssignmentTargetFlow(node);
931
- }
932
- }
933
- function bindAssignmentTargetFlow(node) {
934
- if (isNarrowableReference(node)) {
935
- currentFlow = createFlowMutation(FlowFlags.Assignment, currentFlow, node);
936
- }
937
- else if (node.kind === SyntaxKind.ArrayLiteralExpression) {
938
- for (const e of node.elements) {
939
- if (e.kind === SyntaxKind.SpreadElement) {
940
- bindAssignmentTargetFlow(e.expression);
941
- }
942
- else {
943
- bindDestructuringTargetFlow(e);
944
- }
945
- }
946
- }
947
- else if (node.kind === SyntaxKind.ObjectLiteralExpression) {
948
- for (const p of node.properties) {
949
- if (p.kind === SyntaxKind.PropertyAssignment) {
950
- bindDestructuringTargetFlow(p.initializer);
951
- }
952
- else if (p.kind === SyntaxKind.ShorthandPropertyAssignment) {
953
- bindAssignmentTargetFlow(p.name);
954
- }
955
- else if (p.kind === SyntaxKind.SpreadAssignment) {
956
- bindAssignmentTargetFlow(p.expression);
957
- }
958
- }
959
- }
960
- }
961
- function bindLogicalExpression(node, trueTarget, falseTarget) {
962
- const preRightLabel = createBranchLabel();
963
- if (node.operatorToken.kind === SyntaxKind.AmpersandAmpersandToken) {
964
- bindCondition(node.left, preRightLabel, falseTarget);
965
- }
966
- else {
967
- bindCondition(node.left, trueTarget, preRightLabel);
968
- }
969
- currentFlow = finishFlowLabel(preRightLabel);
970
- bind(node.operatorToken);
971
- bindCondition(node.right, trueTarget, falseTarget);
972
- }
973
- function bindPrefixUnaryExpressionFlow(node) {
974
- if (node.operator === SyntaxKind.ExclamationToken) {
975
- const saveTrueTarget = currentTrueTarget;
976
- currentTrueTarget = currentFalseTarget;
977
- currentFalseTarget = saveTrueTarget;
978
- bindEachChild(node);
979
- currentFalseTarget = currentTrueTarget;
980
- currentTrueTarget = saveTrueTarget;
981
- }
982
- else {
983
- bindEachChild(node);
984
- if (node.operator === SyntaxKind.PlusPlusToken || node.operator === SyntaxKind.MinusMinusToken) {
985
- bindAssignmentTargetFlow(node.operand);
986
- }
987
- }
988
- }
989
- function bindPostfixUnaryExpressionFlow(node) {
990
- bindEachChild(node);
991
- if (node.operator === SyntaxKind.PlusPlusToken || node.operator === SyntaxKind.MinusMinusToken) {
992
- bindAssignmentTargetFlow(node.operand);
993
- }
994
- }
995
- let BindBinaryExpressionFlowState;
996
- (function (BindBinaryExpressionFlowState) {
997
- BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindThenBindChildren"] = 0] = "BindThenBindChildren";
998
- BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["MaybeBindLeft"] = 1] = "MaybeBindLeft";
999
- BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindToken"] = 2] = "BindToken";
1000
- BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindRight"] = 3] = "BindRight";
1001
- BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["FinishBind"] = 4] = "FinishBind";
1002
- })(BindBinaryExpressionFlowState || (BindBinaryExpressionFlowState = {}));
1003
- function bindBinaryExpressionFlow(node) {
1004
- const workStacks = {
1005
- expr: [node],
1006
- state: [1 /* BindBinaryExpressionFlowState.MaybeBindLeft */],
1007
- inStrictMode: [undefined],
1008
- parent: [undefined]
1009
- };
1010
- let stackIndex = 0;
1011
- while (stackIndex >= 0) {
1012
- node = workStacks.expr[stackIndex];
1013
- switch (workStacks.state[stackIndex]) {
1014
- case 0 /* BindBinaryExpressionFlowState.BindThenBindChildren */: {
1015
- // Só no binário aninhado: faz o que o `bind` faz antes do `bindChildren`, que a chamada de fora já fez.
1016
- node.parent = parent;
1017
- const saveInStrictMode = inStrictMode;
1018
- bindWorker(node);
1019
- const saveParent = parent;
1020
- parent = node;
1021
- advanceState(1 /* BindBinaryExpressionFlowState.MaybeBindLeft */, saveInStrictMode, saveParent);
1022
- break;
1023
- }
1024
- case 1 /* BindBinaryExpressionFlowState.MaybeBindLeft */: {
1025
- const operator = node.operatorToken.kind;
1026
- // O lógico continua recursivo, fora da máquina de estados: o encadeamento longo que ela evita é o de `+`.
1027
- if (operator === SyntaxKind.AmpersandAmpersandToken || operator === SyntaxKind.BarBarToken || operator === SyntaxKind.QuestionQuestionToken) {
1028
- if (isTopLevelLogicalExpression(node)) {
1029
- const postExpressionLabel = createBranchLabel();
1030
- bindLogicalExpression(node, postExpressionLabel, postExpressionLabel);
1031
- currentFlow = finishFlowLabel(postExpressionLabel);
1032
- }
1033
- else {
1034
- bindLogicalExpression(node, currentTrueTarget, currentFalseTarget);
1035
- }
1036
- completeNode();
1037
- }
1038
- else {
1039
- advanceState(2 /* BindBinaryExpressionFlowState.BindToken */);
1040
- maybeBind(node.left);
1041
- }
1042
- break;
1043
- }
1044
- case 2 /* BindBinaryExpressionFlowState.BindToken */: {
1045
- advanceState(3 /* BindBinaryExpressionFlowState.BindRight */);
1046
- maybeBind(node.operatorToken);
1047
- break;
1048
- }
1049
- case 3 /* BindBinaryExpressionFlowState.BindRight */: {
1050
- advanceState(4 /* BindBinaryExpressionFlowState.FinishBind */);
1051
- maybeBind(node.right);
1052
- break;
1053
- }
1054
- case 4 /* BindBinaryExpressionFlowState.FinishBind */: {
1055
- const operator = node.operatorToken.kind;
1056
- if (isAssignmentOperator(operator) && !isAssignmentTarget(node)) {
1057
- bindAssignmentTargetFlow(node.left);
1058
- if (operator === SyntaxKind.EqualsToken && node.left.kind === SyntaxKind.ElementAccessExpression) {
1059
- const elementAccess = node.left;
1060
- if (isNarrowableOperand(elementAccess.expression)) {
1061
- currentFlow = createFlowMutation(FlowFlags.ArrayMutation, currentFlow, node);
1062
- }
1063
- }
1064
- }
1065
- completeNode();
1066
- break;
1067
- }
1068
- default: return Debug.fail(`Invalid state ${workStacks.state[stackIndex]} for bindBinaryExpressionFlow`);
1069
- }
1070
- }
1071
- /**
1072
- * Troca o estado do topo da pilha. O `maybeBind` pode empilhar um estado novo, então, dentro de um estado, o
1073
- * `advanceState` vem antes do `maybeBind`.
1074
- */
1075
- function advanceState(state, isInStrictMode, parent) {
1076
- workStacks.state[stackIndex] = state;
1077
- if (isInStrictMode !== undefined) {
1078
- workStacks.inStrictMode[stackIndex] = isInStrictMode;
1079
- }
1080
- if (parent !== undefined) {
1081
- workStacks.parent[stackIndex] = parent;
1082
- }
1083
- }
1084
- function completeNode() {
1085
- if (workStacks.inStrictMode[stackIndex] !== undefined) {
1086
- inStrictMode = workStacks.inStrictMode[stackIndex];
1087
- parent = workStacks.parent[stackIndex];
1088
- }
1089
- stackIndex--;
1090
- }
1091
- /** O binário vai para a pilha; o resto se liga recursivamente. */
1092
- function maybeBind(node) {
1093
- if (node && isBinaryExpression(node)) {
1094
- stackIndex++;
1095
- workStacks.expr[stackIndex] = node;
1096
- workStacks.state[stackIndex] = 0 /* BindBinaryExpressionFlowState.BindThenBindChildren */;
1097
- workStacks.inStrictMode[stackIndex] = undefined;
1098
- workStacks.parent[stackIndex] = undefined;
1099
- }
1100
- else {
1101
- bind(node);
1102
- }
1103
- }
1104
- }
1105
- function bindDeleteExpressionFlow(node) {
1106
- bindEachChild(node);
1107
- if (node.expression.kind === SyntaxKind.PropertyAccessExpression) {
1108
- bindAssignmentTargetFlow(node.expression);
1109
- }
1110
- }
1111
- function bindConditionalExpressionFlow(node) {
1112
- const trueLabel = createBranchLabel();
1113
- const falseLabel = createBranchLabel();
1114
- const postExpressionLabel = createBranchLabel();
1115
- bindCondition(node.condition, trueLabel, falseLabel);
1116
- currentFlow = finishFlowLabel(trueLabel);
1117
- bind(node.questionToken);
1118
- bind(node.whenTrue);
1119
- addAntecedent(postExpressionLabel, currentFlow);
1120
- currentFlow = finishFlowLabel(falseLabel);
1121
- bind(node.colonToken);
1122
- bind(node.whenFalse);
1123
- addAntecedent(postExpressionLabel, currentFlow);
1124
- currentFlow = finishFlowLabel(postExpressionLabel);
1125
- }
1126
- function bindInitializedVariableFlow(node) {
1127
- const name = !isOmittedExpression(node) ? node.name : undefined;
1128
- if (isBindingPattern(name)) {
1129
- for (const child of name.elements) {
1130
- bindInitializedVariableFlow(child);
1131
- }
1132
- }
1133
- else {
1134
- currentFlow = createFlowMutation(FlowFlags.Assignment, currentFlow, node);
1135
- }
1136
- }
1137
- function bindVariableDeclarationFlow(node) {
1138
- bindEachChild(node);
1139
- if (node.initializer || isForInOrOfStatement(node.parent.parent)) {
1140
- bindInitializedVariableFlow(node);
1141
- }
1142
- }
1143
- function bindOptionalExpression(node, trueTarget, falseTarget) {
1144
- doWithConditionalBranches(bind, node, trueTarget, falseTarget);
1145
- if (!isOptionalChain(node) || isOutermostOptionalChain(node)) {
1146
- addAntecedent(trueTarget, createFlowCondition(FlowFlags.TrueCondition, currentFlow, node));
1147
- addAntecedent(falseTarget, createFlowCondition(FlowFlags.FalseCondition, currentFlow, node));
1148
- }
1149
- }
1150
- function bindOptionalChainRest(node) {
1151
- switch (node.kind) {
1152
- case SyntaxKind.PropertyAccessExpression:
1153
- bind(node.questionDotToken);
1154
- bind(node.name);
1155
- break;
1156
- case SyntaxKind.ElementAccessExpression:
1157
- bind(node.questionDotToken);
1158
- bind(node.argumentExpression);
1159
- break;
1160
- case SyntaxKind.CallExpression:
1161
- bind(node.questionDotToken);
1162
- bindEach(node.typeArguments);
1163
- bindEach(node.arguments);
1164
- break;
1165
- }
1166
- }
1167
- function bindOptionalChain(node, trueTarget, falseTarget) {
1168
- // A optional chain tem o fluxo de um lógico: `a?.b` é `a && a.b`, `a?.b?.c` é `a && a.b && a.b.c`. A raiz da
1169
- // cadeia (a expressão com `?.`) é a primeira condição; o resto se liga no ramo verdadeiro, subindo até o elo de
1170
- // fora, que é o lado direito inteiro.
1171
- const preChainLabel = isOptionalChainRoot(node) ? createBranchLabel() : undefined;
1172
- bindOptionalExpression(node.expression, preChainLabel || trueTarget, falseTarget);
1173
- if (preChainLabel) {
1174
- currentFlow = finishFlowLabel(preChainLabel);
1175
- }
1176
- doWithConditionalBranches(bindOptionalChainRest, node, trueTarget, falseTarget);
1177
- if (isOutermostOptionalChain(node)) {
1178
- addAntecedent(trueTarget, createFlowCondition(FlowFlags.TrueCondition, currentFlow, node));
1179
- addAntecedent(falseTarget, createFlowCondition(FlowFlags.FalseCondition, currentFlow, node));
1180
- }
1181
- }
1182
- function bindOptionalChainFlow(node) {
1183
- if (isTopLevelLogicalExpression(node)) {
1184
- const postExpressionLabel = createBranchLabel();
1185
- bindOptionalChain(node, postExpressionLabel, postExpressionLabel);
1186
- currentFlow = finishFlowLabel(postExpressionLabel);
1187
- }
1188
- else {
1189
- bindOptionalChain(node, currentTrueTarget, currentFalseTarget);
1190
- }
1191
- }
1192
- function bindAccessExpressionFlow(node) {
1193
- if (isOptionalChain(node)) {
1194
- bindOptionalChainFlow(node);
1195
- }
1196
- else {
1197
- bindEachChild(node);
1198
- }
1199
- }
1200
- function bindCallExpressionFlow(node) {
1201
- if (isOptionalChain(node)) {
1202
- bindOptionalChainFlow(node);
1203
- }
1204
- else {
1205
- // Numa arrow chamada no lugar (IIFE), os argumentos se ligam antes da arrow: o fluxo dela começa depois deles.
1206
- const expr = skipParentheses(node.expression);
1207
- if (expr.kind === SyntaxKind.ArrowFunction) {
1208
- bindEach(node.typeArguments);
1209
- bindEach(node.arguments);
1210
- bind(node.expression);
1211
- }
1212
- else {
1213
- bindEachChild(node);
1214
- }
1215
- }
1216
- }
1217
- function getContainerFlags(node) {
1218
- switch (node.kind) {
1219
- case SyntaxKind.ObjectLiteralExpression:
1220
- case SyntaxKind.TypeLiteral:
1221
- case SyntaxKind.JsxAttributes:
1222
- return 1 /* ContainerFlags.IsContainer */;
1223
- case SyntaxKind.ModuleDeclaration:
1224
- case SyntaxKind.TypeAliasDeclaration:
1225
- case SyntaxKind.MappedType:
1226
- return 1 /* ContainerFlags.IsContainer */ | 32 /* ContainerFlags.HasLocals */;
1227
- case SyntaxKind.SourceFile:
1228
- return 1 /* ContainerFlags.IsContainer */ | 4 /* ContainerFlags.IsControlFlowContainer */ | 32 /* ContainerFlags.HasLocals */;
1229
- case SyntaxKind.CallSignature:
1230
- case SyntaxKind.FunctionType:
1231
- case SyntaxKind.IndexSignature:
1232
- return 1 /* ContainerFlags.IsContainer */ | 4 /* ContainerFlags.IsControlFlowContainer */ | 32 /* ContainerFlags.HasLocals */ | 8 /* ContainerFlags.IsFunctionLike */;
1233
- case SyntaxKind.ArrowFunction:
1234
- return 1 /* ContainerFlags.IsContainer */ | 4 /* ContainerFlags.IsControlFlowContainer */ | 32 /* ContainerFlags.HasLocals */ | 8 /* ContainerFlags.IsFunctionLike */ | 16 /* ContainerFlags.IsFunctionExpression */;
1235
- case SyntaxKind.ModuleBlock:
1236
- return 4 /* ContainerFlags.IsControlFlowContainer */;
1237
- case SyntaxKind.CatchClause:
1238
- case SyntaxKind.ForStatement:
1239
- case SyntaxKind.ForInStatement:
1240
- case SyntaxKind.ForOfStatement:
1241
- case SyntaxKind.CaseBlock:
1242
- return 2 /* ContainerFlags.IsBlockScopedContainer */;
1243
- case SyntaxKind.Block:
1244
- // O corpo de uma função não é contêiner de bloco: o `let` dele vai para os `locals` da função, junto com os
1245
- // parâmetros, e `((x) => { let x; })` conflita, como deve.
1246
- return isFunctionLike(node.parent) ? 0 /* ContainerFlags.None */ : 2 /* ContainerFlags.IsBlockScopedContainer */;
1247
- }
1248
- return 0 /* ContainerFlags.None */;
1249
- }
1250
- function addToContainerChain(next) {
1251
- if (lastContainer) {
1252
- lastContainer.nextContainer = next;
1253
- }
1254
- lastContainer = next;
1255
- }
1256
- function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) {
1257
- switch (container.kind) {
1258
- // o namespace e o arquivo decidem entre os `locals` e os `exports`
1259
- case SyntaxKind.ModuleDeclaration:
1260
- return declareModuleMember(node, symbolFlags, symbolExcludes);
1261
- case SyntaxKind.SourceFile:
1262
- return declareSourceFileMember(node, symbolFlags, symbolExcludes);
1263
- case SyntaxKind.TypeLiteral:
1264
- case SyntaxKind.ObjectLiteralExpression:
1265
- case SyntaxKind.JsxAttributes:
1266
- // o membro de um objeto ou de um tipo vai para os `members`: só se alcança por uma instância, e nunca
1267
- // está em escopo, nem dentro do próprio corpo (o parâmetro de tipo, sim, como um local)
1268
- return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
1269
- case SyntaxKind.FunctionType:
1270
- case SyntaxKind.CallSignature:
1271
- case SyntaxKind.IndexSignature:
1272
- case SyntaxKind.ArrowFunction:
1273
- case SyntaxKind.TypeAliasDeclaration:
1274
- case SyntaxKind.MappedType:
1275
- // o filho destes contêineres só se alcança lexicamente, de dentro deles: vai para os `locals`, que o
1276
- // checker percorre subindo
1277
- return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
1278
- }
1279
- }
1280
- function declareSourceFileMember(node, symbolFlags, symbolExcludes) {
1281
- return isExternalModule(file)
1282
- ? declareModuleMember(node, symbolFlags, symbolExcludes)
1283
- : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
1284
- }
1285
- function hasExportDeclarations(node) {
1286
- const body = isSourceFile(node) ? node : tryCast(node.body, isModuleBlock);
1287
- return !!body && body.statements.some(s => isExportDeclaration(s) || isExportAssignment(s));
1288
- }
1289
- function setExportContextFlag(node) {
1290
- // Um `.d.ts` ou um módulo ambiente sem `export { … }` nem `export default` exporta todas as declarações dele.
1291
- if (node.flags & NodeFlags.Ambient && !hasExportDeclarations(node)) {
1292
- node.flags |= NodeFlags.ExportContext;
1293
- }
1294
- else {
1295
- node.flags &= ~NodeFlags.ExportContext;
1296
- }
1297
- }
1298
- function bindModuleDeclaration(node) {
1299
- setExportContextFlag(node);
1300
- if (isAmbientModule(node)) {
1301
- if (hasModifier(node, ModifierFlags.Export)) {
1302
- errorOnFirstToken(node, Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible);
1303
- }
1304
- if (isModuleAugmentationExternal(node)) {
1305
- declareModuleSymbol(node);
1306
- }
1307
- else {
1308
- // O `declare global` fora de um módulo ganha o símbolo do módulo ambiente, e a checagem o acusa (TS2669).
1309
- declareSymbolAndAddToSymbolTable(node, SymbolFlags.ValueModule, SymbolFlags.ValueModuleExcludes);
1310
- }
1311
- }
1312
- else {
1313
- declareModuleSymbol(node);
1314
- }
1315
- }
1316
- function declareModuleSymbol(node) {
1317
- const instantiated = getModuleInstanceState(node) !== 0 /* ModuleInstanceState.NonInstantiated */;
1318
- declareSymbolAndAddToSymbolTable(node, instantiated ? SymbolFlags.ValueModule : SymbolFlags.NamespaceModule, instantiated ? SymbolFlags.ValueModuleExcludes : SymbolFlags.NamespaceModuleExcludes);
1319
- }
1320
- function bindFunctionOrConstructorType(node) {
1321
- // `<T>(x: T) => R` ganha o mesmo símbolo que `{ <T>(x: T): R }`: um tipo literal anônimo com a assinatura como
1322
- // único membro, que o resto do checker não distingue da forma longa.
1323
- const symbol = createSymbol(SymbolFlags.Signature, getDeclarationName(node));
1324
- addDeclarationToSymbol(symbol, node, SymbolFlags.Signature);
1325
- const typeLiteralSymbol = createSymbol(SymbolFlags.TypeLiteral, InternalSymbolName.Type);
1326
- addDeclarationToSymbol(typeLiteralSymbol, node, SymbolFlags.TypeLiteral);
1327
- typeLiteralSymbol.members = createSymbolTable();
1328
- typeLiteralSymbol.members.set(symbol.escapedName, symbol);
1329
- }
1330
- function bindObjectLiteralExpression(node) {
1331
- // A mesma chave duas vezes num object literal, em strict mode, é erro (ECMA-262, §11.1.5). O literal da
1332
- // Linguagem só tem propriedades: o método e o acessor, que o tsc também comparava, são recorte.
1333
- if (inStrictMode && !isAssignmentTarget(node)) {
1334
- const seen = createUnderscoreEscapedMap();
1335
- for (const prop of node.properties) {
1336
- if (prop.kind === SyntaxKind.SpreadAssignment || prop.name.kind !== SyntaxKind.Identifier) {
1337
- continue;
1338
- }
1339
- const identifier = prop.name;
1340
- if (!seen.has(identifier.escapedText)) {
1341
- seen.set(identifier.escapedText, true);
1342
- continue;
1343
- }
1344
- const span = getErrorSpanForNode(file, identifier);
1345
- file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode));
1346
- }
1347
- }
1348
- return bindAnonymousDeclaration(node, SymbolFlags.ObjectLiteral, InternalSymbolName.Object);
1349
- }
1350
- function bindJsxAttributes(node) {
1351
- return bindAnonymousDeclaration(node, SymbolFlags.ObjectLiteral, InternalSymbolName.JSXAttributes);
1352
- }
1353
- function bindJsxAttribute(node, symbolFlags, symbolExcludes) {
1354
- return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
1355
- }
1356
- function bindAnonymousDeclaration(node, symbolFlags, name) {
1357
- const symbol = createSymbol(symbolFlags, name);
1358
- if (symbolFlags & SymbolFlags.ClassMember) {
1359
- symbol.parent = container.symbol;
1360
- }
1361
- addDeclarationToSymbol(symbol, node, symbolFlags);
1362
- return symbol;
1363
- }
1364
- function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) {
1365
- switch (blockScopeContainer.kind) {
1366
- case SyntaxKind.ModuleDeclaration:
1367
- declareModuleMember(node, symbolFlags, symbolExcludes);
1368
- break;
1369
- case SyntaxKind.SourceFile:
1370
- if (isExternalModule(container)) {
1371
- declareModuleMember(node, symbolFlags, symbolExcludes);
1372
- break;
1373
- }
1374
- // falls through
1375
- default:
1376
- if (!blockScopeContainer.locals) {
1377
- blockScopeContainer.locals = createSymbolTable();
1378
- addToContainerChain(blockScopeContainer);
1379
- }
1380
- declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
1381
- }
1382
- }
1383
- /** A palavra reservada do strict mode (`implements`, `interface`, `let`, `yield`…) usada como identificador. */
1384
- function checkStrictModeIdentifier(node) {
1385
- if (inStrictMode &&
1386
- node.originalKeywordKind >= SyntaxKind.FirstFutureReservedWord &&
1387
- node.originalKeywordKind <= SyntaxKind.LastFutureReservedWord &&
1388
- !isIdentifierName(node) &&
1389
- !(node.flags & NodeFlags.Ambient)) {
1390
- // com erro de parse no arquivo, o binder não acusa
1391
- if (!file.parseDiagnostics.length) {
1392
- file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(), declarationNameToString(node)));
1393
- }
1394
- }
1395
- }
1396
- function getStrictModeIdentifierMessage() {
1397
- // A mensagem diz por que o código está em strict mode: num módulo, ele é automático.
1398
- if (file.externalModuleIndicator) {
1399
- return Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode;
1400
- }
1401
- return Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode;
1402
- }
1403
- function checkStrictModeBinaryExpression(node) {
1404
- if (inStrictMode && isLeftHandSideExpression(node.left) && isAssignmentOperator(node.operatorToken.kind)) {
1405
- // o `eval` e o `arguments` não são alvo de atribuição (ECMA-262, anexo C)
1406
- checkStrictModeEvalOrArguments(node.left);
1407
- }
1408
- }
1409
- function checkStrictModeCatchClause(node) {
1410
- // nem nome do binding de um `catch`
1411
- if (inStrictMode && node.variableDeclaration) {
1412
- checkStrictModeEvalOrArguments(node.variableDeclaration.name);
1413
- }
1414
- }
1415
- function checkStrictModeDeleteExpression(node) {
1416
- // em strict mode, o `delete` não se aplica a um nome (variável, parâmetro, função)
1417
- if (inStrictMode && node.expression.kind === SyntaxKind.Identifier) {
1418
- const span = getErrorSpanForNode(file, node.expression);
1419
- file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode));
1420
- }
1421
- }
1422
- function isEvalOrArgumentsIdentifier(node) {
1423
- return isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments");
1424
- }
1425
- function checkStrictModeEvalOrArguments(name) {
1426
- if (name && name.kind === SyntaxKind.Identifier) {
1427
- const identifier = name;
1428
- if (isEvalOrArgumentsIdentifier(identifier)) {
1429
- const span = getErrorSpanForNode(file, name);
1430
- file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(), idText(identifier)));
1431
- }
1432
- }
1433
- }
1434
- function getStrictModeEvalOrArgumentsMessage() {
1435
- // A mensagem diz por que o código está em strict mode: num módulo, ele é automático.
1436
- if (file.externalModuleIndicator) {
1437
- return Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode;
1438
- }
1439
- return Diagnostics.Invalid_use_of_0_in_strict_mode;
1440
- }
1441
- function checkStrictModeNumericLiteral(node) {
1442
- if (inStrictMode && node.numericLiteralFlags & TokenFlags.Octal) {
1443
- file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.Octal_literals_are_not_allowed_in_strict_mode));
1444
- }
1445
- }
1446
- function checkStrictModePostfixUnaryExpression(node) {
1447
- // o `eval` e o `arguments` não se incrementam nem se decrementam
1448
- if (inStrictMode) {
1449
- checkStrictModeEvalOrArguments(node.operand);
1450
- }
1451
- }
1452
- function checkStrictModePrefixUnaryExpression(node) {
1453
- if (inStrictMode) {
1454
- if (node.operator === SyntaxKind.PlusPlusToken || node.operator === SyntaxKind.MinusMinusToken) {
1455
- checkStrictModeEvalOrArguments(node.operand);
1456
- }
1457
- }
1458
- }
1459
- function errorOnFirstToken(node, message, arg0, arg1, arg2) {
1460
- const span = getSpanOfTokenAtPosition(file, node.pos);
1461
- file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2));
1462
- }
1463
- function errorOrSuggestionOnRange(isError, startNode, endNode, message) {
1464
- addErrorOrSuggestionDiagnostic(isError, { pos: getTokenPosOfNode(startNode, file), end: endNode.end }, message);
1465
- }
1466
- function addErrorOrSuggestionDiagnostic(isError, range, message) {
1467
- const diag = createFileDiagnostic(file, range.pos, range.end - range.pos, message);
1468
- if (isError) {
1469
- file.bindDiagnostics.push(diag);
1470
- }
1471
- else {
1472
- file.bindSuggestionDiagnostics = append(file.bindSuggestionDiagnostics, { ...diag, category: DiagnosticCategory.Suggestion });
1473
- }
1474
- }
1475
- function bind(node) {
1476
- if (!node) {
1477
- return;
1478
- }
1479
- node.parent = parent;
1480
- const saveInStrictMode = inStrictMode;
1481
- // Primeiro a declaração ganha o símbolo, que vai para os `exports` ou os `members` do contêiner, ou para os
1482
- // `locals` dele; o anônimo (um tipo literal) não vai para tabela nenhuma.
1483
- bindWorker(node);
1484
- // Depois os filhos, com o contêiner que o nó pede. Um token não tem filhos.
1485
- if (node.kind > SyntaxKind.LastToken) {
1486
- const saveParent = parent;
1487
- parent = node;
1488
- const containerFlags = getContainerFlags(node);
1489
- if (containerFlags === 0 /* ContainerFlags.None */) {
1490
- bindChildren(node);
1491
- }
1492
- else {
1493
- bindContainer(node, containerFlags);
1494
- }
1495
- parent = saveParent;
1496
- }
1497
- inStrictMode = saveInStrictMode;
1498
- }
1499
- function bindWorker(node) {
1500
- switch (node.kind) {
1501
- case SyntaxKind.Identifier:
1502
- if (currentFlow && (isExpression(node) || parent.kind === SyntaxKind.ShorthandPropertyAssignment)) {
1503
- node.flowNode = currentFlow;
1504
- }
1505
- return checkStrictModeIdentifier(node);
1506
- case SyntaxKind.PropertyAccessExpression:
1507
- case SyntaxKind.ElementAccessExpression:
1508
- const expr = node;
1509
- if (currentFlow && isNarrowableReference(expr)) {
1510
- expr.flowNode = currentFlow;
1511
- }
1512
- break;
1513
- case SyntaxKind.BinaryExpression:
1514
- // As atribuições especiais de JavaScript e o expando (`f.x = …` declarando `x` numa função) não
1515
- // declaram nada: são legado e recorte (CK-03, CK-38).
1516
- return checkStrictModeBinaryExpression(node);
1517
- case SyntaxKind.CatchClause:
1518
- return checkStrictModeCatchClause(node);
1519
- case SyntaxKind.DeleteExpression:
1520
- return checkStrictModeDeleteExpression(node);
1521
- case SyntaxKind.NumericLiteral:
1522
- return checkStrictModeNumericLiteral(node);
1523
- case SyntaxKind.PostfixUnaryExpression:
1524
- return checkStrictModePostfixUnaryExpression(node);
1525
- case SyntaxKind.PrefixUnaryExpression:
1526
- return checkStrictModePrefixUnaryExpression(node);
1527
- case SyntaxKind.TypePredicate:
1528
- break; // os filhos resolvem
1529
- case SyntaxKind.TypeParameter:
1530
- return bindTypeParameter(node);
1531
- case SyntaxKind.Parameter:
1532
- return bindParameter(node);
1533
- case SyntaxKind.VariableDeclaration:
1534
- return bindVariableDeclarationOrBindingElement(node);
1535
- case SyntaxKind.BindingElement:
1536
- node.flowNode = currentFlow;
1537
- return bindVariableDeclarationOrBindingElement(node);
1538
- case SyntaxKind.PropertySignature:
1539
- return bindPropertyWorker(node);
1540
- case SyntaxKind.PropertyAssignment:
1541
- case SyntaxKind.ShorthandPropertyAssignment:
1542
- return bindPropertyOrMethodOrAccessor(node, SymbolFlags.Property, SymbolFlags.PropertyExcludes);
1543
- case SyntaxKind.CallSignature:
1544
- case SyntaxKind.IndexSignature:
1545
- return declareSymbolAndAddToSymbolTable(node, SymbolFlags.Signature, SymbolFlags.None);
1546
- case SyntaxKind.FunctionType:
1547
- return bindFunctionOrConstructorType(node);
1548
- case SyntaxKind.TypeLiteral:
1549
- case SyntaxKind.MappedType:
1550
- return bindAnonymousTypeWorker(node);
1551
- case SyntaxKind.ObjectLiteralExpression:
1552
- return bindObjectLiteralExpression(node);
1553
- case SyntaxKind.ArrowFunction:
1554
- return bindFunctionExpression(node);
1555
- case SyntaxKind.TypeAliasDeclaration:
1556
- return bindBlockScopedDeclaration(node, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes);
1557
- case SyntaxKind.ModuleDeclaration:
1558
- return bindModuleDeclaration(node);
1559
- case SyntaxKind.JsxAttributes:
1560
- return bindJsxAttributes(node);
1561
- case SyntaxKind.JsxAttribute:
1562
- return bindJsxAttribute(node, SymbolFlags.Property, SymbolFlags.PropertyExcludes);
1563
- case SyntaxKind.NamespaceImport:
1564
- case SyntaxKind.ImportSpecifier:
1565
- case SyntaxKind.ExportSpecifier:
1566
- return declareSymbolAndAddToSymbolTable(node, SymbolFlags.Alias, SymbolFlags.AliasExcludes);
1567
- case SyntaxKind.ImportClause:
1568
- return bindImportClause(node);
1569
- case SyntaxKind.ExportDeclaration:
1570
- return bindExportDeclaration(node);
1571
- case SyntaxKind.ExportAssignment:
1572
- return bindExportAssignment(node);
1573
- case SyntaxKind.SourceFile:
1574
- // O prólogo `"use strict"` não muda nada: o programa já liga em strict mode (o `strict` liga o
1575
- // `alwaysStrict`, CK-24), e a lib, que liga fora dele, não tem prólogo.
1576
- return bindSourceFileIfExternalModule();
1577
- }
1578
- }
1579
- function bindPropertyWorker(node) {
1580
- return bindPropertyOrMethodOrAccessor(node, SymbolFlags.Property | (node.questionToken ? SymbolFlags.Optional : SymbolFlags.None), SymbolFlags.PropertyExcludes);
1581
- }
1582
- function bindAnonymousTypeWorker(node) {
1583
- return bindAnonymousDeclaration(node, SymbolFlags.TypeLiteral, InternalSymbolName.Type);
1584
- }
1585
- function bindSourceFileIfExternalModule() {
1586
- setExportContextFlag(file);
1587
- if (isExternalModule(file)) {
1588
- bindSourceFileAsExternalModule();
1589
- }
1590
- }
1591
- function bindSourceFileAsExternalModule() {
1592
- bindAnonymousDeclaration(file, SymbolFlags.ValueModule, `"${removeFileExtension(file.fileName)}"`);
1593
- }
1594
- function bindExportAssignment(node) {
1595
- if (!container.symbol || !container.symbol.exports) {
1596
- // o `export default` dentro de um bloco
1597
- bindAnonymousDeclaration(node, SymbolFlags.Alias, getDeclarationName(node));
1598
- }
1599
- else {
1600
- // O `export default` de um nome exporta todos os significados dele (alias); o de outra expressão, um valor.
1601
- // Com ele, o módulo não tem outro `export default` (os `excludes` são todos).
1602
- const flags = exportAssignmentIsAlias(node) ? SymbolFlags.Alias : SymbolFlags.Property;
1603
- declareSymbol(container.symbol.exports, container.symbol, node, flags, SymbolFlags.All);
1604
- }
1605
- }
1606
- function bindExportDeclaration(node) {
1607
- if (!container.symbol || !container.symbol.exports) {
1608
- // o `export *` dentro de um bloco
1609
- bindAnonymousDeclaration(node, SymbolFlags.ExportStar, getDeclarationName(node));
1610
- }
1611
- else if (!node.exportClause) {
1612
- // todos os `export *` de um módulo se juntam num símbolo só, o `__export`
1613
- declareSymbol(container.symbol.exports, container.symbol, node, SymbolFlags.ExportStar, SymbolFlags.None);
1614
- }
1615
- else if (isNamespaceExport(node.exportClause)) {
1616
- // o `declareSymbol` sobe pelos pais para achar o nome, e o pai do `export * as ns` ainda não foi ligado
1617
- node.exportClause.parent = node;
1618
- declareSymbol(container.symbol.exports, container.symbol, node.exportClause, SymbolFlags.Alias, SymbolFlags.AliasExcludes);
1619
- }
1620
- }
1621
- function bindImportClause(node) {
1622
- if (node.name) {
1623
- declareSymbolAndAddToSymbolTable(node, SymbolFlags.Alias, SymbolFlags.AliasExcludes);
1624
- }
1625
- }
1626
- function bindVariableDeclarationOrBindingElement(node) {
1627
- if (inStrictMode) {
1628
- checkStrictModeEvalOrArguments(node.name);
1629
- }
1630
- if (!isBindingPattern(node.name)) {
1631
- if (isBlockOrCatchScoped(node)) {
1632
- bindBlockScopedDeclaration(node, SymbolFlags.BlockScopedVariable, SymbolFlags.BlockScopedVariableExcludes);
1633
- }
1634
- else if (isParameterDeclaration(node)) {
1635
- // O elemento de um parâmetro desestruturado declara com os `excludes` de parâmetro, e `([a, a]) => 0`
1636
- // acusa o nome repetido, como `(a, a) => 0`. Os pais já estão ligados: o binder liga antes de descer.
1637
- declareSymbolAndAddToSymbolTable(node, SymbolFlags.FunctionScopedVariable, SymbolFlags.ParameterExcludes);
1638
- }
1639
- }
1640
- }
1641
- function bindParameter(node) {
1642
- if (inStrictMode && !(node.flags & NodeFlags.Ambient)) {
1643
- // nem nome de parâmetro
1644
- checkStrictModeEvalOrArguments(node.name);
1645
- }
1646
- if (isBindingPattern(node.name)) {
1647
- bindAnonymousDeclaration(node, SymbolFlags.FunctionScopedVariable, "__" + node.parent.parameters.indexOf(node));
1648
- }
1649
- else {
1650
- declareSymbolAndAddToSymbolTable(node, SymbolFlags.FunctionScopedVariable, SymbolFlags.ParameterExcludes);
1651
- }
1652
- }
1653
- function bindFunctionExpression(node) {
1654
- if (currentFlow) {
1655
- node.flowNode = currentFlow;
1656
- }
1657
- // a arrow não tem nome: o símbolo é o anônimo `__function`
1658
- return bindAnonymousDeclaration(node, SymbolFlags.Function, InternalSymbolName.Function);
1659
- }
1660
- function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) {
1661
- return hasDynamicName(node)
1662
- ? bindAnonymousDeclaration(node, symbolFlags, InternalSymbolName.Computed)
1663
- : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
1664
- }
1665
- function getInferTypeContainer(node) {
1666
- const extendsType = findAncestor(node, n => n.parent && isConditionalTypeNode(n.parent) && n.parent.extendsType === n);
1667
- return extendsType && extendsType.parent;
1668
- }
1669
- function bindTypeParameter(node) {
1670
- if (node.parent.kind === SyntaxKind.InferType) {
1671
- const container = getInferTypeContainer(node.parent);
1672
- if (container) {
1673
- if (!container.locals) {
1674
- container.locals = createSymbolTable();
1675
- }
1676
- declareSymbol(container.locals, /*parent*/ undefined, node, SymbolFlags.TypeParameter, SymbolFlags.TypeParameterExcludes);
1677
- }
1678
- else {
1679
- bindAnonymousDeclaration(node, SymbolFlags.TypeParameter, getDeclarationName(node));
1680
- }
1681
- }
1682
- else {
1683
- declareSymbolAndAddToSymbolTable(node, SymbolFlags.TypeParameter, SymbolFlags.TypeParameterExcludes);
1684
- }
1685
- }
1686
- // a alcançabilidade
1687
- function shouldReportErrorOnModuleDeclaration(node) {
1688
- const instanceState = getModuleInstanceState(node);
1689
- return instanceState === 1 /* ModuleInstanceState.Instantiated */;
1690
- }
1691
- function checkUnreachable(node) {
1692
- if (!(currentFlow.flags & FlowFlags.Unreachable)) {
1693
- return false;
1694
- }
1695
- if (currentFlow === unreachableFlow) {
1696
- // acusa todo statement que não é vazio, e o namespace instanciado
1697
- const reportError = (isStatementButNotDeclaration(node) && node.kind !== SyntaxKind.EmptyStatement) ||
1698
- (node.kind === SyntaxKind.ModuleDeclaration && shouldReportErrorOnModuleDeclaration(node));
1699
- if (reportError) {
1700
- currentFlow = reportedUnreachableFlow;
1701
- if (!options.allowUnreachableCode) {
1702
- // É erro, e não sugestão, quando a opção pede, fora do contexto ambiente (que já é erro por si).
1703
- const isError = unreachableCodeIsError(options) && !(node.flags & NodeFlags.Ambient);
1704
- eachUnreachableRange(node, (start, end) => errorOrSuggestionOnRange(isError, start, end, Diagnostics.Unreachable_code_detected));
1705
- }
1706
- }
1707
- }
1708
- return true;
1709
- }
1710
- }
1711
- function eachUnreachableRange(node, cb) {
1712
- if (isStatement(node) && isExecutableStatement(node) && isBlock(node.parent)) {
1713
- const { statements } = node.parent;
1714
- const slice = sliceAfter(statements, node);
1715
- getRangesWhere(slice, isExecutableStatement, (start, afterEnd) => cb(slice[start], slice[afterEnd - 1]));
1716
- }
1717
- else {
1718
- cb(node, node);
1719
- }
1720
- }
1721
- /** O statement que executa, ao contrário de uma declaração pura como o `type`. */
1722
- function isExecutableStatement(s) {
1723
- // A declaração de variável sem inicializador também não conta. O teste quer só a que pode ser usada antes de onde
1724
- // aparece, mas o `Let` e o `Const` estão nas flags da lista de declarações, e não nas do statement: vale para toda
1725
- // declaração sem inicializador, e é o veredito do `tsc`.
1726
- return !isPurelyTypeDeclaration(s) &&
1727
- !(isVariableStatement(s) && !(getCombinedNodeFlags(s) & (NodeFlags.Let | NodeFlags.Const)) && s.declarationList.declarations.some(d => !d.initializer));
1728
- }
1729
- function isPurelyTypeDeclaration(s) {
1730
- switch (s.kind) {
1731
- case SyntaxKind.TypeAliasDeclaration:
1732
- return true;
1733
- case SyntaxKind.ModuleDeclaration:
1734
- return getModuleInstanceState(s) !== 1 /* ModuleInstanceState.Instantiated */;
1735
- default:
1736
- return false;
1737
- }
1738
- }
1739
- /** Liga os pais de uma subárvore sem declarar nada, para o estado de instância de um módulo subir por eles antes do bind. */
1740
- function setParentPointers(parent, child) {
1741
- child.parent = parent;
1742
- forEachChild(child, grandchild => setParentPointers(child, grandchild));
1743
- }