Skip to content

Commit 042115a

Browse files
committed
Merge remote-tracking branch 'upstream/master' into drop-var-declarations
2 parents ad2b224 + 3bd4333 commit 042115a

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

59 files changed

+1452
-1822
lines changed

jest.config.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@ module.exports = {
1818
globals: {
1919
"ts-jest": {
2020
tsConfig: "<rootDir>/test/tsconfig.json",
21-
diagnostics: { warnOnly: !isCI },
21+
isolatedModules: true,
22+
diagnostics: false,
2223
},
2324
},
2425
};

package-lock.json

Lines changed: 821 additions & 1172 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -39,24 +39,24 @@
3939
"node": ">=8.5.0"
4040
},
4141
"dependencies": {
42-
"resolve": "^1.11.0",
42+
"resolve": "^1.13.1",
4343
"source-map": "^0.7.3",
44-
"typescript": "^3.6.2"
44+
"typescript": "^3.7.3"
4545
},
4646
"devDependencies": {
4747
"@types/fs-extra": "^8.0.1",
4848
"@types/glob": "^7.1.1",
49-
"@types/jest": "^24.0.15",
50-
"@types/node": "^11.13.14",
49+
"@types/jest": "^24.0.23",
50+
"@types/node": "^12.12.14",
5151
"@types/resolve": "0.0.8",
5252
"fengari": "^0.1.4",
5353
"fs-extra": "^8.1.0",
54-
"javascript-stringify": "^2.0.0",
55-
"jest": "^24.8.0",
56-
"jest-circus": "^24.8.0",
57-
"prettier": "^1.18.2",
58-
"ts-jest": "^24.0.2",
59-
"ts-node": "^7.0.1",
60-
"tslint": "^5.17.0"
54+
"javascript-stringify": "^2.0.1",
55+
"jest": "^24.9.0",
56+
"jest-circus": "^24.9.0",
57+
"prettier": "^1.19.1",
58+
"ts-jest": "^24.2.0",
59+
"ts-node": "^8.5.4",
60+
"tslint": "^5.20.1"
6161
}
6262
}

src/LuaAST.ts

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@ export function setNodeOriginal<T extends Node>(node: T | undefined, tsOriginal:
172172
}
173173

