-
-
Notifications
You must be signed in to change notification settings - Fork 72
/
DeclarationScope.ts
506 lines (476 loc) · 15.1 KB
/
DeclarationScope.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
import * as ts from "typescript";
import * as ESTree from "estree";
import {
Ranged,
createDeclaration,
createReference,
createIdentifier,
withStartEnd,
convertExpression,
createIIFE,
} from "./astHelpers";
import { Transformer } from "./Transformer";
import { UnsupportedSyntaxError } from "./errors";
const IGNORE_TYPENODES = new Set([
ts.SyntaxKind.LiteralType,
ts.SyntaxKind.VoidKeyword,
ts.SyntaxKind.UnknownKeyword,
ts.SyntaxKind.AnyKeyword,
ts.SyntaxKind.BooleanKeyword,
ts.SyntaxKind.NumberKeyword,
ts.SyntaxKind.StringKeyword,
ts.SyntaxKind.ObjectKeyword,
ts.SyntaxKind.NullKeyword,
ts.SyntaxKind.UndefinedKeyword,
ts.SyntaxKind.SymbolKeyword,
ts.SyntaxKind.NeverKeyword,
ts.SyntaxKind.ThisKeyword,
ts.SyntaxKind.ThisType,
ts.SyntaxKind.BigIntKeyword,
]);
interface DeclarationScopeOptions {
id?: ts.Identifier;
range: Ranged;
transformer: Transformer;
}
export class DeclarationScope {
// TODO: having this circular dependency is very unclean… figure out a way
// to avoid it for the usecase of inline imports
transformer: Transformer;
declaration: ESTree.FunctionDeclaration;
iife?: ESTree.ExpressionStatement;
constructor({ id, range, transformer }: DeclarationScopeOptions) {
this.transformer = transformer;
if (id) {
this.declaration = createDeclaration(id, range);
} else {
const { iife, fn } = createIIFE(range);
this.iife = iife;
this.declaration = fn as any;
}
}
/**
* As we walk the AST, we need to keep track of type variable bindings that
* shadow the outer identifiers. To achieve this, we keep a stack of scopes,
* represented as Sets of variable names.
*/
scopes: Array<Set<string>> = [];
pushScope() {
this.scopes.push(new Set());
}
popScope(n = 1) {
for (let i = 0; i < n; i++) {
this.scopes.pop();
}
}
pushTypeVariable(id: ts.Identifier) {
const name = id.getText();
this.scopes[this.scopes.length - 1].add(name);
}
pushRaw(expr: ESTree.AssignmentPattern) {
this.declaration.params.push(expr);
}
pushReference(id: ESTree.Expression) {
let name: string | undefined;
// We convert references from TS AST to ESTree
// to hand them off to rollup.
// This means we have to check the left-most identifier inside our scope
// tree and avoid to create the reference in that case
if (id.type === "Identifier") {
name = id.name;
} else if (id.type === "MemberExpression") {
if (id.object.type === "Identifier") {
name = id.object.name;
}
}
if (name) {
for (const scope of this.scopes) {
if (scope.has(name)) {
return;
}
}
}
this.pushRaw(createReference(id));
}
pushIdentifierReference(id: ts.Identifier) {
this.pushReference(createIdentifier(id));
}
/**
* This will fix up the modifiers of a declaration.
* We want to remove `export (default)?` modifiers, and in that case add a
* missing `declare`. All the others should be untouched.
*/
fixModifiers(node: ts.Node) {
if (!node.modifiers) {
return;
}
const modifiers: Array<string> = [];
let hasDeclare = false;
let start = Infinity;
let end = 0;
for (const mod of node.modifiers) {
if (mod.kind !== ts.SyntaxKind.ExportKeyword && mod.kind !== ts.SyntaxKind.DefaultKeyword) {
modifiers.push(mod.getText());
}
if (mod.kind === ts.SyntaxKind.DeclareKeyword) {
hasDeclare = true;
}
start = Math.min(start, mod.getStart());
end = Math.max(end, mod.getEnd());
}
// function and class *must* have a `declare` modifier
if (!hasDeclare && (ts.isClassDeclaration(node) || ts.isFunctionDeclaration(node))) {
modifiers.unshift("declare");
}
const newModifiers = modifiers.join(" ");
if (!newModifiers && end) {
end += 1;
}
this.transformer.fixups.push({
range: { start, end },
replaceWith: newModifiers,
});
}
convertEntityName(node: ts.EntityName): ESTree.Expression {
if (ts.isIdentifier(node)) {
return createIdentifier(node);
}
return withStartEnd(
{
type: "MemberExpression",
computed: false,
object: this.convertEntityName(node.left),
property: createIdentifier(node.right),
},
// TODO: clean up all the `start` handling!
{ start: node.getStart(), end: node.end },
);
}
convertPropertyAccess(node: ts.PropertyAccessExpression): ESTree.Expression {
// hm, we only care about property access expressions here…
if (!ts.isIdentifier(node.expression) && !ts.isPropertyAccessExpression(node.expression)) {
throw new UnsupportedSyntaxError(node.expression);
}
if (ts.isPrivateIdentifier(node.name)) {
throw new UnsupportedSyntaxError(node.name);
}
let object = ts.isIdentifier(node.expression)
? createIdentifier(node.expression)
: this.convertPropertyAccess(node.expression);
return withStartEnd(
{
type: "MemberExpression",
computed: false,
object,
property: createIdentifier(node.name),
},
// TODO: clean up all the `start` handling!
{ start: node.getStart(), end: node.end },
);
}
convertComputedPropertyName(node: { name?: ts.PropertyName }) {
if (!node.name || !ts.isComputedPropertyName(node.name)) {
return;
}
const { expression } = node.name;
if (ts.isLiteralExpression(expression)) {
return;
}
if (ts.isIdentifier(expression)) {
return this.pushReference(createIdentifier(expression));
}
if (ts.isPropertyAccessExpression(expression)) {
return this.pushReference(this.convertPropertyAccess(expression));
}
throw new UnsupportedSyntaxError(expression);
}
convertParametersAndType(node: ts.SignatureDeclarationBase) {
this.convertComputedPropertyName(node);
const typeVariables = this.convertTypeParameters(node.typeParameters);
for (const param of node.parameters) {
this.convertTypeNode(param.type);
}
this.convertTypeNode(node.type);
this.popScope(typeVariables);
}
convertHeritageClauses(node: ts.InterfaceDeclaration | ts.ClassDeclaration) {
for (const heritage of node.heritageClauses || []) {
for (const type of heritage.types) {
this.pushReference(convertExpression(type.expression));
for (const arg of type.typeArguments || []) {
this.convertTypeNode(arg);
}
}
}
}
convertMembers(members: ts.NodeArray<ts.TypeElement | ts.ClassElement>) {
for (const node of members) {
if (ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isIndexSignatureDeclaration(node)) {
this.convertComputedPropertyName(node);
this.convertTypeNode(node.type);
continue;
}
// istanbul ignore else
if (
ts.isMethodDeclaration(node) ||
ts.isMethodSignature(node) ||
ts.isConstructorDeclaration(node) ||
ts.isConstructSignatureDeclaration(node) ||
ts.isCallSignatureDeclaration(node) ||
ts.isGetAccessorDeclaration(node) ||
ts.isSetAccessorDeclaration(node)
) {
this.convertParametersAndType(node);
} else {
throw new UnsupportedSyntaxError(node);
}
}
}
convertTypeParameters(params?: ts.NodeArray<ts.TypeParameterDeclaration>) {
if (!params) {
return 0;
}
for (const node of params) {
this.convertTypeNode(node.constraint);
this.convertTypeNode(node.default);
this.pushScope();
this.pushTypeVariable(node.name);
}
return params.length;
}
convertTypeNode(node?: ts.TypeNode): any {
if (!node) {
return;
}
if (IGNORE_TYPENODES.has(node.kind)) {
return;
}
if (ts.isTypeReferenceNode(node)) {
this.pushReference(this.convertEntityName(node.typeName));
for (const arg of node.typeArguments || []) {
this.convertTypeNode(arg);
}
return;
}
if (ts.isTypeLiteralNode(node)) {
return this.convertMembers(node.members);
}
if (ts.isArrayTypeNode(node)) {
return this.convertTypeNode(node.elementType);
}
if (ts.isTupleTypeNode(node)) {
for (const type of node.elementTypes) {
this.convertTypeNode(type);
}
return;
}
if (ts.isParenthesizedTypeNode(node) || ts.isTypeOperatorNode(node) || ts.isTypePredicateNode(node)) {
return this.convertTypeNode(node.type);
}
if (ts.isUnionTypeNode(node) || ts.isIntersectionTypeNode(node)) {
for (const type of node.types) {
this.convertTypeNode(type);
}
return;
}
if (ts.isMappedTypeNode(node)) {
const { typeParameter, type } = node;
this.convertTypeNode(typeParameter.constraint);
this.pushScope();
this.pushTypeVariable(node.typeParameter.name);
this.convertTypeNode(type);
this.popScope();
return;
}
if (ts.isConditionalTypeNode(node)) {
this.convertTypeNode(node.checkType);
this.pushScope();
this.convertTypeNode(node.extendsType);
this.convertTypeNode(node.trueType);
this.convertTypeNode(node.falseType);
this.popScope();
return;
}
if (ts.isIndexedAccessTypeNode(node)) {
this.convertTypeNode(node.objectType);
this.convertTypeNode(node.indexType);
return;
}
if (ts.isFunctionOrConstructorTypeNode(node)) {
this.convertParametersAndType(node);
return;
}
if (ts.isImportTypeNode(node)) {
this.convertImportTypeNode(node);
return;
}
if (ts.isTypeQueryNode(node)) {
this.pushReference(this.convertEntityName(node.exprName));
return;
}
if (ts.isTypeNode(node) && node.kind === ts.SyntaxKind.RestType) {
this.convertTypeNode((node as ts.RestTypeNode).type);
return;
}
if (ts.isTypeNode(node) && node.kind === ts.SyntaxKind.OptionalType) {
this.convertTypeNode((node as ts.OptionalTypeNode).type);
return;
}
// istanbul ignore else
if (ts.isInferTypeNode(node)) {
this.pushTypeVariable(node.typeParameter.name);
return;
} else {
throw new UnsupportedSyntaxError(node);
}
}
// For import type nodes of the form
// `import("./foo").Bar`
// we create the following ESTree equivalent:
// 1. `import * as _ from "./foo";` on the toplevel
// 2. `_.Bar` in our declaration scope
convertImportTypeNode(node: ts.ImportTypeNode) {
// istanbul ignore if
if (!ts.isLiteralTypeNode(node.argument) || !ts.isStringLiteral(node.argument.literal)) {
throw new UnsupportedSyntaxError(node, "inline imports should have a literal argument");
}
const fileId = node.argument.literal.text;
const start = node.getStart() + (node.isTypeOf ? "typeof ".length : 0);
const range = {
start,
end: (node.qualifier ? node.qualifier : node).getEnd(),
};
const importId = this.transformer.addFixupLocation(range);
const importIdRef = withStartEnd(
{
type: "Identifier",
name: importId,
},
range,
);
this.transformer.unshiftStatement({
type: "ImportDeclaration",
specifiers: [
{
type: "ImportNamespaceSpecifier",
local: { type: "Identifier", name: importId },
},
],
source: { type: "Literal", value: fileId },
});
if (node.qualifier && ts.isIdentifier(node.qualifier)) {
this.pushReference(
withStartEnd(
{
type: "MemberExpression",
computed: false,
object: importIdRef,
property: createIdentifier(node.qualifier),
},
range,
),
);
} else {
// we definitely need to do some string manipulation on the source code,
// since rollup will not touch the `import("...")` bit at all.
// also, for *internal* namespace references, we have the same problem
// as with re-exporting references… -_-
this.pushReference(importIdRef);
}
}
convertNamespace(node: ts.ModuleDeclaration) {
this.pushScope();
// istanbul ignore if
if (!node.body || !ts.isModuleBlock(node.body)) {
throw new UnsupportedSyntaxError(node, `namespace must have a "ModuleBlock" body.`);
}
const { statements } = node.body;
// first, hoist all the declarations for correct shadowing
for (const stmt of statements) {
if (
ts.isEnumDeclaration(stmt) ||
ts.isFunctionDeclaration(stmt) ||
ts.isClassDeclaration(stmt) ||
ts.isInterfaceDeclaration(stmt) ||
ts.isTypeAliasDeclaration(stmt) ||
ts.isModuleDeclaration(stmt)
) {
// istanbul ignore else
if (stmt.name && ts.isIdentifier(stmt.name)) {
this.pushTypeVariable(stmt.name);
} else {
throw new UnsupportedSyntaxError(stmt, `non-Identifier name not supported`);
}
continue;
}
if (ts.isVariableStatement(stmt)) {
for (const decl of stmt.declarationList.declarations) {
// istanbul ignore else
if (ts.isIdentifier(decl.name)) {
this.pushTypeVariable(decl.name);
} else {
throw new UnsupportedSyntaxError(decl, `non-Identifier name not supported`);
}
}
continue;
}
// istanbul ignore else
if (ts.isExportDeclaration(stmt)) {
// noop
} else {
throw new UnsupportedSyntaxError(stmt, `namespace child (hoisting) not supported yet`);
}
}
// and then walk all the children like normal…
for (const stmt of statements) {
if (ts.isVariableStatement(stmt)) {
for (const decl of stmt.declarationList.declarations) {
if (decl.type) {
this.convertTypeNode(decl.type);
}
}
continue;
}
if (ts.isFunctionDeclaration(stmt)) {
this.convertParametersAndType(stmt);
continue;
}
if (ts.isInterfaceDeclaration(stmt) || ts.isClassDeclaration(stmt)) {
const typeVariables = this.convertTypeParameters(stmt.typeParameters);
this.convertHeritageClauses(stmt);
this.convertMembers(stmt.members);
this.popScope(typeVariables);
continue;
}
if (ts.isTypeAliasDeclaration(stmt)) {
const typeVariables = this.convertTypeParameters(stmt.typeParameters);
this.convertTypeNode(stmt.type);
this.popScope(typeVariables);
continue;
}
if (ts.isModuleDeclaration(stmt)) {
this.convertNamespace(stmt);
continue;
}
if (ts.isEnumDeclaration(stmt)) {
// noop
continue;
}
// istanbul ignore else
if (ts.isExportDeclaration(stmt)) {
if (stmt.exportClause) {
if (ts.isNamespaceExport(stmt.exportClause)) {
throw new UnsupportedSyntaxError(stmt.exportClause);
}
for (const decl of stmt.exportClause.elements) {
const id = decl.propertyName || decl.name;
this.pushIdentifierReference(id);
}
}
} else {
throw new UnsupportedSyntaxError(stmt, `namespace child (walking) not supported yet`);
}
}
this.popScope();
}
}