forked from alangpierce/sucrase
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgetImportExportSpecifierInfo.ts
92 lines (89 loc) · 2.32 KB
/
getImportExportSpecifierInfo.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import {TokenType as tt} from "../parser/tokenizer/types";
import type TokenProcessor from "../TokenProcessor";
export type ImportExportSpecifierInfo =
| {
isType: false;
leftName: string;
rightName: string;
endIndex: number;
}
| {
isType: true;
leftName: null;
rightName: null;
endIndex: number;
};
/**
* Determine information about this named import or named export specifier.
*
* This syntax is the `a` from statements like these:
* import {A} from "./foo";
* export {A};
* export {A} from "./foo";
*
* As it turns out, we can exactly characterize the syntax meaning by simply
* counting the number of tokens, which can be from 1 to 4:
* {A}
* {type A}
* {A as B}
* {type A as B}
*
* In the type case, we never actually need the names in practice, so don't get
* them.
*
* TODO: There's some redundancy with the type detection here and the isType
* flag that's already present on tokens in TS mode. This function could
* potentially be simplified and/or pushed to the call sites to avoid the object
* allocation.
*/
export default function getImportExportSpecifierInfo(
tokens: TokenProcessor,
index: number = tokens.currentIndex(),
): ImportExportSpecifierInfo {
let endIndex = index + 1;
if (isSpecifierEnd(tokens, endIndex)) {
// import {A}
const name = tokens.identifierNameAtIndex(index);
return {
isType: false,
leftName: name,
rightName: name,
endIndex,
};
}
endIndex++;
if (isSpecifierEnd(tokens, endIndex)) {
// import {type A}
return {
isType: true,
leftName: null,
rightName: null,
endIndex,
};
}
endIndex++;
if (isSpecifierEnd(tokens, endIndex)) {
// import {A as B}
return {
isType: false,
leftName: tokens.identifierNameAtIndex(index),
rightName: tokens.identifierNameAtIndex(index + 2),
endIndex,
};
}
endIndex++;
if (isSpecifierEnd(tokens, endIndex)) {
// import {type A as B}
return {
isType: true,
leftName: null,
rightName: null,
endIndex,
};
}
throw new Error(`Unexpected import/export specifier at ${index}`);
}
function isSpecifierEnd(tokens: TokenProcessor, index: number): boolean {
const token = tokens.tokens[index];
return token.type === tt.braceR || token.type === tt.comma;
}