Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

typescript-to-lua

Package Overview
Dependencies
Maintainers
2
Versions
158
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

typescript-to-lua - npm Package Compare versions

Comparing version 0.0.16 to 0.0.17

136

dist/Compiler.js

@@ -7,4 +7,4 @@ #!/usr/bin/env node

var path = require("path");
var yargs = require("yargs");
// ES6 syntax broken
var minimist = require("minimist");
var dedent = require("dedent");

@@ -39,9 +39,2 @@ var Transpiler_1 = require("./Transpiler");

}
// Copy lualib to target dir
// This isnt run in sync because copyFileSync wont report errors.
fs.copyFile(path.resolve(__dirname, "../dist/lualib/typescript.lua"), path.join(options.outDir, "typescript_lualib.lua"), function (err) {
if (err) {
console.log("ERROR: copying lualib to output.");
}
});
program.getSourceFiles().forEach(function (sourceFile) {

@@ -55,3 +48,4 @@ if (!sourceFile.isDeclarationFile) {

if (options.outDir !== options.rootDir) {
outPath = path.join(options.outDir, path.resolve(sourceFile.fileName).replace(rootDir, ""));
var relativeSourcePath = path.resolve(sourceFile.fileName).replace(path.resolve(rootDir), "");
outPath = path.join(options.outDir, relativeSourcePath);
}

@@ -79,3 +73,13 @@ // change extension

});
process.exit(0);
// Copy lualib to target dir
// This isnt run in sync because copyFileSync wont report errors.
fs.copyFile(path.resolve(__dirname, "../dist/lualib/typescript.lua"), path.join(options.outDir, "typescript_lualib.lua"), function (err) {
if (err) {
console.log("ERROR: copying lualib to output.");
process.exit(1);
}
else {
process.exit(0);
}
});
}