174174
function getSourcePosition(sourceNode: ts.Node): TextRange | undefined {
175-
if (sourceNode !== undefined && sourceNode.getSourceFile() !== undefined && sourceNode.pos >= 0) {
175+
if (sourceNode.getSourceFile() !== undefined && sourceNode.pos >= 0) {
176176
const { line, character } = ts.getLineAndCharacterOfPosition(
177177
sourceNode.getSourceFile(),
178178
sourceNode.pos + sourceNode.getLeadingTriviaWidth()
@@ -802,12 +802,7 @@ export type FunctionDefinition = (VariableDeclarationStatement | AssignmentState
802802
export function isFunctionDefinition(
803803
statement: VariableDeclarationStatement | AssignmentStatement
804804
): statement is FunctionDefinition {
805-
return (
806-
statement.left.length === 1 &&
807-
statement.right !== undefined &&
808-
statement.right.length === 1 &&
809-
isFunctionExpression(statement.right[0])
810-
);
805+
return statement.left.length === 1 && statement.right?.length === 1 && isFunctionExpression(statement.right[0]);
811806
}
812807

813808
export type InlineFunctionExpression = FunctionExpression & {
@@ -816,8 +811,7 @@ export type InlineFunctionExpression = FunctionExpression & {
816811

817812
export function isInlineFunctionExpression(expression: FunctionExpression): expression is InlineFunctionExpression {
818813
return (
819-
expression.body.statements !== undefined &&
820-
expression.body.statements.length === 1 &&
814+
expression.body.statements?.length === 1 &&
821815
isReturnStatement(expression.body.statements[0]) &&
822816
(expression.body.statements[0] as ReturnStatement).expressions !== undefined &&
823817
(expression.flags & FunctionExpressionFlags.Inline) !== 0

src/LuaLib.ts

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import * as path from "path";
2-
import { EmitHost } from "./Transpile";
2+
import { EmitHost } from "./transpilation";
33

44
export enum LuaLibFeature {
55
ArrayConcat = "ArrayConcat",
@@ -24,6 +24,7 @@ export enum LuaLibFeature {
2424
ArrayFlat = "ArrayFlat",
2525
ArrayFlatMap = "ArrayFlatMap",
2626
ArraySetLength = "ArraySetLength",
27+
Class = "Class",
2728
ClassIndex = "ClassIndex",
2829
ClassNewIndex = "ClassNewIndex",
2930
Decorate = "Decorate",
@@ -36,6 +37,7 @@ export enum LuaLibFeature {
3637
InstanceOfObject = "InstanceOfObject",
3738
Iterator = "Iterator",
3839
Map = "Map",
40+
New = "New",
3941
NewIndex = "NewIndex",
4042
Number = "Number",
4143
NumberIsFinite = "NumberIsFinite",
@@ -67,7 +69,7 @@ export enum LuaLibFeature {
6769
const luaLibDependencies: { [lib in LuaLibFeature]?: LuaLibFeature[] } = {
6870
ArrayFlat: [LuaLibFeature.ArrayConcat],
6971
ArrayFlatMap: [LuaLibFeature.ArrayConcat],
70-
Error: [LuaLibFeature.FunctionCall],
72+
Error: [LuaLibFeature.New, LuaLibFeature.FunctionCall],
7173
InstanceOf: [LuaLibFeature.Symbol],
7274
Iterator: [LuaLibFeature.Symbol],
7375
ObjectFromEntries: [LuaLibFeature.Iterator, LuaLibFeature.Symbol],
@@ -93,12 +95,12 @@ export function loadLuaLibFeatures(features: Iterable<LuaLibFeature>, emitHost:
9395
dependencies.forEach(load);
9496
}
9597

96-
const featureFile = path.resolve(__dirname, `../dist/lualib/${feature}.lua`);
97-
const luaLibFeature = emitHost.readFile(featureFile);
98+
const featurePath = path.resolve(__dirname, `../dist/lualib/${feature}.lua`);
99+
const luaLibFeature = emitHost.readFile(featurePath);
98100
if (luaLibFeature !== undefined) {
99101
result += luaLibFeature + "\n";
100102
} else {
101-
throw new Error(`Could not read lualib feature ../dist/lualib/${feature}.lua`);
103+
throw new Error(`Could not load lualib feature from '${featurePath}'`);
102104
}
103105
}
104106

@@ -108,3 +110,18 @@ export function loadLuaLibFeatures(features: Iterable<LuaLibFeature>, emitHost:
108110

109111
return result;
110112
}
113+
114+
let luaLibBundleContent: string;
115+
export function getLuaLibBundle(emitHost: EmitHost): string {
116+
if (luaLibBundleContent === undefined) {
117+
const lualibPath = path.resolve(__dirname, "../dist/lualib/lualib_bundle.lua");
118+
const result = emitHost.readFile(lualibPath);
119+
if (result !== undefined) {
120+
luaLibBundleContent = result;
121+
} else {
122+
throw new Error(`Could not load lualib bundle from '${lualibPath}'`);
123+
}
124+
}
125+
126+
return luaLibBundleContent;
127+
}

src/LuaPrinter.ts

Lines changed: 51 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { CompilerOptions, LuaLibImportKind } from "./CompilerOptions";
55
import * as lua from "./LuaAST";
66
import { loadLuaLibFeatures, LuaLibFeature } from "./LuaLib";
77
import { isValidLuaIdentifier, luaKeywords } from "./transformation/utils/safe-names";
8-
import { EmitHost } from "./Transpile";
8+
import { EmitHost } from "./transpilation";
99
import { trimExtension } from "./utils";
1010

1111
// https://www.lua.org/pil/2.4.html
@@ -23,8 +23,7 @@ const escapeStringMap: Record<string, string> = {
2323
"\0": "\\0",
2424
};
2525

26-
export const escapeString = (value: string) =>
27-
`"${value.replace(escapeStringRegExp, char => escapeStringMap[char] || char)}"`;
26+
export const escapeString = (value: string) => `"${value.replace(escapeStringRegExp, char => escapeStringMap[char])}"`;
2827

2928
/**
3029
* Checks that a name is valid for use in lua function declaration syntax:
@@ -198,7 +197,7 @@ export class LuaPrinter {
198197
header += `--[[ Generated with https://github.com/TypeScriptToLua/TypeScriptToLua ]]\n`;
199198
}
200199

201-
const luaLibImport = this.options.luaLibImport || LuaLibImportKind.Require;
200+
const luaLibImport = this.options.luaLibImport ?? LuaLibImportKind.Require;
202201
if (
203202
luaLibImport === LuaLibImportKind.Always ||
204203
(luaLibImport === LuaLibImportKind.Require && luaLibFeatures.size > 0)
@@ -341,11 +340,21 @@ export class LuaPrinter {
341340
// Print all local functions as `local function foo()` instead of `local foo = function` to allow recursion
342341
chunks.push(this.printFunctionDefinition(statement));
343342
} else {
344-
chunks.push(...this.joinChunks(", ", statement.left.map(e => this.printExpression(e))));
343+
chunks.push(
344+
...this.joinChunks(
345+
", ",
346+
statement.left.map(e => this.printExpression(e))
347+
)
348+
);
345349

346350
if (statement.right) {
347351
chunks.push(" = ");
348-
chunks.push(...this.joinChunks(", ", statement.right.map(e => this.printExpression(e))));
352+
chunks.push(
353+
...this.joinChunks(
354+
", ",
355+
statement.right.map(e => this.printExpression(e))
356+
)
357+
);
349358
}
350359
}
351360

@@ -369,9 +378,19 @@ export class LuaPrinter {
369378
}
370379
}
371380

372-
chunks.push(...this.joinChunks(", ", statement.left.map(e => this.printExpression(e))));
381+
chunks.push(
382+
...this.joinChunks(
383+
", ",
384+
statement.left.map(e => this.printExpression(e))
385+
)
386+
);
373387
chunks.push(" = ");
374-
chunks.push(...this.joinChunks(", ", statement.right.map(e => this.printExpression(e))));
388+
chunks.push(
389+
...this.joinChunks(
390+
", ",
391+
statement.right.map(e => this.printExpression(e))
392+
)
393+
);
375394

376395
return this.createSourceNode(statement, chunks);
377396
}
@@ -455,8 +474,14 @@ export class LuaPrinter {
455474
}
456475

457476
public printForInStatement(statement: lua.ForInStatement): SourceNode {
458-
const names = this.joinChunks(", ", statement.names.map(i => this.printIdentifier(i)));
459-
const expressions = this.joinChunks(", ", statement.expressions.map(e => this.printExpression(e)));
477+
const names = this.joinChunks(
478+
", ",
479+
statement.names.map(i => this.printIdentifier(i))
480+
);
481+
const expressions = this.joinChunks(
482+
", ",
483+
statement.expressions.map(e => this.printExpression(e))
484+
);
460485

461486
const chunks: SourceChunk[] = [];
462487

@@ -485,7 +510,12 @@ export class LuaPrinter {
485510

486511
const chunks: SourceChunk[] = [];
487512

488-
chunks.push(...this.joinChunks(", ", statement.expressions.map(e => this.printExpression(e))));
513+
chunks.push(
514+
...this.joinChunks(
515+
", ",
516+
statement.expressions.map(e => this.printExpression(e))
517+
)
518+
);
489519

490520
return this.createSourceNode(statement, [this.indent(), "return ", ...chunks]);
491521
}
@@ -585,7 +615,10 @@ export class LuaPrinter {
585615
chunks.push(" ");
586616
const returnNode: SourceChunk[] = [
587617
"return ",
588-
...this.joinChunks(", ", returnStatement.expressions.map(e => this.printExpression(e))),
618+
...this.joinChunks(
619+
", ",
620+
returnStatement.expressions.map(e => this.printExpression(e))
621+
),
589622
];
590623
chunks.push(this.createSourceNode(returnStatement, returnNode));
591624
chunks.push(this.createSourceNode(expression, " end"));
@@ -777,7 +810,12 @@ export class LuaPrinter {
777810
const chunks: SourceChunk[] = [];
778811

779812
if (expressions.every(isSimpleExpression)) {
780-
chunks.push(...this.joinChunks(", ", expressions.map(e => this.printExpression(e))));
813+
chunks.push(
814+
...this.joinChunks(
815+
", ",
816+
expressions.map(e => this.printExpression(e))
817+
)
818+
);
781819
} else {
782820
chunks.push("\n");
783821
this.pushIndent();

src/NoImplicitSelfTransformer.ts

Lines changed: 0 additions & 10 deletions
This file was deleted.

src/cli/information.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ export function getHelpString(): string {
1919

2020
result += "Options:\n";
2121
for (const option of optionDeclarations) {
22-
const aliasStrings = (option.aliases || []).map(a => "-" + a);
22+
const aliasStrings = (option.aliases ?? []).map(a => "-" + a);
2323
const optionString = aliasStrings.concat(["--" + option.name]).join("|");
2424

2525
const valuesHint = option.type === "enum" ? option.choices.join("|") : option.type;

src/index.ts

Lines changed: 1 addition & 90 deletions
Original file line numberDiff line numberDiff line change
@@ -1,99 +1,10 @@
1-
import * as fs from "fs";
2-
import * as path from "path";
3-
import * as ts from "typescript";
4-
import { parseConfigFileWithSystem } from "./cli/tsconfig";
5-
import { CompilerOptions } from "./CompilerOptions";
6-
import { emitTranspiledFiles, OutputFile } from "./Emit";
7-
import { transpile, TranspiledFile, TranspileResult } from "./Transpile";
8-
91
export { version } from "./cli/information";
102
export { parseCommandLine, ParsedCommandLine, updateParsedConfigFile } from "./cli/parse";
113
export * from "./cli/report";
124
export * from "./CompilerOptions";
13-
export * from "./Emit";
145
export * from "./LuaAST";
156
export { LuaLibFeature } from "./LuaLib";
167
export * from "./LuaPrinter";
178
export * from "./transformation/context";
189
export { TranspileError } from "./transformation/utils/errors";
19-
export * from "./Transpile";
20-
21-
export interface TranspileFilesResult {
22-
diagnostics: ts.Diagnostic[];
23-
emitResult: OutputFile[];
24-
}
25-
26-
export function transpileFiles(rootNames: string[], options: CompilerOptions = {}): TranspileFilesResult {
27-
const program = ts.createProgram(rootNames, options);
28-
const { transpiledFiles, diagnostics: transpileDiagnostics } = transpile({ program });
29-
const emitResult = emitTranspiledFiles(program, transpiledFiles);
30-
31-
const diagnostics = ts.sortAndDeduplicateDiagnostics([
32-
...ts.getPreEmitDiagnostics(program),
33-
...transpileDiagnostics,
34-
]);
35-
36-
return { diagnostics: [...diagnostics], emitResult };
37-
}
38-
39-
export function transpileProject(configFileName: string, optionsToExtend?: CompilerOptions): TranspileFilesResult {
40-
const parseResult = parseConfigFileWithSystem(configFileName, optionsToExtend);
41-
if (parseResult.errors.length > 0) {
42-
return { diagnostics: parseResult.errors, emitResult: [] };
43-
}
44-
45-
return transpileFiles(parseResult.fileNames, parseResult.options);
46-
}
47-
48-
const libCache: { [key: string]: ts.SourceFile } = {};
49-
50-
/** @internal */
51-
export function createVirtualProgram(input: Record<string, string>, options: CompilerOptions = {}): ts.Program {
52-
const compilerHost: ts.CompilerHost = {
53-
fileExists: () => true,
54-
getCanonicalFileName: fileName => fileName,
55-
getCurrentDirectory: () => "",
56-
getDefaultLibFileName: ts.getDefaultLibFileName,
57-
readFile: () => "",
58-
getNewLine: () => "\n",
59-
useCaseSensitiveFileNames: () => false,
60-
writeFile: () => {},
61-
62-
getSourceFile: filename => {
63-
if (filename in input) {
64-
return ts.createSourceFile(filename, input[filename], ts.ScriptTarget.Latest, false);
65-
}
66-
67-
if (filename.startsWith("lib.")) {
68-
if (libCache[filename]) return libCache[filename];
69-
const typeScriptDir = path.dirname(require.resolve("typescript"));
70-
const filePath = path.join(typeScriptDir, filename);
71-
const content = fs.readFileSync(filePath, "utf8");
72-
73-
libCache[filename] = ts.createSourceFile(filename, content, ts.ScriptTarget.Latest, false);
74-
75-
return libCache[filename];
76-
}
77-
},
78-
};
79-
80-
return ts.createProgram(Object.keys(input), options, compilerHost);
81-
}
82-
83-
export function transpileVirtualProject(files: Record<string, string>, options: CompilerOptions = {}): TranspileResult {
84-
const program = createVirtualProgram(files, options);
85-
const result = transpile({ program });
86-
const diagnostics = ts.sortAndDeduplicateDiagnostics([...ts.getPreEmitDiagnostics(program), ...result.diagnostics]);
87-
88-
return { ...result, diagnostics: [...diagnostics] };
89-
}
90-
91-
export interface TranspileStringResult {
92-
diagnostics: ts.Diagnostic[];
93-
file?: TranspiledFile;
94-
}
95-
96-
export function transpileString(main: string, options: CompilerOptions = {}): TranspileStringResult {
97-
const { diagnostics, transpiledFiles } = transpileVirtualProject({ "main.ts": main }, options);
98-
return { diagnostics, file: transpiledFiles.find(({ fileName }) => fileName === "main.ts") };
99-
}
10+
export * from "./transpilation";

0 commit comments

Comments
 (0)