Socket
Socket
Sign inDemoInstall

typescript-to-lua

Package Overview
Dependencies
Maintainers
2
Versions
157
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 1.6.3 to 1.7.0

dist/measure-performance.d.ts

5

dist/cli/parse.js

@@ -82,2 +82,7 @@ "use strict";

},
{
name: "measurePerformance",
description: "Measure performance of the tstl compiler.",
type: "boolean",
},
];

@@ -84,0 +89,0 @@ function updateParsedConfigFile(parsedConfigFile) {

1

dist/CompilerOptions.d.ts

@@ -34,2 +34,3 @@ import * as ts from "typescript";

lua51AllowTryCatchInAsyncAwait?: boolean;
measurePerformance?: boolean;
}

@@ -36,0 +37,0 @@ export declare type CompilerOptions = OmitIndexSignature<ts.CompilerOptions> & TypeScriptToLuaOptions & {

3

dist/lualib-build/plugin.js

@@ -7,3 +7,2 @@ "use strict";

const path = require("path");
const lualib_1 = require("../transformation/utils/lualib");
const LuaLib_1 = require("../LuaLib");

@@ -55,3 +54,3 @@ const util_1 = require("./util");

const fileResult = context.superTransformNode(file)[0];
const usedFeatures = new Set((0, lualib_1.getUsedLuaLibFeatures)(context));
const usedFeatures = new Set(context.usedLuaLibFeatures);
// Get all imports in file

@@ -58,0 +57,0 @@ const importNames = new Set();

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

const elementType = context.checker.getElementTypeOfArrayType(callerType);
if (elementType && ((0, typescript_1.isStringType)(context, elementType) || (0, typescript_1.isNumberType)(context, elementType))) {
if (elementType &&
(0, typescript_1.typeAlwaysHasSomeOfFlags)(context, elementType, ts.TypeFlags.StringLike | ts.TypeFlags.NumberLike)) {
const defaultSeparatorLiteral = lua.createStringLiteral(",");

@@ -109,0 +110,0 @@ const param = params[0];

@@ -8,5 +8,5 @@ "use strict";

const function_context_1 = require("../utils/function-context");
const lua_ast_1 = require("../utils/lua-ast");
const lualib_1 = require("../utils/lualib");
const call_1 = require("../visitors/call");
const lua_ast_1 = require("../utils/lua-ast");
function transformFunctionPrototypeCall(context, node, calledMethod) {

@@ -13,0 +13,0 @@ const callerType = context.checker.getTypeAtLocation(calledMethod.expression);

import * as ts from "typescript";
import * as lua from "../../LuaAST";
import { TransformationContext } from "../context";
export declare function transformGlobalCall(context: TransformationContext, node: ts.CallExpression): lua.Expression | undefined;
export declare function tryTransformBuiltinGlobalCall(context: TransformationContext, node: ts.CallExpression, expressionType: ts.Type): lua.Expression | undefined;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformGlobalCall = void 0;
exports.tryTransformBuiltinGlobalCall = void 0;
const lualib_1 = require("../utils/lualib");
const typescript_1 = require("../utils/typescript");
const call_1 = require("../visitors/call");
function transformGlobalCall(context, node) {
const signature = context.checker.getResolvedSignature(node);
const parameters = (0, call_1.transformArguments)(context, node.arguments, signature);
const expressionType = context.checker.getTypeAtLocation(node.expression);
function tryTransformBuiltinGlobalCall(context, node, expressionType) {
function getParameters() {
const signature = context.checker.getResolvedSignature(node);
return (0, call_1.transformArguments)(context, node.arguments, signature);
}
const name = expressionType.symbol.name;
switch (name) {
case "SymbolConstructor":
return (0, lualib_1.transformLuaLibFunction)(context, lualib_1.LuaLibFeature.Symbol, node, ...parameters);
return (0, lualib_1.transformLuaLibFunction)(context, lualib_1.LuaLibFeature.Symbol, node, ...getParameters());
case "NumberConstructor":
return (0, lualib_1.transformLuaLibFunction)(context, lualib_1.LuaLibFeature.Number, node, ...parameters);
return (0, lualib_1.transformLuaLibFunction)(context, lualib_1.LuaLibFeature.Number, node, ...getParameters());
case "isNaN":
case "isFinite":
const numberParameters = (0, typescript_1.isNumberType)(context, expressionType)
? parameters
: [(0, lualib_1.transformLuaLibFunction)(context, lualib_1.LuaLibFeature.Number, undefined, ...parameters)];
? getParameters()
: [(0, lualib_1.transformLuaLibFunction)(context, lualib_1.LuaLibFeature.Number, undefined, ...getParameters())];
return (0, lualib_1.transformLuaLibFunction)(context, name === "isNaN" ? lualib_1.LuaLibFeature.NumberIsNaN : lualib_1.LuaLibFeature.NumberIsFinite, node, ...numberParameters);
case "parseFloat":
return (0, lualib_1.transformLuaLibFunction)(context, lualib_1.LuaLibFeature.ParseFloat, node, ...parameters);
return (0, lualib_1.transformLuaLibFunction)(context, lualib_1.LuaLibFeature.ParseFloat, node, ...getParameters());
case "parseInt":
return (0, lualib_1.transformLuaLibFunction)(context, lualib_1.LuaLibFeature.ParseInt, node, ...parameters);
return (0, lualib_1.transformLuaLibFunction)(context, lualib_1.LuaLibFeature.ParseInt, node, ...getParameters());
}
}
exports.transformGlobalCall = transformGlobalCall;
exports.tryTransformBuiltinGlobalCall = tryTransformBuiltinGlobalCall;
//# sourceMappingURL=global.js.map

@@ -5,4 +5,4 @@ import * as ts from "typescript";

export declare function transformBuiltinPropertyAccessExpression(context: TransformationContext, node: ts.PropertyAccessExpression): lua.Expression | undefined;
export declare function transformBuiltinCallExpression(context: TransformationContext, node: ts.CallExpression, isOptionalCall: boolean): lua.Expression | undefined;
export declare function transformBuiltinIdentifierExpression(context: TransformationContext, node: ts.Identifier): lua.Expression | undefined;
export declare function transformBuiltinCallExpression(context: TransformationContext, node: ts.CallExpression): lua.Expression | undefined;
export declare function transformBuiltinIdentifierExpression(context: TransformationContext, node: ts.Identifier, symbol: ts.Symbol | undefined): lua.Expression | undefined;
export declare function checkForLuaLibType(context: TransformationContext, type: ts.Type): void;

@@ -25,6 +25,6 @@ "use strict";

if (ts.isIdentifier(node.expression) && (0, typescript_1.isStandardLibraryType)(context, ownerType, undefined)) {
switch (node.expression.text) {
switch (ownerType.symbol.name) {
case "Math":
return (0, math_1.transformMathProperty)(context, node);
case "Symbol":
case "SymbolConstructor":
(0, lualib_1.importLuaLibFeature)(context, lualib_1.LuaLibFeature.Symbol);

@@ -44,98 +44,91 @@ }

exports.transformBuiltinPropertyAccessExpression = transformBuiltinPropertyAccessExpression;
function transformBuiltinCallExpression(context, node, isOptionalCall) {
const unsupportedOptionalCall = () => {
context.diagnostics.push((0, diagnostics_1.unsupportedBuiltinOptionalCall)(node));
return lua.createNilLiteral();
};
function transformBuiltinCallExpression(context, node) {
const expressionType = context.checker.getTypeAtLocation(node.expression);
if (ts.isIdentifier(node.expression) && (0, typescript_1.isStandardLibraryType)(context, expressionType, undefined)) {
checkForLuaLibType(context, expressionType);
const result = (0, global_1.transformGlobalCall)(context, node);
if (result) {
if (isOptionalCall)
return unsupportedOptionalCall();
const result = (0, global_1.tryTransformBuiltinGlobalCall)(context, node, expressionType);
if (result)
return result;
}
}
const calledMethod = ts.getOriginalNode((0, call_1.getCalledExpression)(node));
if (!ts.isPropertyAccessExpression(calledMethod)) {
return;
if (ts.isPropertyAccessExpression(calledMethod)) {
const globalResult = tryTransformBuiltinGlobalMethodCall(context, node, calledMethod);
if (globalResult)
return globalResult;
const prototypeResult = tryTransformBuiltinPropertyCall(context, node, calledMethod);
if (prototypeResult)
return prototypeResult;
// object prototype call may work even without resolved signature/type (which the other builtin calls use)
// e.g. (foo as any).toString()
// prototype methods take precedence (e.g. number.toString(2))
const objectResult = (0, object_1.tryTransformObjectPrototypeCall)(context, node, calledMethod);
if (objectResult)
return objectResult;
}
const isOptionalAccess = calledMethod.questionDotToken;
// If the function being called is of type owner.func, get the type of owner
}
exports.transformBuiltinCallExpression = transformBuiltinCallExpression;
function tryTransformBuiltinGlobalMethodCall(context, node, calledMethod) {
const ownerType = context.checker.getTypeAtLocation(calledMethod.expression);
if ((0, typescript_1.isStandardLibraryType)(context, ownerType, undefined)) {
const symbol = ownerType.getSymbol();
switch (symbol === null || symbol === void 0 ? void 0 : symbol.name) {
case "ArrayConstructor":
if (isOptionalCall || isOptionalAccess)
return unsupportedOptionalCall();
return (0, array_1.transformArrayConstructorCall)(context, node, calledMethod);
case "Console":
if (isOptionalCall || isOptionalAccess)
return unsupportedOptionalCall();
return (0, console_1.transformConsoleCall)(context, node, calledMethod);
case "Math":
if (isOptionalCall || isOptionalAccess)
return unsupportedOptionalCall();
return (0, math_1.transformMathCall)(context, node, calledMethod);
case "StringConstructor":
if (isOptionalCall || isOptionalAccess)
return unsupportedOptionalCall();
return (0, string_1.transformStringConstructorCall)(context, node, calledMethod);
case "ObjectConstructor":
if (isOptionalCall || isOptionalAccess)
return unsupportedOptionalCall();
return (0, object_1.transformObjectConstructorCall)(context, node, calledMethod);
case "SymbolConstructor":
if (isOptionalCall || isOptionalAccess)
return unsupportedOptionalCall();
return (0, symbol_1.transformSymbolConstructorCall)(context, node, calledMethod);
case "NumberConstructor":
if (isOptionalCall || isOptionalAccess)
return unsupportedOptionalCall();
return (0, number_1.transformNumberConstructorCall)(context, node, calledMethod);
case "PromiseConstructor":
if (isOptionalCall || isOptionalAccess)
return unsupportedOptionalCall();
return (0, promise_1.transformPromiseConstructorCall)(context, node, calledMethod);
}
if (!(0, typescript_1.isStandardLibraryType)(context, ownerType, undefined))
return;
const ownerSymbol = ownerType.symbol;
if (!ownerSymbol || ownerSymbol.parent)
return;
let result;
switch (ownerSymbol.name) {
case "ArrayConstructor":
result = (0, array_1.transformArrayConstructorCall)(context, node, calledMethod);
break;
case "Console":
result = (0, console_1.transformConsoleCall)(context, node, calledMethod);
break;
case "Math":
result = (0, math_1.transformMathCall)(context, node, calledMethod);
break;
case "StringConstructor":
result = (0, string_1.transformStringConstructorCall)(context, node, calledMethod);
break;
case "ObjectConstructor":
result = (0, object_1.transformObjectConstructorCall)(context, node, calledMethod);
break;
case "SymbolConstructor":
result = (0, symbol_1.transformSymbolConstructorCall)(context, node, calledMethod);
break;
case "NumberConstructor":
result = (0, number_1.transformNumberConstructorCall)(context, node, calledMethod);
break;
case "PromiseConstructor":
result = (0, promise_1.transformPromiseConstructorCall)(context, node, calledMethod);
break;
}
const isStringFunction = (0, typescript_1.isStringType)(context, ownerType) ||
(calledMethod.questionDotToken && (0, typescript_1.isNullableType)(context, ownerType, typescript_1.isStringType));
if (isStringFunction && (0, typescript_1.hasStandardLibrarySignature)(context, node)) {
if (isOptionalCall)
return unsupportedOptionalCall();
return (0, string_1.transformStringPrototypeCall)(context, node, calledMethod);
if (result && calledMethod.questionDotToken) {
// e.g. console?.log()
context.diagnostics.push((0, diagnostics_1.unsupportedBuiltinOptionalCall)(calledMethod));
}
const isNumberFunction = (0, typescript_1.isNumberType)(context, ownerType) ||
(calledMethod.questionDotToken && (0, typescript_1.isNullableType)(context, ownerType, typescript_1.isNumberType));
if (isNumberFunction && (0, typescript_1.hasStandardLibrarySignature)(context, node)) {
if (isOptionalCall)
return unsupportedOptionalCall();
return (0, number_1.transformNumberPrototypeCall)(context, node, calledMethod);
return result;
}
function tryTransformBuiltinPropertyCall(context, node, calledMethod) {
var _a;
const signatureDeclaration = (_a = context.checker.getResolvedSignature(node)) === null || _a === void 0 ? void 0 : _a.declaration;
if (!signatureDeclaration || !(0, typescript_1.isStandardLibraryDeclaration)(context, signatureDeclaration))
return;
const callSymbol = context.checker.getTypeAtLocation(signatureDeclaration).symbol;
const ownerSymbol = callSymbol.parent;
if (!ownerSymbol || ownerSymbol.parent)
return;
switch (ownerSymbol.name) {
case "String":
return (0, string_1.transformStringPrototypeCall)(context, node, calledMethod);
case "Number":
return (0, number_1.transformNumberPrototypeCall)(context, node, calledMethod);
case "Array":
case "ReadonlyArray":
return (0, array_1.transformArrayPrototypeCall)(context, node, calledMethod);
case "Function":
case "CallableFunction":
case "NewableFunction":
return (0, function_1.transformFunctionPrototypeCall)(context, node, calledMethod);
}
const isArrayFunction = (0, typescript_1.isArrayType)(context, ownerType) ||
(calledMethod.questionDotToken && (0, typescript_1.isNullableType)(context, ownerType, typescript_1.isArrayType));
if (isArrayFunction && (0, typescript_1.hasStandardLibrarySignature)(context, node)) {
if (isOptionalCall)
return unsupportedOptionalCall();
return (0, array_1.transformArrayPrototypeCall)(context, node, calledMethod);
}
const isFunctionFunction = (0, typescript_1.isFunctionType)(ownerType) ||
(calledMethod.questionDotToken && (0, typescript_1.isNullableType)(context, ownerType, (_, t) => (0, typescript_1.isFunctionType)(t)));
if (isFunctionFunction && (0, typescript_1.hasStandardLibrarySignature)(context, node)) {
if (isOptionalCall)
return unsupportedOptionalCall();
return (0, function_1.transformFunctionPrototypeCall)(context, node, calledMethod);
}
const objectResult = (0, object_1.transformObjectPrototypeCall)(context, node, calledMethod);
if (objectResult) {
if (isOptionalCall)
return unsupportedOptionalCall();
return objectResult;
}
}
exports.transformBuiltinCallExpression = transformBuiltinCallExpression;
function transformBuiltinIdentifierExpression(context, node) {
function transformBuiltinIdentifierExpression(context, node, symbol) {
switch (node.text) {

@@ -149,3 +142,3 @@ case "NaN":

case "globalThis":
return lua.createIdentifier("_G", node, (0, symbols_1.getIdentifierSymbolId)(context, node), "globalThis");
return lua.createIdentifier("_G", node, (0, symbols_1.getIdentifierSymbolId)(context, node, symbol), "globalThis");
}

@@ -169,5 +162,6 @@ }

function checkForLuaLibType(context, type) {
if (!type.symbol)
const symbol = type.symbol;
if (!symbol || symbol.parent)
return;
const name = context.checker.getFullyQualifiedName(type.symbol);
const name = symbol.name;
switch (name) {

@@ -190,2 +184,6 @@ case "Map":

return;
case "Promise":
case "PromiseConstructor":
(0, lualib_1.importLuaLibFeature)(context, lualib_1.LuaLibFeature.Promise);
return;
}

@@ -192,0 +190,0 @@ if (builtinErrorTypeNames.has(name)) {

@@ -5,2 +5,2 @@ import * as lua from "../../LuaAST";

export declare function transformObjectConstructorCall(context: TransformationContext, node: ts.CallExpression, calledMethod: ts.PropertyAccessExpression): lua.Expression | undefined;
export declare function transformObjectPrototypeCall(context: TransformationContext, node: ts.CallExpression, calledMethod: ts.PropertyAccessExpression): lua.Expression | undefined;
export declare function tryTransformObjectPrototypeCall(context: TransformationContext, node: ts.CallExpression, calledMethod: ts.PropertyAccessExpression): lua.Expression | undefined;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformObjectPrototypeCall = exports.transformObjectConstructorCall = void 0;
exports.tryTransformObjectPrototypeCall = exports.transformObjectConstructorCall = void 0;
const lua = require("../../LuaAST");

@@ -33,4 +33,3 @@ const diagnostics_1 = require("../utils/diagnostics");

exports.transformObjectConstructorCall = transformObjectConstructorCall;
function transformObjectPrototypeCall(context, node, calledMethod) {
const signature = context.checker.getResolvedSignature(node);
function tryTransformObjectPrototypeCall(context, node, calledMethod) {
const name = calledMethod.name.text;

@@ -43,2 +42,3 @@ switch (name) {

const expr = context.transformExpression(calledMethod.expression);
const signature = context.checker.getResolvedSignature(node);
const parameters = (0, call_1.transformArguments)(context, node.arguments, signature);

@@ -50,3 +50,3 @@ const rawGetIdentifier = lua.createIdentifier("rawget");

}
exports.transformObjectPrototypeCall = transformObjectPrototypeCall;
exports.tryTransformObjectPrototypeCall = tryTransformObjectPrototypeCall;
//# sourceMappingURL=object.js.map

@@ -7,7 +7,9 @@ "use strict";

const lualib_1 = require("../utils/lualib");
const call_1 = require("../visitors/call");
const typescript_1 = require("../utils/typescript");
const call_1 = require("../visitors/call");
function isPromiseClass(context, node) {
if (node.text !== "Promise")
return false;
const type = context.checker.getTypeAtLocation(node);
return (0, typescript_1.isStandardLibraryType)(context, type, undefined) && node.text === "Promise";
return (0, typescript_1.isStandardLibraryType)(context, type, undefined);
}

@@ -14,0 +16,0 @@ exports.isPromiseClass = isPromiseClass;

@@ -103,2 +103,4 @@ "use strict";

return (0, lualib_1.transformLuaLibFunction)(context, lualib_1.LuaLibFeature.StringPadEnd, node, caller, ...params);
case "toString":
return; // will be handled by transformObjectPrototypeCall
default:

@@ -105,0 +107,0 @@ context.diagnostics.push((0, diagnostics_1.unsupportedProperty)(calledMethod.name, "string", expressionName));

@@ -5,2 +5,5 @@ import * as ts from "typescript";

import { ExpressionLikeNode, StatementLikeNode, VisitorMap } from "./visitors";
import { SymbolInfo } from "../utils/symbols";
import { LuaLibFeature } from "../../LuaLib";
import { Scope, ScopeType } from "../utils/scope";
export declare const tempSymbolId: lua.SymbolId;

@@ -37,6 +40,9 @@ export interface AllAccessorDeclarations {

private currentNodeVisitors;
private currentNodeVisitorsIndex;
private nextTempId;
transformNode(node: ts.Node): lua.Node[];
superTransformNode(node: ts.Node): lua.Node[];
private doSuperTransformNode;
transformExpression(node: ExpressionLikeNode): lua.Expression;
private assertIsExpression;
superTransformExpression(node: ExpressionLikeNode): lua.Expression;

@@ -54,2 +60,11 @@ transformStatements(node: StatementLikeNode | readonly StatementLikeNode[]): lua.Statement[];

createTempNameForNode(node: ts.Node): lua.Identifier;
private lastSymbolId;
readonly symbolInfoMap: Map<lua.SymbolId, SymbolInfo>;
readonly symbolIdMaps: Map<ts.Symbol, lua.SymbolId>;
nextSymbolId(): lua.SymbolId;
readonly usedLuaLibFeatures: Set<LuaLibFeature>;
readonly scopeStack: Scope[];
private lastScopeId;
pushScope(type: ScopeType): Scope;
popScope(): Scope;
}

@@ -27,3 +27,13 @@ "use strict";

this.currentNodeVisitors = [];
this.currentNodeVisitorsIndex = 0;
this.nextTempId = 0;
// other utils
this.lastSymbolId = 0;
this.symbolInfoMap = new Map();
this.symbolIdMaps = new Map();
this.usedLuaLibFeatures = new Set();
this.scopeStack = [];
this.lastScopeId = 0;
/** @internal */
this.classSuperInfos = [];
// Use `getParseTreeNode` to get original SourceFile node, before it was substituted by custom transformers.

@@ -35,3 +45,7 @@ // It's required because otherwise `getEmitResolver` won't use cached diagnostics, produced in `emitWorker`

}
transformNode(node, isExpression) {
transformNode(node) {
return (0, lua_ast_1.unwrapVisitorResult)(this.transformNodeRaw(node));
}
/** @internal */
transformNodeRaw(node, isExpression) {
var _a;

@@ -43,3 +57,3 @@ // TODO: Move to visitors?

const nodeVisitors = this.visitorMap.get(node.kind);
if (!nodeVisitors || nodeVisitors.length === 0) {
if (!nodeVisitors) {
this.diagnostics.push((0, diagnostics_1.unsupportedNodeKind)(node, node.kind));

@@ -49,28 +63,37 @@ return isExpression ? [lua.createNilLiteral()] : [];

const previousNodeVisitors = this.currentNodeVisitors;
this.currentNodeVisitors = [...nodeVisitors];
const visitor = this.currentNodeVisitors.pop();
const result = (0, lua_ast_1.unwrapVisitorResult)(visitor.transform(node, this));
const previousNodeVisitorsIndex = this.currentNodeVisitorsIndex;
this.currentNodeVisitors = nodeVisitors;
this.currentNodeVisitorsIndex = nodeVisitors.length - 1;
const visitor = this.currentNodeVisitors[this.currentNodeVisitorsIndex];
const result = visitor(node, this);
this.currentNodeVisitors = previousNodeVisitors;
this.currentNodeVisitorsIndex = previousNodeVisitorsIndex;
return result;
}
superTransformNode(node) {
if (this.currentNodeVisitors.length === 0) {
return (0, lua_ast_1.unwrapVisitorResult)(this.doSuperTransformNode(node));
}
doSuperTransformNode(node) {
if (--this.currentNodeVisitorsIndex < 0) {
throw new Error(`There is no super transform for ${ts.SyntaxKind[node.kind]} visitor`);
}
const visitor = this.currentNodeVisitors.pop();
return (0, lua_ast_1.unwrapVisitorResult)(visitor.transform(node, this));
const visitor = this.currentNodeVisitors[this.currentNodeVisitorsIndex];
return (0, lua_ast_1.unwrapVisitorResult)(visitor(node, this));
}
transformExpression(node) {
const [result] = this.transformNode(node, true);
const result = this.transformNodeRaw(node, true);
return this.assertIsExpression(node, result);
}
assertIsExpression(node, result) {
if (result === undefined) {
throw new Error(`Expression visitor for node type ${ts.SyntaxKind[node.kind]} did not return any result.`);
}
if (Array.isArray(result)) {
return result[0];
}
return result;
}
superTransformExpression(node) {
const [result] = this.superTransformNode(node);
if (result === undefined) {
throw new Error(`Expression visitor for node type ${ts.SyntaxKind[node.kind]} did not return any result.`);
}
return result;
const result = this.doSuperTransformNode(node);
return this.assertIsExpression(node, result);
}

@@ -81,4 +104,5 @@ transformStatements(node) {

const statements = this.transformNode(n);
statements.unshift(...this.popPrecedingStatements());
return statements;
const result = this.popPrecedingStatements();
result.push(...statements);
return result;
});

@@ -90,4 +114,5 @@ }

const statements = this.superTransformNode(n);
statements.unshift(...this.popPrecedingStatements());
return statements;
const result = this.popPrecedingStatements();
result.push(...statements);
return result;
});

@@ -106,6 +131,8 @@ }

(0, utils_1.assert)(precedingStatements);
if (!Array.isArray(statements)) {
statements = [statements];
if (Array.isArray(statements)) {
precedingStatements.push(...statements);
}
precedingStatements.push(...statements);
else {
precedingStatements.push(statements);
}
}

@@ -115,6 +142,8 @@ prependPrecedingStatements(statements) {

(0, utils_1.assert)(precedingStatements);
if (!Array.isArray(statements)) {
statements = [statements];
if (Array.isArray(statements)) {
precedingStatements.unshift(...statements);
}
precedingStatements.unshift(...statements);
else {
precedingStatements.unshift(statements);
}
}

@@ -182,4 +211,17 @@ createTempName(prefix = "temp") {

}
nextSymbolId() {
return ++this.lastSymbolId;
}
pushScope(type) {
const scope = { type, id: ++this.lastScopeId };
this.scopeStack.push(scope);
return scope;
}
popScope() {
const scope = this.scopeStack.pop();
(0, utils_1.assert)(scope);
return scope;
}
}
exports.TransformationContext = TransformationContext;
//# sourceMappingURL=context.js.map

@@ -152,3 +152,3 @@ import * as ts from "typescript";

};
export declare type VisitorMap = Map<ts.SyntaxKind, Array<ObjectVisitor<ts.Node>>>;
export declare type VisitorMap = Map<ts.SyntaxKind, Array<FunctionVisitor<ts.Node>>>;
export {};

@@ -8,3 +8,3 @@ "use strict";

function createVisitorMap(customVisitors) {
const visitorMap = new Map();
const objectVisitorMap = new Map();
for (const visitors of [visitors_1.standardVisitors, ...customVisitors]) {

@@ -16,3 +16,3 @@ const priority = visitors === visitors_1.standardVisitors ? -Infinity : 0;

const syntaxKind = Number(syntaxKindKey);
const nodeVisitors = (0, utils_1.getOrUpdate)(visitorMap, syntaxKind, () => []);
const nodeVisitors = (0, utils_1.getOrUpdate)(objectVisitorMap, syntaxKind, () => []);
const objectVisitor = typeof visitor === "function" ? { transform: visitor, priority } : visitor;

@@ -22,6 +22,7 @@ nodeVisitors.push(objectVisitor);

}
for (const nodeVisitors of visitorMap.values()) {
nodeVisitors.sort((a, b) => { var _a, _b; return ((_a = a.priority) !== null && _a !== void 0 ? _a : 0) - ((_b = b.priority) !== null && _b !== void 0 ? _b : 0); });
const result = new Map();
for (const [kind, nodeVisitors] of objectVisitorMap) {
result.set(kind, nodeVisitors.sort((a, b) => { var _a, _b; return ((_a = a.priority) !== null && _a !== void 0 ? _a : 0) - ((_b = b.priority) !== null && _b !== void 0 ? _b : 0); }).map(visitor => visitor.transform));
}
return visitorMap;
return result;
}

@@ -28,0 +29,0 @@ exports.createVisitorMap = createVisitorMap;

import * as ts from "typescript";
import { TransformationContext } from "../context";
export declare enum AnnotationKind {
Extension = "extension",
MetaExtension = "metaExtension",
CustomConstructor = "customConstructor",
CompileMembersOnly = "compileMembersOnly",
NoResolution = "noResolution",
PureAbstract = "pureAbstract",
Phantom = "phantom",
TupleReturn = "tupleReturn",
LuaIterator = "luaIterator",
LuaTable = "luaTable",
NoSelf = "noSelf",
NoSelfInFile = "noSelfInFile",
Vararg = "vararg",
ForRange = "forRange"
NoSelfInFile = "noSelfInFile"
}

@@ -28,7 +18,1 @@ export interface Annotation {

export declare function getFileAnnotations(sourceFile: ts.SourceFile): AnnotationsMap;
export declare function getSignatureAnnotations(context: TransformationContext, signature: ts.Signature): AnnotationsMap;
export declare function isTupleReturnCall(context: TransformationContext, node: ts.Node): boolean;
export declare function isLuaIteratorType(context: TransformationContext, node: ts.Node): boolean;
export declare function isVarargType(context: TransformationContext, node: ts.Node): boolean;
export declare function isForRangeType(context: TransformationContext, node: ts.Node): boolean;
export declare function getTagArgsFromComment(tag: ts.JSDocTag): string[];
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getTagArgsFromComment = exports.isForRangeType = exports.isVarargType = exports.isLuaIteratorType = exports.isTupleReturnCall = exports.getSignatureAnnotations = exports.getFileAnnotations = exports.getNodeAnnotations = exports.getTypeAnnotations = exports.getSymbolAnnotations = exports.AnnotationKind = void 0;
exports.getFileAnnotations = exports.getNodeAnnotations = exports.getTypeAnnotations = exports.getSymbolAnnotations = exports.AnnotationKind = void 0;
const ts = require("typescript");
var AnnotationKind;
(function (AnnotationKind) {
AnnotationKind["Extension"] = "extension";
AnnotationKind["MetaExtension"] = "metaExtension";
AnnotationKind["CustomConstructor"] = "customConstructor";
AnnotationKind["CompileMembersOnly"] = "compileMembersOnly";
AnnotationKind["NoResolution"] = "noResolution";
AnnotationKind["PureAbstract"] = "pureAbstract";
AnnotationKind["Phantom"] = "phantom";
AnnotationKind["TupleReturn"] = "tupleReturn";
AnnotationKind["LuaIterator"] = "luaIterator";
AnnotationKind["LuaTable"] = "luaTable";
AnnotationKind["NoSelf"] = "noSelf";
AnnotationKind["NoSelfInFile"] = "noSelfInFile";
AnnotationKind["Vararg"] = "vararg";
AnnotationKind["ForRange"] = "forRange";
})(AnnotationKind = exports.AnnotationKind || (exports.AnnotationKind = {}));
function createAnnotation(name, args) {
const kind = Object.values(AnnotationKind).find(k => k.toLowerCase() === name.toLowerCase());
if (kind !== undefined) {
return { kind, args };
}
}
const annotationValues = new Map(Object.values(AnnotationKind).map(k => [k.toLowerCase(), k]));
function collectAnnotations(source, annotationsMap) {
var _a, _b;
for (const tag of source.getJsDocTags()) {
const annotation = createAnnotation(tag.name, (_b = (_a = tag.text) === null || _a === void 0 ? void 0 : _a.map(p => p.text)) !== null && _b !== void 0 ? _b : []);
if (annotation) {
annotationsMap.set(annotation.kind, annotation);
}
const tagName = annotationValues.get(tag.name.toLowerCase());
if (!tagName)
continue;
const annotation = {
kind: tag.name,
args: (_b = (_a = tag.text) === null || _a === void 0 ? void 0 : _a.map(p => p.text)) !== null && _b !== void 0 ? _b : [],
};
annotationsMap.set(tagName, annotation);
}
}
const symbolAnnotations = new WeakMap();
function getSymbolAnnotations(symbol) {
const known = symbolAnnotations.get(symbol);
if (known)
return known;
const annotationsMap = new Map();
collectAnnotations(symbol, annotationsMap);
symbolAnnotations.set(symbol, annotationsMap);
return annotationsMap;

@@ -44,23 +39,41 @@ }

function getTypeAnnotations(type) {
// types are not frequently repeatedly polled for annotations, so it's not worth caching them
const annotationsMap = new Map();
if (type.symbol)
collectAnnotations(type.symbol, annotationsMap);
if (type.aliasSymbol)
collectAnnotations(type.aliasSymbol, annotationsMap);
if (type.symbol) {
getSymbolAnnotations(type.symbol).forEach((value, key) => {
annotationsMap.set(key, value);
});
}
if (type.aliasSymbol) {
getSymbolAnnotations(type.aliasSymbol).forEach((value, key) => {
annotationsMap.set(key, value);
});
}
return annotationsMap;
}
exports.getTypeAnnotations = getTypeAnnotations;
const nodeAnnotations = new WeakMap();
function getNodeAnnotations(node) {
const known = nodeAnnotations.get(node);
if (known)
return known;
const annotationsMap = new Map();
for (const tag of ts.getJSDocTags(node)) {
const tagName = tag.tagName.text;
const annotation = createAnnotation(tagName, getTagArgsFromComment(tag));
if (annotation) {
annotationsMap.set(annotation.kind, annotation);
}
}
collectAnnotationsFromTags(annotationsMap, ts.getAllJSDocTags(node, ts.isJSDocUnknownTag));
nodeAnnotations.set(node, annotationsMap);
return annotationsMap;
}
exports.getNodeAnnotations = getNodeAnnotations;
function collectAnnotationsFromTags(annotationsMap, tags) {
for (const tag of tags) {
const tagName = annotationValues.get(tag.tagName.text.toLowerCase());
if (!tagName)
continue;
annotationsMap.set(tagName, { kind: tagName, args: getTagArgsFromComment(tag) });
}
}
const fileAnnotations = new WeakMap();
function getFileAnnotations(sourceFile) {
const known = fileAnnotations.get(sourceFile);
if (known)
return known;
const annotationsMap = new Map();

@@ -71,7 +84,5 @@ if (sourceFile.statements.length > 0) {

if (jsDoc) {
for (const tag of jsDoc.flatMap(x => { var _a; return (_a = x.tags) !== null && _a !== void 0 ? _a : []; })) {
const tagName = tag.tagName.text;
const annotation = createAnnotation(tagName, getTagArgsFromComment(tag));
if (annotation) {
annotationsMap.set(annotation.kind, annotation);
for (const jsDocElement of jsDoc) {
if (jsDocElement.tags) {
collectAnnotationsFromTags(annotationsMap, jsDocElement.tags);
}

@@ -81,56 +92,6 @@ }

}
fileAnnotations.set(sourceFile, annotationsMap);
return annotationsMap;
}
exports.getFileAnnotations = getFileAnnotations;
function getSignatureAnnotations(context, signature) {
const annotationsMap = new Map();
collectAnnotations(signature, annotationsMap);
// Function properties on interfaces have the JSDoc tags on the parent PropertySignature
const declaration = signature.getDeclaration();
if ((declaration === null || declaration === void 0 ? void 0 : declaration.parent) && ts.isPropertySignature(declaration.parent)) {
const symbol = context.checker.getSymbolAtLocation(declaration.parent.name);
if (symbol) {
collectAnnotations(symbol, annotationsMap);
}
}
return annotationsMap;
}
exports.getSignatureAnnotations = getSignatureAnnotations;
function isTupleReturnCall(context, node) {
if (!ts.isCallExpression(node)) {
return false;
}
const signature = context.checker.getResolvedSignature(node);
if (signature) {
if (getSignatureAnnotations(context, signature).has(AnnotationKind.TupleReturn)) {
return true;
}
// Only check function type for directive if it is declared as an interface or type alias
const declaration = signature.getDeclaration();
const isInterfaceOrAlias = (declaration === null || declaration === void 0 ? void 0 : declaration.parent) &&
((ts.isInterfaceDeclaration(declaration.parent) && ts.isCallSignatureDeclaration(declaration)) ||
ts.isTypeAliasDeclaration(declaration.parent));
if (!isInterfaceOrAlias) {
return false;
}
}
const type = context.checker.getTypeAtLocation(node.expression);
return getTypeAnnotations(type).has(AnnotationKind.TupleReturn);
}
exports.isTupleReturnCall = isTupleReturnCall;
function isLuaIteratorType(context, node) {
const type = context.checker.getTypeAtLocation(node);
return getTypeAnnotations(type).has(AnnotationKind.LuaIterator);
}
exports.isLuaIteratorType = isLuaIteratorType;
function isVarargType(context, node) {
const type = context.checker.getTypeAtLocation(node);
return getTypeAnnotations(type).has(AnnotationKind.Vararg);
}
exports.isVarargType = isVarargType;
function isForRangeType(context, node) {
const type = context.checker.getTypeAtLocation(node);
return getTypeAnnotations(type).has(AnnotationKind.ForRange);
}
exports.isForRangeType = isForRangeType;
function getTagArgsFromComment(tag) {

@@ -147,3 +108,2 @@ if (tag.comment) {

}
exports.getTagArgsFromComment = getTagArgsFromComment;
//# sourceMappingURL=annotations.js.map

@@ -11,2 +11,3 @@ "use strict";

function validateAssignment(context, node, fromType, toType, toName) {
var _a, _b;
if (toType === fromType) {

@@ -25,9 +26,5 @@ return;

validateFunctionAssignment(context, node, fromType, toType, toName);
const fromTypeNode = context.checker.typeToTypeNode(fromType, undefined, undefined);
const toTypeNode = context.checker.typeToTypeNode(toType, undefined, undefined);
if (!fromTypeNode || !toTypeNode) {
return;
}
if ((ts.isArrayTypeNode(toTypeNode) || ts.isTupleTypeNode(toTypeNode)) &&
(ts.isArrayTypeNode(fromTypeNode) || ts.isTupleTypeNode(fromTypeNode))) {
const checker = context.checker;
if ((checker.isTupleType(toType) || checker.isArrayType(toType)) &&
(checker.isTupleType(fromType) || checker.isArrayType(fromType))) {
// Recurse into arrays/tuples

@@ -44,22 +41,29 @@ const fromTypeArguments = fromType.typeArguments;

}
if ((toType.flags & ts.TypeFlags.Object) !== 0 &&
(ts.isTypeLiteralNode(toTypeNode) ||
(toType.objectFlags & ts.ObjectFlags.ClassOrInterface) !== 0) &&
toType.symbol &&
toType.symbol.members &&
fromType.symbol &&
fromType.symbol.members) {
const fromMembers = (_a = fromType.symbol) === null || _a === void 0 ? void 0 : _a.members;
const toMembers = (_b = toType.symbol) === null || _b === void 0 ? void 0 : _b.members;
if (fromMembers && toMembers) {
// Recurse into interfaces
toType.symbol.members.forEach((toMember, escapedMemberName) => {
if (fromType.symbol.members) {
const fromMember = fromType.symbol.members.get(escapedMemberName);
if (toMembers.size < fromMembers.size) {
toMembers.forEach((toMember, escapedMemberName) => {
const fromMember = fromMembers.get(escapedMemberName);
if (fromMember) {
const toMemberType = context.checker.getTypeOfSymbolAtLocation(toMember, node);
const fromMemberType = context.checker.getTypeOfSymbolAtLocation(fromMember, node);
const memberName = ts.unescapeLeadingUnderscores(escapedMemberName);
validateAssignment(context, node, fromMemberType, toMemberType, toName ? `${toName}.${memberName}` : memberName);
validateMember(toMember, fromMember, escapedMemberName);
}
}
});
});
}
else {
fromMembers.forEach((fromMember, escapedMemberName) => {
const toMember = toMembers.get(escapedMemberName);
if (toMember) {
validateMember(toMember, fromMember, escapedMemberName);
}
});
}
}
function validateMember(toMember, fromMember, escapedMemberName) {
const toMemberType = context.checker.getTypeOfSymbolAtLocation(toMember, node);
const fromMemberType = context.checker.getTypeOfSymbolAtLocation(fromMember, node);
const memberName = ts.unescapeLeadingUnderscores(escapedMemberName);
validateAssignment(context, node, fromMemberType, toMemberType, toName ? `${toName}.${memberName}` : memberName);
}
}

@@ -66,0 +70,0 @@ exports.validateAssignment = validateAssignment;

@@ -77,8 +77,5 @@ import * as ts from "typescript";

};
export declare const invalidOperatorMappingUse: ((node: ts.Node, ...args: any[]) => ts.Diagnostic) & {
export declare const invalidCallExtensionUse: ((node: ts.Node, ...args: any[]) => ts.Diagnostic) & {
code: number;
};
export declare const invalidTableExtensionUse: ((node: ts.Node, ...args: any[]) => ts.Diagnostic) & {
code: number;
};
export declare const annotationRemoved: ((node: ts.Node, kind: AnnotationKind) => ts.Diagnostic) & {

@@ -85,0 +82,0 @@ code: number;

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.undefinedInArrayLiteral = exports.unsupportedOptionalCompileMembersOnly = exports.unsupportedBuiltinOptionalCall = exports.awaitMustBeInAsyncFunction = exports.notAllowedOptionalAssignment = exports.annotationDeprecated = exports.annotationRemoved = exports.invalidTableExtensionUse = exports.invalidOperatorMappingUse = exports.invalidMultiReturnAccess = exports.invalidMultiTypeToEmptyPatternOrArrayLiteral = exports.invalidMultiTypeToNonArrayLiteral = exports.invalidMultiFunctionReturnType = exports.invalidMultiFunctionUse = exports.unsupportedVarDeclaration = exports.invalidAmbientIdentifierName = exports.unsupportedProperty = exports.unsupportedForTargetButOverrideAvailable = exports.unsupportedForTarget = exports.unsupportedRightShiftOperator = exports.unsupportedAccessorInObjectLiteral = exports.invalidPairsIterableWithoutDestructuring = exports.invalidMultiIterableWithoutDestructuring = exports.invalidRangeControlVariable = exports.invalidVarargUse = exports.invalidRangeUse = exports.annotationInvalidArgumentCount = exports.decoratorInvalidContext = exports.unsupportedOverloadAssignment = exports.unsupportedSelfFunctionConversion = exports.unsupportedNoSelfFunctionConversion = exports.forbiddenForIn = exports.unsupportedNodeKind = void 0;
exports.undefinedInArrayLiteral = exports.unsupportedOptionalCompileMembersOnly = exports.unsupportedBuiltinOptionalCall = exports.awaitMustBeInAsyncFunction = exports.notAllowedOptionalAssignment = exports.annotationDeprecated = exports.annotationRemoved = exports.invalidCallExtensionUse = exports.invalidMultiReturnAccess = exports.invalidMultiTypeToEmptyPatternOrArrayLiteral = exports.invalidMultiTypeToNonArrayLiteral = exports.invalidMultiFunctionReturnType = exports.invalidMultiFunctionUse = exports.unsupportedVarDeclaration = exports.invalidAmbientIdentifierName = exports.unsupportedProperty = exports.unsupportedForTargetButOverrideAvailable = exports.unsupportedForTarget = exports.unsupportedRightShiftOperator = exports.unsupportedAccessorInObjectLiteral = exports.invalidPairsIterableWithoutDestructuring = exports.invalidMultiIterableWithoutDestructuring = exports.invalidRangeControlVariable = exports.invalidVarargUse = exports.invalidRangeUse = exports.annotationInvalidArgumentCount = exports.decoratorInvalidContext = exports.unsupportedOverloadAssignment = exports.unsupportedSelfFunctionConversion = exports.unsupportedNoSelfFunctionConversion = exports.forbiddenForIn = exports.unsupportedNodeKind = void 0;
const ts = require("typescript");

@@ -55,4 +55,3 @@ const CompilerOptions_1 = require("../../CompilerOptions");

exports.invalidMultiReturnAccess = createErrorDiagnosticFactory("The LuaMultiReturn type can only be accessed via an element access expression of a numeric type.");
exports.invalidOperatorMappingUse = createErrorDiagnosticFactory("This function must always be directly called and cannot be referred to.");
exports.invalidTableExtensionUse = createErrorDiagnosticFactory("This function must be called directly and cannot be referred to.");
exports.invalidCallExtensionUse = createErrorDiagnosticFactory("This function must be called directly and cannot be referred to.");
exports.annotationRemoved = createErrorDiagnosticFactory((kind) => `'@${kind}' has been removed and will no longer have any effect.` +

@@ -59,0 +58,0 @@ `See https://typescripttolua.github.io/docs/advanced/compiler-annotations#${kind.toLowerCase()} for more information.`);

@@ -9,3 +9,3 @@ import * as ts from "typescript";

}
export declare function getDeclarationContextType({ program }: TransformationContext, signatureDeclaration: ts.SignatureDeclaration): ContextType;
export declare function getDeclarationContextType(context: TransformationContext, signatureDeclaration: ts.SignatureDeclaration): ContextType;
export declare function getFunctionContextType(context: TransformationContext, type: ts.Type): ContextType;

@@ -30,5 +30,18 @@ "use strict";

function getExplicitThisParameter(signatureDeclaration) {
return signatureDeclaration.parameters.find(param => ts.isIdentifier(param.name) && param.name.originalKeywordKind === ts.SyntaxKind.ThisKeyword);
const param = signatureDeclaration.parameters[0];
if (param && ts.isIdentifier(param.name) && param.name.originalKeywordKind === ts.SyntaxKind.ThisKeyword) {
return param;
}
}
function getDeclarationContextType({ program }, signatureDeclaration) {
const signatureDeclarationContextTypes = new WeakMap();
function getDeclarationContextType(context, signatureDeclaration) {
const known = signatureDeclarationContextTypes.get(signatureDeclaration);
if (known !== undefined)
return known;
const contextType = computeDeclarationContextType(context, signatureDeclaration);
signatureDeclarationContextTypes.set(signatureDeclaration, contextType);
return contextType;
}
exports.getDeclarationContextType = getDeclarationContextType;
function computeDeclarationContextType(context, signatureDeclaration) {
const thisParameter = getExplicitThisParameter(signatureDeclaration);

@@ -53,6 +66,3 @@ if (thisParameter) {

const scopeDeclaration = (0, typescript_1.findFirstNodeAbove)(signatureDeclaration, (n) => ts.isClassDeclaration(n) || ts.isClassExpression(n) || ts.isInterfaceDeclaration(n));
if (scopeDeclaration === undefined) {
return ContextType.NonVoid;
}
if ((0, annotations_1.getNodeAnnotations)(scopeDeclaration).has(annotations_1.AnnotationKind.NoSelf)) {
if (scopeDeclaration !== undefined && (0, annotations_1.getNodeAnnotations)(scopeDeclaration).has(annotations_1.AnnotationKind.NoSelf)) {
return ContextType.Void;

@@ -63,2 +73,3 @@ }

// When using --noImplicitSelf and the signature is defined in a file targeted by the program apply the @noSelf rule.
const program = context.program;
const options = program.getCompilerOptions();

@@ -79,51 +90,48 @@ if (options.noImplicitSelf) {

}
exports.getDeclarationContextType = getDeclarationContextType;
function reduceContextTypes(contexts) {
const reducer = (a, b) => {
if (a === ContextType.None) {
return b;
}
else if (b === ContextType.None) {
return a;
}
else if (a !== b) {
return ContextType.Mixed;
}
else {
return a;
}
};
return contexts.reduce(reducer, ContextType.None);
let type = ContextType.None;
for (const context of contexts) {
type |= context;
if (type === ContextType.Mixed)
break;
}
return type;
}
function getSignatureDeclarations(context, signatures) {
return signatures.flatMap(signature => {
const signatureDeclaration = signature.getDeclaration();
let inferredType;
if (ts.isMethodDeclaration(signatureDeclaration) &&
ts.isObjectLiteralExpression(signatureDeclaration.parent) &&
!getExplicitThisParameter(signatureDeclaration)) {
inferredType = context.checker.getContextualTypeForObjectLiteralElement(signatureDeclaration);
function getSignatureDeclarations(context, signature) {
const signatureDeclaration = signature.getDeclaration();
let inferredType;
if (ts.isMethodDeclaration(signatureDeclaration) &&
ts.isObjectLiteralExpression(signatureDeclaration.parent) &&
!getExplicitThisParameter(signatureDeclaration)) {
inferredType = context.checker.getContextualTypeForObjectLiteralElement(signatureDeclaration);
}
else if ((ts.isFunctionExpression(signatureDeclaration) || ts.isArrowFunction(signatureDeclaration)) &&
!getExplicitThisParameter(signatureDeclaration)) {
// Infer type of function expressions/arrow functions
inferredType = (0, typescript_1.inferAssignedType)(context, signatureDeclaration);
}
if (inferredType) {
const inferredSignatures = (0, typescript_1.getAllCallSignatures)(inferredType);
if (inferredSignatures.length > 0) {
return inferredSignatures.map(s => s.getDeclaration());
}
else if ((ts.isFunctionExpression(signatureDeclaration) || ts.isArrowFunction(signatureDeclaration)) &&
!getExplicitThisParameter(signatureDeclaration)) {
// Infer type of function expressions/arrow functions
inferredType = (0, typescript_1.inferAssignedType)(context, signatureDeclaration);
}
if (inferredType) {
const inferredSignatures = (0, typescript_1.getAllCallSignatures)(inferredType);
if (inferredSignatures.length > 0) {
return inferredSignatures.map(s => s.getDeclaration());
}
}
return signatureDeclaration;
});
}
return [signatureDeclaration];
}
const typeContextTypes = new WeakMap();
function getFunctionContextType(context, type) {
var _a;
const known = typeContextTypes.get(type);
if (known !== undefined)
return known;
const contextType = computeFunctionContextType(context, type);
typeContextTypes.set(type, contextType);
return contextType;
}
exports.getFunctionContextType = getFunctionContextType;
function computeFunctionContextType(context, type) {
if (type.isTypeParameter()) {
type = (_a = type.getConstraint()) !== null && _a !== void 0 ? _a : type;
const constraint = type.getConstraint();
if (constraint)
return getFunctionContextType(context, constraint);
}
if (type.isUnion()) {
return reduceContextTypes(type.types.map(t => getFunctionContextType(context, t)));
}
const signatures = context.checker.getSignaturesOfType(type, ts.SignatureKind.Call);

@@ -133,6 +141,4 @@ if (signatures.length === 0) {

}
const signatureDeclarations = getSignatureDeclarations(context, signatures);
return reduceContextTypes(signatureDeclarations.map(s => getDeclarationContextType(context, s)));
return reduceContextTypes(signatures.flatMap(s => getSignatureDeclarations(context, s)).map(s => getDeclarationContextType(context, s)));
}
exports.getFunctionContextType = getFunctionContextType;
//# sourceMappingURL=function-context.js.map

@@ -5,55 +5,61 @@ import * as ts from "typescript";

MultiFunction = "MultiFunction",
MultiType = "MultiType",
RangeFunction = "RangeFunction",
VarargConstant = "VarargConstant",
IterableType = "IterableType",
PairsIterableType = "PairsIterableType",
AdditionOperatorType = "AdditionOperatorType",
AdditionOperatorMethodType = "AdditionOperatorMethodType",
SubtractionOperatorType = "SubtractionOperatorType",
SubtractionOperatorMethodType = "SubtractionOperatorMethodType",
MultiplicationOperatorType = "MultiplicationOperatorType",
MultiplicationOperatorMethodType = "MultiplicationOperatorMethodType",
DivisionOperatorType = "DivisionOperatorType",
DivisionOperatorMethodType = "DivisionOperatorMethodType",
ModuloOperatorType = "ModuloOperatorType",
ModuloOperatorMethodType = "ModuloOperatorMethodType",
PowerOperatorType = "PowerOperatorType",
PowerOperatorMethodType = "PowerOperatorMethodType",
FloorDivisionOperatorType = "FloorDivisionOperatorType",
FloorDivisionOperatorMethodType = "FloorDivisionOperatorMethodType",
BitwiseAndOperatorType = "BitwiseAndOperatorType",
BitwiseAndOperatorMethodType = "BitwiseAndOperatorMethodType",
BitwiseOrOperatorType = "BitwiseOrOperatorType",
BitwiseOrOperatorMethodType = "BitwiseOrOperatorMethodType",
BitwiseExclusiveOrOperatorType = "BitwiseExclusiveOrOperatorType",
BitwiseExclusiveOrOperatorMethodType = "BitwiseExclusiveOrOperatorMethodType",
BitwiseLeftShiftOperatorType = "BitwiseLeftShiftOperatorType",
BitwiseLeftShiftOperatorMethodType = "BitwiseLeftShiftOperatorMethodType",
BitwiseRightShiftOperatorType = "BitwiseRightShiftOperatorType",
BitwiseRightShiftOperatorMethodType = "BitwiseRightShiftOperatorMethodType",
ConcatOperatorType = "ConcatOperatorType",
ConcatOperatorMethodType = "ConcatOperatorMethodType",
LessThanOperatorType = "LessThanOperatorType",
LessThanOperatorMethodType = "LessThanOperatorMethodType",
GreaterThanOperatorType = "GreaterThanOperatorType",
GreaterThanOperatorMethodType = "GreaterThanOperatorMethodType",
NegationOperatorType = "NegationOperatorType",
NegationOperatorMethodType = "NegationOperatorMethodType",
BitwiseNotOperatorType = "BitwiseNotOperatorType",
BitwiseNotOperatorMethodType = "BitwiseNotOperatorMethodType",
LengthOperatorType = "LengthOperatorType",
LengthOperatorMethodType = "LengthOperatorMethodType",
TableNewType = "TableNewType",
TableDeleteType = "TableDeleteType",
TableDeleteMethodType = "TableDeleteMethodType",
TableGetType = "TableGetType",
TableGetMethodType = "TableGetMethodType",
TableHasType = "TableHasType",
TableHasMethodType = "TableHasMethodType",
TableSetType = "TableSetType",
TableSetMethodType = "TableSetMethodType"
AdditionOperatorType = "Addition",
AdditionOperatorMethodType = "AdditionMethod",
SubtractionOperatorType = "Subtraction",
SubtractionOperatorMethodType = "SubtractionMethod",
MultiplicationOperatorType = "Multiplication",
MultiplicationOperatorMethodType = "MultiplicationMethod",
DivisionOperatorType = "Division",
DivisionOperatorMethodType = "DivisionMethod",
ModuloOperatorType = "Modulo",
ModuloOperatorMethodType = "ModuloMethod",
PowerOperatorType = "Power",
PowerOperatorMethodType = "PowerMethod",
FloorDivisionOperatorType = "FloorDivision",
FloorDivisionOperatorMethodType = "FloorDivisionMethod",
BitwiseAndOperatorType = "BitwiseAnd",
BitwiseAndOperatorMethodType = "BitwiseAndMethod",
BitwiseOrOperatorType = "BitwiseOr",
BitwiseOrOperatorMethodType = "BitwiseOrMethod",
BitwiseExclusiveOrOperatorType = "BitwiseExclusiveOr",
BitwiseExclusiveOrOperatorMethodType = "BitwiseExclusiveOrMethod",
BitwiseLeftShiftOperatorType = "BitwiseLeftShift",
BitwiseLeftShiftOperatorMethodType = "BitwiseLeftShiftMethod",
BitwiseRightShiftOperatorType = "BitwiseRightShift",
BitwiseRightShiftOperatorMethodType = "BitwiseRightShiftMethod",
ConcatOperatorType = "Concat",
ConcatOperatorMethodType = "ConcatMethod",
LessThanOperatorType = "LessThan",
LessThanOperatorMethodType = "LessThanMethod",
GreaterThanOperatorType = "GreaterThan",
GreaterThanOperatorMethodType = "GreaterThanMethod",
NegationOperatorType = "Negation",
NegationOperatorMethodType = "NegationMethod",
BitwiseNotOperatorType = "BitwiseNot",
BitwiseNotOperatorMethodType = "BitwiseNotMethod",
LengthOperatorType = "Length",
LengthOperatorMethodType = "LengthMethod",
TableNewType = "TableNew",
TableDeleteType = "TableDelete",
TableDeleteMethodType = "TableDeleteMethod",
TableGetType = "TableGet",
TableGetMethodType = "TableGetMethod",
TableHasType = "TableHas",
TableHasMethodType = "TableHasMethod",
TableSetType = "TableSet",
TableSetMethodType = "TableSetMethod",
TableAddKeyType = "TableAddKey",
TableAddKeyMethodType = "TableAddKeyMethod"
}
export declare function isExtensionType(type: ts.Type, extensionKind: ExtensionKind): boolean;
export declare function getExtensionKinds(type: ts.Type): ExtensionKind[];
export declare function isExtensionValue(context: TransformationContext, symbol: ts.Symbol, extensionKind: ExtensionKind): boolean;
export declare function getExtensionKindForType(context: TransformationContext, type: ts.Type): ExtensionKind | undefined;
export declare function getExtensionKindForNode(context: TransformationContext, node: ts.Node): ExtensionKind | undefined;
export declare function getExtensionKindForSymbol(context: TransformationContext, symbol: ts.Symbol): ExtensionKind | undefined;
export declare enum IterableExtensionKind {
Iterable = "Iterable",
Pairs = "Pairs",
PairsKey = "PairsKey"
}
export declare function getIterableExtensionTypeForType(context: TransformationContext, type: ts.Type): IterableExtensionKind | undefined;
export declare function getIterableExtensionKindForNode(context: TransformationContext, node: ts.Node): IterableExtensionKind | undefined;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isExtensionValue = exports.getExtensionKinds = exports.isExtensionType = exports.ExtensionKind = void 0;
exports.getIterableExtensionKindForNode = exports.getIterableExtensionTypeForType = exports.IterableExtensionKind = exports.getExtensionKindForSymbol = exports.getExtensionKindForNode = exports.getExtensionKindForType = exports.ExtensionKind = void 0;
const ts = require("typescript");
var ExtensionKind;
(function (ExtensionKind) {
ExtensionKind["MultiFunction"] = "MultiFunction";
ExtensionKind["MultiType"] = "MultiType";
ExtensionKind["RangeFunction"] = "RangeFunction";
ExtensionKind["VarargConstant"] = "VarargConstant";
ExtensionKind["IterableType"] = "IterableType";
ExtensionKind["PairsIterableType"] = "PairsIterableType";
ExtensionKind["AdditionOperatorType"] = "AdditionOperatorType";
ExtensionKind["AdditionOperatorMethodType"] = "AdditionOperatorMethodType";
ExtensionKind["SubtractionOperatorType"] = "SubtractionOperatorType";
ExtensionKind["SubtractionOperatorMethodType"] = "SubtractionOperatorMethodType";
ExtensionKind["MultiplicationOperatorType"] = "MultiplicationOperatorType";
ExtensionKind["MultiplicationOperatorMethodType"] = "MultiplicationOperatorMethodType";
ExtensionKind["DivisionOperatorType"] = "DivisionOperatorType";
ExtensionKind["DivisionOperatorMethodType"] = "DivisionOperatorMethodType";
ExtensionKind["ModuloOperatorType"] = "ModuloOperatorType";
ExtensionKind["ModuloOperatorMethodType"] = "ModuloOperatorMethodType";
ExtensionKind["PowerOperatorType"] = "PowerOperatorType";
ExtensionKind["PowerOperatorMethodType"] = "PowerOperatorMethodType";
ExtensionKind["FloorDivisionOperatorType"] = "FloorDivisionOperatorType";
ExtensionKind["FloorDivisionOperatorMethodType"] = "FloorDivisionOperatorMethodType";
ExtensionKind["BitwiseAndOperatorType"] = "BitwiseAndOperatorType";
ExtensionKind["BitwiseAndOperatorMethodType"] = "BitwiseAndOperatorMethodType";
ExtensionKind["BitwiseOrOperatorType"] = "BitwiseOrOperatorType";
ExtensionKind["BitwiseOrOperatorMethodType"] = "BitwiseOrOperatorMethodType";
ExtensionKind["BitwiseExclusiveOrOperatorType"] = "BitwiseExclusiveOrOperatorType";
ExtensionKind["BitwiseExclusiveOrOperatorMethodType"] = "BitwiseExclusiveOrOperatorMethodType";
ExtensionKind["BitwiseLeftShiftOperatorType"] = "BitwiseLeftShiftOperatorType";
ExtensionKind["BitwiseLeftShiftOperatorMethodType"] = "BitwiseLeftShiftOperatorMethodType";
ExtensionKind["BitwiseRightShiftOperatorType"] = "BitwiseRightShiftOperatorType";
ExtensionKind["BitwiseRightShiftOperatorMethodType"] = "BitwiseRightShiftOperatorMethodType";
ExtensionKind["ConcatOperatorType"] = "ConcatOperatorType";
ExtensionKind["ConcatOperatorMethodType"] = "ConcatOperatorMethodType";
ExtensionKind["LessThanOperatorType"] = "LessThanOperatorType";
ExtensionKind["LessThanOperatorMethodType"] = "LessThanOperatorMethodType";
ExtensionKind["GreaterThanOperatorType"] = "GreaterThanOperatorType";
ExtensionKind["GreaterThanOperatorMethodType"] = "GreaterThanOperatorMethodType";
ExtensionKind["NegationOperatorType"] = "NegationOperatorType";
ExtensionKind["NegationOperatorMethodType"] = "NegationOperatorMethodType";
ExtensionKind["BitwiseNotOperatorType"] = "BitwiseNotOperatorType";
ExtensionKind["BitwiseNotOperatorMethodType"] = "BitwiseNotOperatorMethodType";
ExtensionKind["LengthOperatorType"] = "LengthOperatorType";
ExtensionKind["LengthOperatorMethodType"] = "LengthOperatorMethodType";
ExtensionKind["TableNewType"] = "TableNewType";
ExtensionKind["TableDeleteType"] = "TableDeleteType";
ExtensionKind["TableDeleteMethodType"] = "TableDeleteMethodType";
ExtensionKind["TableGetType"] = "TableGetType";
ExtensionKind["TableGetMethodType"] = "TableGetMethodType";
ExtensionKind["TableHasType"] = "TableHasType";
ExtensionKind["TableHasMethodType"] = "TableHasMethodType";
ExtensionKind["TableSetType"] = "TableSetType";
ExtensionKind["TableSetMethodType"] = "TableSetMethodType";
ExtensionKind["AdditionOperatorType"] = "Addition";
ExtensionKind["AdditionOperatorMethodType"] = "AdditionMethod";
ExtensionKind["SubtractionOperatorType"] = "Subtraction";
ExtensionKind["SubtractionOperatorMethodType"] = "SubtractionMethod";
ExtensionKind["MultiplicationOperatorType"] = "Multiplication";
ExtensionKind["MultiplicationOperatorMethodType"] = "MultiplicationMethod";
ExtensionKind["DivisionOperatorType"] = "Division";
ExtensionKind["DivisionOperatorMethodType"] = "DivisionMethod";
ExtensionKind["ModuloOperatorType"] = "Modulo";
ExtensionKind["ModuloOperatorMethodType"] = "ModuloMethod";
ExtensionKind["PowerOperatorType"] = "Power";
ExtensionKind["PowerOperatorMethodType"] = "PowerMethod";
ExtensionKind["FloorDivisionOperatorType"] = "FloorDivision";
ExtensionKind["FloorDivisionOperatorMethodType"] = "FloorDivisionMethod";
ExtensionKind["BitwiseAndOperatorType"] = "BitwiseAnd";
ExtensionKind["BitwiseAndOperatorMethodType"] = "BitwiseAndMethod";
ExtensionKind["BitwiseOrOperatorType"] = "BitwiseOr";
ExtensionKind["BitwiseOrOperatorMethodType"] = "BitwiseOrMethod";
ExtensionKind["BitwiseExclusiveOrOperatorType"] = "BitwiseExclusiveOr";
ExtensionKind["BitwiseExclusiveOrOperatorMethodType"] = "BitwiseExclusiveOrMethod";
ExtensionKind["BitwiseLeftShiftOperatorType"] = "BitwiseLeftShift";
ExtensionKind["BitwiseLeftShiftOperatorMethodType"] = "BitwiseLeftShiftMethod";
ExtensionKind["BitwiseRightShiftOperatorType"] = "BitwiseRightShift";
ExtensionKind["BitwiseRightShiftOperatorMethodType"] = "BitwiseRightShiftMethod";
ExtensionKind["ConcatOperatorType"] = "Concat";
ExtensionKind["ConcatOperatorMethodType"] = "ConcatMethod";
ExtensionKind["LessThanOperatorType"] = "LessThan";
ExtensionKind["LessThanOperatorMethodType"] = "LessThanMethod";
ExtensionKind["GreaterThanOperatorType"] = "GreaterThan";
ExtensionKind["GreaterThanOperatorMethodType"] = "GreaterThanMethod";
ExtensionKind["NegationOperatorType"] = "Negation";
ExtensionKind["NegationOperatorMethodType"] = "NegationMethod";
ExtensionKind["BitwiseNotOperatorType"] = "BitwiseNot";
ExtensionKind["BitwiseNotOperatorMethodType"] = "BitwiseNotMethod";
ExtensionKind["LengthOperatorType"] = "Length";
ExtensionKind["LengthOperatorMethodType"] = "LengthMethod";
ExtensionKind["TableNewType"] = "TableNew";
ExtensionKind["TableDeleteType"] = "TableDelete";
ExtensionKind["TableDeleteMethodType"] = "TableDeleteMethod";
ExtensionKind["TableGetType"] = "TableGet";
ExtensionKind["TableGetMethodType"] = "TableGetMethod";
ExtensionKind["TableHasType"] = "TableHas";
ExtensionKind["TableHasMethodType"] = "TableHasMethod";
ExtensionKind["TableSetType"] = "TableSet";
ExtensionKind["TableSetMethodType"] = "TableSetMethod";
ExtensionKind["TableAddKeyType"] = "TableAddKey";
ExtensionKind["TableAddKeyMethodType"] = "TableAddKeyMethod";
})(ExtensionKind = exports.ExtensionKind || (exports.ExtensionKind = {}));
const extensionKindToValueName = {
[ExtensionKind.MultiFunction]: "$multi",
[ExtensionKind.RangeFunction]: "$range",
[ExtensionKind.VarargConstant]: "$vararg",
};
const extensionKindToTypeBrand = {
[ExtensionKind.MultiFunction]: "__luaMultiFunctionBrand",
[ExtensionKind.MultiType]: "__luaMultiReturnBrand",
[ExtensionKind.RangeFunction]: "__luaRangeFunctionBrand",
[ExtensionKind.VarargConstant]: "__luaVarargConstantBrand",
[ExtensionKind.IterableType]: "__luaIterableBrand",
[ExtensionKind.PairsIterableType]: "__luaPairsIterableBrand",
[ExtensionKind.AdditionOperatorType]: "__luaAdditionBrand",
[ExtensionKind.AdditionOperatorMethodType]: "__luaAdditionMethodBrand",
[ExtensionKind.SubtractionOperatorType]: "__luaSubtractionBrand",
[ExtensionKind.SubtractionOperatorMethodType]: "__luaSubtractionMethodBrand",
[ExtensionKind.MultiplicationOperatorType]: "__luaMultiplicationBrand",
[ExtensionKind.MultiplicationOperatorMethodType]: "__luaMultiplicationMethodBrand",
[ExtensionKind.DivisionOperatorType]: "__luaDivisionBrand",
[ExtensionKind.DivisionOperatorMethodType]: "__luaDivisionMethodBrand",
[ExtensionKind.ModuloOperatorType]: "__luaModuloBrand",
[ExtensionKind.ModuloOperatorMethodType]: "__luaModuloMethodBrand",
[ExtensionKind.PowerOperatorType]: "__luaPowerBrand",
[ExtensionKind.PowerOperatorMethodType]: "__luaPowerMethodBrand",
[ExtensionKind.FloorDivisionOperatorType]: "__luaFloorDivisionBrand",
[ExtensionKind.FloorDivisionOperatorMethodType]: "__luaFloorDivisionMethodBrand",
[ExtensionKind.BitwiseAndOperatorType]: "__luaBitwiseAndBrand",
[ExtensionKind.BitwiseAndOperatorMethodType]: "__luaBitwiseAndMethodBrand",
[ExtensionKind.BitwiseOrOperatorType]: "__luaBitwiseOrBrand",
[ExtensionKind.BitwiseOrOperatorMethodType]: "__luaBitwiseOrMethodBrand",
[ExtensionKind.BitwiseExclusiveOrOperatorType]: "__luaBitwiseExclusiveOrBrand",
[ExtensionKind.BitwiseExclusiveOrOperatorMethodType]: "__luaBitwiseExclusiveOrMethodBrand",
[ExtensionKind.BitwiseLeftShiftOperatorType]: "__luaBitwiseLeftShiftBrand",
[ExtensionKind.BitwiseLeftShiftOperatorMethodType]: "__luaBitwiseLeftShiftMethodBrand",
[ExtensionKind.BitwiseRightShiftOperatorType]: "__luaBitwiseRightShiftBrand",
[ExtensionKind.BitwiseRightShiftOperatorMethodType]: "__luaBitwiseRightShiftMethodBrand",
[ExtensionKind.ConcatOperatorType]: "__luaConcatBrand",
[ExtensionKind.ConcatOperatorMethodType]: "__luaConcatMethodBrand",
[ExtensionKind.LessThanOperatorType]: "__luaLessThanBrand",
[ExtensionKind.LessThanOperatorMethodType]: "__luaLessThanMethodBrand",
[ExtensionKind.GreaterThanOperatorType]: "__luaGreaterThanBrand",
[ExtensionKind.GreaterThanOperatorMethodType]: "__luaGreaterThanMethodBrand",
[ExtensionKind.NegationOperatorType]: "__luaNegationBrand",
[ExtensionKind.NegationOperatorMethodType]: "__luaNegationMethodBrand",
[ExtensionKind.BitwiseNotOperatorType]: "__luaBitwiseNotBrand",
[ExtensionKind.BitwiseNotOperatorMethodType]: "__luaBitwiseNotMethodBrand",
[ExtensionKind.LengthOperatorType]: "__luaLengthBrand",
[ExtensionKind.LengthOperatorMethodType]: "__luaLengthMethodBrand",
[ExtensionKind.TableNewType]: "__luaTableNewBrand",
[ExtensionKind.TableDeleteType]: "__luaTableDeleteBrand",
[ExtensionKind.TableDeleteMethodType]: "__luaTableDeleteMethodBrand",
[ExtensionKind.TableGetType]: "__luaTableGetBrand",
[ExtensionKind.TableGetMethodType]: "__luaTableGetMethodBrand",
[ExtensionKind.TableHasType]: "__luaTableHasBrand",
[ExtensionKind.TableHasMethodType]: "__luaTableHasMethodBrand",
[ExtensionKind.TableSetType]: "__luaTableSetBrand",
[ExtensionKind.TableSetMethodType]: "__luaTableSetMethodBrand",
};
function isExtensionType(type, extensionKind) {
const typeBrand = extensionKindToTypeBrand[extensionKind];
return typeBrand !== undefined && type.getProperty(typeBrand) !== undefined;
const extensionValues = new Set(Object.values(ExtensionKind));
function getExtensionKindForType(context, type) {
const value = getPropertyValue(context, type, "__tstlExtension");
if (value && extensionValues.has(value)) {
return value;
}
}
exports.isExtensionType = isExtensionType;
function getExtensionKinds(type) {
return Object.keys(extensionKindToTypeBrand).filter(e => type.getProperty(extensionKindToTypeBrand[e]) !== undefined);
exports.getExtensionKindForType = getExtensionKindForType;
const excludedTypeFlags = ((1 << 18) - 1) | // All flags from Any...Never
ts.TypeFlags.Index |
ts.TypeFlags.NonPrimitive;
function getPropertyValue(context, type, propertyName) {
if (type.flags & excludedTypeFlags)
return;
const property = type.getProperty(propertyName);
if (!property)
return undefined;
const propertyType = context.checker.getTypeOfSymbolAtLocation(property, context.sourceFile);
if (propertyType.isStringLiteral())
return propertyType.value;
}
exports.getExtensionKinds = getExtensionKinds;
function isExtensionValue(context, symbol, extensionKind) {
var _a;
return (symbol.getName() === extensionKindToValueName[extensionKind] &&
((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.some(d => isExtensionType(context.checker.getTypeAtLocation(d), extensionKind))) === true);
function getExtensionKindForNode(context, node) {
const originalNode = ts.getOriginalNode(node);
let type = context.checker.getTypeAtLocation(originalNode);
if (ts.isOptionalChain(originalNode)) {
type = context.checker.getNonNullableType(type);
}
return getExtensionKindForType(context, type);
}
exports.isExtensionValue = isExtensionValue;
exports.getExtensionKindForNode = getExtensionKindForNode;
function getExtensionKindForSymbol(context, symbol) {
const type = context.checker.getTypeOfSymbolAtLocation(symbol, context.sourceFile);
return getExtensionKindForType(context, type);
}
exports.getExtensionKindForSymbol = getExtensionKindForSymbol;
var IterableExtensionKind;
(function (IterableExtensionKind) {
IterableExtensionKind["Iterable"] = "Iterable";
IterableExtensionKind["Pairs"] = "Pairs";
IterableExtensionKind["PairsKey"] = "PairsKey";
})(IterableExtensionKind = exports.IterableExtensionKind || (exports.IterableExtensionKind = {}));
function getIterableExtensionTypeForType(context, type) {
const value = getPropertyValue(context, type, "__tstlIterable");
if (value && value in IterableExtensionKind) {
return value;
}
}
exports.getIterableExtensionTypeForType = getIterableExtensionTypeForType;
function getIterableExtensionKindForNode(context, node) {
const type = context.checker.getTypeAtLocation(node);
return getIterableExtensionTypeForType(context, type);
}
exports.getIterableExtensionKindForNode = getIterableExtensionKindForNode;
//# sourceMappingURL=language-extensions.js.map

@@ -6,4 +6,3 @@ import * as ts from "typescript";

export { LuaLibFeature };
export declare function getUsedLuaLibFeatures(context: TransformationContext): Set<LuaLibFeature>;
export declare function importLuaLibFeature(context: TransformationContext, feature: LuaLibFeature): void;
export declare function transformLuaLibFunction(context: TransformationContext, feature: LuaLibFeature, tsParent?: ts.Node, ...params: lua.Expression[]): lua.CallExpression;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformLuaLibFunction = exports.importLuaLibFeature = exports.getUsedLuaLibFeatures = exports.LuaLibFeature = void 0;
exports.transformLuaLibFunction = exports.importLuaLibFeature = exports.LuaLibFeature = void 0;
const lua = require("../../LuaAST");
const LuaLib_1 = require("../../LuaLib");
Object.defineProperty(exports, "LuaLibFeature", { enumerable: true, get: function () { return LuaLib_1.LuaLibFeature; } });
const utils_1 = require("../../utils");
const luaLibFeatures = new WeakMap();
function getUsedLuaLibFeatures(context) {
return (0, utils_1.getOrUpdate)(luaLibFeatures, context, () => new Set());
}
exports.getUsedLuaLibFeatures = getUsedLuaLibFeatures;
function importLuaLibFeature(context, feature) {
getUsedLuaLibFeatures(context).add(feature);
context.usedLuaLibFeatures.add(feature);
}

@@ -16,0 +10,0 @@ exports.importLuaLibFeature = importLuaLibFeature;

@@ -9,3 +9,3 @@ import * as ts from "typescript";

export declare function hasUnsafeSymbolName(context: TransformationContext, symbol: ts.Symbol, tsOriginal: ts.Identifier): boolean;
export declare function hasUnsafeIdentifierName(context: TransformationContext, identifier: ts.Identifier, checkSymbol?: boolean): boolean;
export declare function hasUnsafeIdentifierName(context: TransformationContext, identifier: ts.Identifier, symbol: ts.Symbol | undefined): boolean;
export declare const createSafeName: (name: string) => string;

@@ -83,8 +83,5 @@ "use strict";

exports.hasUnsafeSymbolName = hasUnsafeSymbolName;
function hasUnsafeIdentifierName(context, identifier, checkSymbol = true) {
if (checkSymbol) {
const symbol = context.checker.getSymbolAtLocation(identifier);
if (symbol) {
return hasUnsafeSymbolName(context, symbol, identifier);
}
function hasUnsafeIdentifierName(context, identifier, symbol) {
if (symbol) {
return hasUnsafeSymbolName(context, symbol, identifier);
}

@@ -91,0 +88,0 @@ return checkName(context, identifier.text, identifier);

@@ -39,4 +39,2 @@ import * as ts from "typescript";

export declare function findScope(context: TransformationContext, scopeTypes: ScopeType): Scope | undefined;
export declare function pushScope(context: TransformationContext, scopeType: ScopeType): Scope;
export declare function popScope(context: TransformationContext): Scope;
export declare function addScopeVariableDeclaration(scope: Scope, declaration: lua.VariableDeclarationStatement): void;

@@ -43,0 +41,0 @@ export declare function hasReferencedUndefinedLocalFunction(context: TransformationContext, scope: Scope): boolean;

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.performHoisting = exports.separateHoistedStatements = exports.isFunctionScopeWithDefinition = exports.hasReferencedSymbol = exports.hasReferencedUndefinedLocalFunction = exports.addScopeVariableDeclaration = exports.popScope = exports.pushScope = exports.findScope = exports.peekScope = exports.markSymbolAsReferencedInCurrentScopes = exports.walkScopesUp = exports.ScopeType = void 0;
exports.performHoisting = exports.separateHoistedStatements = exports.isFunctionScopeWithDefinition = exports.hasReferencedSymbol = exports.hasReferencedUndefinedLocalFunction = exports.addScopeVariableDeclaration = exports.findScope = exports.peekScope = exports.markSymbolAsReferencedInCurrentScopes = exports.walkScopesUp = exports.ScopeType = void 0;
const ts = require("typescript");

@@ -21,8 +21,4 @@ const lua = require("../../LuaAST");

})(ScopeType = exports.ScopeType || (exports.ScopeType = {}));
const scopeStacks = new WeakMap();
function getScopeStack(context) {
return (0, utils_1.getOrUpdate)(scopeStacks, context, () => []);
}
function* walkScopesUp(context) {
const scopeStack = getScopeStack(context);
const scopeStack = context.scopeStack;
for (let i = scopeStack.length - 1; i >= 0; --i) {

@@ -35,3 +31,3 @@ const scope = scopeStack[i];

function markSymbolAsReferencedInCurrentScopes(context, symbolId, identifier) {
for (const scope of getScopeStack(context)) {
for (const scope of context.scopeStack) {
if (!scope.referencedSymbols) {

@@ -46,3 +42,3 @@ scope.referencedSymbols = new Map();

function peekScope(context) {
const scopeStack = getScopeStack(context);
const scopeStack = context.scopeStack;
const scope = scopeStack[scopeStack.length - 1];

@@ -54,23 +50,10 @@ (0, utils_1.assert)(scope);

function findScope(context, scopeTypes) {
return [...getScopeStack(context)].reverse().find(s => scopeTypes & s.type);
for (let i = context.scopeStack.length - 1; i >= 0; --i) {
const scope = context.scopeStack[i];
if (scopeTypes & scope.type) {
return scope;
}
}
}
exports.findScope = findScope;
const scopeIdCounters = new WeakMap();
function pushScope(context, scopeType) {
var _a;
const nextScopeId = ((_a = scopeIdCounters.get(context)) !== null && _a !== void 0 ? _a : 0) + 1;
scopeIdCounters.set(context, nextScopeId);
const scopeStack = getScopeStack(context);
const scope = { type: scopeType, id: nextScopeId };
scopeStack.push(scope);
return scope;
}
exports.pushScope = pushScope;
function popScope(context) {
const scopeStack = getScopeStack(context);
const scope = scopeStack.pop();
(0, utils_1.assert)(scope);
return scope;
}
exports.popScope = popScope;
function addScopeVariableDeclaration(scope, declaration) {

@@ -77,0 +60,0 @@ if (!scope.variableDeclarations) {

@@ -11,2 +11,2 @@ import * as ts from "typescript";

export declare function trackSymbolReference(context: TransformationContext, symbol: ts.Symbol, identifier: ts.Identifier): lua.SymbolId | undefined;
export declare function getIdentifierSymbolId(context: TransformationContext, identifier: ts.Identifier): lua.SymbolId | undefined;
export declare function getIdentifierSymbolId(context: TransformationContext, identifier: ts.Identifier, symbol: ts.Symbol | undefined): lua.SymbolId | undefined;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getIdentifierSymbolId = exports.trackSymbolReference = exports.getSymbolIdOfSymbol = exports.getSymbolInfo = void 0;
const utils_1 = require("../../utils");
const spread_1 = require("../visitors/spread");
const scope_1 = require("./scope");
const symbolIdCounters = new WeakMap();
function nextSymbolId(context) {
var _a;
const symbolId = ((_a = symbolIdCounters.get(context)) !== null && _a !== void 0 ? _a : 0) + 1;
symbolIdCounters.set(context, symbolId);
return symbolId;
}
const symbolInfoMap = new WeakMap();
const symbolIdMaps = new WeakMap();
function getSymbolInfo(context, symbolId) {
return (0, utils_1.getOrUpdate)(symbolInfoMap, context, () => new Map()).get(symbolId);
return context.symbolInfoMap.get(symbolId);
}
exports.getSymbolInfo = getSymbolInfo;
function getSymbolIdOfSymbol(context, symbol) {
return (0, utils_1.getOrUpdate)(symbolIdMaps, context, () => new Map()).get(symbol);
return context.symbolIdMaps.get(symbol);
}
exports.getSymbolIdOfSymbol = getSymbolIdOfSymbol;
function trackSymbolReference(context, symbol, identifier) {
const symbolIds = (0, utils_1.getOrUpdate)(symbolIdMaps, context, () => new Map());
// Track first time symbols are seen
let symbolId = symbolIds.get(symbol);
let symbolId = context.symbolIdMaps.get(symbol);
if (symbolId === undefined) {
symbolId = nextSymbolId(context);
symbolIds.set(symbol, symbolId);
const symbolInfo = (0, utils_1.getOrUpdate)(symbolInfoMap, context, () => new Map());
symbolInfo.set(symbolId, { symbol, firstSeenAtPos: identifier.pos });
symbolId = context.nextSymbolId();
context.symbolIdMaps.set(symbol, symbolId);
context.symbolInfoMap.set(symbolId, { symbol, firstSeenAtPos: identifier.pos });
}

@@ -42,4 +30,3 @@ // If isOptimizedVarArgSpread returns true, the identifier will not appear in the resulting Lua.

exports.trackSymbolReference = trackSymbolReference;
function getIdentifierSymbolId(context, identifier) {
const symbol = context.checker.getSymbolAtLocation(identifier);
function getIdentifierSymbolId(context, identifier, symbol) {
if (symbol) {

@@ -46,0 +33,0 @@ return trackSymbolReference(context, symbol, identifier);

@@ -12,2 +12,3 @@ import * as ts from "typescript";

export declare function getFirstDeclarationInFile(symbol: ts.Symbol, sourceFile: ts.SourceFile): ts.Declaration | undefined;
export declare function isStandardLibraryDeclaration(context: TransformationContext, declaration: ts.Declaration): boolean;
export declare function isStandardLibraryType(context: TransformationContext, type: ts.Type, name: string | undefined): boolean;

@@ -14,0 +15,0 @@ export declare function hasStandardLibrarySignature(context: TransformationContext, callExpression: ts.CallExpression): boolean;

@@ -17,3 +17,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.isConstIdentifier = exports.getFunctionTypeForCall = exports.isExpressionWithEvaluationEffect = exports.getAllCallSignatures = exports.inferAssignedType = exports.hasStandardLibrarySignature = exports.isStandardLibraryType = exports.getFirstDeclarationInFile = exports.findFirstNonOuterParent = exports.findFirstNodeAbove = exports.hasExportEquals = void 0;
exports.isConstIdentifier = exports.getFunctionTypeForCall = exports.isExpressionWithEvaluationEffect = exports.getAllCallSignatures = exports.inferAssignedType = exports.hasStandardLibrarySignature = exports.isStandardLibraryType = exports.isStandardLibraryDeclaration = exports.getFirstDeclarationInFile = exports.findFirstNonOuterParent = exports.findFirstNodeAbove = exports.hasExportEquals = void 0;
const ts = require("typescript");

@@ -66,2 +66,3 @@ __exportStar(require("./nodes"), exports);

}
exports.isStandardLibraryDeclaration = isStandardLibraryDeclaration;
function isStandardLibraryType(context, type, name) {

@@ -68,0 +69,0 @@ const symbol = type.getSymbol();

import * as ts from "typescript";
import { TransformationContext } from "../../context";
export declare function isTypeWithFlags(context: TransformationContext, type: ts.Type, flags: ts.TypeFlags): boolean;
export declare function typeAlwaysSatisfies(context: TransformationContext, type: ts.Type, predicate: (type: ts.Type) => boolean): boolean;
export declare function typeCanSatisfy(context: TransformationContext, type: ts.Type, predicate: (type: ts.Type) => boolean): boolean;
export declare function isNullishType(context: TransformationContext, type: ts.Type): boolean;
export declare function typeAlwaysHasSomeOfFlags(context: TransformationContext, type: ts.Type, flags: ts.TypeFlags): boolean;
export declare function typeCanHaveSomeOfFlags(context: TransformationContext, type: ts.Type, flags: ts.TypeFlags): boolean;
export declare function isStringType(context: TransformationContext, type: ts.Type): boolean;
export declare function isNumberType(context: TransformationContext, type: ts.Type): boolean;
export declare function isNullableType(context: TransformationContext, type: ts.Type, isType: (c: TransformationContext, t: ts.Type) => boolean): boolean;
/**

@@ -11,0 +8,0 @@ * Iterate over a type and its bases until the callback returns true.

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.canBeFalsyWhenNotNull = exports.canBeFalsy = exports.isFunctionType = exports.isArrayType = exports.forTypeOrAnySupertype = exports.isNullableType = exports.isNumberType = exports.isStringType = exports.isNullishType = exports.typeCanSatisfy = exports.typeAlwaysSatisfies = exports.isTypeWithFlags = void 0;
exports.canBeFalsyWhenNotNull = exports.canBeFalsy = exports.isFunctionType = exports.isArrayType = exports.forTypeOrAnySupertype = exports.isNumberType = exports.isStringType = exports.typeCanHaveSomeOfFlags = exports.typeAlwaysHasSomeOfFlags = void 0;
const ts = require("typescript");
function isTypeWithFlags(context, type, flags) {
const predicate = (type) => (type.flags & flags) !== 0;
return typeAlwaysSatisfies(context, type, predicate);
}
exports.isTypeWithFlags = isTypeWithFlags;
function typeAlwaysSatisfies(context, type, predicate) {
function typeAlwaysHasSomeOfFlags(context, type, flags) {
const baseConstraint = context.checker.getBaseConstraintOfType(type);

@@ -15,15 +10,15 @@ if (baseConstraint) {

}
if (predicate(type)) {
if (type.flags & flags) {
return true;
}
if (type.isUnion()) {
return type.types.every(t => typeAlwaysSatisfies(context, t, predicate));
return type.types.every(t => typeAlwaysHasSomeOfFlags(context, t, flags));
}
if (type.isIntersection()) {
return type.types.some(t => typeAlwaysSatisfies(context, t, predicate));
return type.types.some(t => typeAlwaysHasSomeOfFlags(context, t, flags));
}
return false;
}
exports.typeAlwaysSatisfies = typeAlwaysSatisfies;
function typeCanSatisfy(context, type, predicate) {
exports.typeAlwaysHasSomeOfFlags = typeAlwaysHasSomeOfFlags;
function typeCanHaveSomeOfFlags(context, type, flags) {
const baseConstraint = context.checker.getBaseConstraintOfType(type);

@@ -38,32 +33,25 @@ if (!baseConstraint) {

}
if (predicate(type)) {
if (type.flags & flags) {
return true;
}
if (type.isUnion()) {
return type.types.some(t => typeCanSatisfy(context, t, predicate));
return type.types.some(t => typeCanHaveSomeOfFlags(context, t, flags));
}
if (type.isIntersection()) {
return type.types.some(t => typeCanSatisfy(context, t, predicate));
return type.types.some(t => typeCanHaveSomeOfFlags(context, t, flags));
}
return false;
}
exports.typeCanSatisfy = typeCanSatisfy;
function isNullishType(context, type) {
return isTypeWithFlags(context, type, ts.TypeFlags.Undefined | ts.TypeFlags.Null | ts.TypeFlags.VoidLike);
}
exports.isNullishType = isNullishType;
exports.typeCanHaveSomeOfFlags = typeCanHaveSomeOfFlags;
function isStringType(context, type) {
return isTypeWithFlags(context, type, ts.TypeFlags.String | ts.TypeFlags.StringLike | ts.TypeFlags.StringLiteral);
return typeAlwaysHasSomeOfFlags(context, type, ts.TypeFlags.StringLike);
}
exports.isStringType = isStringType;
function isNumberType(context, type) {
return isTypeWithFlags(context, type, ts.TypeFlags.Number | ts.TypeFlags.NumberLike | ts.TypeFlags.NumberLiteral);
return typeAlwaysHasSomeOfFlags(context, type, ts.TypeFlags.NumberLike);
}
exports.isNumberType = isNumberType;
function isNullableType(context, type, isType) {
return (typeCanSatisfy(context, type, t => isType(context, t)) &&
typeAlwaysSatisfies(context, type, t => isType(context, t) || isNullishType(context, t)));
}
exports.isNullableType = isNullableType;
function isExplicitArrayType(context, type) {
if (context.checker.isArrayType(type) || context.checker.isTupleType(type))
return true;
if (type.symbol) {

@@ -78,8 +66,3 @@ const baseConstraint = context.checker.getBaseConstraintOfType(type);

}
const flags = ts.NodeBuilderFlags.InTypeAlias | ts.NodeBuilderFlags.AllowEmptyTuple;
let typeNode = context.checker.typeToTypeNode(type, undefined, flags);
if (typeNode && ts.isTypeOperatorNode(typeNode) && typeNode.operator === ts.SyntaxKind.ReadonlyKeyword) {
typeNode = typeNode.type;
}
return typeNode !== undefined && (ts.isArrayTypeNode(typeNode) || ts.isTupleTypeNode(typeNode));
return false;
}

@@ -90,3 +73,2 @@ /**

function forTypeOrAnySupertype(context, type, predicate) {
var _a;
if (predicate(type)) {

@@ -98,3 +80,6 @@ return true;

}
return ((_a = type.getBaseTypes()) !== null && _a !== void 0 ? _a : []).some(superType => forTypeOrAnySupertype(context, superType, predicate));
const baseTypes = type.getBaseTypes();
if (!baseTypes)
return false;
return baseTypes.some(superType => forTypeOrAnySupertype(context, superType, predicate));
}

@@ -112,2 +97,4 @@ exports.forTypeOrAnySupertype = forTypeOrAnySupertype;

const strictNullChecks = context.options.strict === true || context.options.strictNullChecks === true;
if (!strictNullChecks && !type.isLiteral())
return true;
const falsyFlags = ts.TypeFlags.Boolean |

@@ -121,6 +108,9 @@ ts.TypeFlags.BooleanLiteral |

ts.TypeFlags.Null;
return typeCanSatisfy(context, type, type => (type.flags & falsyFlags) !== 0 || (!strictNullChecks && !type.isLiteral()));
return typeCanHaveSomeOfFlags(context, type, falsyFlags);
}
exports.canBeFalsy = canBeFalsy;
function canBeFalsyWhenNotNull(context, type) {
const strictNullChecks = context.options.strict === true || context.options.strictNullChecks === true;
if (!strictNullChecks && !type.isLiteral())
return true;
const falsyFlags = ts.TypeFlags.Boolean |

@@ -132,5 +122,5 @@ ts.TypeFlags.BooleanLiteral |

ts.TypeFlags.Any;
return typeCanSatisfy(context, type, type => (type.flags & falsyFlags) !== 0);
return typeCanHaveSomeOfFlags(context, type, falsyFlags);
}
exports.canBeFalsyWhenNotNull = canBeFalsyWhenNotNull;
//# sourceMappingURL=types.js.map

@@ -79,6 +79,2 @@ "use strict";

const isOptionalLeft = (0, optional_chaining_1.isOptionalContinuation)(node.expression);
const annotations = (0, annotations_1.getTypeAnnotations)(type);
if (annotations.has(annotations_1.AnnotationKind.LuaTable)) {
context.diagnostics.push((0, diagnostics_1.annotationRemoved)(node, annotations_1.AnnotationKind.LuaTable));
}
const constEnumValue = (0, enum_1.tryGetConstEnumValue)(context, node);

@@ -95,2 +91,3 @@ if (constEnumValue) {

// Do not output path for member only enums
const annotations = (0, annotations_1.getTypeAnnotations)(type);
if (annotations.has(annotations_1.AnnotationKind.CompileMembersOnly)) {

@@ -97,0 +94,0 @@ if (isOptionalLeft) {

@@ -12,5 +12,5 @@ "use strict";

function transformScopeBlock(context, node, scopeType) {
(0, scope_1.pushScope)(context, scopeType);
context.pushScope(scopeType);
const statements = (0, scope_1.performHoisting)(context, context.transformStatements(node.statements));
const scope = (0, scope_1.popScope)(context);
const scope = context.popScope();
return [lua.createBlock(statements, node), scope];

@@ -20,5 +20,5 @@ }

const transformBlock = (node, context) => {
(0, scope_1.pushScope)(context, scope_1.ScopeType.Block);
context.pushScope(scope_1.ScopeType.Block);
const statements = (0, scope_1.performHoisting)(context, context.transformStatements(node.statements));
(0, scope_1.popScope)(context);
context.popScope();
return lua.createDoStatement(statements, node);

@@ -25,0 +25,0 @@ };

@@ -7,3 +7,2 @@ "use strict";

const builtins_1 = require("../builtins");
const annotations_1 = require("../utils/annotations");
const assignment_validation_1 = require("../utils/assignment-validation");

@@ -20,4 +19,4 @@ const function_context_1 = require("../utils/function-context");

const optional_chaining_1 = require("./optional-chaining");
const language_extensions_1 = require("./language-extensions");
const import_1 = require("./modules/import");
const call_extension_1 = require("./language-extensions/call-extension");
function validateArguments(context, params, signature) {

@@ -29,5 +28,5 @@ if (!signature || signature.parameters.length < params.length) {

const signatureParameter = signature.parameters[index];
const paramType = context.checker.getTypeAtLocation(param);
if (signatureParameter.valueDeclaration !== undefined) {
const signatureType = context.checker.getTypeAtLocation(signatureParameter.valueDeclaration);
const paramType = context.checker.getTypeAtLocation(param);
(0, assignment_validation_1.validateAssignment)(context, param, paramType, signatureType, signatureParameter.name);

@@ -163,16 +162,10 @@ }

const wrapResultInTable = (0, multi_1.isMultiReturnCall)(context, node) && (0, multi_1.shouldMultiReturnCallBeWrapped)(context, node);
if ((0, annotations_1.isTupleReturnCall)(context, node)) {
context.diagnostics.push((0, diagnostics_1.annotationRemoved)(node, annotations_1.AnnotationKind.TupleReturn));
}
const builtinOrExtensionResult = (_a = (0, builtins_1.transformBuiltinCallExpression)(context, node, optionalContinuation !== undefined)) !== null && _a !== void 0 ? _a : (0, language_extensions_1.transformLanguageExtensionCallExpression)(context, node, optionalContinuation !== undefined);
const builtinOrExtensionResult = (_a = (0, builtins_1.transformBuiltinCallExpression)(context, node)) !== null && _a !== void 0 ? _a : (0, call_extension_1.transformLanguageExtensionCallExpression)(context, node);
if (builtinOrExtensionResult) {
// unsupportedOptionalCall diagnostic already present
if (optionalContinuation !== undefined) {
context.diagnostics.push((0, diagnostics_1.unsupportedBuiltinOptionalCall)(node));
}
return wrapResultInTable ? (0, lua_ast_1.wrapInTable)(builtinOrExtensionResult) : builtinOrExtensionResult;
}
if (ts.isPropertyAccessExpression(calledExpression)) {
const ownerType = context.checker.getTypeAtLocation(calledExpression.expression);
const annotations = (0, annotations_1.getTypeAnnotations)(ownerType);
if (annotations.has(annotations_1.AnnotationKind.LuaTable)) {
context.diagnostics.push((0, diagnostics_1.annotationRemoved)(node, annotations_1.AnnotationKind.LuaTable));
}
const result = transformPropertyCall(context, node, calledExpression);

@@ -218,9 +211,5 @@ return wrapResultInTable ? (0, lua_ast_1.wrapInTable)(result) : result;

function getCalledExpression(node) {
function unwrapExpression(expression) {
expression = ts.skipOuterExpressions(expression);
return ts.isNonNullExpression(expression) ? unwrapExpression(expression.expression) : expression;
}
return unwrapExpression(node.expression);
return ts.skipOuterExpressions(node.expression);
}
exports.getCalledExpression = getCalledExpression;
//# sourceMappingURL=call.js.map

@@ -6,5 +6,2 @@ "use strict";

const lua = require("../../../LuaAST");
const utils_1 = require("../../../utils");
const annotations_1 = require("../../utils/annotations");
const diagnostics_1 = require("../../utils/diagnostics");
const export_1 = require("../../utils/export");

@@ -19,3 +16,3 @@ const lua_ast_1 = require("../../utils/lua-ast");

const method_1 = require("./members/method");
const utils_2 = require("./utils");
const utils_1 = require("./utils");
const setup_1 = require("./setup");

@@ -41,3 +38,2 @@ const transformClassDeclaration = (declaration, context) => {

exports.transformClassAsExpression = transformClassAsExpression;
const classSuperInfos = new WeakMap();
function transformClassLikeDeclaration(classDeclaration, context, nameOverride) {

@@ -54,18 +50,10 @@ let className;

}
const annotations = (0, annotations_1.getTypeAnnotations)(context.checker.getTypeAtLocation(classDeclaration));
if (annotations.has(annotations_1.AnnotationKind.Extension)) {
context.diagnostics.push((0, diagnostics_1.annotationRemoved)(classDeclaration, annotations_1.AnnotationKind.Extension));
}
if (annotations.has(annotations_1.AnnotationKind.MetaExtension)) {
context.diagnostics.push((0, diagnostics_1.annotationRemoved)(classDeclaration, annotations_1.AnnotationKind.MetaExtension));
}
// Get type that is extended
const extendedTypeNode = (0, utils_2.getExtendedNode)(context, classDeclaration);
const extendedType = (0, utils_2.getExtendedType)(context, classDeclaration);
const superInfo = (0, utils_1.getOrUpdate)(classSuperInfos, context, () => []);
superInfo.push({ className, extendedTypeNode });
const extendedTypeNode = (0, utils_1.getExtendedNode)(classDeclaration);
const extendedType = (0, utils_1.getExtendedType)(context, classDeclaration);
context.classSuperInfos.push({ className, extendedTypeNode });
// Get all properties with value
const properties = classDeclaration.members.filter(ts.isPropertyDeclaration).filter(member => member.initializer);
// Divide properties into static and non-static
const instanceFields = properties.filter(prop => !(0, utils_2.isStaticNode)(prop));
const instanceFields = properties.filter(prop => !(0, utils_1.isStaticNode)(prop));
const result = [];

@@ -136,3 +124,3 @@ let localClassName;

else if (ts.isPropertyDeclaration(member)) {
if ((0, utils_2.isStaticNode)(member)) {
if ((0, utils_1.isStaticNode)(member)) {
const statement = (0, fields_1.transformStaticPropertyDeclaration)(context, member, localClassName);

@@ -161,7 +149,7 @@ if (statement)

}
superInfo.pop();
context.classSuperInfos.pop();
return { statements: result, name: className };
}
const transformSuperExpression = (expression, context) => {
const superInfos = (0, utils_1.getOrUpdate)(classSuperInfos, context, () => []);
const superInfos = context.classSuperInfos;
const superInfo = superInfos[superInfos.length - 1];

@@ -168,0 +156,0 @@ if (!superInfo)

@@ -25,3 +25,3 @@ "use strict";

// Transform body
const scope = (0, scope_1.pushScope)(context, scope_1.ScopeType.Function);
const scope = context.pushScope(scope_1.ScopeType.Function);
const body = (0, function_1.transformFunctionBodyContent)(context, statement.body);

@@ -62,3 +62,3 @@ const [params, dotsLiteral, restParamName] = (0, function_1.transformParameters)(context, statement.parameters, (0, lua_ast_1.createSelfIdentifier)());

const constructorWasGenerated = statement.pos === -1;
(0, scope_1.popScope)(context);
context.popScope();
return lua.createAssignmentStatement(createConstructorName(className), lua.createFunctionExpression(block, params, dotsLiteral, lua.NodeFlags.Declaration), constructorWasGenerated ? classDeclaration : statement);

@@ -65,0 +65,0 @@ }

@@ -13,7 +13,2 @@ "use strict";

var _a, _b;
const type = context.checker.getTypeAtLocation(node);
const annotations = (0, annotations_1.getTypeAnnotations)(type);
if (annotations.has(annotations_1.AnnotationKind.LuaTable)) {
context.diagnostics.push((0, diagnostics_1.annotationRemoved)(node, annotations_1.AnnotationKind.LuaTable));
}
if ((0, table_1.isTableNewCall)(context, node)) {

@@ -24,2 +19,4 @@ return lua.createTableExpression(undefined, node);

const [name, params] = (0, call_1.transformCallAndArguments)(context, node.expression, (_a = node.arguments) !== null && _a !== void 0 ? _a : [ts.factory.createTrue()], signature);
const type = context.checker.getTypeAtLocation(node);
const annotations = (0, annotations_1.getTypeAnnotations)(type);
const customConstructorAnnotation = annotations.get(annotations_1.AnnotationKind.CustomConstructor);

@@ -26,0 +23,0 @@ if (customConstructorAnnotation) {

@@ -5,2 +5,2 @@ import * as ts from "typescript";

export declare function createClassSetup(context: TransformationContext, statement: ts.ClassLikeDeclarationBase, className: lua.Identifier, localClassName: lua.Identifier, extendsType?: ts.Type): lua.Statement[];
export declare function getReflectionClassName(context: TransformationContext, declaration: ts.ClassLikeDeclarationBase, className: lua.Identifier): lua.Expression;
export declare function getReflectionClassName(declaration: ts.ClassLikeDeclarationBase, className: lua.Identifier): lua.Expression;

@@ -37,5 +37,5 @@ "use strict";

// localClassName.name = className
result.push(lua.createAssignmentStatement(lua.createTableIndexExpression(lua.cloneIdentifier(localClassName), lua.createStringLiteral("name")), getReflectionClassName(context, statement, className), statement));
result.push(lua.createAssignmentStatement(lua.createTableIndexExpression(lua.cloneIdentifier(localClassName), lua.createStringLiteral("name")), getReflectionClassName(statement, className), statement));
if (extendsType) {
const extendedNode = (0, utils_2.getExtendedNode)(context, statement);
const extendedNode = (0, utils_2.getExtendedNode)(statement);
(0, utils_1.assert)(extendedNode);

@@ -47,3 +47,3 @@ result.push(lua.createExpressionStatement((0, lualib_1.transformLuaLibFunction)(context, lualib_1.LuaLibFeature.ClassExtends, (0, utils_2.getExtendsClause)(statement), lua.cloneIdentifier(localClassName), context.transformExpression(extendedNode.expression))));

exports.createClassSetup = createClassSetup;
function getReflectionClassName(context, declaration, className) {
function getReflectionClassName(declaration, className) {
if (declaration.name) {

@@ -58,3 +58,3 @@ return lua.createStringLiteral(declaration.name.text);

}
if ((0, utils_2.getExtendedNode)(context, declaration)) {
if ((0, utils_2.getExtendedNode)(declaration)) {
return lua.createTableIndexExpression(className, lua.createStringLiteral("name"));

@@ -61,0 +61,0 @@ }

@@ -5,3 +5,3 @@ import * as ts from "typescript";

export declare function getExtendsClause(node: ts.ClassLikeDeclarationBase): ts.HeritageClause | undefined;
export declare function getExtendedNode(context: TransformationContext, node: ts.ClassLikeDeclarationBase): ts.ExpressionWithTypeArguments | undefined;
export declare function getExtendedNode(node: ts.ClassLikeDeclarationBase): ts.ExpressionWithTypeArguments | undefined;
export declare function getExtendedType(context: TransformationContext, node: ts.ClassLikeDeclarationBase): ts.Type | undefined;

@@ -5,4 +5,2 @@ "use strict";

const ts = require("typescript");
const annotations_1 = require("../../utils/annotations");
const diagnostics_1 = require("../../utils/diagnostics");
function isStaticNode(node) {

@@ -18,11 +16,6 @@ var _a;

exports.getExtendsClause = getExtendsClause;
function getExtendedNode(context, node) {
function getExtendedNode(node) {
const extendsClause = getExtendsClause(node);
if (!extendsClause)
return;
const superType = context.checker.getTypeAtLocation(extendsClause.types[0]);
const annotations = (0, annotations_1.getTypeAnnotations)(superType);
if (annotations.has(annotations_1.AnnotationKind.PureAbstract)) {
context.diagnostics.push((0, diagnostics_1.annotationRemoved)(extendsClause, annotations_1.AnnotationKind.PureAbstract));
}
return extendsClause.types[0];

@@ -32,3 +25,3 @@ }

function getExtendedType(context, node) {
const extendedNode = getExtendedNode(context, node);
const extendedNode = getExtendedNode(node);
return extendedNode && context.checker.getTypeAtLocation(extendedNode);

@@ -35,0 +28,0 @@ }

@@ -37,6 +37,6 @@ "use strict";

function transformIfStatement(statement, context) {
(0, scope_1.pushScope)(context, scope_1.ScopeType.Conditional);
context.pushScope(scope_1.ScopeType.Conditional);
const condition = context.transformExpression(statement.expression);
const statements = (0, scope_1.performHoisting)(context, (0, block_1.transformBlockOrStatement)(context, statement.thenStatement));
(0, scope_1.popScope)(context);
context.popScope();
const ifBlock = lua.createBlock(statements);

@@ -64,5 +64,5 @@ if (statement.elseStatement) {

else {
(0, scope_1.pushScope)(context, scope_1.ScopeType.Conditional);
context.pushScope(scope_1.ScopeType.Conditional);
const elseStatements = (0, scope_1.performHoisting)(context, (0, block_1.transformBlockOrStatement)(context, statement.elseStatement));
(0, scope_1.popScope)(context);
context.popScope();
const elseBlock = lua.createBlock(elseStatements);

@@ -69,0 +69,0 @@ return lua.createIfStatement(condition, ifBlock, elseBlock);

@@ -6,3 +6,3 @@ import * as ts from "typescript";

export declare function createCallableTable(functionExpression: lua.Expression): lua.Expression;
export declare function isFunctionTypeWithProperties(functionType: ts.Type): boolean;
export declare function isFunctionTypeWithProperties(context: TransformationContext, functionType: ts.Type): boolean;
export declare function transformFunctionBodyContent(context: TransformationContext, body: ts.ConciseBody): lua.Statement[];

@@ -9,0 +9,0 @@ export declare function transformFunctionBodyHeader(context: TransformationContext, bodyScope: Scope, parameters: ts.NodeArray<ts.ParameterDeclaration>, spreadIdentifier?: lua.Identifier): lua.Statement[];

@@ -7,4 +7,2 @@ "use strict";

const utils_1 = require("../../utils");
const annotations_1 = require("../utils/annotations");
const diagnostics_1 = require("../utils/diagnostics");
const export_1 = require("../utils/export");

@@ -60,5 +58,5 @@ const function_context_1 = require("../utils/function-context");

exports.createCallableTable = createCallableTable;
function isFunctionTypeWithProperties(functionType) {
function isFunctionTypeWithProperties(context, functionType) {
if (functionType.isUnion()) {
return functionType.types.some(isFunctionTypeWithProperties);
return functionType.types.some(t => isFunctionTypeWithProperties(context, t));
}

@@ -68,3 +66,3 @@ else {

functionType.getProperties().length > 0 &&
(0, language_extensions_1.getExtensionKinds)(functionType).length === 0 // ignore TSTL extension functions like $range
(0, language_extensions_1.getExtensionKindForType)(context, functionType) === undefined // ignore TSTL extension functions like $range
);

@@ -116,3 +114,3 @@ }

function transformFunctionBody(context, parameters, body, spreadIdentifier, node) {
const scope = (0, scope_1.pushScope)(context, scope_1.ScopeType.Function);
const scope = context.pushScope(scope_1.ScopeType.Function);
scope.node = node;

@@ -124,3 +122,3 @@ let bodyStatements = transformFunctionBodyContent(context, body);

const headerStatements = transformFunctionBodyHeader(context, scope, parameters, spreadIdentifier);
(0, scope_1.popScope)(context);
context.popScope();
return [[...headerStatements, ...bodyStatements], scope];

@@ -199,5 +197,2 @@ }

}
if ((0, annotations_1.getNodeAnnotations)(node).has(annotations_1.AnnotationKind.TupleReturn)) {
context.diagnostics.push((0, diagnostics_1.annotationRemoved)(node, annotations_1.AnnotationKind.TupleReturn));
}
const [functionExpression, functionScope] = transformFunctionToExpression(context, node);

@@ -214,3 +209,3 @@ const isNamedFunctionExpression = ts.isFunctionExpression(node) && node.name;

const nameIdentifier = (0, identifier_1.transformIdentifier)(context, node.name);
if (isFunctionTypeWithProperties(context.checker.getTypeAtLocation(node))) {
if (isFunctionTypeWithProperties(context, context.checker.getTypeAtLocation(node))) {
context.addPrecedingStatements([

@@ -228,3 +223,3 @@ lua.createVariableDeclarationStatement(nameIdentifier),

}
return isNamedFunctionExpression && isFunctionTypeWithProperties(context.checker.getTypeAtLocation(node))
return isNamedFunctionExpression && isFunctionTypeWithProperties(context, context.checker.getTypeAtLocation(node))
? createCallableTable(functionExpression)

@@ -236,5 +231,2 @@ : functionExpression;

var _a;
if ((0, annotations_1.getNodeAnnotations)(node).has(annotations_1.AnnotationKind.TupleReturn)) {
context.diagnostics.push((0, diagnostics_1.annotationRemoved)(node, annotations_1.AnnotationKind.TupleReturn));
}
// Don't transform functions without body (overload declarations)

@@ -260,3 +252,3 @@ if (node.body === undefined) {

// Wrap functions with properties into a callable table
const wrappedFunction = node.name && isFunctionTypeWithProperties(context.checker.getTypeAtLocation(node.name))
const wrappedFunction = node.name && isFunctionTypeWithProperties(context, context.checker.getTypeAtLocation(node.name))
? createCallableTable(functionExpression)

@@ -263,0 +255,0 @@ : functionExpression;

@@ -5,2 +5,3 @@ import * as ts from "typescript";

export declare function transformIdentifier(context: TransformationContext, identifier: ts.Identifier): lua.Identifier;
export declare function transformIdentifierWithSymbol(context: TransformationContext, node: ts.Identifier, symbol: ts.Symbol | undefined): lua.Expression;
export declare const transformIdentifierExpression: FunctionVisitor<ts.Identifier>;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformIdentifierExpression = exports.transformIdentifier = void 0;
exports.transformIdentifierExpression = exports.transformIdentifierWithSymbol = exports.transformIdentifier = void 0;
const ts = require("typescript");

@@ -9,55 +9,46 @@ const lua = require("../../LuaAST");

const context_1 = require("../context");
const annotations_1 = require("../utils/annotations");
const diagnostics_1 = require("../utils/diagnostics");
const export_1 = require("../utils/export");
const lualib_1 = require("../utils/lualib");
const safe_names_1 = require("../utils/safe-names");
const symbols_1 = require("../utils/symbols");
const multi_1 = require("./language-extensions/multi");
const operators_1 = require("./language-extensions/operators");
const range_1 = require("./language-extensions/range");
const table_1 = require("./language-extensions/table");
const vararg_1 = require("./language-extensions/vararg");
const optional_chaining_1 = require("./optional-chaining");
const typescript_1 = require("../utils/typescript");
const language_extensions_1 = require("../utils/language-extensions");
const call_extension_1 = require("./language-extensions/call-extension");
const identifier_1 = require("./language-extensions/identifier");
function transformIdentifier(context, identifier) {
return transformNonValueIdentifier(context, identifier, context.checker.getSymbolAtLocation(identifier));
}
exports.transformIdentifier = transformIdentifier;
function transformNonValueIdentifier(context, identifier, symbol) {
if ((0, optional_chaining_1.isOptionalContinuation)(identifier)) {
return lua.createIdentifier(identifier.text, undefined, context_1.tempSymbolId);
}
if ((0, multi_1.isMultiFunctionNode)(context, identifier)) {
context.diagnostics.push((0, diagnostics_1.invalidMultiFunctionUse)(identifier));
return lua.createAnonymousIdentifier(identifier);
const extensionKind = symbol
? (0, language_extensions_1.getExtensionKindForSymbol)(context, symbol)
: (0, language_extensions_1.getExtensionKindForNode)(context, identifier);
if (extensionKind) {
if (call_extension_1.callExtensions.has(extensionKind)) {
context.diagnostics.push((0, diagnostics_1.invalidCallExtensionUse)(identifier));
// fall through
}
else if ((0, identifier_1.isIdentifierExtensionValue)(symbol, extensionKind)) {
(0, identifier_1.reportInvalidExtensionValue)(context, identifier, extensionKind);
return lua.createAnonymousIdentifier(identifier);
}
}
if ((0, operators_1.isOperatorMapping)(context, identifier)) {
context.diagnostics.push((0, diagnostics_1.invalidOperatorMappingUse)(identifier));
}
if ((0, table_1.isTableExtensionIdentifier)(context, identifier)) {
context.diagnostics.push((0, diagnostics_1.invalidTableExtensionUse)(identifier));
}
if ((0, range_1.isRangeFunctionNode)(context, identifier)) {
context.diagnostics.push((0, diagnostics_1.invalidRangeUse)(identifier));
return lua.createAnonymousIdentifier(identifier);
}
if ((0, vararg_1.isVarargConstantNode)(context, identifier)) {
context.diagnostics.push((0, diagnostics_1.invalidVarargUse)(identifier));
return lua.createAnonymousIdentifier(identifier);
}
if ((0, annotations_1.isForRangeType)(context, identifier)) {
context.diagnostics.push((0, diagnostics_1.annotationRemoved)(identifier, annotations_1.AnnotationKind.ForRange));
}
if ((0, promise_1.isPromiseClass)(context, identifier)) {
(0, lualib_1.importLuaLibFeature)(context, lualib_1.LuaLibFeature.Promise);
return (0, promise_1.createPromiseIdentifier)(identifier);
}
const type = context.checker.getTypeAtLocation(identifier);
if ((0, typescript_1.isStandardLibraryType)(context, type, undefined)) {
(0, builtins_1.checkForLuaLibType)(context, type);
if ((0, promise_1.isPromiseClass)(context, identifier)) {
return (0, promise_1.createPromiseIdentifier)(identifier);
}
}
const text = (0, safe_names_1.hasUnsafeIdentifierName)(context, identifier) ? (0, safe_names_1.createSafeName)(identifier.text) : identifier.text;
const symbolId = (0, symbols_1.getIdentifierSymbolId)(context, identifier);
const text = (0, safe_names_1.hasUnsafeIdentifierName)(context, identifier, symbol)
? (0, safe_names_1.createSafeName)(identifier.text)
: identifier.text;
const symbolId = (0, symbols_1.getIdentifierSymbolId)(context, identifier, symbol);
return lua.createIdentifier(text, identifier, symbolId, identifier.text);
}
exports.transformIdentifier = transformIdentifier;
const transformIdentifierExpression = (node, context) => {
const symbol = context.checker.getSymbolAtLocation(node);
function transformIdentifierWithSymbol(context, node, symbol) {
if (symbol) {

@@ -67,4 +58,4 @@ const exportScope = (0, export_1.getSymbolExportScope)(context, symbol);

const name = symbol.name;
const text = (0, safe_names_1.hasUnsafeIdentifierName)(context, node) ? (0, safe_names_1.createSafeName)(name) : name;
const symbolId = (0, symbols_1.getIdentifierSymbolId)(context, node);
const text = (0, safe_names_1.hasUnsafeIdentifierName)(context, node, symbol) ? (0, safe_names_1.createSafeName)(name) : name;
const symbolId = (0, symbols_1.getIdentifierSymbolId)(context, node, symbol);
const identifier = lua.createIdentifier(text, node, symbolId, name);

@@ -74,12 +65,17 @@ return (0, export_1.createExportedIdentifier)(context, identifier, exportScope);

}
if (node.originalKeywordKind === ts.SyntaxKind.UndefinedKeyword) {
return lua.createNilLiteral();
}
const builtinResult = (0, builtins_1.transformBuiltinIdentifierExpression)(context, node);
const builtinResult = (0, builtins_1.transformBuiltinIdentifierExpression)(context, node, symbol);
if (builtinResult) {
return builtinResult;
}
return transformIdentifier(context, node);
return transformNonValueIdentifier(context, node, symbol);
}
exports.transformIdentifierWithSymbol = transformIdentifierWithSymbol;
const transformIdentifierExpression = (node, context) => {
if (node.originalKeywordKind === ts.SyntaxKind.UndefinedKeyword) {
return lua.createNilLiteral(node);
}
const symbol = context.checker.getSymbolAtLocation(node);
return transformIdentifierWithSymbol(context, node, symbol);
};
exports.transformIdentifierExpression = transformIdentifierExpression;
//# sourceMappingURL=identifier.js.map
import * as ts from "typescript";
import * as lua from "../../../LuaAST";
import { TransformationContext } from "../../context";
export declare function isIterableType(type: ts.Type): boolean;
export declare function returnsIterableType(context: TransformationContext, node: ts.CallExpression): boolean;
export declare function isIterableExpression(context: TransformationContext, expression: ts.Expression): boolean;
export declare function transformForOfIterableStatement(context: TransformationContext, statement: ts.ForOfStatement, block: lua.Block): lua.Statement;
export declare function transformForOfPairsIterableStatement(context: TransformationContext, statement: ts.ForOfStatement, block: lua.Block): lua.Statement;
export declare function transformForOfPairsKeyIterableStatement(context: TransformationContext, statement: ts.ForOfStatement, block: lua.Block): lua.Statement;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformForOfIterableStatement = exports.isIterableExpression = exports.returnsIterableType = exports.isIterableType = void 0;
exports.transformForOfPairsKeyIterableStatement = exports.transformForOfPairsIterableStatement = exports.transformForOfIterableStatement = void 0;
const ts = require("typescript");
const lua = require("../../../LuaAST");
const extensions = require("../../utils/language-extensions");
const utils_1 = require("../loops/utils");

@@ -12,19 +11,3 @@ const variable_declaration_1 = require("../variable-declaration");

const multi_1 = require("./multi");
function isIterableType(type) {
return extensions.isExtensionType(type, extensions.ExtensionKind.IterableType);
}
exports.isIterableType = isIterableType;
function returnsIterableType(context, node) {
const signature = context.checker.getResolvedSignature(node);
const type = signature === null || signature === void 0 ? void 0 : signature.getReturnType();
return type ? isIterableType(type) : false;
}
exports.returnsIterableType = returnsIterableType;
function isIterableExpression(context, expression) {
const type = context.checker.getTypeAtLocation(expression);
return isIterableType(type);
}
exports.isIterableExpression = isIterableExpression;
function transformForOfMultiIterableStatement(context, statement, block) {
const luaIterator = context.transformExpression(statement.expression);
function transformForOfMultiIterableStatement(context, statement, block, luaIterator, invalidMultiUseDiagnostic) {
let identifiers = [];

@@ -39,3 +22,3 @@ if (ts.isVariableDeclarationList(statement.initializer)) {

else {
context.diagnostics.push((0, diagnostics_1.invalidMultiIterableWithoutDestructuring)(binding));
context.diagnostics.push(invalidMultiUseDiagnostic(binding));
}

@@ -53,3 +36,3 @@ }

else {
context.diagnostics.push((0, diagnostics_1.invalidMultiIterableWithoutDestructuring)(statement.initializer));
context.diagnostics.push(invalidMultiUseDiagnostic(statement.initializer));
}

@@ -65,3 +48,4 @@ if (identifiers.length === 0) {

if (((_a = type.aliasTypeArguments) === null || _a === void 0 ? void 0 : _a.length) === 2 && (0, multi_1.isMultiReturnType)(type.aliasTypeArguments[0])) {
return transformForOfMultiIterableStatement(context, statement, block);
const luaIterator = context.transformExpression(statement.expression);
return transformForOfMultiIterableStatement(context, statement, block, luaIterator, diagnostics_1.invalidMultiIterableWithoutDestructuring);
}

@@ -73,2 +57,17 @@ const luaIterator = context.transformExpression(statement.expression);

exports.transformForOfIterableStatement = transformForOfIterableStatement;
function transformForOfPairsIterableStatement(context, statement, block) {
const pairsCall = lua.createCallExpression(lua.createIdentifier("pairs"), [
context.transformExpression(statement.expression),
]);
return transformForOfMultiIterableStatement(context, statement, block, pairsCall, diagnostics_1.invalidPairsIterableWithoutDestructuring);
}
exports.transformForOfPairsIterableStatement = transformForOfPairsIterableStatement;
function transformForOfPairsKeyIterableStatement(context, statement, block) {
const pairsCall = lua.createCallExpression(lua.createIdentifier("pairs"), [
context.transformExpression(statement.expression),
]);
const identifier = (0, utils_1.transformForInitializer)(context, statement.initializer, block);
return lua.createForInStatement(block, [identifier], [pairsCall], statement);
}
exports.transformForOfPairsKeyIterableStatement = transformForOfPairsKeyIterableStatement;
//# sourceMappingURL=iterable.js.map

@@ -11,2 +11,1 @@ import * as ts from "typescript";

export declare function shouldMultiReturnCallBeWrapped(context: TransformationContext, node: ts.CallExpression): boolean;
export declare function findMultiAssignmentViolations(context: TransformationContext, node: ts.ObjectLiteralExpression): ts.Node[];
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.findMultiAssignmentViolations = exports.shouldMultiReturnCallBeWrapped = exports.isInMultiReturnFunction = exports.isMultiFunctionNode = exports.isMultiReturnCall = exports.returnsMultiType = exports.isMultiFunctionCall = exports.canBeMultiReturnType = exports.isMultiReturnType = void 0;
exports.shouldMultiReturnCallBeWrapped = exports.isInMultiReturnFunction = exports.isMultiFunctionNode = exports.isMultiReturnCall = exports.returnsMultiType = exports.isMultiFunctionCall = exports.canBeMultiReturnType = exports.isMultiReturnType = void 0;
const ts = require("typescript");
const extensions = require("../../utils/language-extensions");
const language_extensions_1 = require("../../utils/language-extensions");
const typescript_1 = require("../../utils/typescript");
const iterable_1 = require("./iterable");
const diagnostics_1 = require("../../utils/diagnostics");
const multiReturnExtensionName = "__tstlMultiReturn";
function isMultiReturnType(type) {
return extensions.isExtensionType(type, extensions.ExtensionKind.MultiType);
return type.getProperty(multiReturnExtensionName) !== undefined;
}
exports.isMultiReturnType = isMultiReturnType;
function canBeMultiReturnType(type) {
return isMultiReturnType(type) || (type.isUnion() && type.types.some(canBeMultiReturnType));
return isMultiReturnType(type) || (type.isUnion() && type.types.some(t => canBeMultiReturnType(t)));
}

@@ -32,4 +32,5 @@ exports.canBeMultiReturnType = canBeMultiReturnType;

function isMultiFunctionNode(context, node) {
const symbol = context.checker.getSymbolAtLocation(node);
return symbol ? extensions.isExtensionValue(context, symbol, extensions.ExtensionKind.MultiFunction) : false;
return (ts.isIdentifier(node) &&
node.text === "$multi" &&
(0, language_extensions_1.getExtensionKindForNode)(context, node) === extensions.ExtensionKind.MultiFunction);
}

@@ -79,3 +80,4 @@ exports.isMultiFunctionNode = isMultiFunctionNode;

// LuaIterable in for...of
if (ts.isForOfStatement(node.parent) && (0, iterable_1.isIterableExpression)(context, node)) {
if (ts.isForOfStatement(node.parent) &&
(0, language_extensions_1.getIterableExtensionKindForNode)(context, node) === language_extensions_1.IterableExtensionKind.Iterable) {
return false;

@@ -86,18 +88,2 @@ }

exports.shouldMultiReturnCallBeWrapped = shouldMultiReturnCallBeWrapped;
function findMultiAssignmentViolations(context, node) {
const result = [];
for (const element of node.properties) {
if (!ts.isShorthandPropertyAssignment(element))
continue;
const valueSymbol = context.checker.getShorthandAssignmentValueSymbol(element);
if (valueSymbol) {
if (extensions.isExtensionValue(context, valueSymbol, extensions.ExtensionKind.MultiFunction)) {
context.diagnostics.push((0, diagnostics_1.invalidMultiFunctionUse)(element));
result.push(element);
}
}
}
return result;
}
exports.findMultiAssignmentViolations = findMultiAssignmentViolations;
//# sourceMappingURL=multi.js.map

@@ -1,5 +0,2 @@

import * as ts from "typescript";
import * as lua from "../../../LuaAST";
import { TransformationContext } from "../../context";
export declare function isOperatorMapping(context: TransformationContext, node: ts.CallExpression | ts.Identifier): boolean;
export declare function transformOperatorMappingExpression(context: TransformationContext, node: ts.CallExpression, isOptionalCall: boolean): lua.Expression | undefined;
import { LanguageExtensionCallTransformerMap } from "./call-extension";
export declare const operatorExtensionTransformers: LanguageExtensionCallTransformerMap;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformOperatorMappingExpression = exports.isOperatorMapping = void 0;
exports.operatorExtensionTransformers = void 0;
const ts = require("typescript");
const lua = require("../../../LuaAST");
const extensions = require("../../utils/language-extensions");
const utils_1 = require("../../../utils");
const typescript_1 = require("../../utils/typescript");
const CompilerOptions_1 = require("../../../CompilerOptions");
const diagnostics_1 = require("../../utils/diagnostics");
const language_extensions_1 = require("../../utils/language-extensions");
const binaryOperatorMappings = new Map([
[extensions.ExtensionKind.AdditionOperatorType, lua.SyntaxKind.AdditionOperator],
[extensions.ExtensionKind.AdditionOperatorMethodType, lua.SyntaxKind.AdditionOperator],
[extensions.ExtensionKind.SubtractionOperatorType, lua.SyntaxKind.SubtractionOperator],
[extensions.ExtensionKind.SubtractionOperatorMethodType, lua.SyntaxKind.SubtractionOperator],
[extensions.ExtensionKind.MultiplicationOperatorType, lua.SyntaxKind.MultiplicationOperator],
[extensions.ExtensionKind.MultiplicationOperatorMethodType, lua.SyntaxKind.MultiplicationOperator],
[extensions.ExtensionKind.DivisionOperatorType, lua.SyntaxKind.DivisionOperator],
[extensions.ExtensionKind.DivisionOperatorMethodType, lua.SyntaxKind.DivisionOperator],
[extensions.ExtensionKind.ModuloOperatorType, lua.SyntaxKind.ModuloOperator],
[extensions.ExtensionKind.ModuloOperatorMethodType, lua.SyntaxKind.ModuloOperator],
[extensions.ExtensionKind.PowerOperatorType, lua.SyntaxKind.PowerOperator],
[extensions.ExtensionKind.PowerOperatorMethodType, lua.SyntaxKind.PowerOperator],
[extensions.ExtensionKind.FloorDivisionOperatorType, lua.SyntaxKind.FloorDivisionOperator],
[extensions.ExtensionKind.FloorDivisionOperatorMethodType, lua.SyntaxKind.FloorDivisionOperator],
[extensions.ExtensionKind.BitwiseAndOperatorType, lua.SyntaxKind.BitwiseAndOperator],
[extensions.ExtensionKind.BitwiseAndOperatorMethodType, lua.SyntaxKind.BitwiseAndOperator],
[extensions.ExtensionKind.BitwiseOrOperatorType, lua.SyntaxKind.BitwiseOrOperator],
[extensions.ExtensionKind.BitwiseOrOperatorMethodType, lua.SyntaxKind.BitwiseOrOperator],
[extensions.ExtensionKind.BitwiseExclusiveOrOperatorType, lua.SyntaxKind.BitwiseExclusiveOrOperator],
[extensions.ExtensionKind.BitwiseExclusiveOrOperatorMethodType, lua.SyntaxKind.BitwiseExclusiveOrOperator],
[extensions.ExtensionKind.BitwiseLeftShiftOperatorType, lua.SyntaxKind.BitwiseLeftShiftOperator],
[extensions.ExtensionKind.BitwiseLeftShiftOperatorMethodType, lua.SyntaxKind.BitwiseLeftShiftOperator],
[extensions.ExtensionKind.BitwiseRightShiftOperatorType, lua.SyntaxKind.BitwiseRightShiftOperator],
[extensions.ExtensionKind.BitwiseRightShiftOperatorMethodType, lua.SyntaxKind.BitwiseRightShiftOperator],
[extensions.ExtensionKind.ConcatOperatorType, lua.SyntaxKind.ConcatOperator],
[extensions.ExtensionKind.ConcatOperatorMethodType, lua.SyntaxKind.ConcatOperator],
[extensions.ExtensionKind.LessThanOperatorType, lua.SyntaxKind.LessThanOperator],
[extensions.ExtensionKind.LessThanOperatorMethodType, lua.SyntaxKind.LessThanOperator],
[extensions.ExtensionKind.GreaterThanOperatorType, lua.SyntaxKind.GreaterThanOperator],
[extensions.ExtensionKind.GreaterThanOperatorMethodType, lua.SyntaxKind.GreaterThanOperator],
[language_extensions_1.ExtensionKind.AdditionOperatorType, lua.SyntaxKind.AdditionOperator],
[language_extensions_1.ExtensionKind.AdditionOperatorMethodType, lua.SyntaxKind.AdditionOperator],
[language_extensions_1.ExtensionKind.SubtractionOperatorType, lua.SyntaxKind.SubtractionOperator],
[language_extensions_1.ExtensionKind.SubtractionOperatorMethodType, lua.SyntaxKind.SubtractionOperator],
[language_extensions_1.ExtensionKind.MultiplicationOperatorType, lua.SyntaxKind.MultiplicationOperator],
[language_extensions_1.ExtensionKind.MultiplicationOperatorMethodType, lua.SyntaxKind.MultiplicationOperator],
[language_extensions_1.ExtensionKind.DivisionOperatorType, lua.SyntaxKind.DivisionOperator],
[language_extensions_1.ExtensionKind.DivisionOperatorMethodType, lua.SyntaxKind.DivisionOperator],
[language_extensions_1.ExtensionKind.ModuloOperatorType, lua.SyntaxKind.ModuloOperator],
[language_extensions_1.ExtensionKind.ModuloOperatorMethodType, lua.SyntaxKind.ModuloOperator],
[language_extensions_1.ExtensionKind.PowerOperatorType, lua.SyntaxKind.PowerOperator],
[language_extensions_1.ExtensionKind.PowerOperatorMethodType, lua.SyntaxKind.PowerOperator],
[language_extensions_1.ExtensionKind.FloorDivisionOperatorType, lua.SyntaxKind.FloorDivisionOperator],
[language_extensions_1.ExtensionKind.FloorDivisionOperatorMethodType, lua.SyntaxKind.FloorDivisionOperator],
[language_extensions_1.ExtensionKind.BitwiseAndOperatorType, lua.SyntaxKind.BitwiseAndOperator],
[language_extensions_1.ExtensionKind.BitwiseAndOperatorMethodType, lua.SyntaxKind.BitwiseAndOperator],
[language_extensions_1.ExtensionKind.BitwiseOrOperatorType, lua.SyntaxKind.BitwiseOrOperator],
[language_extensions_1.ExtensionKind.BitwiseOrOperatorMethodType, lua.SyntaxKind.BitwiseOrOperator],
[language_extensions_1.ExtensionKind.BitwiseExclusiveOrOperatorType, lua.SyntaxKind.BitwiseExclusiveOrOperator],
[language_extensions_1.ExtensionKind.BitwiseExclusiveOrOperatorMethodType, lua.SyntaxKind.BitwiseExclusiveOrOperator],
[language_extensions_1.ExtensionKind.BitwiseLeftShiftOperatorType, lua.SyntaxKind.BitwiseLeftShiftOperator],
[language_extensions_1.ExtensionKind.BitwiseLeftShiftOperatorMethodType, lua.SyntaxKind.BitwiseLeftShiftOperator],
[language_extensions_1.ExtensionKind.BitwiseRightShiftOperatorType, lua.SyntaxKind.BitwiseRightShiftOperator],
[language_extensions_1.ExtensionKind.BitwiseRightShiftOperatorMethodType, lua.SyntaxKind.BitwiseRightShiftOperator],
[language_extensions_1.ExtensionKind.ConcatOperatorType, lua.SyntaxKind.ConcatOperator],
[language_extensions_1.ExtensionKind.ConcatOperatorMethodType, lua.SyntaxKind.ConcatOperator],
[language_extensions_1.ExtensionKind.LessThanOperatorType, lua.SyntaxKind.LessThanOperator],
[language_extensions_1.ExtensionKind.LessThanOperatorMethodType, lua.SyntaxKind.LessThanOperator],
[language_extensions_1.ExtensionKind.GreaterThanOperatorType, lua.SyntaxKind.GreaterThanOperator],
[language_extensions_1.ExtensionKind.GreaterThanOperatorMethodType, lua.SyntaxKind.GreaterThanOperator],
]);
const unaryOperatorMappings = new Map([
[extensions.ExtensionKind.NegationOperatorType, lua.SyntaxKind.NegationOperator],
[extensions.ExtensionKind.NegationOperatorMethodType, lua.SyntaxKind.NegationOperator],
[extensions.ExtensionKind.BitwiseNotOperatorType, lua.SyntaxKind.BitwiseNotOperator],
[extensions.ExtensionKind.BitwiseNotOperatorMethodType, lua.SyntaxKind.BitwiseNotOperator],
[extensions.ExtensionKind.LengthOperatorType, lua.SyntaxKind.LengthOperator],
[extensions.ExtensionKind.LengthOperatorMethodType, lua.SyntaxKind.LengthOperator],
[language_extensions_1.ExtensionKind.NegationOperatorType, lua.SyntaxKind.NegationOperator],
[language_extensions_1.ExtensionKind.NegationOperatorMethodType, lua.SyntaxKind.NegationOperator],
[language_extensions_1.ExtensionKind.BitwiseNotOperatorType, lua.SyntaxKind.BitwiseNotOperator],
[language_extensions_1.ExtensionKind.BitwiseNotOperatorMethodType, lua.SyntaxKind.BitwiseNotOperator],
[language_extensions_1.ExtensionKind.LengthOperatorType, lua.SyntaxKind.LengthOperator],
[language_extensions_1.ExtensionKind.LengthOperatorMethodType, lua.SyntaxKind.LengthOperator],
]);
const operatorMapExtensions = [...binaryOperatorMappings.keys(), ...unaryOperatorMappings.keys()];
const bitwiseOperatorMapExtensions = new Set([
extensions.ExtensionKind.BitwiseAndOperatorType,
extensions.ExtensionKind.BitwiseAndOperatorMethodType,
extensions.ExtensionKind.BitwiseOrOperatorType,
extensions.ExtensionKind.BitwiseOrOperatorMethodType,
extensions.ExtensionKind.BitwiseExclusiveOrOperatorType,
extensions.ExtensionKind.BitwiseExclusiveOrOperatorMethodType,
extensions.ExtensionKind.BitwiseLeftShiftOperatorType,
extensions.ExtensionKind.BitwiseLeftShiftOperatorMethodType,
extensions.ExtensionKind.BitwiseRightShiftOperatorType,
extensions.ExtensionKind.BitwiseRightShiftOperatorMethodType,
extensions.ExtensionKind.BitwiseNotOperatorType,
extensions.ExtensionKind.BitwiseNotOperatorMethodType,
language_extensions_1.ExtensionKind.BitwiseAndOperatorType,
language_extensions_1.ExtensionKind.BitwiseAndOperatorMethodType,
language_extensions_1.ExtensionKind.BitwiseOrOperatorType,
language_extensions_1.ExtensionKind.BitwiseOrOperatorMethodType,
language_extensions_1.ExtensionKind.BitwiseExclusiveOrOperatorType,
language_extensions_1.ExtensionKind.BitwiseExclusiveOrOperatorMethodType,
language_extensions_1.ExtensionKind.BitwiseLeftShiftOperatorType,
language_extensions_1.ExtensionKind.BitwiseLeftShiftOperatorMethodType,
language_extensions_1.ExtensionKind.BitwiseRightShiftOperatorType,
language_extensions_1.ExtensionKind.BitwiseRightShiftOperatorMethodType,
language_extensions_1.ExtensionKind.BitwiseNotOperatorType,
language_extensions_1.ExtensionKind.BitwiseNotOperatorMethodType,
]);
function getOperatorMapExtensionKindForCall(context, node) {
const type = (0, typescript_1.getFunctionTypeForCall)(context, node);
return type && operatorMapExtensions.find(extensionKind => extensions.isExtensionType(type, extensionKind));
const requiresLua53 = new Set([
...bitwiseOperatorMapExtensions,
language_extensions_1.ExtensionKind.FloorDivisionOperatorType,
language_extensions_1.ExtensionKind.FloorDivisionOperatorMethodType,
]);
exports.operatorExtensionTransformers = {};
for (const kind of binaryOperatorMappings.keys()) {
exports.operatorExtensionTransformers[kind] = transformBinaryOperator;
}
function isOperatorMapping(context, node) {
if (ts.isCallExpression(node)) {
return getOperatorMapExtensionKindForCall(context, node) !== undefined;
for (const kind of unaryOperatorMappings.keys()) {
exports.operatorExtensionTransformers[kind] = transformUnaryOperator;
}
function transformBinaryOperator(context, node, kind) {
if (requiresLua53.has(kind))
checkHasLua53(context, node, kind);
let args = node.arguments;
if (args.length === 1 &&
(ts.isPropertyAccessExpression(node.expression) || ts.isElementAccessExpression(node.expression))) {
args = [node.expression.expression, ...args];
}
const luaOperator = binaryOperatorMappings.get(kind);
(0, utils_1.assert)(luaOperator);
return lua.createBinaryExpression(context.transformExpression(args[0]), context.transformExpression(args[1]), luaOperator);
}
function transformUnaryOperator(context, node, kind) {
if (requiresLua53.has(kind))
checkHasLua53(context, node, kind);
let arg;
if (node.arguments.length === 0 &&
(ts.isPropertyAccessExpression(node.expression) || ts.isElementAccessExpression(node.expression))) {
arg = node.expression.expression;
}
else {
const type = context.checker.getTypeAtLocation(node);
return operatorMapExtensions.some(extensionKind => extensions.isExtensionType(type, extensionKind));
arg = node.arguments[0];
}
const luaOperator = unaryOperatorMappings.get(kind);
(0, utils_1.assert)(luaOperator);
return lua.createUnaryExpression(context.transformExpression(arg), luaOperator);
}
exports.isOperatorMapping = isOperatorMapping;
function transformOperatorMappingExpression(context, node, isOptionalCall) {
const extensionKind = getOperatorMapExtensionKindForCall(context, node);
if (!extensionKind)
return undefined;
if (isOptionalCall) {
context.diagnostics.push((0, diagnostics_1.unsupportedBuiltinOptionalCall)(node));
return lua.createNilLiteral();
}
function checkHasLua53(context, node, kind) {
const isBefore53 = context.luaTarget === CompilerOptions_1.LuaTarget.Lua51 ||

@@ -94,35 +110,12 @@ context.luaTarget === CompilerOptions_1.LuaTarget.Lua52 ||

const luaTarget = context.luaTarget === CompilerOptions_1.LuaTarget.Universal ? CompilerOptions_1.LuaTarget.Lua51 : context.luaTarget;
if (bitwiseOperatorMapExtensions.has(extensionKind)) {
context.diagnostics.push((0, diagnostics_1.unsupportedForTarget)(node, "Native bitwise operations", luaTarget));
}
else if (extensionKind === extensions.ExtensionKind.FloorDivisionOperatorType ||
extensionKind === extensions.ExtensionKind.FloorDivisionOperatorMethodType) {
if (kind === language_extensions_1.ExtensionKind.FloorDivisionOperatorType ||
kind === language_extensions_1.ExtensionKind.FloorDivisionOperatorMethodType) {
context.diagnostics.push((0, diagnostics_1.unsupportedForTarget)(node, "Floor division operator", luaTarget));
}
}
const args = node.arguments.slice();
if (binaryOperatorMappings.has(extensionKind)) {
if (args.length === 1 &&
(ts.isPropertyAccessExpression(node.expression) || ts.isElementAccessExpression(node.expression))) {
args.unshift(node.expression.expression);
}
const luaOperator = binaryOperatorMappings.get(extensionKind);
(0, utils_1.assert)(luaOperator);
return lua.createBinaryExpression(context.transformExpression(args[0]), context.transformExpression(args[1]), luaOperator);
}
else {
let arg;
if (args.length === 0 &&
(ts.isPropertyAccessExpression(node.expression) || ts.isElementAccessExpression(node.expression))) {
arg = node.expression.expression;
}
else {
arg = args[0];
// is bitwise operator
context.diagnostics.push((0, diagnostics_1.unsupportedForTarget)(node, "Native bitwise operations", luaTarget));
}
const luaOperator = unaryOperatorMappings.get(extensionKind);
(0, utils_1.assert)(luaOperator);
return lua.createUnaryExpression(context.transformExpression(arg), luaOperator);
}
}
exports.transformOperatorMappingExpression = transformOperatorMappingExpression;
//# sourceMappingURL=operators.js.map

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

const diagnostics_1 = require("../../utils/diagnostics");
const language_extensions_1 = require("../../utils/language-extensions");
function isRangeFunction(context, expression) {

@@ -18,4 +19,5 @@ return isRangeFunctionNode(context, expression.expression);

function isRangeFunctionNode(context, node) {
const symbol = context.checker.getSymbolAtLocation(node);
return symbol ? extensions.isExtensionValue(context, symbol, extensions.ExtensionKind.RangeFunction) : false;
return (ts.isIdentifier(node) &&
node.text === "$range" &&
(0, language_extensions_1.getExtensionKindForNode)(context, node) === extensions.ExtensionKind.RangeFunction);
}

@@ -22,0 +24,0 @@ exports.isRangeFunctionNode = isRangeFunctionNode;

import * as ts from "typescript";
import * as lua from "../../../LuaAST";
import { TransformationContext } from "../../context";
export declare function isTableExtensionIdentifier(context: TransformationContext, node: ts.Identifier): boolean;
import { ExtensionKind } from "../../utils/language-extensions";
import { LanguageExtensionCallTransformer } from "./call-extension";
export declare function isTableNewCall(context: TransformationContext, node: ts.NewExpression): boolean;
export declare function transformTableExtensionCall(context: TransformationContext, node: ts.CallExpression, isOptionalCall: boolean): lua.Expression | undefined;
export declare const tableNewExtensions: ExtensionKind[];
export declare const tableExtensionTransformers: {
[P in ExtensionKind]?: LanguageExtensionCallTransformer;
};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformTableExtensionCall = exports.isTableNewCall = exports.isTableExtensionIdentifier = void 0;
exports.tableExtensionTransformers = exports.tableNewExtensions = exports.isTableNewCall = void 0;
const ts = require("typescript");
const lua = require("../../../LuaAST");
const extensions = require("../../utils/language-extensions");
const typescript_1 = require("../../utils/typescript");
const language_extensions_1 = require("../../utils/language-extensions");
const expression_list_1 = require("../expression-list");
const diagnostics_1 = require("../../utils/diagnostics");
const tableCallExtensions = [
extensions.ExtensionKind.TableDeleteType,
extensions.ExtensionKind.TableDeleteMethodType,
extensions.ExtensionKind.TableGetType,
extensions.ExtensionKind.TableGetMethodType,
extensions.ExtensionKind.TableHasType,
extensions.ExtensionKind.TableHasMethodType,
extensions.ExtensionKind.TableSetType,
extensions.ExtensionKind.TableSetMethodType,
];
const tableExtensions = [extensions.ExtensionKind.TableNewType, ...tableCallExtensions];
function getTableExtensionKindForCall(context, node, validExtensions) {
const type = (0, typescript_1.getFunctionTypeForCall)(context, node);
return type && validExtensions.find(extensionKind => extensions.isExtensionType(type, extensionKind));
}
function isTableExtensionIdentifier(context, node) {
const type = context.checker.getTypeAtLocation(node);
return tableExtensions.some(extensionKind => extensions.isExtensionType(type, extensionKind));
}
exports.isTableExtensionIdentifier = isTableExtensionIdentifier;
function isTableNewCall(context, node) {
const type = context.checker.getTypeAtLocation(node.expression);
return extensions.isExtensionType(type, extensions.ExtensionKind.TableNewType);
return (0, language_extensions_1.getExtensionKindForNode)(context, node.expression) === language_extensions_1.ExtensionKind.TableNewType;
}
exports.isTableNewCall = isTableNewCall;
function transformTableExtensionCall(context, node, isOptionalCall) {
const extensionType = getTableExtensionKindForCall(context, node, tableCallExtensions);
if (!extensionType)
return;
if (isOptionalCall) {
context.diagnostics.push((0, diagnostics_1.unsupportedBuiltinOptionalCall)(node));
return lua.createNilLiteral();
}
if (extensionType === extensions.ExtensionKind.TableDeleteType ||
extensionType === extensions.ExtensionKind.TableDeleteMethodType) {
return transformTableDeleteExpression(context, node, extensionType);
}
if (extensionType === extensions.ExtensionKind.TableGetType ||
extensionType === extensions.ExtensionKind.TableGetMethodType) {
return transformTableGetExpression(context, node, extensionType);
}
if (extensionType === extensions.ExtensionKind.TableHasType ||
extensionType === extensions.ExtensionKind.TableHasMethodType) {
return transformTableHasExpression(context, node, extensionType);
}
if (extensionType === extensions.ExtensionKind.TableSetType ||
extensionType === extensions.ExtensionKind.TableSetMethodType) {
return transformTableSetExpression(context, node, extensionType);
}
}
exports.transformTableExtensionCall = transformTableExtensionCall;
exports.tableNewExtensions = [language_extensions_1.ExtensionKind.TableNewType];
exports.tableExtensionTransformers = {
[language_extensions_1.ExtensionKind.TableDeleteType]: transformTableDeleteExpression,
[language_extensions_1.ExtensionKind.TableDeleteMethodType]: transformTableDeleteExpression,
[language_extensions_1.ExtensionKind.TableGetType]: transformTableGetExpression,
[language_extensions_1.ExtensionKind.TableGetMethodType]: transformTableGetExpression,
[language_extensions_1.ExtensionKind.TableHasType]: transformTableHasExpression,
[language_extensions_1.ExtensionKind.TableHasMethodType]: transformTableHasExpression,
[language_extensions_1.ExtensionKind.TableSetType]: transformTableSetExpression,
[language_extensions_1.ExtensionKind.TableSetMethodType]: transformTableSetExpression,
[language_extensions_1.ExtensionKind.TableAddKeyType]: transformTableAddExpression,
[language_extensions_1.ExtensionKind.TableAddKeyMethodType]: transformTableAddExpression,
};
function transformTableDeleteExpression(context, node, extensionKind) {
const args = node.arguments.slice();
if (extensionKind === extensions.ExtensionKind.TableDeleteMethodType &&
if (extensionKind === language_extensions_1.ExtensionKind.TableDeleteMethodType &&
(ts.isPropertyAccessExpression(node.expression) || ts.isElementAccessExpression(node.expression))) {

@@ -68,15 +32,19 @@ // In case of method (no table argument), push method owner to front of args list

}
const [table, accessExpression] = (0, expression_list_1.transformExpressionList)(context, args);
// arg0[arg1] = nil
const [table, accessExpression] = (0, expression_list_1.transformExpressionList)(context, args);
context.addPrecedingStatements(lua.createAssignmentStatement(lua.createTableIndexExpression(table, accessExpression), lua.createNilLiteral(), node));
return lua.createBooleanLiteral(true);
}
function transformWithTableArgument(context, node) {
if (ts.isPropertyAccessExpression(node.expression) || ts.isElementAccessExpression(node.expression)) {
return (0, expression_list_1.transformExpressionList)(context, [node.expression.expression, ...node.arguments]);
}
// todo: report diagnostic?
return [lua.createNilLiteral(), ...(0, expression_list_1.transformExpressionList)(context, node.arguments)];
}
function transformTableGetExpression(context, node, extensionKind) {
const args = node.arguments.slice();
if (extensionKind === extensions.ExtensionKind.TableGetMethodType &&
(ts.isPropertyAccessExpression(node.expression) || ts.isElementAccessExpression(node.expression))) {
// In case of method (no table argument), push method owner to front of args list
args.unshift(node.expression.expression);
}
const [table, accessExpression] = (0, expression_list_1.transformExpressionList)(context, args);
const args = extensionKind === language_extensions_1.ExtensionKind.TableGetMethodType
? transformWithTableArgument(context, node)
: (0, expression_list_1.transformExpressionList)(context, node.arguments);
const [table, accessExpression] = args;
// arg0[arg1]

@@ -86,10 +54,7 @@ return lua.createTableIndexExpression(table, accessExpression, node);

function transformTableHasExpression(context, node, extensionKind) {
const args = node.arguments.slice();
if (extensionKind === extensions.ExtensionKind.TableHasMethodType &&
(ts.isPropertyAccessExpression(node.expression) || ts.isElementAccessExpression(node.expression))) {
// In case of method (no table argument), push method owner to front of args list
args.unshift(node.expression.expression);
}
const args = extensionKind === language_extensions_1.ExtensionKind.TableHasMethodType
? transformWithTableArgument(context, node)
: (0, expression_list_1.transformExpressionList)(context, node.arguments);
const [table, accessExpression] = args;
// arg0[arg1]
const [table, accessExpression] = (0, expression_list_1.transformExpressionList)(context, args);
const tableIndexExpression = lua.createTableIndexExpression(table, accessExpression);

@@ -100,13 +65,19 @@ // arg0[arg1] ~= nil

function transformTableSetExpression(context, node, extensionKind) {
const args = node.arguments.slice();
if (extensionKind === extensions.ExtensionKind.TableSetMethodType &&
(ts.isPropertyAccessExpression(node.expression) || ts.isElementAccessExpression(node.expression))) {
// In case of method (no table argument), push method owner to front of args list
args.unshift(node.expression.expression);
}
const args = extensionKind === language_extensions_1.ExtensionKind.TableSetMethodType
? transformWithTableArgument(context, node)
: (0, expression_list_1.transformExpressionList)(context, node.arguments);
const [table, accessExpression, value] = args;
// arg0[arg1] = arg2
const [table, accessExpression, value] = (0, expression_list_1.transformExpressionList)(context, args);
context.addPrecedingStatements(lua.createAssignmentStatement(lua.createTableIndexExpression(table, accessExpression), value, node));
return lua.createNilLiteral();
}
function transformTableAddExpression(context, node, extensionKind) {
const args = extensionKind === language_extensions_1.ExtensionKind.TableAddKeyMethodType
? transformWithTableArgument(context, node)
: (0, expression_list_1.transformExpressionList)(context, node.arguments);
const [table, value] = args;
// arg0[arg1] = true
context.addPrecedingStatements(lua.createAssignmentStatement(lua.createTableIndexExpression(table, value), lua.createBooleanLiteral(true), node));
return lua.createNilLiteral();
}
//# sourceMappingURL=table.js.map

@@ -5,13 +5,17 @@ "use strict";

const extensions = require("../../utils/language-extensions");
const language_extensions_1 = require("../../utils/language-extensions");
const scope_1 = require("../../utils/scope");
function isGlobalVarargConstant(context, symbol, scope) {
return (scope.type === scope_1.ScopeType.File &&
extensions.isExtensionValue(context, symbol, extensions.ExtensionKind.VarargConstant));
return scope.type === scope_1.ScopeType.File && isVarargConstantSymbol(context, symbol);
}
exports.isGlobalVarargConstant = isGlobalVarargConstant;
function isVarargConstantSymbol(context, symbol) {
return (symbol.getName() === "$vararg" &&
(0, language_extensions_1.getExtensionKindForSymbol)(context, symbol) === extensions.ExtensionKind.VarargConstant);
}
function isVarargConstantNode(context, node) {
const symbol = context.checker.getSymbolAtLocation(node);
return symbol ? extensions.isExtensionValue(context, symbol, extensions.ExtensionKind.VarargConstant) : false;
return symbol !== undefined && isVarargConstantSymbol(context, symbol);
}
exports.isVarargConstantNode = isVarargConstantNode;
//# sourceMappingURL=vararg.js.map

@@ -8,5 +8,3 @@ "use strict";

const diagnostics_1 = require("../utils/diagnostics");
const export_1 = require("../utils/export");
const lualib_1 = require("../utils/lualib");
const safe_names_1 = require("../utils/safe-names");
const symbols_1 = require("../utils/symbols");

@@ -16,3 +14,3 @@ const typescript_1 = require("../utils/typescript");

const expression_list_1 = require("./expression-list");
const multi_1 = require("./language-extensions/multi");
const identifier_1 = require("./identifier");
// TODO: Move to object-literal.ts?

@@ -35,17 +33,3 @@ function transformPropertyName(context, node) {

function createShorthandIdentifier(context, valueSymbol, propertyIdentifier) {
const propertyName = propertyIdentifier.text;
const isUnsafeName = valueSymbol
? (0, safe_names_1.hasUnsafeSymbolName)(context, valueSymbol, propertyIdentifier)
: (0, safe_names_1.hasUnsafeIdentifierName)(context, propertyIdentifier, false);
const name = isUnsafeName ? (0, safe_names_1.createSafeName)(propertyName) : propertyName;
let identifier = context.transformExpression(ts.factory.createIdentifier(name));
lua.setNodeOriginal(identifier, propertyIdentifier);
if (valueSymbol !== undefined && lua.isIdentifier(identifier)) {
identifier.symbolId = (0, symbols_1.getSymbolIdOfSymbol)(context, valueSymbol);
const exportScope = (0, export_1.getSymbolExportScope)(context, valueSymbol);
if (exportScope) {
identifier = (0, export_1.createExportedIdentifier)(context, identifier, exportScope);
}
}
return identifier;
return (0, identifier_1.transformIdentifierWithSymbol)(context, propertyIdentifier, valueSymbol);
}

@@ -62,7 +46,2 @@ exports.createShorthandIdentifier = createShorthandIdentifier;

const transformObjectLiteralExpression = (expression, context) => {
const violations = (0, multi_1.findMultiAssignmentViolations)(context, expression);
if (violations.length > 0) {
context.diagnostics.push(...violations.map(e => (0, diagnostics_1.invalidMultiFunctionUse)(e)));
return lua.createNilLiteral(expression);
}
const properties = [];

@@ -69,0 +48,0 @@ const initializers = [];

@@ -6,10 +6,9 @@ "use strict";

const lua = require("../../../LuaAST");
const annotations_1 = require("../../utils/annotations");
const diagnostics_1 = require("../../utils/diagnostics");
const lualib_1 = require("../../utils/lualib");
const typescript_1 = require("../../utils/typescript");
const iterable_1 = require("../language-extensions/iterable");
const pairsIterable_1 = require("../language-extensions/pairsIterable");
const range_1 = require("../language-extensions/range");
const utils_1 = require("./utils");
const language_extensions_1 = require("../../utils/language-extensions");
const utils_2 = require("../../../utils");
function transformForOfArrayStatement(context, statement, block) {

@@ -32,22 +31,23 @@ const valueVariable = (0, utils_1.transformForInitializer)(context, statement.initializer, block);

}
else if (ts.isCallExpression(node.expression) && (0, annotations_1.isForRangeType)(context, node.expression.expression)) {
context.diagnostics.push((0, diagnostics_1.annotationRemoved)(node.expression, annotations_1.AnnotationKind.ForRange));
const iterableExtensionType = (0, language_extensions_1.getIterableExtensionKindForNode)(context, node.expression);
if (iterableExtensionType) {
if (iterableExtensionType === language_extensions_1.IterableExtensionKind.Iterable) {
return (0, iterable_1.transformForOfIterableStatement)(context, node, body);
}
else if (iterableExtensionType === language_extensions_1.IterableExtensionKind.Pairs) {
return (0, iterable_1.transformForOfPairsIterableStatement)(context, node, body);
}
else if (iterableExtensionType === language_extensions_1.IterableExtensionKind.PairsKey) {
return (0, iterable_1.transformForOfPairsKeyIterableStatement)(context, node, body);
}
else {
(0, utils_2.assertNever)(iterableExtensionType);
}
}
else if ((0, iterable_1.isIterableExpression)(context, node.expression)) {
return (0, iterable_1.transformForOfIterableStatement)(context, node, body);
}
else if ((0, pairsIterable_1.isPairsIterableExpression)(context, node.expression)) {
return (0, pairsIterable_1.transformForOfPairsIterableStatement)(context, node, body);
}
else if ((0, annotations_1.isLuaIteratorType)(context, node.expression)) {
context.diagnostics.push((0, diagnostics_1.annotationRemoved)(node.expression, annotations_1.AnnotationKind.LuaIterator));
}
else if ((0, typescript_1.isArrayType)(context, context.checker.getTypeAtLocation(node.expression))) {
if ((0, typescript_1.isArrayType)(context, context.checker.getTypeAtLocation(node.expression))) {
return transformForOfArrayStatement(context, node, body);
}
else {
return transformForOfIteratorStatement(context, node, body);
}
return transformForOfIteratorStatement(context, node, body);
};
exports.transformForOfStatement = transformForOfStatement;
//# sourceMappingURL=for-of.js.map

@@ -15,5 +15,5 @@ "use strict";

function transformLoopBody(context, loop) {
(0, scope_1.pushScope)(context, scope_1.ScopeType.Loop);
context.pushScope(scope_1.ScopeType.Loop);
const body = (0, scope_1.performHoisting)(context, (0, block_1.transformBlockOrStatement)(context, loop.statement));
const scope = (0, scope_1.popScope)(context);
const scope = context.popScope();
const scopeId = scope.id;

@@ -39,3 +39,3 @@ if (!scope.loopContinued) {

const valueVariable = lua.createIdentifier("____value");
(0, scope_1.pushScope)(context, scope_1.ScopeType.LoopInitializer);
context.pushScope(scope_1.ScopeType.LoopInitializer);
if (ts.isVariableDeclarationList(initializer)) {

@@ -50,3 +50,3 @@ // Declaration of new variable

// Single variable declared in for loop
(0, scope_1.popScope)(context);
context.popScope();
return (0, identifier_1.transformIdentifier)(context, binding);

@@ -61,3 +61,3 @@ }

}
(0, scope_1.popScope)(context);
context.popScope();
return valueVariable;

@@ -64,0 +64,0 @@ }

@@ -6,4 +6,2 @@ "use strict";

const lua = require("../../LuaAST");
const annotations_1 = require("../utils/annotations");
const diagnostics_1 = require("../utils/diagnostics");
const export_1 = require("../utils/export");

@@ -37,12 +35,5 @@ const lua_ast_1 = require("../utils/lua-ast");

}
// Static context -> namespace dictionary keeping the current namespace for each transformation context
const currentNamespaces = new WeakMap();
const transformModuleDeclaration = (node, context) => {
var _a, _b;
const annotations = (0, annotations_1.getTypeAnnotations)(context.checker.getTypeAtLocation(node));
// If phantom namespace elide the declaration and return the body
if (annotations.has(annotations_1.AnnotationKind.Phantom)) {
context.diagnostics.push((0, diagnostics_1.annotationRemoved)(node, annotations_1.AnnotationKind.Phantom));
}
const currentNamespace = currentNamespaces.get(context);
const currentNamespace = context.currentNamespaces;
const result = [];

@@ -80,11 +71,11 @@ const symbol = context.checker.getSymbolAtLocation(node.name);

// Keep previous namespace to reset after block transpilation
currentNamespaces.set(context, node);
context.currentNamespaces = node;
// Transform moduleblock to block and visit it
if (moduleHasEmittedBody(node)) {
(0, scope_1.pushScope)(context, scope_1.ScopeType.Block);
context.pushScope(scope_1.ScopeType.Block);
const statements = (0, scope_1.performHoisting)(context, context.transformStatements(ts.isModuleBlock(node.body) ? node.body.statements : node.body));
(0, scope_1.popScope)(context);
context.popScope();
result.push(lua.createDoStatement(statements));
}
currentNamespaces.set(context, currentNamespace);
context.currentNamespaces = currentNamespace;
return result;

@@ -91,0 +82,0 @@ };

@@ -63,3 +63,2 @@ "use strict";

function createReturnStatement(context, values, node) {
const results = [...values];
if ((0, typescript_1.isInAsyncFunction)(node)) {

@@ -72,5 +71,5 @@ return lua.createReturnStatement([

// Bubble up explicit return flag and check if we're inside a try/catch block
results.unshift(lua.createBooleanLiteral(true));
values = [lua.createBooleanLiteral(true), ...values];
}
return lua.createReturnStatement(results, node);
return lua.createReturnStatement(values, node);
}

@@ -77,0 +76,0 @@ exports.createReturnStatement = createReturnStatement;

@@ -8,3 +8,2 @@ "use strict";

const lua_ast_1 = require("../utils/lua-ast");
const lualib_1 = require("../utils/lualib");
const preceding_statements_1 = require("../utils/preceding-statements");

@@ -32,5 +31,5 @@ const scope_1 = require("../utils/scope");

else {
(0, scope_1.pushScope)(context, scope_1.ScopeType.File);
context.pushScope(scope_1.ScopeType.File);
statements = (0, scope_1.performHoisting)(context, context.transformStatements(node.statements));
(0, scope_1.popScope)(context);
context.popScope();
if (context.isModule) {

@@ -47,5 +46,5 @@ // If export equals was not used. Create the exports table.

const trivia = (_b = (_a = node.getFullText().match(/^#!.*\r?\n/)) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : "";
return lua.createFile(statements, (0, lualib_1.getUsedLuaLibFeatures)(context), trivia, node);
return lua.createFile(statements, context.usedLuaLibFeatures, trivia, node);
};
exports.transformSourceFileNode = transformSourceFileNode;
//# sourceMappingURL=sourceFile.js.map

@@ -6,3 +6,2 @@ "use strict";

const lua = require("../../LuaAST");
const annotations_1 = require("../utils/annotations");
const lua_ast_1 = require("../utils/lua-ast");

@@ -13,3 +12,2 @@ const lualib_1 = require("../utils/lualib");

const multi_1 = require("./language-extensions/multi");
const diagnostics_1 = require("../utils/diagnostics");
const vararg_1 = require("./language-extensions/vararg");

@@ -58,5 +56,2 @@ function isOptimizedVarArgSpread(context, symbol, identifier) {

if (ts.isIdentifier(tsInnerExpression)) {
if ((0, annotations_1.isVarargType)(context, tsInnerExpression)) {
context.diagnostics.push((0, diagnostics_1.annotationRemoved)(node, annotations_1.AnnotationKind.Vararg));
}
const symbol = context.checker.getSymbolAtLocation(tsInnerExpression);

@@ -63,0 +58,0 @@ if (symbol && isOptimizedVarArgSpread(context, symbol, tsInnerExpression)) {

@@ -42,3 +42,3 @@ "use strict";

const transformSwitchStatement = (statement, context) => {
const scope = (0, scope_1.pushScope)(context, scope_1.ScopeType.Switch);
const scope = context.pushScope(scope_1.ScopeType.Switch);
// Give the switch and condition accumulator a unique name to prevent nested switches from acting up.

@@ -162,3 +162,3 @@ const switchName = `____switch${scope.id}`;

}
(0, scope_1.popScope)(context);
context.popScope();
// Add the switch expression after hoisting

@@ -165,0 +165,0 @@ const expression = context.transformExpression(statement.expression);

@@ -204,3 +204,3 @@ "use strict";

return false;
return (0, function_1.isFunctionTypeWithProperties)(context.checker.getTypeAtLocation(statement.name));
return (0, function_1.isFunctionTypeWithProperties)(context, context.checker.getTypeAtLocation(statement.name));
}

@@ -207,0 +207,0 @@ }

@@ -5,4 +5,6 @@ "use strict";

const utils_1 = require("./utils");
const performance = require("../measure-performance");
function getPlugins(program) {
var _a;
performance.startSection("getPlugins");
const diagnostics = [];

@@ -24,2 +26,3 @@ const pluginsFromOptions = [];

}
performance.endSection("getPlugins");
return { diagnostics, plugins: pluginsFromOptions };

@@ -26,0 +29,0 @@ }

@@ -24,6 +24,35 @@ "use strict";

this.emitHost = emitHost;
this.resultsCache = new Map();
this.diagnostics = [];
this.resolvedFiles = new Map();
this.processedDependencies = new Set();
// value is false if already searched but not found
this.pathToFile = new Map();
this.noResolvePaths = new Set(options.noResolvePaths);
}
resolve(file, required) {
addAndResolveDependencies(file) {
if (this.resolvedFiles.has(file.fileName))
return;
this.resolvedFiles.set(file.fileName, file);
for (const required of findRequiredPaths(file.code)) {
// Do not resolve noResolution paths
if (required.startsWith("@NoResolution:")) {
// Remove @NoResolution prefix if not building in library mode
if (!isBuildModeLibrary(this.program)) {
const path = required.replace("@NoResolution:", "");
replaceRequireInCode(file, required, path);
replaceRequireInSourceMap(file, required, path);
}
// Skip
continue;
}
// Try to resolve the import starting from the directory `file` is in
this.resolveImport(file, required);
}
}
resolveImport(file, required) {
// Do no resolve lualib - always use the lualib of the application entry point, not the lualib from external packages
if (required === "lualib_bundle") {
this.resolvedFiles.set("lualib_bundle", { fileName: "lualib_bundle", code: "" });
return;
}
if (this.noResolvePaths.has(required)) {

@@ -33,67 +62,113 @@ if (this.options.tstlVerbose) {

}
return { resolvedFiles: [], diagnostics: [] };
return;
}
const resolvedDependency = resolveDependency(file, required, this.program, this.emitHost);
if (resolvedDependency) {
if (this.options.tstlVerbose) {
console.log(`Resolved ${required} to ${(0, utils_1.normalizeSlashes)(resolvedDependency)}`);
const dependencyPath = this.resolveDependencyPath(file, required);
if (!dependencyPath)
return this.couldNotResolveImport(required, file);
if (this.options.tstlVerbose) {
console.log(`Resolved ${required} to ${(0, utils_1.normalizeSlashes)(dependencyPath)}`);
}
this.processDependency(dependencyPath);
// Figure out resolved require path and dependency output path
if (shouldRewriteRequires(dependencyPath, this.program)) {
const resolvedRequire = (0, transpiler_1.getEmitPathRelativeToOutDir)(dependencyPath, this.program);
replaceRequireInCode(file, required, resolvedRequire);
replaceRequireInSourceMap(file, required, resolvedRequire);
}
}
processDependency(dependencyPath) {
if (this.processedDependencies.has(dependencyPath))
return;
this.processedDependencies.add(dependencyPath);
if (!shouldIncludeDependency(dependencyPath, this.program))
return;
// If dependency is not part of project, add dependency to output and resolve its dependencies recursively
const dependencyContent = this.emitHost.readFile(dependencyPath);
if (dependencyContent === undefined) {
this.diagnostics.push((0, diagnostics_1.couldNotReadDependency)(dependencyPath));
return;
}
const dependency = {
fileName: dependencyPath,
code: dependencyContent,
};
this.addAndResolveDependencies(dependency);
}
couldNotResolveImport(required, file) {
const fallbackRequire = fallbackResolve(required, (0, transpiler_1.getSourceDir)(this.program), path.dirname(file.fileName));
replaceRequireInCode(file, required, fallbackRequire);
replaceRequireInSourceMap(file, required, fallbackRequire);
this.diagnostics.push((0, diagnostics_1.couldNotResolveRequire)(required, path.relative((0, transpiler_1.getProjectRoot)(this.program), file.fileName)));
}
resolveDependencyPath(requiringFile, dependency) {
var _a;
const fileDirectory = path.dirname(requiringFile.fileName);
if (this.options.tstlVerbose) {
console.log(`Resolving "${dependency}" from ${(0, utils_1.normalizeSlashes)(requiringFile.fileName)}`);
}
// Check if the import is relative
const isRelative = ["/", "./", "../"].some(p => dependency.startsWith(p));
// If the import is relative, always resolve it relative to the requiring file
// If the import is not relative, resolve it relative to options.baseUrl if it is set
const relativeTo = isRelative ? fileDirectory : (_a = this.options.baseUrl) !== null && _a !== void 0 ? _a : fileDirectory;
// Check if file is a file in the project
const resolvedPath = path.join(relativeTo, dependency);
const fileFromPath = this.getFileFromPath(resolvedPath);
if (fileFromPath)
return fileFromPath;
// Check if this is a sibling of a required lua file
if (requiringFile.fileName.endsWith(".lua")) {
const luaFilePath = resolveLuaPath(fileDirectory, dependency, this.emitHost);
if (luaFilePath) {
return luaFilePath;
}
// Figure out resolved require path and dependency output path
const resolvedRequire = (0, transpiler_1.getEmitPathRelativeToOutDir)(resolvedDependency, this.program);
if (shouldRewriteRequires(resolvedDependency, this.program)) {
replaceRequireInCode(file, required, resolvedRequire);
replaceRequireInSourceMap(file, required, resolvedRequire);
}
// Not a TS file in our project sources, use resolver to check if we can find dependency
try {
const resolveResult = resolver.resolveSync({}, fileDirectory, dependency);
if (resolveResult)
return resolveResult;
}
catch (e) {
// resolveSync errors if it fails to resolve
}
return undefined;
}
getFileFromPath(resolvedPath) {
const existingFile = this.pathToFile.get(resolvedPath);
if (existingFile)
return existingFile;
if (existingFile === false)
return undefined;
const file = this.searchForFileFromPath(resolvedPath);
this.pathToFile.set(resolvedPath, file !== null && file !== void 0 ? file : false);
return file;
}
searchForFileFromPath(resolvedPath) {
const possibleProjectFiles = [
resolvedPath,
resolvedPath + ".ts",
path.join(resolvedPath, "index.ts"),
resolvedPath + ".tsx",
path.join(resolvedPath, "index.tsx"), // tsx index
];
for (const possibleFile of possibleProjectFiles) {
if (isProjectFile(possibleFile, this.program)) {
return possibleFile;
}
// Check cache to prevent resolving nested dependencies double to break dependency loops
if (this.resultsCache.has(resolvedDependency)) {
if (this.options.tstlVerbose) {
console.log(`Resolution cache hit for ${(0, utils_1.normalizeSlashes)(resolvedDependency)}`);
}
return this.resultsCache.get(resolvedDependency);
}
// Check if this is a lua file in the project sources
const possibleLuaProjectFiles = [
resolvedPath + ".lua",
path.join(resolvedPath, "index.lua"),
path.join(resolvedPath, "init.lua"), // lua looks for <require>/init.lua if it cannot find <require>.lua
];
for (const possibleFile of possibleLuaProjectFiles) {
if (this.emitHost.fileExists(possibleFile)) {
return possibleFile;
}
// If dependency is not part of project, add dependency to output and resolve its dependencies recursively
if (shouldIncludeDependency(resolvedDependency, this.program)) {
// If dependency resolved successfully, read its content
const dependencyContent = this.emitHost.readFile(resolvedDependency);
if (dependencyContent === undefined) {
return { resolvedFiles: [], diagnostics: [(0, diagnostics_1.couldNotReadDependency)(resolvedDependency)] };
}
const dependency = {
fileName: resolvedDependency,
code: dependencyContent,
};
const nestedDependencies = resolveFileDependencies(dependency, this);
// Cache result and return
const result = {
resolvedFiles: [dependency, ...nestedDependencies.resolvedFiles],
diagnostics: [...nestedDependencies.diagnostics],
};
this.resultsCache.set(resolvedDependency, result);
return result;
}
else {
const result = {
resolvedFiles: [],
diagnostics: [],
};
this.resultsCache.set(resolvedDependency, result);
return result;
}
}
else {
const fallbackRequire = fallbackResolve(required, (0, transpiler_1.getSourceDir)(this.program), path.dirname(file.fileName));
replaceRequireInCode(file, required, fallbackRequire);
replaceRequireInSourceMap(file, required, fallbackRequire);
return {
resolvedFiles: [],
diagnostics: [
(0, diagnostics_1.couldNotResolveRequire)(required, path.relative((0, transpiler_1.getProjectRoot)(this.program), file.fileName)),
],
};
}
}
}
function resolveDependencies(program, files, emitHost) {
const outFiles = [...files];
const diagnostics = [];
const options = program.getCompilerOptions();

@@ -106,95 +181,7 @@ const resolutionContext = new ResolutionContext(program, options, emitHost);

}
const resolutionResult = resolveFileDependencies(file, resolutionContext);
outFiles.push(...resolutionResult.resolvedFiles);
diagnostics.push(...resolutionResult.diagnostics);
resolutionContext.addAndResolveDependencies(file);
}
return { resolvedFiles: deduplicateResolvedFiles(outFiles), diagnostics };
return { resolvedFiles: [...resolutionContext.resolvedFiles.values()], diagnostics: resolutionContext.diagnostics };
}
exports.resolveDependencies = resolveDependencies;
function deduplicateResolvedFiles(files) {
return [...new Map(files.map(f => [f.fileName, f])).values()];
}
function resolveFileDependencies(file, context) {
const dependencies = [];
const diagnostics = [];
for (const required of findRequiredPaths(file.code)) {
// Do no resolve lualib - always use the lualib of the application entry point, not the lualib from external packages
if (required === "lualib_bundle") {
dependencies.push({ fileName: "lualib_bundle", code: "" });
continue;
}
// Do not resolve noResolution paths
if (required.startsWith("@NoResolution:")) {
// Remove @NoResolution prefix if not building in library mode
if (!isBuildModeLibrary(context.program)) {
const path = required.replace("@NoResolution:", "");
replaceRequireInCode(file, required, path);
replaceRequireInSourceMap(file, required, path);
}
// Skip
continue;
}
// Try to resolve the import starting from the directory `file` is in
const resolvedDependency = context.resolve(file, required);
dependencies.push(...resolvedDependency.resolvedFiles);
diagnostics.push(...resolvedDependency.diagnostics);
}
return { resolvedFiles: deduplicateResolvedFiles(dependencies), diagnostics };
}
function resolveDependency(requiringFile, dependency, program, emitHost) {
var _a;
const options = program.getCompilerOptions();
const fileDirectory = path.dirname(requiringFile.fileName);
if (options.tstlVerbose) {
console.log(`Resolving "${dependency}" from ${(0, utils_1.normalizeSlashes)(requiringFile.fileName)}`);
}
// Check if the import is relative
const isRelative = ["/", "./", "../"].some(p => dependency.startsWith(p));
// If the import is relative, always resolve it relative to the requiring file
// If the import is not relative, resolve it relative to options.baseUrl if it is set
const relativeTo = isRelative ? fileDirectory : (_a = options.baseUrl) !== null && _a !== void 0 ? _a : fileDirectory;
// Check if file is a file in the project
const resolvedPath = path.join(relativeTo, dependency);
const possibleProjectFiles = [
resolvedPath,
resolvedPath + ".ts",
path.join(resolvedPath, "index.ts"),
resolvedPath + ".tsx",
path.join(resolvedPath, "index.tsx"), // tsx index
];
for (const possibleFile of possibleProjectFiles) {
if (isProjectFile(possibleFile, program)) {
return possibleFile;
}
}
// Check if this is a lua file in the project sources
const possibleLuaProjectFiles = [
resolvedPath + ".lua",
path.join(resolvedPath, "index.lua"),
path.join(resolvedPath, "init.lua"), // lua looks for <require>/init.lua if it cannot find <require>.lua
];
for (const possibleFile of possibleLuaProjectFiles) {
if (emitHost.fileExists(possibleFile)) {
return possibleFile;
}
}
// Check if this is a sibling of a required lua file
if (requiringFile.fileName.endsWith(".lua")) {
const luaFilePath = resolveLuaPath(fileDirectory, dependency, emitHost);
if (luaFilePath) {
return luaFilePath;
}
}
// Not a TS file in our project sources, use resolver to check if we can find dependency
try {
const resolveResult = resolver.resolveSync({}, fileDirectory, dependency);
if (resolveResult) {
return resolveResult;
}
}
catch (e) {
// resolveSync errors if it fails to resolve
}
return undefined;
}
function resolveLuaPath(fromPath, dependency, emitHost) {

@@ -229,17 +216,13 @@ const splitDependency = dependency.split(".");

function shouldRewriteRequires(resolvedDependency, program) {
return !isNodeModulesFile(resolvedDependency) || !isBuildModeLibrary(program);
return !isBuildModeLibrary(program) || !isNodeModulesFile(resolvedDependency);
}
function shouldIncludeDependency(resolvedDependency, program) {
// Never include lua files (again) that are transpiled from project sources
if (!hasSourceFileInProject(resolvedDependency, program)) {
// Always include lua files not in node_modules (internal lua sources)
if (!isNodeModulesFile(resolvedDependency)) {
return true;
}
else {
// Only include node_modules files if not in library mode
return !isBuildModeLibrary(program);
}
}
return false;
if (hasSourceFileInProject(resolvedDependency, program))
return false;
// Always include lua files not in node_modules (internal lua sources)
if (!isNodeModulesFile(resolvedDependency))
return true;
// Only include node_modules files if not in library mode
return !isBuildModeLibrary(program);
}

@@ -246,0 +229,0 @@ function isBuildModeLibrary(program) {

@@ -11,4 +11,6 @@ "use strict";

const transformers_1 = require("./transformers");
const performance = require("../measure-performance");
function getProgramTranspileResult(emitHost, writeFileResult, { program, sourceFiles: targetSourceFiles, customTransformers = {}, plugins = [] }) {
var _a, _b;
performance.startSection("beforeTransform");
const options = program.getCompilerOptions();

@@ -40,2 +42,3 @@ if (options.tstlVerbose) {

if (preEmitDiagnostics.length > 0) {
performance.endSection("beforeTransform");
return { diagnostics: preEmitDiagnostics, transpiledFiles };

@@ -56,5 +59,8 @@ }

}
performance.startSection("transpile");
const { file, diagnostics: transformDiagnostics } = (0, transformation_1.transformSourceFile)(program, sourceFile, visitorMap);
diagnostics.push(...transformDiagnostics);
performance.endSection("transpile");
if (!options.noEmit && !options.emitDeclarationOnly) {
performance.startSection("print");
if (options.tstlVerbose) {

@@ -70,2 +76,3 @@ console.log(`Printing ${sourceFile.fileName}`);

});
performance.endSection("print");
}

@@ -85,2 +92,3 @@ };

};
performance.endSection("beforeTransform");
if (targetSourceFiles) {

@@ -101,2 +109,3 @@ for (const file of targetSourceFiles) {

}
performance.startSection("afterPrint");
options.noEmit = oldNoEmit;

@@ -112,2 +121,3 @@ if (options.noEmit || (options.noEmitOnError && diagnostics.length > 0)) {

}
performance.endSection("afterPrint");
return { diagnostics, transpiledFiles };

@@ -114,0 +124,0 @@ }

@@ -18,2 +18,3 @@ import * as ts from "typescript";

emit(emitOptions: EmitOptions): EmitResult;
private emitFiles;
protected getEmitPlan(program: ts.Program, diagnostics: ts.Diagnostic[], files: ProcessedFile[]): {

@@ -20,0 +21,0 @@ emitPlan: EmitFile[];

@@ -13,2 +13,3 @@ "use strict";

const transpile_1 = require("./transpile");
const performance = require("../measure-performance");
class Transpiler {

@@ -19,15 +20,24 @@ constructor({ emitHost = ts.sys } = {}) {

emit(emitOptions) {
var _a, _b;
const { program, writeFile = this.emitHost.writeFile, plugins: optionsPlugins = [] } = emitOptions;
const options = program.getCompilerOptions();
const { diagnostics: getPluginsDiagnostics, plugins: configPlugins } = (0, plugins_1.getPlugins)(program);
const plugins = [...optionsPlugins, ...configPlugins];
const { diagnostics, transpiledFiles: freshFiles } = (0, transpile_1.getProgramTranspileResult)(this.emitHost, writeFile, {
const { diagnostics: transpileDiagnostics, transpiledFiles: freshFiles } = (0, transpile_1.getProgramTranspileResult)(this.emitHost, writeFile, {
...emitOptions,
plugins,
});
const { emitPlan } = this.getEmitPlan(program, diagnostics, freshFiles);
const { emitPlan } = this.getEmitPlan(program, transpileDiagnostics, freshFiles);
const emitDiagnostics = this.emitFiles(program, plugins, emitPlan, writeFile);
return {
diagnostics: getPluginsDiagnostics.concat(transpileDiagnostics, emitDiagnostics),
emitSkipped: emitPlan.length === 0,
};
}
emitFiles(program, plugins, emitPlan, writeFile) {
var _a, _b;
performance.startSection("emit");
const options = program.getCompilerOptions();
if (options.tstlVerbose) {
console.log("Emitting output");
}
const diagnostics = [];
for (const plugin of plugins) {

@@ -52,5 +62,7 @@ if (plugin.beforeEmit) {

}
return { diagnostics: getPluginsDiagnostics.concat(diagnostics), emitSkipped: emitPlan.length === 0 };
performance.endSection("emit");
return diagnostics;
}
getEmitPlan(program, diagnostics, files) {
performance.startSection("getEmitPlan");
const options = program.getCompilerOptions();

@@ -86,2 +98,3 @@ if (options.tstlVerbose) {

}
performance.endSection("getEmitPlan");
return { emitPlan };

@@ -88,0 +101,0 @@ }

@@ -12,2 +12,3 @@ #!/usr/bin/env node

const CompilerOptions_1 = require("./CompilerOptions");
const performance = require("./measure-performance");
const shouldBePretty = ({ pretty } = {}) => { var _a, _b, _c; return pretty !== undefined ? pretty : (_c = (_b = (_a = ts.sys).writeOutputIsTTY) === null || _b === void 0 ? void 0 : _b.call(_a)) !== null && _c !== void 0 ? _c : false; };

@@ -79,2 +80,5 @@ let reportDiagnostic = (0, report_1.createDiagnosticReporter)(false);

function performCompilation(rootNames, projectReferences, options, configFileParsingDiagnostics) {
if (options.measurePerformance)
performance.enableMeasurement();
performance.startSection("createProgram");
const program = ts.createProgram({

@@ -87,5 +91,8 @@ rootNames,

const preEmitDiagnostics = ts.getPreEmitDiagnostics(program);
performance.endSection("createProgram");
const { diagnostics: transpileDiagnostics, emitSkipped } = new tstl.Transpiler().emit({ program });
const diagnostics = ts.sortAndDeduplicateDiagnostics([...preEmitDiagnostics, ...transpileDiagnostics]);
diagnostics.forEach(reportDiagnostic);
if (options.measurePerformance)
reportPerformance();
const exitCode = diagnostics.filter(d => d.category === ts.DiagnosticCategory.Error).length === 0

@@ -115,2 +122,4 @@ ? ts.ExitStatus.Success

const options = builderProgram.getCompilerOptions();
if (options.measurePerformance)
performance.enableMeasurement();
const configFileParsingDiagnostics = updateConfigFile(options);

@@ -142,2 +151,4 @@ let sourceFiles;

diagnostics.forEach(reportDiagnostic);
if (options.measurePerformance)
reportPerformance();
const errors = diagnostics.filter(d => d.category === ts.DiagnosticCategory.Error);

@@ -148,2 +159,12 @@ hadErrorLastTime = errors.length > 0;

}
function reportPerformance() {
if (performance.isMeasurementEnabled()) {
console.log("Performance measurements: ");
performance.forEachMeasure((name, duration) => {
console.log(` ${name}: ${duration.toFixed(2)}ms`);
});
console.log(`Total: ${performance.getTotalDuration().toFixed(2)}ms`);
performance.disableMeasurement();
}
}
function checkNodeVersion() {

@@ -150,0 +171,0 @@ const [major, minor] = process.version.slice(1).split(".").map(Number);

@@ -6,3 +6,3 @@ type AnyTable = Record<any, any>;

/**
* Indicates a type is a language extension provided by TypescriptToLua.
* Indicates a type is a language extension provided by TypescriptToLua when used as a value or function call.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions

@@ -12,5 +12,17 @@ *

*/
declare type LuaExtension<TBrand extends string> = { [T in TBrand]: { readonly __luaExtensionSymbol: unique symbol } };
declare interface LuaExtension<TBrand extends string> {
readonly __tstlExtension: TBrand;
}
/**
* Indicates a type is a language extension provided by TypescriptToLua when used in a for-of loop.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TBrand A string used to uniquely identify the language extension type
*/
declare interface LuaIterationExtension<TBrand extends string> {
readonly __tstlIterable: TBrand;
}
/**
* Returns multiple values from a function, by wrapping them in a LuaMultiReturn tuple.

@@ -22,3 +34,3 @@ * For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions

*/
declare const $multi: (<T extends any[]>(...values: T) => LuaMultiReturn<T>) & LuaExtension<"__luaMultiFunctionBrand">;
declare const $multi: (<T extends any[]>(...values: T) => LuaMultiReturn<T>) & LuaExtension<"MultiFunction">;

@@ -31,3 +43,5 @@ /**

*/
declare type LuaMultiReturn<T extends any[]> = T & LuaExtension<"__luaMultiReturnBrand">;
declare type LuaMultiReturn<T extends any[]> = T & {
readonly __tstlMultiReturn: any;
};

@@ -43,3 +57,3 @@ /**

declare const $range: ((start: number, limit: number, step?: number) => Iterable<number>) &
LuaExtension<"__luaRangeFunctionBrand">;
LuaExtension<"RangeFunction">;

@@ -50,3 +64,3 @@ /**

*/
declare const $vararg: string[] & LuaExtension<"__luaVarargConstantBrand">;
declare const $vararg: string[] & LuaExtension<"VarargConstant">;

@@ -85,3 +99,3 @@ /**

LuaIterator<TValue, TState> &
LuaExtension<"__luaIterableBrand">;
LuaIterationExtension<"Iterable">;

@@ -96,5 +110,12 @@ /**

declare type LuaPairsIterable<TKey extends AnyNotNil, TValue> = Iterable<[TKey, TValue]> &
LuaExtension<"__luaPairsIterableBrand">;
LuaIterationExtension<"Pairs">;
/**
* Represents an object that can be iterated with pairs(), where only the key value is used.
*
* @param TKey The type of the key returned each iteration.
*/
declare type LuaPairsKeyIterable<TKey extends AnyNotNil> = Iterable<TKey> & LuaIterationExtension<"PairsKey">;
/**
* Calls to functions with this type are translated to `left + right`.

@@ -107,4 +128,3 @@ * For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions

*/
declare type LuaAddition<TLeft, TRight, TReturn> = ((left: TLeft, right: TRight) => TReturn) &
LuaExtension<"__luaAdditionBrand">;
declare type LuaAddition<TLeft, TRight, TReturn> = ((left: TLeft, right: TRight) => TReturn) & LuaExtension<"Addition">;

@@ -118,4 +138,3 @@ /**

*/
declare type LuaAdditionMethod<TRight, TReturn> = ((right: TRight) => TReturn) &
LuaExtension<"__luaAdditionMethodBrand">;
declare type LuaAdditionMethod<TRight, TReturn> = ((right: TRight) => TReturn) & LuaExtension<"AdditionMethod">;

@@ -131,3 +150,3 @@ /**

declare type LuaSubtraction<TLeft, TRight, TReturn> = ((left: TLeft, right: TRight) => TReturn) &
LuaExtension<"__luaSubtractionBrand">;
LuaExtension<"Subtraction">;

@@ -141,4 +160,3 @@ /**

*/
declare type LuaSubtractionMethod<TRight, TReturn> = ((right: TRight) => TReturn) &
LuaExtension<"__luaSubtractionMethodBrand">;
declare type LuaSubtractionMethod<TRight, TReturn> = ((right: TRight) => TReturn) & LuaExtension<"SubtractionMethod">;

@@ -154,3 +172,3 @@ /**

declare type LuaMultiplication<TLeft, TRight, TReturn> = ((left: TLeft, right: TRight) => TReturn) &
LuaExtension<"__luaMultiplicationBrand">;
LuaExtension<"Multiplication">;

@@ -165,3 +183,3 @@ /**

declare type LuaMultiplicationMethod<TRight, TReturn> = ((right: TRight) => TReturn) &
LuaExtension<"__luaMultiplicationMethodBrand">;
LuaExtension<"MultiplicationMethod">;

@@ -176,4 +194,3 @@ /**

*/
declare type LuaDivision<TLeft, TRight, TReturn> = ((left: TLeft, right: TRight) => TReturn) &
LuaExtension<"__luaDivisionBrand">;
declare type LuaDivision<TLeft, TRight, TReturn> = ((left: TLeft, right: TRight) => TReturn) & LuaExtension<"Division">;

@@ -187,4 +204,3 @@ /**

*/
declare type LuaDivisionMethod<TRight, TReturn> = ((right: TRight) => TReturn) &
LuaExtension<"__luaDivisionMethodBrand">;
declare type LuaDivisionMethod<TRight, TReturn> = ((right: TRight) => TReturn) & LuaExtension<"DivisionMethod">;

@@ -199,4 +215,3 @@ /**

*/
declare type LuaModulo<TLeft, TRight, TReturn> = ((left: TLeft, right: TRight) => TReturn) &
LuaExtension<"__luaModuloBrand">;
declare type LuaModulo<TLeft, TRight, TReturn> = ((left: TLeft, right: TRight) => TReturn) & LuaExtension<"Modulo">;

@@ -210,3 +225,3 @@ /**

*/
declare type LuaModuloMethod<TRight, TReturn> = ((right: TRight) => TReturn) & LuaExtension<"__luaModuloMethodBrand">;
declare type LuaModuloMethod<TRight, TReturn> = ((right: TRight) => TReturn) & LuaExtension<"ModuloMethod">;

@@ -221,4 +236,3 @@ /**

*/
declare type LuaPower<TLeft, TRight, TReturn> = ((left: TLeft, right: TRight) => TReturn) &
LuaExtension<"__luaPowerBrand">;
declare type LuaPower<TLeft, TRight, TReturn> = ((left: TLeft, right: TRight) => TReturn) & LuaExtension<"Power">;

@@ -232,3 +246,3 @@ /**

*/
declare type LuaPowerMethod<TRight, TReturn> = ((right: TRight) => TReturn) & LuaExtension<"__luaPowerMethodBrand">;
declare type LuaPowerMethod<TRight, TReturn> = ((right: TRight) => TReturn) & LuaExtension<"PowerMethod">;

@@ -244,3 +258,3 @@ /**

declare type LuaFloorDivision<TLeft, TRight, TReturn> = ((left: TLeft, right: TRight) => TReturn) &
LuaExtension<"__luaFloorDivisionBrand">;
LuaExtension<"FloorDivision">;

@@ -255,3 +269,3 @@ /**

declare type LuaFloorDivisionMethod<TRight, TReturn> = ((right: TRight) => TReturn) &
LuaExtension<"__luaFloorDivisionMethodBrand">;
LuaExtension<"FloorDivisionMethod">;

@@ -267,3 +281,3 @@ /**

declare type LuaBitwiseAnd<TLeft, TRight, TReturn> = ((left: TLeft, right: TRight) => TReturn) &
LuaExtension<"__luaBitwiseAndBrand">;
LuaExtension<"BitwiseAnd">;

@@ -277,4 +291,3 @@ /**

*/
declare type LuaBitwiseAndMethod<TRight, TReturn> = ((right: TRight) => TReturn) &
LuaExtension<"__luaBitwiseAndMethodBrand">;
declare type LuaBitwiseAndMethod<TRight, TReturn> = ((right: TRight) => TReturn) & LuaExtension<"BitwiseAndMethod">;

@@ -290,3 +303,3 @@ /**

declare type LuaBitwiseOr<TLeft, TRight, TReturn> = ((left: TLeft, right: TRight) => TReturn) &
LuaExtension<"__luaBitwiseOrBrand">;
LuaExtension<"BitwiseOr">;

@@ -300,4 +313,3 @@ /**

*/
declare type LuaBitwiseOrMethod<TRight, TReturn> = ((right: TRight) => TReturn) &
LuaExtension<"__luaBitwiseOrMethodBrand">;
declare type LuaBitwiseOrMethod<TRight, TReturn> = ((right: TRight) => TReturn) & LuaExtension<"BitwiseOrMethod">;

@@ -313,3 +325,3 @@ /**

declare type LuaBitwiseExclusiveOr<TLeft, TRight, TReturn> = ((left: TLeft, right: TRight) => TReturn) &
LuaExtension<"__luaBitwiseExclusiveOrBrand">;
LuaExtension<"BitwiseExclusiveOr">;

@@ -324,3 +336,3 @@ /**

declare type LuaBitwiseExclusiveOrMethod<TRight, TReturn> = ((right: TRight) => TReturn) &
LuaExtension<"__luaBitwiseExclusiveOrMethodBrand">;
LuaExtension<"BitwiseExclusiveOrMethod">;

@@ -336,3 +348,3 @@ /**

declare type LuaBitwiseLeftShift<TLeft, TRight, TReturn> = ((left: TLeft, right: TRight) => TReturn) &
LuaExtension<"__luaBitwiseLeftShiftBrand">;
LuaExtension<"BitwiseLeftShift">;

@@ -347,3 +359,3 @@ /**

declare type LuaBitwiseLeftShiftMethod<TRight, TReturn> = ((right: TRight) => TReturn) &
LuaExtension<"__luaBitwiseLeftShiftMethodBrand">;
LuaExtension<"BitwiseLeftShiftMethod">;

@@ -359,3 +371,3 @@ /**

declare type LuaBitwiseRightShift<TLeft, TRight, TReturn> = ((left: TLeft, right: TRight) => TReturn) &
LuaExtension<"__luaBitwiseRightShiftBrand">;
LuaExtension<"BitwiseRightShift">;

@@ -370,3 +382,3 @@ /**

declare type LuaBitwiseRightShiftMethod<TRight, TReturn> = ((right: TRight) => TReturn) &
LuaExtension<"__luaBitwiseRightShiftMethodBrand">;
LuaExtension<"BitwiseRightShiftMethod">;

@@ -381,4 +393,3 @@ /**

*/
declare type LuaConcat<TLeft, TRight, TReturn> = ((left: TLeft, right: TRight) => TReturn) &
LuaExtension<"__luaConcatBrand">;
declare type LuaConcat<TLeft, TRight, TReturn> = ((left: TLeft, right: TRight) => TReturn) & LuaExtension<"Concat">;

@@ -392,3 +403,3 @@ /**

*/
declare type LuaConcatMethod<TRight, TReturn> = ((right: TRight) => TReturn) & LuaExtension<"__luaConcatMethodBrand">;
declare type LuaConcatMethod<TRight, TReturn> = ((right: TRight) => TReturn) & LuaExtension<"ConcatMethod">;

@@ -403,4 +414,3 @@ /**

*/
declare type LuaLessThan<TLeft, TRight, TReturn> = ((left: TLeft, right: TRight) => TReturn) &
LuaExtension<"__luaLessThanBrand">;
declare type LuaLessThan<TLeft, TRight, TReturn> = ((left: TLeft, right: TRight) => TReturn) & LuaExtension<"LessThan">;

@@ -414,4 +424,3 @@ /**

*/
declare type LuaLessThanMethod<TRight, TReturn> = ((right: TRight) => TReturn) &
LuaExtension<"__luaLessThanMethodBrand">;
declare type LuaLessThanMethod<TRight, TReturn> = ((right: TRight) => TReturn) & LuaExtension<"LessThanMethod">;

@@ -427,3 +436,3 @@ /**

declare type LuaGreaterThan<TLeft, TRight, TReturn> = ((left: TLeft, right: TRight) => TReturn) &
LuaExtension<"__luaGreaterThanBrand">;
LuaExtension<"GreaterThan">;

@@ -437,4 +446,3 @@ /**

*/
declare type LuaGreaterThanMethod<TRight, TReturn> = ((right: TRight) => TReturn) &
LuaExtension<"__luaGreaterThanMethodBrand">;
declare type LuaGreaterThanMethod<TRight, TReturn> = ((right: TRight) => TReturn) & LuaExtension<"GreaterThanMethod">;

@@ -448,3 +456,3 @@ /**

*/
declare type LuaNegation<TOperand, TReturn> = ((operand: TOperand) => TReturn) & LuaExtension<"__luaNegationBrand">;
declare type LuaNegation<TOperand, TReturn> = ((operand: TOperand) => TReturn) & LuaExtension<"Negation">;

@@ -457,3 +465,3 @@ /**

*/
declare type LuaNegationMethod<TReturn> = (() => TReturn) & LuaExtension<"__luaNegationMethodBrand">;
declare type LuaNegationMethod<TReturn> = (() => TReturn) & LuaExtension<"NegationMethod">;

@@ -467,3 +475,3 @@ /**

*/
declare type LuaBitwiseNot<TOperand, TReturn> = ((operand: TOperand) => TReturn) & LuaExtension<"__luaBitwiseNotBrand">;
declare type LuaBitwiseNot<TOperand, TReturn> = ((operand: TOperand) => TReturn) & LuaExtension<"BitwiseNot">;

@@ -476,3 +484,3 @@ /**

*/
declare type LuaBitwiseNotMethod<TReturn> = (() => TReturn) & LuaExtension<"__luaBitwiseNotMethodBrand">;
declare type LuaBitwiseNotMethod<TReturn> = (() => TReturn) & LuaExtension<"BitwiseNotMethod">;

@@ -486,3 +494,3 @@ /**

*/
declare type LuaLength<TOperand, TReturn> = ((operand: TOperand) => TReturn) & LuaExtension<"__luaLengthBrand">;
declare type LuaLength<TOperand, TReturn> = ((operand: TOperand) => TReturn) & LuaExtension<"Length">;

@@ -495,3 +503,3 @@ /**

*/
declare type LuaLengthMethod<TReturn> = (() => TReturn) & LuaExtension<"__luaLengthMethodBrand">;
declare type LuaLengthMethod<TReturn> = (() => TReturn) & LuaExtension<"LengthMethod">;

@@ -510,3 +518,3 @@ /**

) => TValue) &
LuaExtension<"__luaTableGetBrand">;
LuaExtension<"TableGet">;

@@ -521,3 +529,3 @@ /**

declare type LuaTableGetMethod<TKey extends AnyNotNil, TValue> = ((key: TKey) => TValue) &
LuaExtension<"__luaTableGetMethodBrand">;
LuaExtension<"TableGetMethod">;

@@ -537,3 +545,3 @@ /**

) => void) &
LuaExtension<"__luaTableSetBrand">;
LuaExtension<"TableSet">;

@@ -548,5 +556,22 @@ /**

declare type LuaTableSetMethod<TKey extends AnyNotNil, TValue> = ((key: TKey, value: TValue) => void) &
LuaExtension<"__luaTableSetMethodBrand">;
LuaExtension<"TableSetMethod">;
/**
* Calls to functions with this type are translated to `table[key] = true`.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TTable The type to access as a Lua table.
* @param TKey The type of the key to use to access the table.
*/
declare type LuaTableAddKey<TTable extends AnyTable, TKey extends AnyNotNil> = ((table: TTable, key: TKey) => void) &
LuaExtension<"TableAddKey">;
/**
* Calls to methods with this type are translated to `table[key] = true`, where `table` is the object with the method.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
* @param TKey The type of the key to use to access the table.
*/
declare type LuaTableAddKeyMethod<TKey extends AnyNotNil> = ((key: TKey) => void) & LuaExtension<"TableAddKeyMethod">;
/**
* Calls to functions with this type are translated to `table[key] ~= nil`.

@@ -559,3 +584,3 @@ * For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions

declare type LuaTableHas<TTable extends AnyTable, TKey extends AnyNotNil> = ((table: TTable, key: TKey) => boolean) &
LuaExtension<"__luaTableHasBrand">;
LuaExtension<"TableHas">;

@@ -568,4 +593,3 @@ /**

*/
declare type LuaTableHasMethod<TKey extends AnyNotNil> = ((key: TKey) => boolean) &
LuaExtension<"__luaTableHasMethodBrand">;
declare type LuaTableHasMethod<TKey extends AnyNotNil> = ((key: TKey) => boolean) & LuaExtension<"TableHasMethod">;

@@ -580,3 +604,3 @@ /**

declare type LuaTableDelete<TTable extends AnyTable, TKey extends AnyNotNil> = ((table: TTable, key: TKey) => boolean) &
LuaExtension<"__luaTableDeleteBrand">;
LuaExtension<"TableDelete">;

@@ -590,3 +614,3 @@ /**

declare type LuaTableDeleteMethod<TKey extends AnyNotNil> = ((key: TKey) => boolean) &
LuaExtension<"__luaTableDeleteMethodBrand">;
LuaExtension<"TableDeleteMethod">;

@@ -619,3 +643,3 @@ /**

>) &
LuaExtension<"__luaTableNewBrand">;
LuaExtension<"TableNew">;

@@ -630,1 +654,66 @@ /**

declare const LuaTable: LuaTableConstructor;
/**
* A convenience type for working directly with a Lua table, used as a map.
*
* This differs from LuaTable in that the `get` method may return `nil`.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
* @param K The type of the keys used to access the table.
* @param V The type of the values stored in the table.
*/
declare interface LuaMap<K extends AnyNotNil = AnyNotNil, V = any> extends LuaPairsIterable<K, V> {
get: LuaTableGetMethod<K, V | undefined>;
set: LuaTableSetMethod<K, V>;
has: LuaTableHasMethod<K>;
delete: LuaTableDeleteMethod<K>;
}
/**
* A convenience type for working directly with a Lua table, used as a map.
*
* This differs from LuaTable in that the `get` method may return `nil`.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
* @param K The type of the keys used to access the table.
* @param V The type of the values stored in the table.
*/
declare const LuaMap: (new <K extends AnyNotNil = AnyNotNil, V = any>() => LuaMap<K, V>) & LuaExtension<"TableNew">;
/**
* Readonly version of {@link LuaMap}.
*
* @param K The type of the keys used to access the table.
* @param V The type of the values stored in the table.
*/
declare interface LuaReadonlyMap<K extends AnyNotNil = AnyNotNil, V = any> extends LuaPairsIterable<K, V> {
get: LuaTableGetMethod<K, V>;
has: LuaTableHasMethod<K>;
}
/**
* A convenience type for working directly with a Lua table, used as a set.
*
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
* @param T The type of the keys used to access the table.
*/
declare interface LuaSet<T extends AnyNotNil = AnyNotNil> extends LuaPairsKeyIterable<T> {
add: LuaTableAddKeyMethod<T>;
has: LuaTableHasMethod<T>;
delete: LuaTableDeleteMethod<T>;
}
/**
* A convenience type for working directly with a Lua table, used as a set.
*
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
* @param T The type of the keys used to access the table.
*/
declare const LuaSet: (new <T extends AnyNotNil = AnyNotNil>() => LuaSet<T>) & LuaExtension<"TableNew">;
/**
* Readonly version of {@link LuaSet}.
*
* @param T The type of the keys used to access the table.
*/
declare interface LuaReadonlySet<T extends AnyNotNil = AnyNotNil> extends LuaPairsKeyIterable<T> {
has: LuaTableHasMethod<T>;
}
{
"name": "typescript-to-lua",
"version": "1.6.3",
"version": "1.7.0",
"description": "A generic TypeScript to Lua transpiler. Write your code in TypeScript and publish Lua!",

@@ -68,3 +68,3 @@ "repository": "https://github.com/TypeScriptToLua/TypeScriptToLua",

"jest-circus": "^27.3.0",
"lua-types": "2.10.1",
"lua-types": "^2.11.0",
"lua-wasm-bindings": "^0.2.2",

@@ -71,0 +71,0 @@ "prettier": "^2.3.2",

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

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