Skip to content

Commit d407ca6

Browse files
committed
Some minor refactors
1 parent 6a3af12 commit d407ca6

8 files changed

Lines changed: 34 additions & 35 deletions

File tree

src/LuaAST.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
// Simplified Lua AST based roughly on http://lua-users.org/wiki/MetaLuaAbstractSyntaxTree,
2-
// https://www.lua.org/manual/5.3/manual.html (9 – The Complete Syntax of Lua) and the TS AST implementation
2+
// https://www.lua.org/manual/5.3/manual.html#9 and the TS AST implementation
33

44
// We can elide a lot of nodes especially tokens and keywords
5-
// because we dont create the AST from text
5+
// because we don't create the AST from text
66

77
import * as ts from "typescript";
88

src/LuaPrinter.ts

Lines changed: 14 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -31,10 +31,7 @@ const escapeString = (value: string) => `"${value.replace(escapeStringRegExp, ch
3131
* `foo.bar` => passes (`function foo.bar()` is valid)
3232
* `getFoo().bar` => fails (`function getFoo().bar()` would be illegal)
3333
*/
34-
function isValidLuaFunctionDeclarationName(str: string): boolean {
35-
const match = str.match(/[a-zA-Z0-9_\.]+/);
36-
return match !== null && match[0] === str;
37-
}
34+
const isValidLuaFunctionDeclarationName = (str: string) => /^[a-zA-Z0-9_\.]+$/.test(str);
3835

3936
/**
4037
* Returns true if expression contains no function calls.
@@ -172,24 +169,21 @@ export class LuaPrinter {
172169
}
173170

174171
private printStackTraceOverride(rootNode: SourceNode): string {
175-
let line = 1;
176-
const map: { [line: number]: number } = {};
172+
let currentLine = 1;
173+
const map: Record<number, number> = {};
177174
rootNode.walk((chunk, mappedPosition) => {
178175
if (mappedPosition.line !== undefined && mappedPosition.line > 0) {
179-
if (map[line] === undefined) {
180-
map[line] = mappedPosition.line;
176+
if (map[currentLine] === undefined) {
177+
map[currentLine] = mappedPosition.line;
181178
} else {
182-
map[line] = Math.min(map[line], mappedPosition.line);
179+
map[currentLine] = Math.min(map[currentLine], mappedPosition.line);
183180
}
184181
}
185-
line += chunk.split("\n").length - 1;
186-
});
187182

188-
const mapItems = [];
189-
for (const lineNr in map) {
190-
mapItems.push(`["${lineNr}"] = ${map[lineNr]}`);
191-
}
183+
currentLine += chunk.split("\n").length - 1;
184+
});
192185

186+
const mapItems = Object.entries(map).map(([line, original]) => `["${line}"] = ${original}`);
193187
const mapString = "{" + mapItems.join(",") + "}";
194188

195189
return `__TS__SourceMapTraceBack(debug.getinfo(1).short_src, ${mapString});`;
@@ -203,15 +197,14 @@ export class LuaPrinter {
203197
}
204198

205199
const luaLibImport = this.options.luaLibImport || LuaLibImportKind.Inline;
206-
// Require lualib bundle
207200
if (
208-
(luaLibImport === LuaLibImportKind.Require && luaLibFeatures.size > 0) ||
209-
luaLibImport === LuaLibImportKind.Always
201+
luaLibImport === LuaLibImportKind.Always ||
202+
(luaLibImport === LuaLibImportKind.Require && luaLibFeatures.size > 0)
210203
) {
204+
// Require lualib bundle
211205
header += `require("lualib_bundle");\n`;
212-
}
213-
// Inline lualib features
214-
else if (luaLibImport === LuaLibImportKind.Inline && luaLibFeatures.size > 0) {
206+
} else if (luaLibImport === LuaLibImportKind.Inline && luaLibFeatures.size > 0) {
207+
// Inline lualib features
215208
header += "-- Lua Library inline imports\n";
216209
header += loadLuaLibFeatures(luaLibFeatures, this.emitHost);
217210
}

src/Transpile.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import * as ts from "typescript";
22
import { CompilerOptions } from "./CompilerOptions";
33
import { Block } from "./LuaAST";
44
import { createPrinter } from "./LuaPrinter";
5-
import { Plugin } from "./plugins";
5+
import { getPlugins, Plugin } from "./plugins";
66
import { createVisitorMap, transformSourceFile } from "./transformation";
77
import { getCustomTransformers } from "./TSTransformers";
88
import { isNonNull } from "./utils";
@@ -37,7 +37,7 @@ export function transpile({
3737
program,
3838
sourceFiles: targetSourceFiles,
3939
customTransformers = {},
40-
plugins = [],
40+
plugins: pluginsFromOptions = [],
4141
emitHost = ts.sys,
4242
}: TranspileOptions): TranspileResult {
4343
const options = program.getCompilerOptions() as CompilerOptions;
@@ -76,6 +76,7 @@ export function transpile({
7676
}
7777
}
7878

79+
const plugins = getPlugins(program, diagnostics, pluginsFromOptions);
7980
const visitorMap = createVisitorMap(plugins.map(p => p.visitors).filter(isNonNull));
8081
const printer = createPrinter(plugins.map(p => p.printer).filter(isNonNull));
8182
const processSourceFile = (sourceFile: ts.SourceFile) => {

src/plugins.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import * as ts from "typescript";
12
import { Printer } from "./LuaPrinter";
23
import { Visitors } from "./transformation/context";
34

@@ -16,3 +17,11 @@ export interface Plugin {
1617
*/
1718
printer?: Printer;
1819
}
20+
21+
export function getPlugins(
22+
_program: ts.Program,
23+
_diagnostics: ts.Diagnostic[],
24+
pluginsFromOptions: Plugin[]
25+
): Plugin[] {
26+
return pluginsFromOptions;
27+
}

src/transformation/builtins/console.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,7 @@ import { TransformationContext } from "../context";
44
import { PropertyCallExpression, transformArguments } from "../transformers/call";
55
import { UnsupportedProperty } from "../utils/errors";
66

7-
const isStringFormatTemplate = (expression: ts.Expression) =>
8-
ts.isStringLiteral(expression) && expression.text.match(/\%/g) !== null;
7+
const isStringFormatTemplate = (node: ts.Expression) => ts.isStringLiteral(node) && node.text.includes("%");
98

109
export function transformConsoleCall(
1110
context: TransformationContext,

src/transformation/utils/annotations.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,9 @@ export interface Annotation {
2626
}
2727

2828
function createAnnotation(name: string, args: string[]): Annotation | undefined {
29-
const annotationKind = Object.values(AnnotationKind).find(k => k.toLowerCase() === name.toLowerCase());
30-
if (annotationKind !== undefined) {
31-
return { kind: annotationKind, args };
29+
const kind = Object.values(AnnotationKind).find(k => k.toLowerCase() === name.toLowerCase());
30+
if (kind !== undefined) {
31+
return { kind, args };
3232
}
3333
}
3434

src/transformation/utils/safe-names.ts

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,10 +51,7 @@ export const luaBuiltins: ReadonlySet<string> = new Set([
5151
"unpack",
5252
]);
5353

54-
export function isValidLuaIdentifier(str: string): boolean {
55-
const match = str.match(/[a-zA-Z_][a-zA-Z0-9_]*/);
56-
return match !== null && match[0] === str;
57-
}
54+
export const isValidLuaIdentifier = (str: string) => /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(str);
5855

5956
export const isUnsafeName = (name: string) =>
6057
luaKeywords.has(name) || luaBuiltins.has(name) || !isValidLuaIdentifier(name);

src/transformation/utils/typescript/nodes.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ export function isDestructuringAssignment(node: ts.Node): node is ts.Destructuri
1313
}
1414

1515
export function isAmbientNode(node: ts.Declaration): boolean {
16-
return !((ts.getCombinedModifierFlags(node) & ts.ModifierFlags.Ambient) === 0);
16+
return (ts.getCombinedModifierFlags(node) & ts.ModifierFlags.Ambient) !== 0;
1717
}
1818

1919
export function isDeclaration(node: ts.Node): node is ts.Declaration {

0 commit comments

Comments
 (0)