Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2,792 changes: 707 additions & 2,085 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@
"deep-equal": "^1.0.1",
"fengari": "^0.1.2",
"glob": "^7.1.2",
"nyc": "^11.9.0",
"nyc": "^13.3.0",
"rimraf": "^2.6.3",
"threads": "^0.12.0",
"ts-node": "^7.0.0",
Expand Down
10 changes: 8 additions & 2 deletions src/Compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,14 @@ export function createStringCompilerProgram(
}
if (filename.indexOf(".d.ts") !== -1) {
if (!libCache[filename]) {
libCache[filename] =
fs.readFileSync(path.join(path.dirname(require.resolve("typescript")), filename)).toString();
const typeScriptDir = path.dirname(require.resolve("typescript"));
const filePath = path.join(typeScriptDir, filename);
if (fs.existsSync(filePath)) {
libCache[filename] = fs.readFileSync(filePath).toString();
} else {
const pathWithLibPrefix = path.join(typeScriptDir, "lib." + filename);
libCache[filename] = fs.readFileSync(pathWithLibPrefix).toString();
}
}
return ts.createSourceFile(filename, libCache[filename], ts.ScriptTarget.Latest, false);
}
Expand Down
4 changes: 4 additions & 0 deletions src/LuaLib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ export enum LuaLibFeature {
InstanceOf = "InstanceOf",
Iterator = "Iterator",
Map = "Map",
ObjectAssign = "ObjectAssign",
ObjectEntries = "ObjectEntries",
ObjectKeys = "ObjectKeys",
ObjectValues = "ObjectValues",
Set = "Set",
StringReplace = "StringReplace",
StringSplit = "StringSplit",
Expand Down
92 changes: 62 additions & 30 deletions src/LuaTransformer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1750,7 +1750,7 @@ export class LuaTransformer {
return tstl.createForInStatement(
block,
[this.transformIdentifier(statement.initializer.declarations[0].name as ts.Identifier)],
[this.transformLuaLibFunction(LuaLibFeature.Iterator, iterable)]
[this.transformLuaLibFunction(LuaLibFeature.Iterator, statement.expression, iterable)]
);

} else {
Expand All @@ -1763,7 +1763,7 @@ export class LuaTransformer {
return tstl.createForInStatement(
block,
[valueVariable],
[this.transformLuaLibFunction(LuaLibFeature.Iterator, iterable)]
[this.transformLuaLibFunction(LuaLibFeature.Iterator, statement.expression, iterable)]
);
}
}
Expand Down Expand Up @@ -2122,7 +2122,7 @@ export class LuaTransformer {
// Cannot use instanceof on extension classes
throw TSTLErrors.InvalidInstanceOfExtension(expression);
}
return this.transformLuaLibFunction(LuaLibFeature.InstanceOf, lhs, rhs);
return this.transformLuaLibFunction(LuaLibFeature.InstanceOf, expression, lhs, rhs);

case ts.SyntaxKind.CommaToken:
return this.createImmediatelyInvokedFunctionExpression(
Expand Down Expand Up @@ -2827,23 +2827,25 @@ export class LuaTransformer {
const ownerType = this.checker.getTypeAtLocation(node.expression.expression);

if (ownerType.symbol && ownerType.symbol.escapedName === "Math") {
parameters = this.transformArguments(node.arguments);
return tstl.createCallExpression(
this.transformMathExpression(node.expression.name),
parameters,
this.transformArguments(node.arguments),
node
);
}

if (ownerType.symbol && ownerType.symbol.escapedName === "StringConstructor") {
parameters = this.transformArguments(node.arguments);
return tstl.createCallExpression(
this.transformStringExpression(node.expression.name),
parameters,
this.transformArguments(node.arguments),
node
);
}

if (ownerType.symbol && ownerType.symbol.escapedName === "ObjectConstructor") {
return this.transformObjectCallExpression(node);
}

switch (ownerType.flags) {
case ts.TypeFlags.String:
case ts.TypeFlags.StringLiteral:
Expand Down Expand Up @@ -3170,9 +3172,9 @@ export class LuaTransformer {
const expressionName = expression.name.escapedText as string;
switch (expressionName) {
case "replace":
return this.transformLuaLibFunction(LuaLibFeature.StringReplace, caller, ...params);
return this.transformLuaLibFunction(LuaLibFeature.StringReplace, node, caller, ...params);
case "concat":
return this.transformLuaLibFunction(LuaLibFeature.StringConcat, caller, ...params);
return this.transformLuaLibFunction(LuaLibFeature.StringConcat, node, caller, ...params);
case "indexOf":
const stringExpression =
node.arguments.length === 1
Expand Down Expand Up @@ -3229,7 +3231,7 @@ export class LuaTransformer {
case "toUpperCase":
return this.createStringCall("upper", node, caller);
case "split":
return this.transformLuaLibFunction(LuaLibFeature.StringSplit, caller, ...params);
return this.transformLuaLibFunction(LuaLibFeature.StringSplit, node, caller, ...params);
case "charAt":
const firstParamPlusOne = this.expressionPlusOne(params[0]);
return this.createStringCall("sub", node, caller, firstParamPlusOne, firstParamPlusOne);
Expand Down Expand Up @@ -3258,7 +3260,7 @@ export class LuaTransformer {
}

// Transpile a String._ property
public transformStringExpression(identifier: ts.Identifier): tstl.TableIndexExpression {
public transformStringExpression(identifier: ts.Identifier): ExpressionVisitResult {
const identifierString = identifier.escapedText as string;

switch (identifierString) {
Expand All @@ -3276,46 +3278,71 @@ export class LuaTransformer {
}
}

// Transpile an Object._ property
public transformObjectCallExpression(expression: ts.CallExpression): ExpressionVisitResult {
const method = expression.expression as ts.PropertyAccessExpression;
const parameters = this.transformArguments(expression.arguments);
const caller = this.transformExpression(expression.expression);
const methodName = method.name.escapedText;

switch (methodName) {
case "assign":
return this.transformLuaLibFunction(LuaLibFeature.ObjectAssign, expression, ...parameters);
case "entries":
return this.transformLuaLibFunction(LuaLibFeature.ObjectEntries, expression, ...parameters);
case "keys":
return this.transformLuaLibFunction(LuaLibFeature.ObjectKeys, expression, ...parameters);
case "values":
return this.transformLuaLibFunction(LuaLibFeature.ObjectValues, expression, ...parameters);
default:
throw TSTLErrors.UnsupportedForTarget(
`object property ${methodName}`,
this.options.luaTarget,
expression
);
}
}

public transformArrayCallExpression(node: ts.CallExpression): tstl.CallExpression {
const expression = node.expression as ts.PropertyAccessExpression;
const params = this.transformArguments(node.arguments);
const caller = this.transformExpression(expression.expression);
const expressionName = expression.name.escapedText;
switch (expressionName) {
case "concat":
return this.transformLuaLibFunction(LuaLibFeature.ArrayConcat, caller, ...params);
return this.transformLuaLibFunction(LuaLibFeature.ArrayConcat, node, caller, ...params);
case "push":
return this.transformLuaLibFunction(LuaLibFeature.ArrayPush, caller, ...params);
return this.transformLuaLibFunction(LuaLibFeature.ArrayPush, node, caller, ...params);
case "reverse":
return this.transformLuaLibFunction(LuaLibFeature.ArrayReverse, caller);
return this.transformLuaLibFunction(LuaLibFeature.ArrayReverse, node, caller);
case "shift":
return this.transformLuaLibFunction(LuaLibFeature.ArrayShift, caller);
return this.transformLuaLibFunction(LuaLibFeature.ArrayShift, node, caller);
case "unshift":
return this.transformLuaLibFunction(LuaLibFeature.ArrayUnshift, caller, ...params);
return this.transformLuaLibFunction(LuaLibFeature.ArrayUnshift, node, caller, ...params);
case "sort":
return this.transformLuaLibFunction(LuaLibFeature.ArraySort, caller);
return this.transformLuaLibFunction(LuaLibFeature.ArraySort, node, caller);
case "pop":
return tstl.createCallExpression(
tstl.createTableIndexExpression(tstl.createIdentifier("table"), tstl.createStringLiteral("remove")),
[caller],
node
);
case "forEach":
return this.transformLuaLibFunction(LuaLibFeature.ArrayForEach, caller, ...params);
return this.transformLuaLibFunction(LuaLibFeature.ArrayForEach, node, caller, ...params);
case "indexOf":
return this.transformLuaLibFunction(LuaLibFeature.ArrayIndexOf, caller, ...params);
return this.transformLuaLibFunction(LuaLibFeature.ArrayIndexOf, node, caller, ...params);
case "map":
return this.transformLuaLibFunction(LuaLibFeature.ArrayMap, caller, ...params);
return this.transformLuaLibFunction(LuaLibFeature.ArrayMap, node, caller, ...params);
case "filter":
return this.transformLuaLibFunction(LuaLibFeature.ArrayFilter, caller, ...params);
return this.transformLuaLibFunction(LuaLibFeature.ArrayFilter, node, caller, ...params);
case "some":
return this.transformLuaLibFunction(LuaLibFeature.ArraySome, caller, ...params);
return this.transformLuaLibFunction(LuaLibFeature.ArraySome, node, caller, ...params);
case "every":
return this.transformLuaLibFunction(LuaLibFeature.ArrayEvery, caller, ...params);
return this.transformLuaLibFunction(LuaLibFeature.ArrayEvery, node, caller, ...params);
case "slice":
return this.transformLuaLibFunction(LuaLibFeature.ArraySlice, caller, ...params);
return this.transformLuaLibFunction(LuaLibFeature.ArraySlice, node, caller, ...params);
case "splice":
return this.transformLuaLibFunction(LuaLibFeature.ArraySplice, caller, ...params);
return this.transformLuaLibFunction(LuaLibFeature.ArraySplice, node, caller, ...params);
case "join":
const parameters = node.arguments.length === 0
? [caller, tstl.createStringLiteral(",")]
Expand All @@ -3342,11 +3369,11 @@ export class LuaTransformer {
const expressionName = expression.name.escapedText;
switch (expressionName) {
case "apply":
return this.transformLuaLibFunction(LuaLibFeature.FunctionApply, caller, ...params);
return this.transformLuaLibFunction(LuaLibFeature.FunctionApply, node, caller, ...params);
case "bind":
return this.transformLuaLibFunction(LuaLibFeature.FunctionBind, caller, ...params);
return this.transformLuaLibFunction(LuaLibFeature.FunctionBind, node, caller, ...params);
case "call":
return this.transformLuaLibFunction(LuaLibFeature.FunctionCall, caller, ...params);
return this.transformLuaLibFunction(LuaLibFeature.FunctionCall, node, caller, ...params);
default:
throw TSTLErrors.UnsupportedProperty("function", expressionName as string, node);
}
Expand Down Expand Up @@ -3529,10 +3556,15 @@ export class LuaTransformer {
tstl.createStringLiteral(identifier.text));
}

public transformLuaLibFunction(func: LuaLibFeature, ...params: tstl.Expression[]): tstl.CallExpression {
public transformLuaLibFunction(
func: LuaLibFeature,
tsParent: ts.Expression,
...params: tstl.Expression[]
): tstl.CallExpression
{
this.importLuaLibFeature(func);
const functionIdentifier = tstl.createIdentifier(`__TS__${func}`);
return tstl.createCallExpression(functionIdentifier, params);
return tstl.createCallExpression(functionIdentifier, params, tsParent);
}

public checkForLuaLibType(type: ts.Type): void {
Expand Down
1 change: 0 additions & 1 deletion src/TSHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import * as ts from "typescript";

import {Decorator, DecoratorKind} from "./Decorator";
import * as tstl from "./LuaAST";
import {TSTLErrors} from "./TSTLErrors";

export enum ContextType {
None,
Expand Down
14 changes: 14 additions & 0 deletions src/lualib/ObjectAssign.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// https://tc39.github.io/ecma262/#sec-object.assign
function __TS__ObjectAssign<T extends object>(to: T, ...sources: object[]): T {
if (to === undefined) {
return to;
}

for (const source of sources) {
for (const key in source) {
to[key] = source[key];
}
}

return to;
}
7 changes: 7 additions & 0 deletions src/lualib/ObjectEntries.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
function __TS__ObjectEntries(obj: any): Array<string | number> {
const result = [];
for (const key in obj) {
result[result.length] = [key, obj[key]];
}
return result;
}
7 changes: 7 additions & 0 deletions src/lualib/ObjectKeys.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
function __TS__ObjectKeys(obj: any): Array<string | number> {
const result = [];
for (const key in obj) {
result[result.length] = key;
}
return result;
}
7 changes: 7 additions & 0 deletions src/lualib/ObjectValues.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
function __TS__ObjectValues(obj: any): Array<string | number> {
const result = [];
for (const key in obj) {
result[result.length] = obj[key];
}
return result;
}
86 changes: 85 additions & 1 deletion test/unit/lualib/lualib.spec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { Expect, Test, TestCase } from "alsatian";
import * as ts from "typescript";
import * as util from "../../src/util";
import { LuaLibImportKind } from "../../../src/CompilerOptions";

export class LuaLibArrayTests
export class LuaLibTests
{
@TestCase([0, 1, 2, 3], [1, 2, 3, 4])
@Test("forEach")
Expand Down Expand Up @@ -378,4 +380,86 @@ export class LuaLibArrayTests
// Assert
Expect(result).toBe(expected);
}

@TestCase("{a: 3}", "{}", {a : 3})
@TestCase("{}", "{a: 3}", {a : 3})
@TestCase("{a: 3}", "{a: 5}", {a : 5})
@TestCase("{a: 3}", "{b: 5},{c: 7}", {a : 3, b: 5, c: 7})
@Test("Object.Assign")
public objectAssign(initial: string, parameters: string, expected: object): void {
const jsonResult = util.transpileAndExecute(`
return JSONStringify(Object.assign(${initial},${parameters}));
`);

const result = JSON.parse(jsonResult);
for (const key in expected) {
Expect(result[key]).toBe(expected[key]);
}
}

@TestCase("{}", [])
@TestCase("{abc: 3}", ["abc,3"])
@TestCase("{abc: 3, def: 'xyz'}", ["abc,3", "def,xyz"])
@Test("Object.entries")
public objectEntries(obj: string, expected: string[]): void {
const result = util.transpileAndExecute(`
const obj = ${obj};
return Object.entries(obj).map(e => e.join(",")).join(";");
`, {target: ts.ScriptTarget.ES2018, lib: ["es2018"], luaLibImport: LuaLibImportKind.Require}) as string;

const foundKeys = result.split(";");
if (expected.length === 0) {
Expect(foundKeys.length).toBe(1);
Expect(foundKeys[0]).toBe("");
} else {
Expect(foundKeys.length).toBe(expected.length);
for (const key of expected) {
Expect(foundKeys.indexOf(key) >= 0).toBeTruthy();
}
}
}

@TestCase("{}", [])
@TestCase("{abc: 3}", ["abc"])
@TestCase("{abc: 3, def: 'xyz'}", ["abc", "def"])
@Test("Object.keys")
public objectKeys(obj: string, expected: string[]): void {
const result = util.transpileAndExecute(`
const obj = ${obj};
return Object.keys(obj).join(",");
`) as string;

const foundKeys = result.split(",");
if (expected.length === 0) {
Expect(foundKeys.length).toBe(1);
Expect(foundKeys[0]).toBe("");
} else {
Expect(foundKeys.length).toBe(expected.length);
for (const key of expected) {
Expect(foundKeys.indexOf(key) >= 0).toBeTruthy();
}
}
}

@TestCase("{}", [])
@TestCase("{abc: 'def'}", ["def"])
@TestCase("{abc: 3, def: 'xyz'}", ["3", "xyz"])
@Test("Object.values")
public objectValues(obj: string, expected: string[]): void {
const result = util.transpileAndExecute(`
const obj = ${obj};
return Object.values(obj).join(",");
`, {target: ts.ScriptTarget.ES2018, lib: ["es2018"], luaLibImport: LuaLibImportKind.Require}) as string;

const foundValues = result.split(",");
if (expected.length === 0) {
Expect(foundValues.length).toBe(1);
Expect(foundValues[0]).toBe("");
} else {
Expect(foundValues.length).toBe(expected.length);
for (const key of expected) {
Expect(foundValues.indexOf(key) >= 0).toBeTruthy();
}
}
}
}