-
-
Notifications
You must be signed in to change notification settings - Fork 185
Expand file tree
/
Copy pathLuaLib.ts
More file actions
313 lines (282 loc) · 10.7 KB
/
LuaLib.ts
File metadata and controls
313 lines (282 loc) · 10.7 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
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
import * as path from "path";
import { EmitHost } from "./transpilation";
import * as lua from "./LuaAST";
import { LuaTarget } from "./CompilerOptions";
import { getOrUpdate } from "./utils";
export enum LuaLibFeature {
ArrayAt = "ArrayAt",
ArrayConcat = "ArrayConcat",
ArrayEntries = "ArrayEntries",
ArrayEvery = "ArrayEvery",
ArrayFill = "ArrayFill",
ArrayFilter = "ArrayFilter",
ArrayForEach = "ArrayForEach",
ArrayFind = "ArrayFind",
ArrayFindIndex = "ArrayFindIndex",
ArrayFrom = "ArrayFrom",
ArrayIncludes = "ArrayIncludes",
ArrayIndexOf = "ArrayIndexOf",
ArrayIsArray = "ArrayIsArray",
ArrayJoin = "ArrayJoin",
ArrayMap = "ArrayMap",
ArrayPush = "ArrayPush",
ArrayPushArray = "ArrayPushArray",
ArrayReduce = "ArrayReduce",
ArrayReduceRight = "ArrayReduceRight",
ArrayReverse = "ArrayReverse",
ArrayUnshift = "ArrayUnshift",
ArraySort = "ArraySort",
ArraySlice = "ArraySlice",
ArraySome = "ArraySome",
ArraySplice = "ArraySplice",
ArrayToObject = "ArrayToObject",
ArrayFlat = "ArrayFlat",
ArrayFlatMap = "ArrayFlatMap",
ArraySetLength = "ArraySetLength",
ArrayToReversed = "ArrayToReversed",
ArrayToSorted = "ArrayToSorted",
ArrayToSpliced = "ArrayToSpliced",
ArrayWith = "ArrayWith",
Await = "Await",
Class = "Class",
ClassExtends = "ClassExtends",
CloneDescriptor = "CloneDescriptor",
CountVarargs = "CountVarargs",
Decorate = "Decorate",
DecorateLegacy = "DecorateLegacy",
DecorateParam = "DecorateParam",
Delete = "Delete",
DelegatedYield = "DelegatedYield",
DescriptorGet = "DescriptorGet",
DescriptorSet = "DescriptorSet",
Error = "Error",
FunctionBind = "FunctionBind",
Generator = "Generator",
InstanceOf = "InstanceOf",
InstanceOfObject = "InstanceOfObject",
Iterator = "Iterator",
LuaIteratorSpread = "LuaIteratorSpread",
Map = "Map",
MapGroupBy = "MapGroupBy",
Match = "Match",
MathAtan2 = "MathAtan2",
MathModf = "MathModf",
MathSign = "MathSign",
MathTrunc = "MathTrunc",
New = "New",
Number = "Number",
NumberIsFinite = "NumberIsFinite",
NumberIsInteger = "NumberIsInteger",
NumberIsNaN = "NumberIsNaN",
NumberParseInt = "ParseInt",
NumberParseFloat = "ParseFloat",
NumberToString = "NumberToString",
NumberToFixed = "NumberToFixed",
ObjectAssign = "ObjectAssign",
ObjectDefineProperty = "ObjectDefineProperty",
ObjectEntries = "ObjectEntries",
ObjectFromEntries = "ObjectFromEntries",
ObjectGetOwnPropertyDescriptor = "ObjectGetOwnPropertyDescriptor",
ObjectGetOwnPropertyDescriptors = "ObjectGetOwnPropertyDescriptors",
ObjectGroupBy = "ObjectGroupBy",
ObjectKeys = "ObjectKeys",
ObjectRest = "ObjectRest",
ObjectValues = "ObjectValues",
ParseFloat = "ParseFloat",
ParseInt = "ParseInt",
Promise = "Promise",
PromiseAll = "PromiseAll",
PromiseAllSettled = "PromiseAllSettled",
PromiseAny = "PromiseAny",
PromiseRace = "PromiseRace",
Set = "Set",
SetDescriptor = "SetDescriptor",
SparseArrayNew = "SparseArrayNew",
SparseArrayPush = "SparseArrayPush",
SparseArraySpread = "SparseArraySpread",
WeakMap = "WeakMap",
WeakSet = "WeakSet",
SourceMapTraceBack = "SourceMapTraceBack",
Spread = "Spread",
StringAccess = "StringAccess",
StringCharAt = "StringCharAt",
StringCharCodeAt = "StringCharCodeAt",
StringEndsWith = "StringEndsWith",
StringIncludes = "StringIncludes",
StringPadEnd = "StringPadEnd",
StringPadStart = "StringPadStart",
StringReplace = "StringReplace",
StringReplaceAll = "StringReplaceAll",
StringSlice = "StringSlice",
StringSplit = "StringSplit",
StringStartsWith = "StringStartsWith",
StringSubstr = "StringSubstr",
StringSubstring = "StringSubstring",
StringTrim = "StringTrim",
StringTrimEnd = "StringTrimEnd",
StringTrimStart = "StringTrimStart",
Symbol = "Symbol",
SymbolRegistry = "SymbolRegistry",
TypeOf = "TypeOf",
Unpack = "Unpack",
Using = "Using",
UsingAsync = "UsingAsync",
}
export interface LuaLibFeatureInfo {
dependencies?: LuaLibFeature[];
exports: string[];
}
export type LuaLibModulesInfo = Record<LuaLibFeature, LuaLibFeatureInfo>;
export function resolveLuaLibDir(luaTarget: LuaTarget) {
const luaLibDir = luaTarget === LuaTarget.Lua50 ? "5.0" : "universal";
return path.resolve(__dirname, path.join("..", "dist", "lualib", luaLibDir));
}
export const luaLibModulesInfoFileName = "lualib_module_info.json";
const luaLibModulesInfo = new Map<LuaTarget, LuaLibModulesInfo>();
export function getLuaLibModulesInfo(luaTarget: LuaTarget, emitHost: EmitHost): LuaLibModulesInfo {
if (!luaLibModulesInfo.has(luaTarget)) {
const lualibPath = path.join(resolveLuaLibDir(luaTarget), luaLibModulesInfoFileName);
const result = emitHost.readFile(lualibPath);
if (result !== undefined) {
luaLibModulesInfo.set(luaTarget, JSON.parse(result) as LuaLibModulesInfo);
} else {
throw new Error(`Could not load lualib dependencies from '${lualibPath}'`);
}
}
return luaLibModulesInfo.get(luaTarget)!;
}
// This caches the names of lualib exports to their LuaLibFeature, avoiding a linear search for every lookup
const lualibExportToFeature = new Map<LuaTarget, ReadonlyMap<string, LuaLibFeature>>();
export function getLuaLibExportToFeatureMap(
luaTarget: LuaTarget,
emitHost: EmitHost
): ReadonlyMap<string, LuaLibFeature> {
if (!lualibExportToFeature.has(luaTarget)) {
const luaLibModulesInfo = getLuaLibModulesInfo(luaTarget, emitHost);
const map = new Map<string, LuaLibFeature>();
for (const [feature, info] of Object.entries(luaLibModulesInfo)) {
for (const exportName of info.exports) {
map.set(exportName, feature as LuaLibFeature);
}
}
lualibExportToFeature.set(luaTarget, map);
}
return lualibExportToFeature.get(luaTarget)!;
}
const lualibFeatureCache = new Map<LuaTarget, Map<LuaLibFeature, string>>();
export function readLuaLibFeature(feature: LuaLibFeature, luaTarget: LuaTarget, emitHost: EmitHost): string {
const featureMap = getOrUpdate(lualibFeatureCache, luaTarget, () => new Map());
if (!featureMap.has(feature)) {
const featurePath = path.join(resolveLuaLibDir(luaTarget), `${feature}.lua`);
const luaLibFeature = emitHost.readFile(featurePath);
if (luaLibFeature === undefined) {
throw new Error(`Could not load lualib feature from '${featurePath}'`);
}
featureMap.set(feature, luaLibFeature);
}
return featureMap.get(feature)!;
}
export function resolveRecursiveLualibFeatures(
features: Iterable<LuaLibFeature>,
luaTarget: LuaTarget,
emitHost: EmitHost,
luaLibModulesInfo: LuaLibModulesInfo = getLuaLibModulesInfo(luaTarget, emitHost)
): LuaLibFeature[] {
const loadedFeatures = new Set<LuaLibFeature>();
const result: LuaLibFeature[] = [];
function load(feature: LuaLibFeature): void {
if (loadedFeatures.has(feature)) return;
loadedFeatures.add(feature);
const dependencies = luaLibModulesInfo[feature]?.dependencies;
if (dependencies) {
dependencies.forEach(load);
}
result.push(feature);
}
for (const feature of features) {
load(feature);
}
return result;
}
export function loadInlineLualibFeatures(
features: Iterable<LuaLibFeature>,
luaTarget: LuaTarget,
emitHost: EmitHost
): string {
return resolveRecursiveLualibFeatures(features, luaTarget, emitHost)
.map(feature => readLuaLibFeature(feature, luaTarget, emitHost))
.join("\n");
}
export function loadImportedLualibFeatures(
features: Iterable<LuaLibFeature>,
luaTarget: LuaTarget,
emitHost: EmitHost
): lua.Statement[] {
const luaLibModuleInfo = getLuaLibModulesInfo(luaTarget, emitHost);
const imports = Array.from(features).flatMap(feature => luaLibModuleInfo[feature].exports);
if (imports.length === 0) {
return [];
}
const requireCall = lua.createCallExpression(lua.createIdentifier("require"), [
lua.createStringLiteral("lualib_bundle"),
]);
const luaLibId = lua.createIdentifier("____lualib");
const importStatement = lua.createVariableDeclarationStatement(luaLibId, requireCall);
const statements: lua.Statement[] = [importStatement];
// local <export> = ____luaLib.<export>
for (const item of imports) {
statements.push(
lua.createVariableDeclarationStatement(
lua.createIdentifier(item),
lua.createTableIndexExpression(luaLibId, lua.createStringLiteral(item))
)
);
}
return statements;
}
const luaLibBundleContent = new Map<string, string>();
export function getLuaLibBundle(luaTarget: LuaTarget, emitHost: EmitHost): string {
const lualibPath = path.join(resolveLuaLibDir(luaTarget), "lualib_bundle.lua");
if (!luaLibBundleContent.has(lualibPath)) {
const result = emitHost.readFile(lualibPath);
if (result !== undefined) {
luaLibBundleContent.set(lualibPath, result);
} else {
throw new Error(`Could not load lualib bundle from '${lualibPath}'`);
}
}
return luaLibBundleContent.get(lualibPath) as string;
}
export function getLualibBundleReturn(exportedValues: string[]): string {
return `\nreturn {\n${exportedValues.map(exportName => ` ${exportName} = ${exportName}`).join(",\n")}\n}\n`;
}
export function buildMinimalLualibBundle(
features: Iterable<LuaLibFeature>,
luaTarget: LuaTarget,
emitHost: EmitHost
): string {
const code = loadInlineLualibFeatures(features, luaTarget, emitHost);
const moduleInfo = getLuaLibModulesInfo(luaTarget, emitHost);
const exports = Array.from(features).flatMap(feature => moduleInfo[feature].exports);
return code + getLualibBundleReturn(exports);
}
export function findUsedLualibFeatures(
luaTarget: LuaTarget,
emitHost: EmitHost,
luaContents: string[]
): Set<LuaLibFeature> {
const features = new Set<LuaLibFeature>();
const exportToFeatureMap = getLuaLibExportToFeatureMap(luaTarget, emitHost);
for (const lua of luaContents) {
const regex = /^local (\w+) = ____lualib\.(\w+)$/gm;
while (true) {
const match = regex.exec(lua);
if (!match) break;
const [, localName, exportName] = match;
if (localName !== exportName) continue;
const feature = exportToFeatureMap.get(exportName);
if (feature) features.add(feature);
}
}
return features;
}