-
-
Notifications
You must be signed in to change notification settings - Fork 185
Expand file tree
/
Copy pathcontext.ts
More file actions
269 lines (227 loc) · 10.9 KB
/
context.ts
File metadata and controls
269 lines (227 loc) · 10.9 KB
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
import * as ts from "typescript";
import { CompilerOptions, LuaTarget } from "../../CompilerOptions";
import * as lua from "../../LuaAST";
import { assert, castArray } from "../../utils";
import { unsupportedNodeKind } from "../utils/diagnostics";
import { unwrapVisitorResult, OneToManyVisitorResult } from "../utils/lua-ast";
import { createSafeName } from "../utils/safe-names";
import { ExpressionLikeNode, StatementLikeNode, VisitorMap, FunctionVisitor } from "./visitors";
import { SymbolInfo } from "../utils/symbols";
import { LuaLibFeature } from "../../LuaLib";
import { Scope, ScopeType } from "../utils/scope";
import { ClassSuperInfo } from "../visitors/class";
export const tempSymbolId = -1 as lua.SymbolId;
export interface AllAccessorDeclarations {
firstAccessor: ts.AccessorDeclaration;
getAccessor: ts.GetAccessorDeclaration | undefined;
setAccessor: ts.SetAccessorDeclaration | undefined;
}
export interface EmitResolver {
isValueAliasDeclaration(node: ts.Node): boolean;
isReferencedAliasDeclaration(node: ts.Node, checkChildren?: boolean): boolean;
isTopLevelValueImportEqualsWithEntityName(node: ts.ImportEqualsDeclaration): boolean;
}
export interface TypeCheckerWithEmitResolver extends ts.TypeChecker {
getEmitResolver(sourceFile?: ts.SourceFile, cancellationToken?: ts.CancellationToken): EmitResolver;
}
export class TransformationContext {
public readonly diagnostics: ts.Diagnostic[] = [];
public readonly checker = this.program.getTypeChecker() as TypeCheckerWithEmitResolver;
public readonly resolver: EmitResolver;
public readonly precedingStatementsStack: lua.Statement[][] = [];
public readonly options: CompilerOptions = this.program.getCompilerOptions();
public readonly luaTarget = this.options.luaTarget ?? LuaTarget.Universal;
public readonly isModule = ts.isExternalModule(this.sourceFile);
public readonly isStrict =
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
(this.options.alwaysStrict ?? this.options.strict) ||
(this.isModule && this.options.target !== undefined && this.options.target >= ts.ScriptTarget.ES2015);
constructor(public program: ts.Program, public sourceFile: ts.SourceFile, private visitorMap: VisitorMap) {
// Use `getParseTreeNode` to get original SourceFile node, before it was substituted by custom transformers.
// It's required because otherwise `getEmitResolver` won't use cached diagnostics, produced in `emitWorker`
// and would try to re-analyze the file, which would fail because of replaced nodes.
const originalSourceFile = ts.getParseTreeNode(sourceFile, ts.isSourceFile) ?? sourceFile;
this.resolver = this.checker.getEmitResolver(originalSourceFile);
}
private currentNodeVisitors: ReadonlyArray<FunctionVisitor<ts.Node>> = [];
private currentNodeVisitorsIndex = 0;
private nextTempId = 0;
public transformNode(node: ts.Node): lua.Node[] {
return unwrapVisitorResult(this.transformNodeRaw(node));
}
/** @internal */
public transformNodeRaw(node: ts.Node, isExpression?: boolean) {
// TODO: Move to visitors?
if (
ts.canHaveModifiers(node) &&
node.modifiers?.some(modifier => modifier.kind === ts.SyntaxKind.DeclareKeyword)
) {
return [];
}
const nodeVisitors = this.visitorMap.get(node.kind);
if (!nodeVisitors) {
this.diagnostics.push(unsupportedNodeKind(node, node.kind));
return isExpression ? [lua.createNilLiteral()] : [];
}
const previousNodeVisitors = this.currentNodeVisitors;
const previousNodeVisitorsIndex = this.currentNodeVisitorsIndex;
this.currentNodeVisitors = nodeVisitors;
this.currentNodeVisitorsIndex = nodeVisitors.length - 1;
const visitor = this.currentNodeVisitors[this.currentNodeVisitorsIndex];
const result = visitor(node, this);
this.currentNodeVisitors = previousNodeVisitors;
this.currentNodeVisitorsIndex = previousNodeVisitorsIndex;
return result;
}
public superTransformNode(node: ts.Node): lua.Node[] {
return unwrapVisitorResult(this.doSuperTransformNode(node));
}
private doSuperTransformNode(node: ts.Node): OneToManyVisitorResult<lua.Node> {
if (--this.currentNodeVisitorsIndex < 0) {
throw new Error(`There is no super transform for ${ts.SyntaxKind[node.kind]} visitor`);
}
const visitor = this.currentNodeVisitors[this.currentNodeVisitorsIndex];
return unwrapVisitorResult(visitor(node, this));
}
public transformExpression(node: ExpressionLikeNode): lua.Expression {
const result = this.transformNodeRaw(node, true);
return this.assertIsExpression(node, result);
}
private assertIsExpression(node: ExpressionLikeNode, result: OneToManyVisitorResult<lua.Node>): lua.Expression {
if (result === undefined) {
throw new Error(`Expression visitor for node type ${ts.SyntaxKind[node.kind]} did not return any result.`);
}
if (Array.isArray(result)) {
return result[0] as lua.Expression;
}
return result as lua.Expression;
}
public superTransformExpression(node: ExpressionLikeNode): lua.Expression {
const result = this.doSuperTransformNode(node);
return this.assertIsExpression(node, result);
}
public transformStatements(node: StatementLikeNode | readonly StatementLikeNode[]): lua.Statement[] {
return castArray(node).flatMap(n => {
this.pushPrecedingStatements();
const statements = this.transformNode(n) as lua.Statement[];
const result = this.popPrecedingStatements();
result.push(...statements);
return result;
});
}
public superTransformStatements(node: StatementLikeNode | readonly StatementLikeNode[]): lua.Statement[] {
return castArray(node).flatMap(n => {
this.pushPrecedingStatements();
const statements = this.superTransformNode(n) as lua.Statement[];
const result = this.popPrecedingStatements();
result.push(...statements);
return result;
});
}
public pushPrecedingStatements() {
this.precedingStatementsStack.push([]);
}
public popPrecedingStatements() {
const precedingStatements = this.precedingStatementsStack.pop();
assert(precedingStatements);
return precedingStatements;
}
public addPrecedingStatements(statements: lua.Statement | lua.Statement[]) {
const precedingStatements = this.precedingStatementsStack[this.precedingStatementsStack.length - 1];
assert(precedingStatements);
if (Array.isArray(statements)) {
precedingStatements.push(...statements);
} else {
precedingStatements.push(statements);
}
}
public prependPrecedingStatements(statements: lua.Statement | lua.Statement[]) {
const precedingStatements = this.precedingStatementsStack[this.precedingStatementsStack.length - 1];
assert(precedingStatements);
if (Array.isArray(statements)) {
precedingStatements.unshift(...statements);
} else {
precedingStatements.unshift(statements);
}
}
public createTempName(prefix = "temp") {
prefix = prefix.replace(/^_*/, ""); // Strip leading underscores because createSafeName will add them again
return createSafeName(`${prefix}_${this.nextTempId++}`);
}
private getTempNameForLuaExpression(expression: lua.Expression): string | undefined {
if (lua.isStringLiteral(expression)) {
return expression.value;
} else if (lua.isNumericLiteral(expression)) {
return `_${expression.value.toString()}`;
} else if (lua.isIdentifier(expression)) {
return expression.text;
} else if (lua.isCallExpression(expression)) {
const name = this.getTempNameForLuaExpression(expression.expression);
if (name) {
return `${name}_result`;
}
} else if (lua.isTableIndexExpression(expression)) {
const tableName = this.getTempNameForLuaExpression(expression.table);
const indexName = this.getTempNameForLuaExpression(expression.index);
if (tableName || indexName) {
return `${tableName ?? "table"}_${indexName ?? "index"}`;
}
}
}
public createTempNameForLuaExpression(expression: lua.Expression) {
const name = this.getTempNameForLuaExpression(expression);
const identifier = lua.createIdentifier(this.createTempName(name), undefined, tempSymbolId);
lua.setNodePosition(identifier, lua.getOriginalPos(expression));
return identifier;
}
private getTempNameForNode(node: ts.Node): string | undefined {
if (ts.isStringLiteral(node) || ts.isIdentifier(node) || ts.isMemberName(node)) {
return node.text;
} else if (ts.isNumericLiteral(node)) {
return `_${node.text}`;
} else if (ts.isCallExpression(node)) {
const name = this.getTempNameForNode(node.expression);
if (name) {
return `${name}_result`;
}
} else if (ts.isElementAccessExpression(node) || ts.isPropertyAccessExpression(node)) {
const tableName = this.getTempNameForNode(node.expression);
const indexName = ts.isElementAccessExpression(node)
? this.getTempNameForNode(node.argumentExpression)
: node.name.text;
if (tableName || indexName) {
return `${tableName ?? "table"}_${indexName ?? "index"}`;
}
}
}
public createTempNameForNode(node: ts.Node) {
const name = this.getTempNameForNode(node);
return lua.createIdentifier(this.createTempName(name), node, tempSymbolId);
}
// other utils
private lastSymbolId = 0;
public readonly symbolInfoMap = new Map<lua.SymbolId, SymbolInfo>();
public readonly symbolIdMaps = new Map<ts.Symbol, lua.SymbolId>();
public nextSymbolId(): lua.SymbolId {
return ++this.lastSymbolId as lua.SymbolId;
}
public readonly usedLuaLibFeatures = new Set<LuaLibFeature>();
public readonly scopeStack: Scope[] = [];
private lastScopeId = 0;
public pushScope(type: ScopeType, node: ts.Node): Scope {
const scope: Scope = { type, id: ++this.lastScopeId, node };
this.scopeStack.push(scope);
return scope;
}
public popScope(): Scope {
const scope = this.scopeStack.pop();
assert(scope);
return scope;
}
// Static context -> namespace dictionary keeping the current namespace for each transformation context
// see visitors/namespace.ts
/** @internal */
public currentNamespaces: ts.ModuleDeclaration | undefined;
/** @internal */
public classSuperInfos: ClassSuperInfo[] = [];
}