Skip to content

Commit 00c38b6

Browse files
committed
Allow to specify custom printer through plugins
1 parent e802505 commit 00c38b6

File tree

3 files changed

+47
-29
lines changed

3 files changed

+47
-29
lines changed

src/LuaPrinter.ts

Lines changed: 41 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import * as path from "path";
22
import { Mapping, SourceMapGenerator, SourceNode } from "source-map";
3+
import * as ts from "typescript";
34
import { CompilerOptions, LuaLibImportKind } from "./CompilerOptions";
45
import * as lua from "./LuaAST";
56
import { loadLuaLibFeatures, LuaLibFeature } from "./LuaLib";
@@ -75,6 +76,25 @@ function isSimpleExpression(expression: lua.Expression): boolean {
7576

7677
type SourceChunk = string | SourceNode;
7778

79+
export interface PrintResult {
80+
code: string;
81+
sourceMap: string;
82+
}
83+
84+
export type PrinterFactory = (program: ts.Program, emitHost: EmitHost) => Printer;
85+
export type Printer = LuaPrinter["print"];
86+
87+
export function createPrinter(program: ts.Program, emitHost: EmitHost, factories: PrinterFactory[]): Printer {
88+
if (factories.length === 0) {
89+
const printer = new LuaPrinter(program.getCompilerOptions(), emitHost);
90+
return (...args) => printer.print(...args);
91+
} else if (factories.length === 1) {
92+
return factories[0](program, emitHost);
93+
} else {
94+
throw new Error("Only one plugin can specify 'createPrinter'");
95+
}
96+
}
97+
7898
export class LuaPrinter {
7999
private static operatorMap: { [key in lua.Operator]: string } = {
80100
[lua.SyntaxKind.AdditionOperator]: "+",
@@ -105,36 +125,35 @@ export class LuaPrinter {
105125
};
106126

107127
private currentIndent = "";
108-
private sourceFile = "";
128+
private sourceFile!: string;
109129

110130
public constructor(private options: CompilerOptions, private emitHost: EmitHost) {}
111131

112-
public print(block: lua.Block, luaLibFeatures: Set<LuaLibFeature>, sourceFile = ""): [string, string] {
132+
public print(block: lua.Block, luaLibFeatures: Set<LuaLibFeature>, fileName: string): PrintResult {
113133
// Add traceback lualib if sourcemap traceback option is enabled
114134
if (this.options.sourceMapTraceback) {
115135
luaLibFeatures.add(LuaLibFeature.SourceMapTraceBack);
116136
}
117137

118-
const rootSourceNode = this.printImplementation(block, luaLibFeatures, sourceFile);
119-
120138
const sourceRoot =
121139
this.options.sourceRoot ||
122140
(this.options.outDir ? path.relative(this.options.outDir, this.options.rootDir || process.cwd()) : ".");
123141

124-
const sourceMap = this.buildSourceMap(sourceFile, sourceRoot, rootSourceNode);
142+
const rootSourceNode = this.printImplementation(block, luaLibFeatures, fileName);
143+
const sourceMap = this.buildSourceMap(fileName, sourceRoot, rootSourceNode);
125144

126-
let codeResult = rootSourceNode.toString();
145+
let code = rootSourceNode.toString();
127146

128147
if (this.options.inlineSourceMap) {
129-
codeResult += "\n" + this.printInlineSourceMap(sourceMap);
148+
code += "\n" + this.printInlineSourceMap(sourceMap);
130149
}
131150

132151
if (this.options.sourceMapTraceback) {
133152
const stackTraceOverride = this.printStackTraceOverride(rootSourceNode);
134-
codeResult = codeResult.replace("{#SourceMapTraceback}", stackTraceOverride);
153+
code = code.replace("{#SourceMapTraceback}", stackTraceOverride);
135154
}
136155

137-
return [codeResult, sourceMap.toString()];
156+
return { code, sourceMap: sourceMap.toString() };
138157
}
139158

140159
private printInlineSourceMap(sourceMap: SourceMapGenerator): string {
@@ -168,27 +187,25 @@ export class LuaPrinter {
168187
return `__TS__SourceMapTraceBack(debug.getinfo(1).short_src, ${mapString});`;
169188
}
170189

171-
private printImplementation(block: lua.Block, luaLibFeatures?: Set<LuaLibFeature>, sourceFile = ""): SourceNode {
190+
private printImplementation(block: lua.Block, luaLibFeatures: Set<LuaLibFeature>, sourceFile: string): SourceNode {
172191
let header = "";
173192

174193
if (!this.options.noHeader) {
175194
header += `--[[ Generated with https://github.com/TypeScriptToLua/TypeScriptToLua ]]\n`;
176195
}
177196

178-
if (luaLibFeatures) {
179-
const luaLibImport = this.options.luaLibImport || LuaLibImportKind.Inline;
180-
// Require lualib bundle
181-
if (
182-
(luaLibImport === LuaLibImportKind.Require && luaLibFeatures.size > 0) ||
183-
luaLibImport === LuaLibImportKind.Always
184-
) {
185-
header += `require("lualib_bundle");\n`;
186-
}
187-
// Inline lualib features
188-
else if (luaLibImport === LuaLibImportKind.Inline && luaLibFeatures.size > 0) {
189-
header += "-- Lua Library inline imports\n";
190-
header += loadLuaLibFeatures(luaLibFeatures, this.emitHost);
191-
}
197+
const luaLibImport = this.options.luaLibImport || LuaLibImportKind.Inline;
198+
// Require lualib bundle
199+
if (
200+
(luaLibImport === LuaLibImportKind.Require && luaLibFeatures.size > 0) ||
201+
luaLibImport === LuaLibImportKind.Always
202+
) {
203+
header += `require("lualib_bundle");\n`;
204+
}
205+
// Inline lualib features
206+
else if (luaLibImport === LuaLibImportKind.Inline && luaLibFeatures.size > 0) {
207+
header += "-- Lua Library inline imports\n";
208+
header += loadLuaLibFeatures(luaLibFeatures, this.emitHost);
192209
}
193210

194211
this.sourceFile = path.basename(sourceFile);

src/Transpile.ts

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import * as ts from "typescript";
22
import { CompilerOptions } from "./CompilerOptions";
33
import { Block } from "./LuaAST";
4-
import { LuaPrinter } from "./LuaPrinter";
4+
import { createPrinter } from "./LuaPrinter";
55
import { Plugin } from "./plugins";
66
import { createVisitorMap, transformSourceFile } from "./transformation";
77
import { getCustomTransformers } from "./TSTransformers";
@@ -27,7 +27,6 @@ export interface TranspileOptions {
2727
customTransformers?: ts.CustomTransformers;
2828
plugins?: Plugin[];
2929
emitHost?: EmitHost;
30-
printer?: LuaPrinter;
3130
}
3231

3332
export interface EmitHost {
@@ -40,7 +39,6 @@ export function transpile({
4039
customTransformers = {},
4140
plugins = [],
4241
emitHost = ts.sys,
43-
printer = new LuaPrinter(program.getCompilerOptions(), emitHost),
4442
}: TranspileOptions): TranspileResult {
4543
const options = program.getCompilerOptions() as CompilerOptions;
4644

@@ -79,6 +77,7 @@ export function transpile({
7977
}
8078

8179
const visitorMap = createVisitorMap(plugins.map(p => p.visitors).filter(isNonNull));
80+
const print = createPrinter(program, emitHost, plugins.map(p => p.createPrinter).filter(isNonNull));
8281
const processSourceFile = (sourceFile: ts.SourceFile) => {
8382
const { luaAst, luaLibFeatures, diagnostics: transformDiagnostics } = transformSourceFile(
8483
program,
@@ -87,8 +86,8 @@ export function transpile({
8786
);
8887
diagnostics.push(...transformDiagnostics);
8988
if (!options.noEmit && !options.emitDeclarationOnly) {
90-
const [lua, sourceMap] = printer.print(luaAst, luaLibFeatures, sourceFile.fileName);
91-
updateTranspiledFile(sourceFile.fileName, { luaAst, lua, sourceMap });
89+
const { code, sourceMap } = print(luaAst, luaLibFeatures, sourceFile.fileName);
90+
updateTranspiledFile(sourceFile.fileName, { luaAst, lua: code, sourceMap });
9291
}
9392
};
9493

src/plugins.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
1+
import { PrinterFactory } from "./LuaPrinter";
12
import { Visitors } from "./transformation/context";
23

34
export interface Plugin {
5+
createPrinter?: PrinterFactory;
46
visitors?: Visitors;
57
}

0 commit comments

Comments
 (0)