@@ -89,59 +93,63 @@ function printAST(node, indent) {

}
// Removes the option and value form argv
function removeInvalidOptionsFromArgv(commandLine, invalidOptions) {
var result = commandLine.slice();
for (var _i = 0, invalidOptions_1 = invalidOptions; _i < invalidOptions_1.length; _i++) {
var opt = invalidOptions_1[_i];
var index = result.indexOf('--' + opt);
if (index === -1) {
index = result.indexOf('-' + opt);
}
if (index !== -1) {
result.splice(index, 2);
}
}
return result;
}
// Polyfill for report diagnostics
function logError(commandLine) {
function logError(commandLine, tstlOptionKeys) {
var tsInvalidCompilerOptionErrorCode = 5023;
var ignoredErrorCount = 0;
if (commandLine.errors.length !== 0) {
commandLine.errors.forEach(function (err) {
console.log(err.messageText);
// Ignore errors caused by tstl specific compiler options
if (err.code == tsInvalidCompilerOptionErrorCode) {
for (var _i = 0, tstlOptionKeys_1 = tstlOptionKeys; _i < tstlOptionKeys_1.length; _i++) {
var key = tstlOptionKeys_1[_i];
if (err.messageText.toString().indexOf(key) != -1) {
ignoredErrorCount += 1;
}
}
}
else {
console.log(err.messageText);
}
});
process.exit(1);
if (commandLine.errors.length > ignoredErrorCount) {
process.exit(1);
}
}
}
function executeCommandLine(args) {
// Right now luaTarget, version and help are the only cli options, if more are added we should
// add a more advanced custom parser
var argv = minimist(args, {
string: ['l'],
alias: { h: 'help', v: 'version', l: 'luaTarget' },
"default": { luaTarget: 'JIT' },
'--': true,
stopEarly: true
});
var tstlVersion;
try {
tstlVersion = require('../package').version;
var tstlOptions = {
'lt': {
alias: 'luaTarget',
choices: ['JIT', '5.1', '5.2', '5.3'],
"default": 'JIT',
describe: 'Specify Lua target version.',
type: 'string'
},
'ah': {
alias: 'addHeader',
describe: 'Specify if a header will be added to compiled files.',
"default": true,
type: 'boolean'
}
};
var tstlOptionKeys = [];
for (var key in tstlOptions) {
var optionName = key;
if (tstlOptions[key].alias) {
optionName = tstlOptions[key].alias;
}
tstlOptionKeys.push(optionName);
}
catch (e) {
tstlVersion = "0.0.0";
var argv = yargs
.usage(dedent("tstl [options] [files...]\n \n In addition to the options listed below you can also pass options for the typescript compiler (For a list of options use tsc -h).\n \n NOTES:\n - The tsc options might have no effect.\n - Options in tsconfig.json are prioritized."))
.example('tstl path/to/file.ts [...]', 'Compile files')
.example('tstl -p path/to/tsconfig.json', 'Compile project')
.options(tstlOptions)
.argv;
var commandLine = ts.parseCommandLine(args);
logError(commandLine, tstlOptionKeys);
// Add tstl CLI options
for (var _i = 0, tstlOptionKeys_2 = tstlOptionKeys; _i < tstlOptionKeys_2.length; _i++) {
var key = tstlOptionKeys_2[_i];
commandLine.options[key] = argv[key];
}
var helpString = dedent("Version: " + tstlVersion + "\n Syntax: tstl [options] [files...]\n\n In addtion to the options listed below you can also pass options for the\n typescript compiler (For a list of options use tsc -h). NOTE: The tsc options\n might have no effect.\n\n Options:\n --version Show version number\n --luaTarget, -l Specify Lua target version: 'JIT' (Default), '5.1', '5.2',\n '5.3'\n --project, -p Compile the project given the path to its configuration file,\n or to a folder with a 'tsconfig.json'\n --help Show this message\n ");
if (argv.help) {
console.log(helpString);
process.exit(0);
}
if (argv.version) {
console.log("Version: " + require('../package').version);
}
if (!Transpiler_1.LuaTranspiler.AvailableLuaTargets.some(function (val) { return val === argv.luaTarget; })) {
console.error("Invalid lua target valid targets are: " + Transpiler_1.LuaTranspiler.AvailableLuaTargets.toString());
}
// Remove tstl options otherwise ts will emit an error
var sanitizedArgs = removeInvalidOptionsFromArgv(args, ['l', 'luaTarget']);
var commandLine = ts.parseCommandLine(sanitizedArgs);
logError(commandLine);
commandLine.options.luaTarget = argv.luaTarget;
var configPath;

@@ -175,6 +183,8 @@ if (commandLine.options.project) {

commandLine = ts.parseJsonConfigFileContent(configJson.config, ts.sys, path.dirname(configPath), commandLine.options);
// Append lua target to options array since its ignored by TS parsers
// option supplied on CLI is prioritized
if (argv.luaTarget === "JIT" && commandLine.raw.luaTarget !== argv.luaTarget) {
commandLine.options.luaTarget = commandLine.raw.luaTarget;
// Add compiler options that are ignored by TS parsers
// Options supplied in tsconfig are prioritized to allow for CLI defaults
for (var compilerOption in commandLine.raw.compilerOptions) {
if (tstlOptionKeys.indexOf(compilerOption) != -1) {
commandLine.options[compilerOption] = commandLine.raw.compilerOptions[compilerOption];
}
}

@@ -185,3 +195,3 @@ }

}
logError(commandLine);
logError(commandLine, tstlOptionKeys);
compile(commandLine.fileNames, commandLine.options);

@@ -188,0 +198,0 @@ }

@@ -344,4 +344,3 @@ "use strict";

this.genVarCounter++;
result += this.indent + ("local " + jumpTableName + " = {\n");
this.pushIndent();
result += this.indent + ("local " + jumpTableName + " = {}\n");
// If statement to go to right entry label

@@ -351,7 +350,7 @@ clauses.forEach(function (clause, index) {

result += _this.indent + "-- case:\n";
result += _this.indent + ("[" + _this.transpileExpression(clause.expression, true) + "] = function(self)\n");
result += _this.indent + (jumpTableName + "[" + _this.transpileExpression(clause.expression, true) + "] = function()\n");
}
if (ts.isDefaultClause(clause)) {
result += _this.indent + "-- default:\n";
result += _this.indent + ("[\"____default" + _this.genVarCounter + "\"] = function(self)\n");
result += _this.indent + (jumpTableName + "[\"____default" + _this.genVarCounter + "\"] = function()\n");
}

@@ -375,6 +374,6 @@ _this.pushIndent();

if (ts.isCaseClause(nextClause)) {
result += _this.indent + ("self[" + _this.transpileExpression(nextClause.expression, true) + "]()\n");
result += _this.indent + (jumpTableName + "[" + _this.transpileExpression(nextClause.expression, true) + "]()\n");
}
else {
result += _this.indent + ("self[\"____default" + _this.genVarCounter + "\"]()\n");
result += _this.indent + (jumpTableName + "[\"____default" + _this.genVarCounter + "\"]()\n");
}

@@ -387,8 +386,6 @@ }

_this.popIndent();
result += _this.indent + "end,\n";
result += _this.indent + "end\n";
});
this.popIndent();
result += this.indent + "}\n";
result += this.indent + ("if " + jumpTableName + "[" + expression + "] then " + jumpTableName + "[" + expression + "](" + jumpTableName + ")\n");
result += this.indent + ("elseif " + jumpTableName + "[\"____default" + this.genVarCounter + "\"] then " + jumpTableName + "[\"____default" + this.genVarCounter + "\"](" + jumpTableName + ") end\n");
result += this.indent + ("if " + jumpTableName + "[" + expression + "] then " + jumpTableName + "[" + expression + "]()\n");
result += this.indent + ("elseif " + jumpTableName + "[\"____default" + this.genVarCounter + "\"] then " + jumpTableName + "[\"____default" + this.genVarCounter + "\"]() end\n");
result += this.indent + "--------Switch statement end--------\n";

@@ -648,2 +645,5 @@ //Increment counter for next switch statement

break;
case ts.SyntaxKind.InKeyword:
result = rhs + "[" + lhs + "]~=nil";
break;
default:

@@ -667,6 +667,6 @@ throw new TranspileError("Unsupported binary operator kind: " + ts.tokenToString(node.operatorToken.kind), node);

if (ts.isTemplateTail(span.literal)) {
parts.push(expr + ("..\"" + span.literal.text + "\""));
parts.push("tostring(" + expr + ")..\"" + span.literal.text + "\"");
}
else {
parts.push(expr + ("..\"" + span.literal.text + "\""));
parts.push("tostring(" + expr + ")..\"" + span.literal.text + "\"");
}

@@ -717,16 +717,10 @@ });

