forked from TypeScriptToLua/TypeScriptToLua
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlua-ast.ts
More file actions
235 lines (199 loc) · 8.62 KB
/
lua-ast.ts
File metadata and controls
235 lines (199 loc) · 8.62 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
import * as ts from "typescript";
import { LuaTarget } from "../../CompilerOptions";
import * as lua from "../../LuaAST";
import { assert, castArray } from "../../utils";
import { TransformationContext } from "../context";
import { createExportedIdentifier, getIdentifierExportScope } from "./export";
import { peekScope, ScopeType, Scope } from "./scope";
import { transformLuaLibFunction } from "./lualib";
import { LuaLibFeature } from "../../LuaLib";
export type OneToManyVisitorResult<T extends lua.Node> = T | T[] | undefined;
export function unwrapVisitorResult<T extends lua.Node>(result: OneToManyVisitorResult<T>): T[] {
return result === undefined ? [] : castArray(result);
}
export function createSelfIdentifier(tsOriginal?: ts.Node): lua.Identifier {
return lua.createIdentifier("self", tsOriginal, undefined, "this");
}
export function createExportsIdentifier(): lua.Identifier {
return lua.createIdentifier("____exports");
}
export function addToNumericExpression(expression: lua.Expression, change: number): lua.Expression {
if (change === 0) return expression;
const literalValue = getNumberLiteralValue(expression);
if (literalValue !== undefined) {
const newNode = lua.createNumericLiteral(literalValue + change);
lua.setNodePosition(newNode, expression);
return newNode;
}
if (lua.isBinaryExpression(expression)) {
if (
lua.isNumericLiteral(expression.right) &&
((expression.operator === lua.SyntaxKind.SubtractionOperator && expression.right.value === change) ||
(expression.operator === lua.SyntaxKind.AdditionOperator && expression.right.value === -change))
) {
return expression.left;
}
}
return change > 0
? lua.createBinaryExpression(expression, lua.createNumericLiteral(change), lua.SyntaxKind.AdditionOperator)
: lua.createBinaryExpression(expression, lua.createNumericLiteral(-change), lua.SyntaxKind.SubtractionOperator);
}
export function getNumberLiteralValue(expression?: lua.Expression) {
if (!expression) return undefined;
if (lua.isNumericLiteral(expression)) return expression.value;
if (
lua.isUnaryExpression(expression) &&
expression.operator === lua.SyntaxKind.NegationOperator &&
lua.isNumericLiteral(expression.operand)
) {
return -expression.operand.value;
}
return undefined;
}
// Prefer use of transformToImmediatelyInvokedFunctionExpression to maintain correct scope. If you use this directly,
// ensure you push/pop a function scope appropriately to avoid incorrect vararg optimization.
export function createImmediatelyInvokedFunctionExpression(
statements: lua.Statement[],
result: lua.Expression | lua.Expression[],
tsOriginal?: ts.Node
): lua.CallExpression {
const body = [...statements, lua.createReturnStatement(castArray(result))];
const flags = statements.length === 0 ? lua.FunctionExpressionFlags.Inline : lua.FunctionExpressionFlags.None;
const iife = lua.createFunctionExpression(lua.createBlock(body), undefined, undefined, flags);
return lua.createCallExpression(iife, [], tsOriginal);
}
export function createUnpackCall(
context: TransformationContext,
expression: lua.Expression,
tsOriginal?: ts.Node
): lua.Expression {
if (context.luaTarget === LuaTarget.Universal) {
return transformLuaLibFunction(context, LuaLibFeature.Unpack, tsOriginal, expression);
}
const unpack =
context.luaTarget === LuaTarget.Lua51 || context.luaTarget === LuaTarget.LuaJIT
? lua.createIdentifier("unpack")
: lua.createTableIndexExpression(lua.createIdentifier("table"), lua.createStringLiteral("unpack"));
return lua.createCallExpression(unpack, [expression], tsOriginal);
}
export function wrapInTable(...expressions: lua.Expression[]): lua.TableExpression {
const fields = expressions.map(e => lua.createTableFieldExpression(e));
return lua.createTableExpression(fields);
}
export function wrapInToStringForConcat(expression: lua.Expression): lua.Expression {
if (
lua.isStringLiteral(expression) ||
lua.isNumericLiteral(expression) ||
(lua.isBinaryExpression(expression) && expression.operator === lua.SyntaxKind.ConcatOperator)
) {
return expression;
}
return lua.createCallExpression(lua.createIdentifier("tostring"), [expression]);
}
export function createHoistableVariableDeclarationStatement(
context: TransformationContext,
identifier: lua.Identifier,
initializer?: lua.Expression,
tsOriginal?: ts.Node
): lua.AssignmentStatement | lua.VariableDeclarationStatement {
const declaration = lua.createVariableDeclarationStatement(identifier, initializer, tsOriginal);
if (identifier.symbolId !== undefined) {
const scope = peekScope(context);
assert(scope.type !== ScopeType.Switch);
if (!scope.variableDeclarations) {
scope.variableDeclarations = [];
}
scope.variableDeclarations.push(declaration);
}
return declaration;
}
function hasMultipleReferences(scope: Scope, identifiers: lua.Identifier | lua.Identifier[]) {
const scopeSymbols = scope.referencedSymbols;
if (!scopeSymbols) {
return false;
}
const referenceLists = castArray(identifiers).map(i => i.symbolId && scopeSymbols.get(i.symbolId));
return referenceLists.some(symbolRefs => symbolRefs && symbolRefs.length > 1);
}
export function createLocalOrExportedOrGlobalDeclaration(
context: TransformationContext,
lhs: lua.Identifier | lua.Identifier[],
rhs?: lua.Expression | lua.Expression[],
tsOriginal?: ts.Node,
overrideExportScope?: ts.SourceFile | ts.ModuleDeclaration
): lua.Statement[] {
let declaration: lua.VariableDeclarationStatement | undefined;
let assignment: lua.AssignmentStatement | undefined;
const isFunctionDeclaration = tsOriginal !== undefined && ts.isFunctionDeclaration(tsOriginal);
const identifiers = castArray(lhs);
if (identifiers.length === 0) {
return [];
}
const exportScope = overrideExportScope ?? getIdentifierExportScope(context, identifiers[0]);
if (exportScope) {
// exported
if (!rhs) {
return [];
} else {
assignment = lua.createAssignmentStatement(
identifiers.map(identifier => createExportedIdentifier(context, identifier, exportScope)),
rhs,
tsOriginal
);
}
} else {
const scope = peekScope(context);
const isTopLevelVariable = scope.type === ScopeType.File;
if (context.isModule || !isTopLevelVariable) {
if (scope.type === ScopeType.Switch || (!isFunctionDeclaration && hasMultipleReferences(scope, lhs))) {
// Split declaration and assignment of identifiers that reference themselves in their declaration
declaration = lua.createVariableDeclarationStatement(lhs, undefined, tsOriginal);
if (rhs) {
assignment = lua.createAssignmentStatement(lhs, rhs, tsOriginal);
}
} else {
declaration = lua.createVariableDeclarationStatement(lhs, rhs, tsOriginal);
}
// Remember local variable declarations for hoisting later
if (!scope.variableDeclarations) {
scope.variableDeclarations = [];
}
scope.variableDeclarations.push(declaration);
if (scope.type === ScopeType.Switch) {
declaration = undefined;
}
} else if (rhs) {
// global
assignment = lua.createAssignmentStatement(lhs, rhs, tsOriginal);
} else {
return [];
}
}
if (isFunctionDeclaration) {
// Remember function definitions for hoisting later
const functionSymbolId = (lhs as lua.Identifier).symbolId;
const scope = peekScope(context);
if (functionSymbolId && scope.functionDefinitions) {
const definitions = scope.functionDefinitions.get(functionSymbolId);
if (definitions) {
definitions.definition = declaration ?? assignment;
}
}
}
if (declaration && assignment) {
return [declaration, assignment];
} else if (declaration) {
return [declaration];
} else if (assignment) {
return [assignment];
} else {
return [];
}
}
export const createNaN = (tsOriginal?: ts.Node) =>
lua.createBinaryExpression(
lua.createNumericLiteral(0),
lua.createNumericLiteral(0),
lua.SyntaxKind.DivisionOperator,
tsOriginal
);