1 | import {ContextualKeyword} from "../parser/tokenizer/keywords";
|
2 | import {TokenType as tt} from "../parser/tokenizer/types";
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 | export default function getTSImportedNames(tokens) {
|
13 | const importedNames = new Set();
|
14 | for (let i = 0; i < tokens.tokens.length; i++) {
|
15 | if (
|
16 | tokens.matches1AtIndex(i, tt._import) &&
|
17 | !tokens.matches3AtIndex(i, tt._import, tt.name, tt.eq)
|
18 | ) {
|
19 | collectNamesForImport(tokens, i, importedNames);
|
20 | }
|
21 | }
|
22 | return importedNames;
|
23 | }
|
24 |
|
25 | function collectNamesForImport(
|
26 | tokens,
|
27 | index,
|
28 | importedNames,
|
29 | ) {
|
30 | index++;
|
31 |
|
32 | if (tokens.matches1AtIndex(index, tt.parenL)) {
|
33 |
|
34 | return;
|
35 | }
|
36 |
|
37 | if (tokens.matches1AtIndex(index, tt.name)) {
|
38 | importedNames.add(tokens.identifierNameAtIndex(index));
|
39 | index++;
|
40 | if (tokens.matches1AtIndex(index, tt.comma)) {
|
41 | index++;
|
42 | }
|
43 | }
|
44 |
|
45 | if (tokens.matches1AtIndex(index, tt.star)) {
|
46 |
|
47 | index += 2;
|
48 | importedNames.add(tokens.identifierNameAtIndex(index));
|
49 | index++;
|
50 | }
|
51 |
|
52 | if (tokens.matches1AtIndex(index, tt.braceL)) {
|
53 | index++;
|
54 | collectNamesForNamedImport(tokens, index, importedNames);
|
55 | }
|
56 | }
|
57 |
|
58 | function collectNamesForNamedImport(
|
59 | tokens,
|
60 | index,
|
61 | importedNames,
|
62 | ) {
|
63 | while (true) {
|
64 | if (tokens.matches1AtIndex(index, tt.braceR)) {
|
65 | return;
|
66 | }
|
67 |
|
68 |
|
69 |
|
70 | let name = tokens.identifierNameAtIndex(index);
|
71 | index++;
|
72 | if (tokens.matchesContextualAtIndex(index, ContextualKeyword._as)) {
|
73 | index++;
|
74 | name = tokens.identifierNameAtIndex(index);
|
75 | index++;
|
76 | }
|
77 | importedNames.add(name);
|
78 | if (tokens.matches2AtIndex(index, tt.comma, tt.braceR)) {
|
79 | return;
|
80 | } else if (tokens.matches1AtIndex(index, tt.braceR)) {
|
81 | return;
|
82 | } else if (tokens.matches1AtIndex(index, tt.comma)) {
|
83 | index++;
|
84 | } else {
|
85 | throw new Error(`Unexpected token: ${JSON.stringify(tokens.tokens[index])}`);
|
86 | }
|
87 | }
|
88 | }
|