-
-
Notifications
You must be signed in to change notification settings - Fork 185
Expand file tree
/
Copy pathplugin.ts
More file actions
188 lines (165 loc) · 8.03 KB
/
plugin.ts
File metadata and controls
188 lines (165 loc) · 8.03 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
import { SourceNode } from "source-map";
import * as ts from "typescript";
import * as tstl from "..";
import * as path from "path";
import {
getLualibBundleReturn,
LuaLibFeature,
LuaLibModulesInfo,
luaLibModulesInfoFileName,
resolveRecursiveLualibFeatures,
} from "../LuaLib";
import { EmitHost, ProcessedFile } from "../transpilation/utils";
import {
isExportAlias,
isExportAssignment,
isExportsReturn,
isExportTableDeclaration,
isImport,
isRequire,
} from "./util";
import { createDiagnosticFactoryWithCode } from "../utils";
export const lualibDiagnostic = createDiagnosticFactoryWithCode(200000, (message: string, file?: ts.SourceFile) => ({
messageText: message,
file,
start: file && 0,
length: file && 0,
}));
class LuaLibPlugin implements tstl.Plugin {
// Plugin members
public visitors = {
[ts.SyntaxKind.SourceFile]: this.lualibFileVisitor.bind(this),
};
public printer: tstl.Printer = (program, emitHost, fileName, file) =>
new LuaLibPrinter(emitHost, program, fileName).print(file);
public afterPrint(program: ts.Program, options: tstl.CompilerOptions, emitHost: EmitHost, result: ProcessedFile[]) {
void options;
// Write lualib dependency json
const { result: luaLibModuleInfo, diagnostics } = this.createLuaLibModulesInfo();
const emitBOM = options.emitBOM ?? false;
emitHost.writeFile(
path.join(tstl.getEmitOutDir(program), luaLibModulesInfoFileName),
JSON.stringify(luaLibModuleInfo, null, 2),
emitBOM
);
// Flatten the output folder structure; we do not want to keep the target-specific directories
for (const file of result) {
let outPath = file.fileName;
while (outPath.includes("lualib") && path.basename(path.dirname(outPath)) !== "lualib") {
const upOne = path.join(path.dirname(outPath), "..", path.basename(outPath));
outPath = path.normalize(upOne);
}
file.fileName = outPath;
}
// Create map of result files keyed by their 'lualib name'
const exportedLualibFeatures = new Map(result.map(f => [path.basename(f.fileName).split(".")[0], f.code]));
// Figure out the order required in the bundle by recursively resolving all dependency features
const allFeatures = Object.values(LuaLibFeature) as LuaLibFeature[];
const luaTarget = options.luaTarget ?? tstl.LuaTarget.Universal;
const orderedFeatures = resolveRecursiveLualibFeatures(allFeatures, luaTarget, emitHost, luaLibModuleInfo);
// Concatenate lualib files into bundle with exports table and add lualib_bundle.lua to results
let lualibBundle = orderedFeatures.map(f => exportedLualibFeatures.get(LuaLibFeature[f])).join("\n");
const exports = allFeatures.flatMap(feature => luaLibModuleInfo[feature].exports);
lualibBundle += getLualibBundleReturn(exports);
result.push({ fileName: "lualib_bundle.lua", code: lualibBundle });
return diagnostics;
}
// Internals
protected featureExports: Map<tstl.LuaLibFeature, Set<string>> = new Map();
protected featureDependencies: Map<tstl.LuaLibFeature, Set<tstl.LuaLibFeature>> = new Map();
protected lualibFileVisitor(file: ts.SourceFile, context: tstl.TransformationContext): tstl.File {
const featureName = path.basename(file.fileName, ".ts") as tstl.LuaLibFeature;
if (!(featureName in tstl.LuaLibFeature)) {
context.diagnostics.push(lualibDiagnostic(`File is not a lualib feature: ${featureName}`, file));
}
// Transpile file as normal with tstl
const fileResult = context.superTransformNode(file)[0] as tstl.File;
const usedFeatures = new Set<tstl.LuaLibFeature>(context.usedLuaLibFeatures);
// Get all imports in file
const importNames = new Set<string>();
const imports = file.statements.filter(ts.isImportDeclaration);
for (const { importClause, moduleSpecifier } of imports) {
if (importClause?.namedBindings && ts.isNamedImports(importClause.namedBindings)) {
for (const { name } of importClause.namedBindings.elements) {
importNames.add(name.text);
}
}
// track lualib imports
if (ts.isStringLiteral(moduleSpecifier)) {
const featureName = path.basename(moduleSpecifier.text, ".ts") as tstl.LuaLibFeature;
if (featureName in tstl.LuaLibFeature) {
usedFeatures.add(featureName);
}
}
}
const filteredStatements = fileResult.statements
.filter(
s => !isExportTableDeclaration(s) && !isRequire(s) && !isImport(s, importNames) && !isExportsReturn(s)
)
.map(statement => {
if (isExportAlias(statement)) {
const name = statement.left[0];
const exportName = statement.right[0].index.value;
if (name.text === exportName) return undefined; // Remove "x = x" statements
return tstl.createAssignmentStatement(name, tstl.createIdentifier(exportName));
}
return statement;
})
.filter(statement => statement !== undefined);
const exportNames = filteredStatements.filter(isExportAssignment).map(s => s.left[0].index.value);
if (!filteredStatements.every(isExportAssignment)) {
// If there are local statements, wrap them in a do ... end with exports outside
const exports = tstl.createVariableDeclarationStatement(exportNames.map(k => tstl.createIdentifier(k)));
// transform export assignments to local assignments
const bodyStatements = filteredStatements.map(s =>
isExportAssignment(s)
? tstl.createAssignmentStatement(tstl.createIdentifier(s.left[0].index.value), s.right[0])
: s
);
fileResult.statements = [exports, tstl.createDoStatement(bodyStatements)];
} else {
// transform export assignments to local variable declarations
fileResult.statements = filteredStatements.map(s =>
tstl.createVariableDeclarationStatement(tstl.createIdentifier(s.left[0].index.value), s.right[0])
);
}
// Save dependency information
this.featureExports.set(featureName, new Set(exportNames));
if (usedFeatures.size > 0) {
this.featureDependencies.set(featureName, usedFeatures);
}
return fileResult;
}
protected createLuaLibModulesInfo(): { result: LuaLibModulesInfo; diagnostics: ts.Diagnostic[] } {
const result: Partial<LuaLibModulesInfo> = {};
const diagnostics: ts.Diagnostic[] = [];
for (const feature of Object.values(tstl.LuaLibFeature)) {
const exports = this.featureExports.get(feature);
if (!exports) {
diagnostics.push(lualibDiagnostic(`Missing file for lualib feature: ${feature}`));
continue;
}
const dependencies = this.featureDependencies.get(feature);
result[feature] = {
exports: Array.from(exports),
dependencies: dependencies ? Array.from(dependencies) : undefined,
};
}
return { result: result as LuaLibModulesInfo, diagnostics };
}
}
class LuaLibPrinter extends tstl.LuaPrinter {
// Strip all exports during print
public printTableIndexExpression(expression: tstl.TableIndexExpression): SourceNode {
if (
tstl.isIdentifier(expression.table) &&
expression.table.text === "____exports" &&
tstl.isStringLiteral(expression.index)
) {
return super.printExpression(tstl.createIdentifier(expression.index.value));
}
return super.printTableIndexExpression(expression);
}
}
const pluginInstance = new LuaLibPlugin();
export default pluginInstance;