var expType = this.checker.getTypeAtLocation(node.expression.expression);
// Don't include instance if the type is a namespace
if (expType.symbol && expType.symbol.flags & ts.SymbolFlags.Namespace) {
var callPath_1 = this.transpileExpression(node.expression);
if (expType.symbol && expType.symbol.escapedName == "Math") {
var params_1 = this.transpileArguments(node.arguments);
return callPath_1 + "(" + params_1 + ")";
return this.transpileMathExpression(node.expression.name) + ("(" + params_1 + ")");
}
if (expType.symbol && expType.symbol.escapedName == "Math") {
if (this.transpileExpression(node.expression.expression) === "String") {
var params_2 = this.transpileArguments(node.arguments);
return this.transpileMathExpression(node.expression.name) + ("(" + params_2 + ")");
return this.transpileStringExpression(node.expression.name) + ("(" + params_2 + ")");
}
if (this.transpileExpression(node.expression.expression) === "String") {
var params_3 = this.transpileArguments(node.arguments);
return this.transpileStringExpression(node.expression.name) + ("(" + params_3 + ")");
}
switch (expType.flags) {

@@ -740,28 +734,13 @@ case ts.TypeFlags.String:

}
// Include context parameter if present
if (expType && expType.symbol) {
var funcName = node.expression.name.escapedText;
var funcHolder = TSHelper_1.TSHelper.findMemberHolder(expType, funcName, this.checker);
// ===== EXPERIMENTAL https://github.com/Perryvw/TypescriptToLua/issues/56
if (ts.isParenthesizedExpression(node.expression.expression)
&& (ts.isAsExpression(node.expression.expression.expression)
|| ts.isTypeAssertion(node.expression.expression.expression))
&& ts.isTypeReferenceNode(node.expression.expression.expression.type)) {
var castTypeNode = node.expression.expression.expression.type;
if (this.checker.getTypeFromTypeNode(castTypeNode).symbol.name == funcHolder) {
funcHolder = castTypeNode.getText();
}
}
// ===== END EXPERIMENTAL
if (funcHolder === undefined) {
throw new TranspileError("Could not find func " + funcName + " on " + expType.symbol.name, node);
}
var callPath_2 = funcHolder + "." + funcName;
var params_4 = this.transpileArguments(node.arguments, node.expression.expression);
return callPath_2 + "(" + params_4 + ")";
if (expType.symbol && (expType.symbol.flags & ts.SymbolFlags.Namespace)) {
// Don't replace . with : for namespaces
var callPath_1 = this.transpileExpression(node.expression);
var params_3 = this.transpileArguments(node.arguments);
return callPath_1 + "(" + params_3 + ")";
}
else {
var callPath_3 = this.transpileExpression(node.expression);
var params_5 = this.transpileArguments(node.arguments, node.expression.expression);
return callPath_3 + "(" + params_5 + ")";
// Replace last . with : here
var callPath_2 = this.transpileExpression(node.expression.expression) + ":" + node.expression.name.escapedText;
var params_4 = this.transpileArguments(node.arguments);
return callPath_2 + "(" + params_4 + ")";
}

@@ -771,5 +750,5 @@ }

if (node.expression.kind == ts.SyntaxKind.SuperKeyword) {
var callPath_4 = this.transpileExpression(node.expression);
var params_6 = this.transpileArguments(node.arguments, ts.createNode(ts.SyntaxKind.ThisKeyword));
return "self.__base.constructor(" + params_6 + ")";
var callPath_3 = this.transpileExpression(node.expression);
var params_5 = this.transpileArguments(node.arguments, ts.createNode(ts.SyntaxKind.ThisKeyword));
return "self.__base.constructor(" + params_5 + ")";
}

@@ -837,6 +816,3 @@ var callPath = this.transpileExpression(node.expression);

case "push":
if (node.arguments.length > 1) {
throw new TranspileError("Unsupported array function: " + expression.name.escapedText + " with more than one argument", node);
}
return "table.insert(" + caller + ", " + params + ")";
return "TS_push(" + caller + ", " + params + ")";
case "forEach":

@@ -843,0 +819,0 @@ return "TS_forEach(" + caller + ", " + params + ")";

@@ -28,2 +28,12 @@ "use strict";

};
// Breaks down a mask into all flag names.
TSHelper.enumNames = function (mask, haystack) {
var result = [mask];
for (var name in haystack) {
if ((mask & haystack[name]) != 0 && mask >= haystack[name]) {
result.push(name);
}
}
return result;
};
TSHelper.containsStatement = function (statements, kind) {

@@ -30,0 +40,0 @@ return statements.some(function (statement) { return statement.kind === kind; });

{
"name": "typescript-to-lua",
"license": "MIT",
"version": "0.0.16",
"version": "0.0.17",
"repository": "https://github.com/Perryvw/TypescriptToLua",

@@ -25,6 +25,7 @@ "scripts": {

"dedent": "^0.7.0",
"minimist": "^1.2.0",
"typescript": "^2.7.2"
"typescript": "^2.7.2",
"yargs": "^11.0.0"
},
"devDependencies": {
"@types/yargs": "^11.0.0",
"alsatian": "^2.2.1",

@@ -31,0 +32,0 @@ "codecov": "^3.0.0",

@@ -17,25 +17,47 @@ # TypescriptToLua

`tstl path/to-my-file.ts path/to-my-other-file.ts`
`tstl path/to/file.ts path/to/other-file.ts`
**Compile Projects**
`tstl -p path/to-my/tsconfig.json`
`tstl -p path/to/tsconfig.json`
**Options**
```
Syntax: tstl [options] [files...]
tstl [options] [files...]
In addtion to the options listed below you can also pass options for the
typescript compiler (For a list of options use tsc -h). NOTE: The tsc options
might have no effect.
In addition to the options listed below you can also pass options for the
typescript compiler (For a list of options use tsc -h).
NOTES:
- The tsc options might have no effect.
- Options in tsconfig.json are prioritized.
Options:
--version Show version number
--luaTarget, -l Specify Lua target version: 'JIT' (Default), '5.1', '5.2',
'5.3'
--project, -p Compile the project given the path to its configuration file,
or to a folder with a 'tsconfig.json'
--help Show this message
--help Show help [boolean]
--version Show version number [boolean]
--lt, --luaTarget Specify Lua target version.
[string] [choices: "JIT", "5.1", "5.2", "5.3"] [default: "JIT"]
--lld, --luaLibDir Specify typescript_lualib.lua location relative to outDir.
[string] [default: "./"]
--ah, --addHeader Specify if a header will be added to compiled files.
[boolean] [default: true]
Examples:
tstl path/to/file.ts [...] Compile files
tstl -p path/to/tsconfig.json Compile project
```
**Example tsconfig.json**
```
{
"compilerOptions": {
"noImplicitAny" : true,
"noImplicitThis" : true,
"alwaysStrict" : true,
"strictNullChecks": true,
"luaTarget": "JIT"
}
}
```
## Sublime Text integration

@@ -42,0 +64,0 @@ This compiler works great in combination with the [Sublime Text Typescript plugin](https://github.com/Microsoft/TypeScript-Sublime-Plugin) (available through the package manager as `TypeScript`).

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc