@tslite/checker 1.9.0 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,55 @@
1
+ Apache License
2
+
3
+ Version 2.0, January 2004
4
+
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
16
+
17
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
18
+
19
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
20
+
21
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
22
+
23
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
24
+
25
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
26
+
27
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
28
+
29
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
30
+
31
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
32
+
33
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
34
+
35
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
36
+
37
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
38
+
39
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
40
+
41
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
42
+
43
+ If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44
+
45
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46
+
47
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48
+
49
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50
+
51
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52
+
53
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54
+
55
+ END OF TERMS AND CONDITIONS
package/NOTICE ADDED
@@ -0,0 +1,14 @@
1
+ TypeScript 3.9.10 — o compilador (src/compiler e src/shims), copiado da tag v3.9.10
2
+ (commit b7de5e3c4cd) de https://github.com/microsoft/TypeScript.
3
+
4
+ Copyright (c) Microsoft Corporation. All rights reserved.
5
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
6
+ this file except in compliance with the License. You may obtain a copy of the
7
+ License at http://www.apache.org/licenses/LICENSE-2.0 (o texto está em LICENSE).
8
+
9
+ Todos os arquivos de src/ foram modificados: o namespace `ts` do outFile virou
10
+ módulo ES, com os imports explícitos, por um codemod (packages/codemod deste
11
+ repositório). Cada arquivo diz de qual arquivo da tag veio, na primeira linha.
12
+ As mudanças seguintes a essa conversão (os cortes do recorte da Linguagem, do legado,
13
+ da configuração fixa, do host e do emit) estão registradas no §6 do
14
+ docs/ARCHITECTURE.md do pacote do checker (packages/checker).
@@ -0,0 +1,9 @@
1
+ export * from "@tslite/parser";
2
+ export * from "@tslite/binder";
3
+ export * from "@tslite/printer";
4
+ export * from "../types.js";
5
+ export * from "../utilities.js";
6
+ export * from "../symbolWalker.js";
7
+ export * from "../checker.js";
8
+ export * from "../check.js";
9
+ export * as moduleSpecifiers from "./ts.moduleSpecifiers.js";
@@ -0,0 +1,12 @@
1
+ // O namespace `ts` do outFile da tag, estendido com o checker: a parse tree, o binder e o printer, e depois o checker e o
2
+ // contrato do adaptador. A parse tree vem direta, e não pelos barris do binder e do printer, que a reexportam: no vitest,
3
+ // cada `export *` é um getter a mais em cada leitura de nome (§3 do `docs/ARCHITECTURE.md`).
4
+ export * from "@tslite/parser";
5
+ export * from "@tslite/binder";
6
+ export * from "@tslite/printer";
7
+ export * from "../types.js";
8
+ export * from "../utilities.js";
9
+ export * from "../symbolWalker.js";
10
+ export * from "../checker.js";
11
+ export * from "../check.js";
12
+ export * as moduleSpecifiers from "./ts.moduleSpecifiers.js";
@@ -0,0 +1 @@
1
+ export * from "../moduleSpecifiers.js";
@@ -0,0 +1,2 @@
1
+ // O namespace `ts.moduleSpecifiers` do outFile da tag.
2
+ export * from "../moduleSpecifiers.js";
@@ -0,0 +1,75 @@
1
+ import type { CancellationToken, CompilerOptions, Diagnostic, DiagnosticWithLocation, SourceFile, TypeChecker, UnderscoreEscapedMap } from "./_namespaces/ts.js";
2
+ /** O que o `check` pergunta a quem hospeda. */
3
+ export interface CheckHost {
4
+ getCurrentDirectory(): string;
5
+ useCaseSensitiveFileNames(): boolean;
6
+ /**
7
+ * O arquivo a que o import `moduleName` do arquivo `containingFile` resolve, pelo nome, ou `undefined` se não
8
+ * resolve (CK-46): o arquivo, ou nada.
9
+ */
10
+ resolveModule(moduleName: string, containingFile: string): string | undefined;
11
+ }
12
+ /** O programa ligado e tipado. */
13
+ export interface CheckResult {
14
+ getSourceFiles(): readonly SourceFile[];
15
+ getSourceFile(fileName: string): SourceFile | undefined;
16
+ /**
17
+ * Se o arquivo é a lib, como o `isSourceFileDefaultLibrary` do `Program` da tag: o que tem a diretiva
18
+ * `/// <reference no-default-lib="true"/>`. O language service não renomeia o que ela declara.
19
+ */
20
+ isSourceFileDefaultLibrary(file: SourceFile): boolean;
21
+ /**
22
+ * Os nomes que o binder declarou nos arquivos com um significado classificável (o tipo, o parâmetro de tipo, o
23
+ * namespace, o alias), como o `getClassifiableNames` do `Program` da tag. A classificação semântica do language
24
+ * service só pergunta ao checker pelo identificador que está aqui.
25
+ */
26
+ getClassifiableNames(): UnderscoreEscapedMap<true>;
27
+ /** O checker que produz os diagnósticos; responde às perguntas de tipo e de símbolo. */
28
+ getTypeChecker(): TypeChecker;
29
+ /**
30
+ * Os diagnósticos do programa, como o `getPreEmitDiagnostics`: de parse, globais, de bind e de check.
31
+ * @param cancellationToken consultado antes de cada arquivo e nos pontos em que o checker o consulta; o cancelamento
32
+ * lança `OperationCanceledException`, e o checker que a checagem usava é descartado: o próximo pedido cria outro
33
+ */
34
+ getDiagnostics(cancellationToken?: CancellationToken): readonly Diagnostic[];
35
+ /** Os diagnósticos de parse do arquivo, como o `getSyntacticDiagnostics(sourceFile)` do `Program` da tag. */
36
+ getSyntacticDiagnostics(sourceFile: SourceFile): readonly DiagnosticWithLocation[];
37
+ /**
38
+ * Os diagnósticos de bind e de check do arquivo, com as diretivas `@ts-ignore` e `@ts-expect-error`, como o
39
+ * `getSemanticDiagnostics(sourceFile)` do `Program` da tag: calculados uma vez por arquivo, e guardados. O
40
+ * cancelamento é o do `getDiagnostics`.
41
+ */
42
+ getSemanticDiagnostics(sourceFile: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[];
43
+ /** As sugestões que o checker acusa no arquivo, como o `getSuggestionDiagnostics(sourceFile)` do `Program` da tag. */
44
+ getSuggestionDiagnostics(sourceFile: SourceFile, cancellationToken?: CancellationToken): readonly DiagnosticWithLocation[];
45
+ /**
46
+ * Os diagnósticos das checagens extras pedidas (o grupo 2, CK-33), à parte dos da checagem: os de um programa com
47
+ * as opções do `tsc` que as ligam, sobre os mesmos arquivos. Os arquivos se parseiam de novo, do mesmo texto, porque
48
+ * o binder grava o que o grupo 2 lê só com as opções ligadas, e uma árvore se liga uma vez só; a lib, que não se
49
+ * checa, entra como está. Os diagnósticos citam os arquivos do programa, e o host é perguntado de novo pelos
50
+ * imports.
51
+ */
52
+ getExtraDiagnostics(checks: ExtraChecks, cancellationToken?: CancellationToken): readonly Diagnostic[];
53
+ }
54
+ /**
55
+ * As checagens extras, pelas opções do `tsc` que as ligam (CK-06, grupo 2): o unused (`noUnusedLocals`,
56
+ * `noUnusedParameters`), o retorno implícito (`noImplicitReturns`), o fallthrough (`noFallthroughCasesInSwitch`) e o
57
+ * inalcançável como erro (`allowUnreachableCode: false`).
58
+ */
59
+ export type ExtraChecks = Pick<CompilerOptions, "noUnusedLocals" | "noUnusedParameters" | "noImplicitReturns" | "noFallthroughCasesInSwitch" | "allowUnreachableCode">;
60
+ /**
61
+ * Liga e tipa um programa que quem chama já montou, na configuração fixa do checker (CK-24): nenhuma opção entra no
62
+ * contrato (CK-47).
63
+ * @param files os arquivos do programa, na ordem dele (as libs primeiro, como o `Program` as ordena)
64
+ */
65
+ export declare function check(files: readonly SourceFile[], host: CheckHost): CheckResult;
66
+ /**
67
+ * Os imports e as augmentations de módulo do arquivo, em `imports`, `moduleAugmentations` e `ambientModuleNames`:
68
+ * o que se resolve, e o que o checker funde na inicialização.
69
+ */
70
+ export declare function collectExternalModuleReferences(file: SourceFile): void;
71
+ /**
72
+ * Os nomes de módulo do arquivo que se resolvem: os dos imports. A única augmentation é o `declare global`, de nome
73
+ * identificador, que não se resolve.
74
+ */
75
+ export declare function getModuleNames({ imports }: SourceFile): string[];
package/dist/check.js ADDED
@@ -0,0 +1,316 @@
1
+ // O contrato do adaptador: a entrada pequena por onde quem hospeda a cópia a usa, sem o `Program`.
2
+ //
3
+ // Quem chama decide o programa — quais arquivos entram, em que ordem, e para onde cada import resolve (a
4
+ // resolução é do host, CK-46) — e entrega os `SourceFile` já parseados. O `check` liga e tipa esses arquivos
5
+ // e devolve os diagnósticos, na mesma ordem de avaliação e com a mesma montagem do `getPreEmitDiagnostics`
6
+ // do `program.ts` da tag, e o checker que os produziu, para as perguntas de tipo e de símbolo.
7
+ import { Debug, Diagnostics, ModifierFlags, NodeFlags, OperationCanceledException, ScriptKind, SyntaxKind, addRange, append, bindSourceFile, computeLineAndCharacterOfPosition, copyEntries, createCommentDirectivesMap, createDiagnosticForRange, createGetCanonicalFileName, createMap, createSourceFile, createTypeChecker, createUnderscoreEscapedMap, emptyArray, extensionFromPath, flatMap, flatten, forEachChild, getExternalModuleName, getLineStarts, getTextOfIdentifierOrLiteral, hasModifier, isAmbientModule, isAnyImportOrReExport, isExternalModule, isExternalModuleNameRelative, isImportCall, isLiteralImportTypeNode, isModuleDeclaration, isRequireCall, isSourceFileJS, isStringLiteral, isStringLiteralLike, setResolvedModule, skipTypeChecking, sortAndDeduplicateDiagnostics, toPath, } from "./_namespaces/ts.js";
8
+ /** Os códigos que as checagens extras dão. */
9
+ const extraCheckCodes = new Set([
10
+ Diagnostics._0_is_declared_but_its_value_is_never_read.code,
11
+ Diagnostics._0_is_declared_but_never_used.code,
12
+ Diagnostics.All_imports_in_import_declaration_are_unused.code,
13
+ Diagnostics.All_destructured_elements_are_unused.code,
14
+ Diagnostics.All_variables_are_unused.code,
15
+ Diagnostics.All_type_parameters_are_unused.code,
16
+ Diagnostics.Not_all_code_paths_return_a_value.code,
17
+ Diagnostics.Fallthrough_case_in_switch.code,
18
+ Diagnostics.Unreachable_code_detected.code,
19
+ ]);
20
+ /**
21
+ * Liga e tipa um programa que quem chama já montou, na configuração fixa do checker (CK-24): nenhuma opção entra no
22
+ * contrato (CK-47).
23
+ * @param files os arquivos do programa, na ordem dele (as libs primeiro, como o `Program` as ordena)
24
+ */
25
+ export function check(files, host) {
26
+ return checkWithOptions(files, {}, host);
27
+ }
28
+ /** O `check`, com as opções que o checker e o binder ainda leem: só as das checagens extras. */
29
+ function checkWithOptions(files, options, host) {
30
+ const currentDirectory = host.getCurrentDirectory();
31
+ const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames());
32
+ const filesByPath = createMap();
33
+ for (const file of files) {
34
+ const path = toPath(file.fileName, currentDirectory, getCanonicalFileName);
35
+ file.path = path;
36
+ file.resolvedPath = path;
37
+ file.originalFileName = file.fileName;
38
+ filesByPath.set(path, file);
39
+ }
40
+ // As resoluções que o host decidiu, no arquivo, onde o checker as lê (`getResolvedModule`). A extensão sai do nome,
41
+ // como a resolução da tag a dá.
42
+ for (const file of files) {
43
+ collectExternalModuleReferences(file);
44
+ if (file.imports.length) {
45
+ for (const moduleName of getModuleNames(file)) {
46
+ const resolvedFileName = host.resolveModule(moduleName, file.fileName);
47
+ const resolution = resolvedFileName === undefined ? undefined : { resolvedFileName, extension: extensionFromPath(resolvedFileName) };
48
+ setResolvedModule(file, moduleName, resolution);
49
+ }
50
+ }
51
+ }
52
+ // A ligação de cada arquivo, antes do checker existir (CK-28). Ela é idempotente: o arquivo que chega ligado — a lib,
53
+ // ou o ambiente reaproveitado entre checagens — fica como está.
54
+ for (const file of files) {
55
+ bindSourceFile(file, options);
56
+ }
57
+ const checkerHost = {
58
+ getCompilerOptions: () => options,
59
+ getSourceFiles: () => files,
60
+ getSourceFile: fileName => filesByPath.get(toPath(fileName, currentDirectory, getCanonicalFileName)),
61
+ getCurrentDirectory: () => currentDirectory,
62
+ useCaseSensitiveFileNames: () => host.useCaseSensitiveFileNames(),
63
+ };
64
+ let typeChecker;
65
+ let diagnostics;
66
+ let classifiableNames;
67
+ // O `cachedBindAndCheckDiagnosticsForFile` do `program.ts` da tag: os de bind e de check de cada arquivo.
68
+ const cachedBindAndCheckDiagnosticsForFile = createMap();
69
+ return {
70
+ getSourceFiles: () => files,
71
+ getSourceFile: checkerHost.getSourceFile,
72
+ isSourceFileDefaultLibrary,
73
+ getClassifiableNames,
74
+ getTypeChecker,
75
+ getDiagnostics: cancellationToken => diagnostics || (diagnostics = getPreEmitDiagnostics(cancellationToken)),
76
+ getSyntacticDiagnostics: getSyntacticDiagnosticsForFile,
77
+ getSemanticDiagnostics: getBindAndCheckDiagnosticsForFile,
78
+ getSuggestionDiagnostics,
79
+ getExtraDiagnostics,
80
+ };
81
+ function getExtraDiagnostics(checks, cancellationToken) {
82
+ const copies = files.map(file => file.hasNoDefaultLib ? file : createSourceFile(file.fileName, file.text, file.languageVersion, /*setParentNodes*/ false, file.scriptKind));
83
+ const extra = checkWithOptions(copies, { ...options, ...checks }, host);
84
+ const original = (file) => file && filesByPath.get(file.path);
85
+ return extra.getDiagnostics(cancellationToken)
86
+ .filter(d => extraCheckCodes.has(d.code))
87
+ .map(d => ({
88
+ ...d,
89
+ file: original(d.file),
90
+ relatedInformation: d.relatedInformation && d.relatedInformation.map(r => ({ ...r, file: original(r.file) })),
91
+ }));
92
+ }
93
+ /**
94
+ * Na tag, também o arquivo de nome igual ao da lib default, ou ao de uma lib do `--lib`, mas só com o `noLib`, que a
95
+ * configuração fixa não liga (CK-24).
96
+ */
97
+ function isSourceFileDefaultLibrary(file) {
98
+ return file.hasNoDefaultLib;
99
+ }
100
+ /** Na tag, ele criava o checker antes, para ligar os arquivos; aqui eles já estão ligados (CK-28). */
101
+ function getClassifiableNames() {
102
+ if (!classifiableNames) {
103
+ classifiableNames = createUnderscoreEscapedMap();
104
+ for (const sourceFile of files) {
105
+ copyEntries(sourceFile.classifiableNames, classifiableNames);
106
+ }
107
+ }
108
+ return classifiableNames;
109
+ }
110
+ function getTypeChecker() {
111
+ return typeChecker || (typeChecker = createTypeChecker(checkerHost));
112
+ }
113
+ // Do `getPreEmitDiagnostics`: os de parse, os globais (que criam o checker) e os de bind e de check, arquivo a
114
+ // arquivo, nessa ordem. O programa não tem diagnóstico de opção nem de arquivo: esses são do host.
115
+ function getPreEmitDiagnostics(cancellationToken) {
116
+ let all;
117
+ all = addRange(all, forEachFile(getSyntacticDiagnosticsForFile, cancellationToken));
118
+ all = addRange(all, files.length ? sortAndDeduplicateDiagnostics(getTypeChecker().getGlobalDiagnostics().slice()) : emptyArray);
119
+ all = addRange(all, forEachFile(getBindAndCheckDiagnosticsForFile, cancellationToken));
120
+ return sortAndDeduplicateDiagnostics(all || emptyArray);
121
+ }
122
+ /** Os diagnósticos de todos os arquivos, como o `getDiagnosticsHelper` do programa: o token se consulta antes de cada um. */
123
+ function forEachFile(getDiagnostics, cancellationToken) {
124
+ return sortAndDeduplicateDiagnostics(flatMap(files, sourceFile => {
125
+ if (cancellationToken) {
126
+ cancellationToken.throwIfCancellationRequested();
127
+ }
128
+ return getDiagnostics(sourceFile, cancellationToken);
129
+ }));
130
+ }
131
+ function getSyntacticDiagnosticsForFile(sourceFile) {
132
+ return sourceFile.parseDiagnostics;
133
+ }
134
+ /**
135
+ * Os de bind e de check do arquivo, guardados, como o `getAndCacheDiagnostics` da tag. Na tag, os semânticos de um
136
+ * arquivo juntam a eles os do processamento dos arquivos e das opções, que são do host, e aqui não existem.
137
+ */
138
+ function getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken) {
139
+ const cachedResult = cachedBindAndCheckDiagnosticsForFile.get(sourceFile.path);
140
+ if (cachedResult) {
141
+ return cachedResult;
142
+ }
143
+ const result = getBindAndCheckDiagnosticsForFileNoCache(sourceFile, cancellationToken);
144
+ cachedBindAndCheckDiagnosticsForFile.set(sourceFile.path, result);
145
+ return result;
146
+ }
147
+ function getSuggestionDiagnostics(sourceFile, cancellationToken) {
148
+ return runWithCancellationToken(() => {
149
+ return getTypeChecker().getSuggestionDiagnostics(sourceFile, cancellationToken);
150
+ });
151
+ }
152
+ function getBindAndCheckDiagnosticsForFileNoCache(sourceFile, cancellationToken) {
153
+ return runWithCancellationToken(() => {
154
+ if (skipTypeChecking(sourceFile)) {
155
+ return emptyArray;
156
+ }
157
+ const checker = getTypeChecker();
158
+ Debug.assert(!!sourceFile.bindDiagnostics);
159
+ const isTsNoCheck = !!sourceFile.checkJsDirective && sourceFile.checkJsDirective.enabled === false;
160
+ // Só se checam os arquivos TypeScript, e os `External` e `Deferred` que um plugin acrescenta.
161
+ const includeBindAndCheckDiagnostics = !isTsNoCheck && (sourceFile.scriptKind === ScriptKind.TS || sourceFile.scriptKind === ScriptKind.TSX ||
162
+ sourceFile.scriptKind === ScriptKind.External || sourceFile.scriptKind === ScriptKind.Deferred);
163
+ const bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : emptyArray;
164
+ const checkDiagnostics = includeBindAndCheckDiagnostics ? checker.getDiagnostics(sourceFile, cancellationToken) : emptyArray;
165
+ return getMergedBindAndCheckDiagnostics(sourceFile, bindDiagnostics, checkDiagnostics);
166
+ });
167
+ }
168
+ /**
169
+ * Roda uma checagem que o token pode interromper. Interrompido no meio de uma operação, o checker pode ter ficado
170
+ * num estado inválido, e é descartado: o próximo pedido cria outro.
171
+ */
172
+ function runWithCancellationToken(func) {
173
+ try {
174
+ return func();
175
+ }
176
+ catch (e) {
177
+ if (e instanceof OperationCanceledException) {
178
+ typeChecker = undefined;
179
+ }
180
+ throw e;
181
+ }
182
+ }
183
+ function getMergedBindAndCheckDiagnostics(sourceFile, ...allDiagnostics) {
184
+ const flatDiagnostics = flatten(allDiagnostics);
185
+ if (!sourceFile.commentDirectives?.length) {
186
+ return flatDiagnostics;
187
+ }
188
+ const { diagnostics, directives } = getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, flatDiagnostics);
189
+ for (const errorExpectation of directives.getUnusedExpectations()) {
190
+ diagnostics.push(createDiagnosticForRange(sourceFile, errorExpectation.range, Diagnostics.Unused_ts_expect_error_directive));
191
+ }
192
+ return diagnostics;
193
+ }
194
+ /** Os diagnósticos sem os que um `// @ts-ignore` ou `// @ts-expect-error` cobre; cada diretiva que cobre fica marcada como usada. */
195
+ function getDiagnosticsWithPrecedingDirectives(sourceFile, commentDirectives, flatDiagnostics) {
196
+ const directives = createCommentDirectivesMap(sourceFile, commentDirectives);
197
+ const diagnostics = flatDiagnostics.filter(diagnostic => markPrecedingCommentDirectiveLine(diagnostic, directives) === -1);
198
+ return { diagnostics, directives };
199
+ }
200
+ /** A linha da diretiva que precede o diagnóstico, ou -1. A busca sobe por linhas vazias e de comentário. */
201
+ function markPrecedingCommentDirectiveLine(diagnostic, directives) {
202
+ const { file, start } = diagnostic;
203
+ if (!file) {
204
+ return -1;
205
+ }
206
+ const lineStarts = getLineStarts(file);
207
+ let line = computeLineAndCharacterOfPosition(lineStarts, start).line - 1;
208
+ while (line >= 0) {
209
+ if (directives.markUsed(line)) {
210
+ return line;
211
+ }
212
+ const lineText = file.text.slice(lineStarts[line], lineStarts[line + 1]).trim();
213
+ if (lineText !== "" && !/^(\s*)\/\/(.*)$/.test(lineText)) {
214
+ return -1;
215
+ }
216
+ line--;
217
+ }
218
+ return -1;
219
+ }
220
+ }
221
+ /**
222
+ * Os imports e as augmentations de módulo do arquivo, em `imports`, `moduleAugmentations` e `ambientModuleNames`:
223
+ * o que se resolve, e o que o checker funde na inicialização.
224
+ */
225
+ export function collectExternalModuleReferences(file) {
226
+ if (file.imports) {
227
+ return;
228
+ }
229
+ const isJavaScriptFile = isSourceFileJS(file);
230
+ const isExternalModuleFile = isExternalModule(file);
231
+ // O `file.imports` pode já existir com um import dinâmico.
232
+ let imports;
233
+ let moduleAugmentations;
234
+ let ambientModules;
235
+ for (const node of file.statements) {
236
+ collectModuleReferences(node, /*inAmbientModule*/ false);
237
+ }
238
+ if ((file.flags & NodeFlags.PossiblyContainsDynamicImport) || isJavaScriptFile) {
239
+ collectDynamicImportOrRequireCalls(file);
240
+ }
241
+ file.imports = imports || emptyArray;
242
+ file.moduleAugmentations = moduleAugmentations || emptyArray;
243
+ file.ambientModuleNames = ambientModules || emptyArray;
244
+ return;
245
+ function collectModuleReferences(node, inAmbientModule) {
246
+ if (isAnyImportOrReExport(node)) {
247
+ const moduleNameExpr = getExternalModuleName(node);
248
+ // Dentro de um módulo ambiente, o import só alcança nomes de módulo de topo, e não relativos.
249
+ if (moduleNameExpr && isStringLiteral(moduleNameExpr) && moduleNameExpr.text && (!inAmbientModule || !isExternalModuleNameRelative(moduleNameExpr.text))) {
250
+ imports = append(imports, moduleNameExpr);
251
+ }
252
+ }
253
+ else if (isModuleDeclaration(node)) {
254
+ if (isAmbientModule(node) && (inAmbientModule || hasModifier(node, ModifierFlags.Ambient) || file.isDeclarationFile)) {
255
+ const nameText = getTextOfIdentifierOrLiteral(node.name);
256
+ // O módulo ambiente é augmentation quando o arquivo é módulo (no topo) ou quando está aninhado, com nome
257
+ // não relativo, num módulo ambiente de topo.
258
+ if (isExternalModuleFile || (inAmbientModule && !isExternalModuleNameRelative(nameText))) {
259
+ (moduleAugmentations || (moduleAugmentations = [])).push(node.name);
260
+ }
261
+ else if (!inAmbientModule) {
262
+ if (file.isDeclarationFile) {
263
+ // o nome do módulo ambiente de um `.d.ts` global
264
+ (ambientModules || (ambientModules = [])).push(nameText);
265
+ }
266
+ // O corpo de um módulo ambiente é sempre um bloco de módulo, quando existe.
267
+ const body = node.body;
268
+ if (body) {
269
+ for (const statement of body.statements) {
270
+ collectModuleReferences(statement, /*inAmbientModule*/ true);
271
+ }
272
+ }
273
+ }
274
+ }
275
+ }
276
+ }
277
+ function collectDynamicImportOrRequireCalls(file) {
278
+ const r = /import|require/g;
279
+ while (r.exec(file.text) !== null) { // eslint-disable-line no-null/no-null
280
+ const node = getNodeAtPosition(file, r.lastIndex);
281
+ if (isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) {
282
+ imports = append(imports, node.arguments[0]);
283
+ }
284
+ // A lista de argumentos tem de ter um só, mesmo com erro de parse.
285
+ else if (isImportCall(node) && node.arguments.length === 1 && isStringLiteralLike(node.arguments[0])) {
286
+ imports = append(imports, node.arguments[0]);
287
+ }
288
+ else if (isLiteralImportTypeNode(node)) {
289
+ imports = append(imports, node.argument.literal);
290
+ }
291
+ }
292
+ }
293
+ /** O token na posição, incluída a trivia de antes. */
294
+ function getNodeAtPosition(sourceFile, position) {
295
+ let current = sourceFile;
296
+ const getContainingChild = (child) => {
297
+ if (child.pos <= position && (position < child.end || (position === child.end && (child.kind === SyntaxKind.EndOfFileToken)))) {
298
+ return child;
299
+ }
300
+ };
301
+ while (true) {
302
+ const child = forEachChild(current, getContainingChild);
303
+ if (!child) {
304
+ return current;
305
+ }
306
+ current = child;
307
+ }
308
+ }
309
+ }
310
+ /**
311
+ * Os nomes de módulo do arquivo que se resolvem: os dos imports. A única augmentation é o `declare global`, de nome
312
+ * identificador, que não se resolve.
313
+ */
314
+ export function getModuleNames({ imports }) {
315
+ return imports.map(i => i.text);
316
+ }
@@ -0,0 +1,5 @@
1
+ import type { Signature, Symbol, TypeChecker, TypeCheckerHost } from "./_namespaces/ts.js";
2
+ export declare function getSymbolId(symbol: Symbol): number;
3
+ export declare function createTypeChecker(host: TypeCheckerHost): TypeChecker;
4
+ export declare function signatureHasRestParameter(s: Signature): boolean;
5
+ export declare function signatureHasLiteralTypes(s: Signature): boolean;