dukat
Version:
Converter definition files to Kotlin declarations. Currently support TypeScript declarations
1,000 lines (981 loc) • 1.09 MB
JavaScript
(function(e, a) { for(var i in a) e[i] = a[i]; }(exports, /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(1);
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createSourceSet = void 0;
var DukatLanguageServiceHost_1 = __webpack_require__(2);
var AstConverter_1 = __webpack_require__(5);
var ts = __webpack_require__(3);
var declarations = __webpack_require__(8);
var DeclarationResolver_1 = __webpack_require__(16);
var ExportContext_1 = __webpack_require__(13);
var DocumentCache_1 = __webpack_require__(17);
var DependencyBuilder_1 = __webpack_require__(18);
var cache = new DocumentCache_1.DocumentCache();
function getLibPaths(program, libPath, libs) {
if (libs === void 0) { libs = new Set(); }
if (libPath === undefined) {
return libs;
}
var value = ts.normalizePath(libPath.fileName);
if (libs.has(value)) {
return libs;
}
libs.add(value);
libPath.libReferenceDirectives.forEach(function (libReference) {
getLibPaths(program, program.getLibFileFromReference(libReference), libs);
});
return libs;
}
var SourceBundleBuilder = /** @class */ (function () {
function SourceBundleBuilder(tsConfig, stdLib, emitDiagnostics, failOnWarnings, originalFiles) {
var _this = this;
this.tsConfig = tsConfig;
this.stdLib = stdLib;
this.emitDiagnostics = emitDiagnostics;
this.failOnWarnings = failOnWarnings;
this.program = this.createProgram(originalFiles);
if (emitDiagnostics) {
this.printWarningsAndTreatThemAsErrors(this.program);
}
this.libsSet = getLibPaths(this.program, this.program.getSourceFile(this.stdLib));
var dependencyBuilder = new DependencyBuilder_1.DependencyBuilder(this.program);
originalFiles.forEach(function (file) {
dependencyBuilder.buildFileDependencies(file);
});
this.dependencyBuilder = dependencyBuilder;
this.astConverter = new AstConverter_1.AstConverter(new ExportContext_1.ExportContext(), this.program.getTypeChecker(), new DeclarationResolver_1.DeclarationResolver(this.program), function (node) { return _this.isLibSource(node); });
}
SourceBundleBuilder.prototype.isLibSource = function (node) {
var src = (typeof node == "string") ? node : (node.getSourceFile().fileName);
return this.libsSet.has(ts.normalizePath(src));
};
SourceBundleBuilder.prototype.printWarningsAndTreatThemAsErrors = function (program) {
var diagnostics = ts.getPreEmitDiagnostics(program).concat(program.emit().diagnostics);
if (diagnostics.length > 0) {
diagnostics.forEach(function (diagnostic) {
var _a = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start), line = _a.line, character = _a.character;
var message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n");
console.log("[warning] [tsc] TS" + diagnostic.code + ": " + message + " " + diagnostic.file.fileName + ":" + (line + 1) + ":" + (character + 1));
});
if (this.failOnWarnings) {
throw new Error("failing on warnings");
}
}
};
SourceBundleBuilder.prototype.createProgram = function (files) {
var host = new DukatLanguageServiceHost_1.DukatLanguageServiceHost(this.tsConfig, this.stdLib);
files.forEach(function (fileName) { return host.register(fileName); });
var languageService = ts.createLanguageService(host, ts.createDocumentRegistryInternal(void 0, void 0, cache || void 0));
var program = languageService.getProgram();
if (program == null) {
throw new Error("failed to create languageService");
}
return program;
};
SourceBundleBuilder.prototype.createBundle = function () {
var _this = this;
var sourceSet = new declarations.SourceSetDeclarationProto();
var sourceFiles = new Array();
this.dependencyBuilder.forEachDependency(function (dep) {
sourceFiles.push(_this.astConverter.createSourceFileDeclaration(_this.program.getSourceFile(dep.fileName), function (node) { return dep.accept(node); }));
});
sourceSet.setSourcesList(sourceFiles);
return sourceSet;
};
return SourceBundleBuilder;
}());
function createSourceSet(tsConfig, stdlib, emitDiagnostics, failOnWarnings, files) {
return new SourceBundleBuilder(tsConfig, stdlib, emitDiagnostics, failOnWarnings, files).createBundle();
}
exports.createSourceSet = createSourceSet;
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DukatLanguageServiceHost = void 0;
var ts = __webpack_require__(3);
var Logger_1 = __webpack_require__(4);
var DukatLanguageServiceHost = /** @class */ (function () {
function DukatLanguageServiceHost(tsConfig, defaultLib, knownFiles, currentDirectory) {
if (knownFiles === void 0) { knownFiles = new Set(); }
if (currentDirectory === void 0) { currentDirectory = ""; }
this.tsConfig = tsConfig;
this.defaultLib = defaultLib;
this.knownFiles = knownFiles;
this.currentDirectory = currentDirectory;
this.fileResolver = ts.sys;
}
DukatLanguageServiceHost.prototype.getCompilationSettings = function () {
if (this.tsConfig) {
var parsedCmd = ts.getParsedCommandLineOfConfigFile(this.tsConfig, ts.getDefaultCompilerOptions(), this);
return parsedCmd.options;
}
else {
var compilerOptions = ts.getDefaultCompilerOptions();
compilerOptions.allowJs = true;
return compilerOptions;
}
};
DukatLanguageServiceHost.prototype.getScriptFileNames = function () {
return Array.from(this.knownFiles);
};
DukatLanguageServiceHost.prototype.getScriptVersion = function (fileName) {
return "0";
};
DukatLanguageServiceHost.prototype.getDefaultLibFileName = function (options) {
return this.defaultLib;
};
DukatLanguageServiceHost.prototype.getCurrentDirectory = function () {
return this.currentDirectory;
};
DukatLanguageServiceHost.prototype.getScriptSnapshot = function (fileName) {
var contents = this.fileResolver.readFile(fileName);
return ts.ScriptSnapshot.fromString(contents);
};
DukatLanguageServiceHost.prototype.log = function (message) {
DukatLanguageServiceHost.log.debug(message);
};
DukatLanguageServiceHost.prototype.register = function (knownFile) {
this.knownFiles.add(knownFile);
};
DukatLanguageServiceHost.prototype.readFile = function (filePath) {
return this.fileResolver.readFile(filePath);
};
DukatLanguageServiceHost.prototype.fileExists = function (filePath) {
return this.fileResolver.fileExists(filePath);
};
DukatLanguageServiceHost.prototype.readDirectory = function (path, extensions, exclude, include, depth) {
return this.fileResolver.readDirectory(path, extensions, exclude, include, depth);
};
DukatLanguageServiceHost.prototype.onUnRecoverableConfigFileDiagnostic = function (diagnostic) {
var error = new Error(diagnostic.messageText);
error.tsDiagnostic = diagnostic;
throw error;
};
DukatLanguageServiceHost.log = Logger_1.createLogger("DukatLanguageServiceHost");
return DukatLanguageServiceHost;
}());
exports.DukatLanguageServiceHost = DukatLanguageServiceHost;
/***/ }),
/* 3 */
/***/ (function(module, exports) {
module.exports = require("typescript");
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createLogger = void 0;
var LogLevel;
(function (LogLevel) {
LogLevel[LogLevel["FATAL"] = 0] = "FATAL";
LogLevel[LogLevel["ERROR"] = 1] = "ERROR";
LogLevel[LogLevel["WARN"] = 2] = "WARN";
LogLevel[LogLevel["INFO"] = 3] = "INFO";
LogLevel[LogLevel["DEBUG"] = 4] = "DEBUG";
LogLevel[LogLevel["TRACE"] = 5] = "TRACE";
})(LogLevel || (LogLevel = {}));
var SimpleLogger = /** @class */ (function () {
function SimpleLogger(prefix, output) {
if (output === void 0) { output = SimpleLogger.console_logger; }
this.prefix = prefix;
this.output = output;
this.commonPrefix = "[ts]";
this.logLevel = parseInt(process.env.DUKAT_LOGLEVEL, 10);
}
SimpleLogger.prototype.logMessage = function (message, logDescriptor) {
return this.commonPrefix + " [" + logDescriptor + "] [" + this.prefix + "] " + message;
};
SimpleLogger.prototype.log = function (message) {
this.output(message);
};
SimpleLogger.prototype.guardLog = function (message, logLevel, logDescriptor) {
if (logLevel <= this.logLevel) {
this.log(this.logMessage(message, logDescriptor));
}
};
SimpleLogger.prototype.debug = function (message) {
this.guardLog(message, LogLevel.DEBUG, "DEBUG");
};
SimpleLogger.prototype.info = function (message) {
this.guardLog(message, LogLevel.INFO, "INFO");
};
SimpleLogger.prototype.trace = function (message) {
this.guardLog(message, LogLevel.TRACE, "TRACE");
};
SimpleLogger.prototype.warn = function (message) {
this.guardLog(message, LogLevel.WARN, "WARN");
};
SimpleLogger.console_logger = function (message) {
console.log(message);
};
return SimpleLogger;
}());
function createLogger(name, output) {
if (output === void 0) { output = SimpleLogger.console_logger; }
return new SimpleLogger(name, output);
}
exports.createLogger = createLogger;
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spread = (this && this.__spread) || function () {
for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
return ar;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AstConverter = void 0;
var ts = __webpack_require__(3);
var Logger_1 = __webpack_require__(4);
var uid_1 = __webpack_require__(6);
var AstFactory_1 = __webpack_require__(7);
var AstExpressionConverter_1 = __webpack_require__(12);
var ExportContext_1 = __webpack_require__(13);
var TsInternals_1 = __webpack_require__(11);
var declarations_1 = __webpack_require__(8);
var MODULE_KIND = declarations_1.ModuleDeclarationProto.MODULE_KIND;
var MODIFIER_KIND = declarations_1.ModifierDeclarationProto.MODIFIER_KIND;
var resolveModulePath_1 = __webpack_require__(14);
var ExportAssignmentResolver_1 = __webpack_require__(15);
var AstConverter = /** @class */ (function () {
function AstConverter(exportContext, typeChecker, declarationResolver, isLibNode) {
this.exportContext = exportContext;
this.typeChecker = typeChecker;
this.declarationResolver = declarationResolver;
this.isLibNode = isLibNode;
this.log = Logger_1.createLogger("AstConverter");
this.unsupportedDeclarations = new Set();
this.exportResolver = new ExportAssignmentResolver_1.ExportAssignmentResolver(this.typeChecker);
this.astFactory = new AstFactory_1.AstFactory();
this.astExpressionConverter = new AstExpressionConverter_1.AstExpressionConverter(this, this.astFactory);
}
AstConverter.prototype.getReferences = function (sourceFile) {
var e_1, _a, e_2, _b;
var _this = this;
var curDir = TsInternals_1.tsInternals.getDirectoryPath(sourceFile.fileName);
var visitedReferences = new Set();
var referencedFiles = new Array();
sourceFile.referencedFiles.forEach(function (referencedFile) {
if (!visitedReferences.has(referencedFile.fileName)) {
visitedReferences.add(referencedFile.fileName);
referencedFiles.push(_this.astFactory.createReferenceClause(referencedFile.fileName, ts.getNormalizedAbsolutePath(referencedFile.fileName, curDir)));
}
});
if (sourceFile.resolvedTypeReferenceDirectiveNames instanceof Map) {
try {
for (var _c = __values(sourceFile.resolvedTypeReferenceDirectiveNames), _d = _c.next(); !_d.done; _d = _c.next()) {
var _e = __read(_d.value, 2), _ = _e[0], referenceDirective = _e[1];
if (referenceDirective && referenceDirective.hasOwnProperty("resolvedFileName")) {
if (!visitedReferences.has(referenceDirective.resolvedFileName)) {
visitedReferences.add(referenceDirective.resolvedFileName);
referencedFiles.push(this.astFactory.createReferenceClause(_, TsInternals_1.tsInternals.normalizePath(referenceDirective.resolvedFileName)));
}
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
}
finally { if (e_1) throw e_1.error; }
}
}
try {
//TODO: Consider to place it to getImports
for (var _f = __values(sourceFile.imports), _g = _f.next(); !_g.done; _g = _f.next()) {
var importDeclaration = _g.value;
var modulePath = resolveModulePath_1.resolveModulePath(importDeclaration);
if (modulePath) {
if (!visitedReferences.has(modulePath)) {
visitedReferences.add(modulePath);
referencedFiles.push(this.astFactory.createReferenceClause("_", modulePath));
}
}
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
}
finally { if (e_2) throw e_2.error; }
}
return referencedFiles;
};
AstConverter.prototype.getImports = function (sourceFile) {
var _this = this;
var imports = [];
sourceFile.forEachChild(function (node) {
if (ts.isImportDeclaration(node)) {
if (node.importClause) {
var namedBindings = node.importClause.namedBindings;
if (namedBindings) {
var importClause = void 0;
if (ts.isNamespaceImport(namedBindings)) {
importClause = _this.astFactory.createNamespaceImportClause(namedBindings.name.getText());
}
else {
importClause = _this.astFactory.createNamedImportsClause(namedBindings.elements.map(function (importSpecifier) {
return _this.createImportSpecifier(importSpecifier);
}));
}
if (importClause) {
var referenceFile = resolveModulePath_1.resolveModulePath(node.moduleSpecifier);
if (referenceFile) {
importClause.setReferencedfile(referenceFile);
}
imports.push(importClause);
}
}
}
}
});
return imports;
};
AstConverter.prototype.createModuleFromSourceFile = function (sourceFile, filter) {
var packageNameFragments = sourceFile.fileName.split("/");
var sourceName = sourceFile.fileName;
var statements = filter ? sourceFile.statements.filter(filter) : sourceFile.statements;
return this.astFactory.createModuleDeclaration(this.isLibNode(sourceFile) ? AstFactory_1.AstFactory.TSLIBROOT : AstFactory_1.AstFactory.ROOT, this.getImports(sourceFile), this.getReferences(sourceFile), this.convertStatements(statements), this.convertModifiers(sourceFile.modifiers), uid_1.uid(), sourceName, [], sourceFile.isDeclarationFile ? MODULE_KIND.DECLARATION_FILE : MODULE_KIND.SOURCE_FILE);
};
AstConverter.prototype.createSourceFileDeclaration = function (sourceFile, filter) {
this.exportResolver.visit(sourceFile);
return this.astFactory.createSourceFileDeclaration(sourceFile.fileName, this.createModuleFromSourceFile(sourceFile, filter));
};
AstConverter.prototype.printDiagnostics = function () {
var _this = this;
this.log.debug("following declarations has been skipped: ");
this.unsupportedDeclarations.forEach(function (id) {
_this.log.debug("SKIPPED " + ts.SyntaxKind[id] + " (" + id + ")");
});
};
AstConverter.prototype.createModuleDeclarationAsTopLevel = function (packageName, imports, references, declarations, modifiers, uid, resourceName, definitions, kind) {
return this.astFactory.createModuleDeclarationAsTopLevel(this.astFactory.createModuleDeclaration(packageName, imports, references, declarations, modifiers, uid, resourceName, definitions, kind));
};
AstConverter.prototype.convertName = function (name) {
//TODO: this should be process at frontend
if (ts.isNumericLiteral(name)) {
return "`" + name.getText() + "`";
}
else if (ts.isStringLiteral(name)) {
var text = name.getText();
return text.substring(1, text.length - 1);
}
else if (ts.isIdentifier(name)) {
return name.getText();
}
return null;
};
AstConverter.prototype.convertPropertyDeclaration = function (nativePropertyDeclaration) {
var name = this.convertName(nativePropertyDeclaration.name);
if (name != null) {
return this.astFactory.declareProperty(name, nativePropertyDeclaration.initializer ?
this.astExpressionConverter.convertExpression(nativePropertyDeclaration.initializer) : null, this.convertType(nativePropertyDeclaration.type), [], false, this.convertModifiers(nativePropertyDeclaration.modifiers), nativePropertyDeclaration.type != undefined);
}
return null;
};
AstConverter.prototype.convertTypeParams = function (nativeTypeDeclarations) {
var _this = this;
var typeParameterDeclarations = [];
if (nativeTypeDeclarations) {
typeParameterDeclarations = nativeTypeDeclarations.map(function (typeParam) {
var constraint = typeParam.constraint;
var defaultValue = typeParam.default ? _this.convertType(typeParam.default) : null;
return _this.astFactory.createTypeParam(_this.astFactory.createIdentifierDeclarationAsNameEntity(typeParam.name.getText()), constraint ? [
_this.convertType(constraint)
] : [], defaultValue);
});
}
return typeParameterDeclarations;
};
AstConverter.prototype.convertTypeParamsToTokens = function (nativeTypeDeclarations) {
var _this = this;
var typeParameterDeclarations = [];
if (nativeTypeDeclarations) {
typeParameterDeclarations = nativeTypeDeclarations.map(function (typeParam) {
return _this.astFactory.createIdentifierDeclaration(typeParam.name.getText());
});
}
return typeParameterDeclarations;
};
AstConverter.prototype.getStatementsFromBlock = function (block) {
var e_3, _a;
var statements = [];
try {
for (var _b = __values(block.statements), _c = _b.next(); !_c.done; _c = _b.next()) {
var statement = _c.value;
statements.push.apply(statements, __spread(this.convertStatement(statement)));
}
}
catch (e_3_1) { e_3 = { error: e_3_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_3) throw e_3.error; }
}
return statements;
};
AstConverter.prototype.convertBlock = function (block) {
if (block) {
var statements = this.getStatementsFromBlock(block);
return this.astFactory.createBlockDeclaration(statements);
}
else {
return null;
}
};
AstConverter.prototype.convertBlockStatement = function (block) {
var statements = this.getStatementsFromBlock(block);
return this.astFactory.createBlockStatementDeclaration(statements);
};
AstConverter.prototype.convertFunctionDeclaration = function (functionDeclaration) {
var _this = this;
var typeParameterDeclarations = this.convertTypeParams(functionDeclaration.typeParameters);
var parameterDeclarations = functionDeclaration.parameters
.map(function (param, count) { return _this.convertParameterDeclaration(param, count); });
if (!functionDeclaration.name) {
return null;
}
if (ts.isIdentifier(functionDeclaration.name)) {
var uid_2 = this.exportContext.getUID(functionDeclaration);
var returnType = functionDeclaration.type ?
this.convertType(functionDeclaration.type) : this.createTypeDeclaration("Unit");
return this.astFactory.createFunctionDeclarationAsTopLevel(functionDeclaration.name.text, parameterDeclarations, returnType, typeParameterDeclarations, this.convertModifiers(functionDeclaration.modifiers, functionDeclaration), this.convertBlock(functionDeclaration.body), this.convertDefinitions(functionDeclaration), uid_2, functionDeclaration.asteriskToken);
}
return null;
};
AstConverter.prototype.convertModifiers = function (nativeModifiers, parent) {
var _this = this;
if (parent === void 0) { parent = undefined; }
var res = [];
if (parent) {
var resolveAssignment = this.exportResolver.resolveStatement(parent);
if (resolveAssignment) {
if (!resolveAssignment.isExportEquals) {
res.push(this.astFactory.createModifierDeclaration(MODIFIER_KIND.EXPORT), this.astFactory.createModifierDeclaration(MODIFIER_KIND.DEFAULT));
}
else {
this.astFactory.createModifierDeclaration(MODIFIER_KIND.SYNTH_EXPORT_ASSIGNMENT);
}
}
}
if (nativeModifiers) {
nativeModifiers.forEach(function (modifier) {
if (modifier.kind == ts.SyntaxKind.StaticKeyword) {
res.push(_this.astFactory.createModifierDeclaration(MODIFIER_KIND.STATIC));
}
else if (modifier.kind == ts.SyntaxKind.DeclareKeyword) {
res.push(_this.astFactory.createModifierDeclaration(MODIFIER_KIND.DECLARE));
}
else if (modifier.kind == ts.SyntaxKind.ExportKeyword) {
res.push(_this.astFactory.createModifierDeclaration(MODIFIER_KIND.EXPORT));
}
else if (modifier.kind == ts.SyntaxKind.DefaultKeyword) {
res.push(_this.astFactory.createModifierDeclaration(MODIFIER_KIND.DEFAULT));
}
});
}
return res;
};
AstConverter.prototype.convertMethodSignatureDeclaration = function (declaration) {
var _this = this;
var typeParameterDeclarations = this.convertTypeParams(declaration.typeParameters);
var parameterDeclarations = declaration.parameters
.map(function (param, count) { return _this.convertParameterDeclaration(param, count); });
if (ts.isIdentifier(declaration.name)) {
return this.astFactory.createMethodSignatureDeclaration(declaration.name ? declaration.name.getText() : "", parameterDeclarations, declaration.type ?
this.convertType(declaration.type) : this.createTypeDeclaration("Unit"), typeParameterDeclarations, !!declaration.questionToken, this.convertModifiers(declaration.modifiers));
}
return null;
};
AstConverter.prototype.convertMethodDeclaration = function (declaration) {
var _this = this;
var typeParameterDeclarations = this.convertTypeParams(declaration.typeParameters);
var parameterDeclarations = declaration.parameters
.map(function (param, count) { return _this.convertParameterDeclaration(param, count); });
if (ts.isIdentifier(declaration.name)) {
return this.createMethodDeclaration(declaration.name ? declaration.name.getText() : "", parameterDeclarations, declaration.type ?
this.convertType(declaration.type) : this.createTypeDeclaration("Unit"), typeParameterDeclarations, this.convertModifiers(declaration.modifiers), declaration.questionToken, declaration.asteriskToken, this.convertBlock(declaration.body));
}
return null;
};
AstConverter.prototype.createMethodDeclaration = function (name, parameters, type, typeParams, modifiers, optional, isGenerator, body) {
return this.astFactory.createMethodDeclaration(name, parameters, type, typeParams, modifiers, optional, isGenerator, body);
};
AstConverter.prototype.createTypeDeclaration = function (value, params) {
if (params === void 0) { params = []; }
return this.astFactory.createTypeReferenceDeclarationAsParamValue(this.astFactory.createIdentifierDeclarationAsNameEntity(value), params, null);
};
AstConverter.prototype.createParameterDeclaration = function (name, type, initializer, vararg, optional, explicitlyDeclaredType) {
return this.astFactory.createParameterDeclaration(name, type, initializer, vararg, optional, explicitlyDeclaredType);
};
AstConverter.prototype.createProperty = function (value, initializer, type, typeParams, optional, explicitlyDeclaredType) {
if (typeParams === void 0) { typeParams = []; }
return this.astFactory.declareProperty(value, initializer, type, typeParams, optional, [], explicitlyDeclaredType);
};
AstConverter.prototype.createIntersectionType = function (params) {
return this.astFactory.createIntersectionTypeDeclaration(params);
};
AstConverter.prototype.convertEntityName = function (entityName) {
if (ts.isQualifiedName(entityName)) {
return this.astFactory.createQualifiedNameEntity(this.convertEntityName(entityName.left), this.convertEntityName(entityName.right).getIdentifier());
}
return this.astFactory.createIdentifierDeclarationAsNameEntity(entityName.getText());
};
AstConverter.prototype.convertTypeArguments = function (typeArguments) {
var _this = this;
if (typeArguments == undefined) {
return [];
}
else {
return typeArguments
.map(function (argumentType) {
return _this.convertType(argumentType);
});
}
};
AstConverter.prototype.createImportSpecifier = function (importSpecifier) {
return this.astFactory.createImportSpecifier(importSpecifier.name, importSpecifier.propertyName, this.createUid(importSpecifier.name));
};
AstConverter.prototype.createUid = function (identifier) {
var declarations = ExportContext_1.resolveDeclarations(identifier, this.typeChecker);
if (declarations[0]) {
return this.exportContext.getUID(declarations[0]);
}
return null;
};
AstConverter.prototype.createTypeReferenceFromSymbol = function (declaration) {
if (declaration == null) {
return null;
}
var kind = declarations_1.ReferenceDeclarationProto.KIND.IRRELEVANT_KIND;
if (ts.isClassDeclaration(declaration)) {
kind = declarations_1.ReferenceDeclarationProto.KIND.CLASS;
}
else if (ts.isInterfaceDeclaration(declaration)) {
kind = declarations_1.ReferenceDeclarationProto.KIND.INTERFACE;
}
var typeReference = null;
if (ts.isImportSpecifier(declaration)) {
var uid_3 = this.createUid(declaration.name);
if (uid_3) {
var origin = declaration.propertyName ? declarations_1.ReferenceDeclarationProto.ORIGIN.NAMED_IMPORT : declarations_1.ReferenceDeclarationProto.ORIGIN.IMPORT;
typeReference = this.astFactory.createReferenceEntity(uid_3, origin, kind);
}
}
else if (ts.isImportEqualsDeclaration(declaration)) {
var importedSymbol = this.typeChecker.getSymbolAtLocation(declaration.name);
if (importedSymbol) {
var declaredTyped = this.typeChecker.getDeclaredTypeOfSymbol(importedSymbol);
if (declaredTyped.symbol && Array.isArray(declaredTyped.symbol.declarations)) {
typeReference = this.astFactory.createReferenceEntity(this.exportContext.getUID(declaredTyped.symbol.declarations[0]), declarations_1.ReferenceDeclarationProto.ORIGIN.IRRELEVANT, kind);
}
}
}
else {
typeReference = this.astFactory.createReferenceEntity(this.exportContext.getUID(declaration), declarations_1.ReferenceDeclarationProto.ORIGIN.IRRELEVANT, kind);
}
return typeReference;
};
AstConverter.prototype.convertType = function (type) {
var _this = this;
if (type == undefined) {
return this.createTypeDeclaration("Any");
}
else {
if (type.kind == ts.SyntaxKind.VoidKeyword) {
return this.createTypeDeclaration("Unit");
}
else if (ts.isArrayTypeNode(type)) {
return this.astFactory.createTypeReferenceDeclarationAsParamValue(this.astFactory.createIdentifierDeclarationAsNameEntity("Array"), [this.convertType(type.elementType)], this.createTypeReferenceFromSymbol(type));
}
else if (ts.isUnionTypeNode(type)) {
var params = type.types
.map(function (argumentType) { return _this.convertType(argumentType); });
return this.astFactory.createUnionTypeDeclaration(params);
}
else if (ts.isIntersectionTypeNode(type)) {
var params = type.types
.map(function (argumentType) { return _this.convertType(argumentType); });
return this.createIntersectionType(params);
}
else if (ts.isTypeReferenceNode(type)) {
var params = this.convertTypeArguments(type.typeArguments);
var entity = this.convertEntityName(type.typeName);
var symbol = this.typeChecker.getSymbolAtLocation(type.typeName);
var typeReference = null;
var declaration = this.getFirstDeclaration(symbol);
if (declaration) {
if (ts.isTypeParameterDeclaration(declaration)) {
return this.astFactory.createTypeParamReferenceDeclarationAsParamValue(entity);
}
typeReference = this.createTypeReferenceFromSymbol(declaration);
}
return this.astFactory.createTypeReferenceDeclarationAsParamValue(entity, params, typeReference);
}
else if (type.kind == ts.SyntaxKind.ParenthesizedType) {
return this.convertType(type.type);
}
else if (type.kind == ts.SyntaxKind.NullKeyword) {
return this.createTypeDeclaration("null");
}
else if (type.kind == ts.SyntaxKind.UndefinedKeyword) {
return this.createTypeDeclaration("undefined");
}
else if (type.kind == ts.SyntaxKind.StringKeyword) {
return this.createTypeDeclaration("string");
}
else if (type.kind == ts.SyntaxKind.BooleanKeyword) {
return this.createTypeDeclaration("boolean");
}
else if (type.kind == ts.SyntaxKind.NumberKeyword) {
return this.createTypeDeclaration("number");
}
else if (type.kind == ts.SyntaxKind.AnyKeyword) {
return this.createTypeDeclaration("any");
}
else if (type.kind == ts.SyntaxKind.FunctionType) {
var parameterDeclarations = type.parameters.map(function (param, count) { return _this.convertParameterDeclaration(param, count); });
return this.astFactory.createFunctionTypeDeclaration(parameterDeclarations, this.convertType(type.type));
}
else if (ts.isTypeLiteralNode(type)) {
return this.convertTypeLiteralToObjectLiteralDeclaration(type);
}
else if (ts.isThisTypeNode(type)) {
return this.astFactory.createThisTypeDeclaration();
}
else if (ts.isLiteralTypeNode(type)) {
// TODO: we need to pass information on literal futher and convert it in some lowering
var literal = type.literal;
if ((literal.kind == ts.SyntaxKind.TrueKeyword) || (literal.kind == ts.SyntaxKind.FalseKeyword)) {
return this.createTypeDeclaration("boolean");
}
else if (literal.kind == ts.SyntaxKind.FirstLiteralToken) {
return this.astFactory.createNumericLiteralDeclaration(literal.getText());
}
else if (ts.isStringLiteral(literal)) {
return this.astFactory.createStringLiteralDeclaration(literal.text);
}
else {
return this.astFactory.createStringLiteralDeclaration(literal.getText());
}
}
else if (ts.isTupleTypeNode(type)) {
return this.astFactory.createTupleDeclaration(type.elementTypes.map(function (elementType) { return _this.convertType(elementType); }));
}
else if (ts.isTypePredicateNode(type)) {
return this.createTypeDeclaration("boolean");
}
else if (type.kind == ts.SyntaxKind.ObjectKeyword) {
return this.createTypeDeclaration("object");
}
else if (ts.isTypeOperatorNode(type)) {
switch (type.operator) {
case ts.SyntaxKind.KeyOfKeyword:
return this.astFactory.createKeyOfTypeDeclaration(this.convertType(type.type));
case ts.SyntaxKind.ReadonlyKeyword:
return this.convertType(type.type);
default:
return this.convertType(type.type);
}
}
else if (ts.isIndexedAccessTypeNode(type)) {
return this.astFactory.createIndexTypeDeclaration(this.convertType(type.objectType), this.convertType(type.indexType));
}
else {
// TODO: use raiseConcern for this
this.unsupportedDeclarations.add(type.kind);
return this.createTypeDeclaration("any");
}
}
};
AstConverter.prototype.convertParameterDeclarations = function (parameters) {
var _this = this;
return parameters.map(function (parameter, count) { return _this.convertParameterDeclaration(parameter, count); });
};
AstConverter.prototype.convertParameterDeclaration = function (param, index) {
var initializer = null;
if (param.initializer != null) {
initializer = this.astExpressionConverter.convertExpression(param.initializer);
}
var paramType = this.convertType(param.type);
var name = ts.isIdentifier(param.name) ? param.name.getText() : "__" + index;
return this.createParameterDeclaration(name, paramType, initializer, !!param.dotDotDotToken, !!param.questionToken, param.type != undefined);
};
AstConverter.prototype.convertPropertySignature = function (node) {
var name = this.convertName(node.name);
if (name !== null) {
return this.createProperty(name, node.initializer ?
this.astExpressionConverter.convertExpression(node.initializer) : null, this.convertType(node.type), [], !!node.questionToken, node.type != undefined);
}
return null;
};
AstConverter.prototype.convertIndexSignature = function (indexSignatureDeclaration) {
var _this = this;
var parameterDeclarations = indexSignatureDeclaration.parameters
.map(function (param, count) { return _this.convertParameterDeclaration(param, count); });
return this.astFactory.createIndexSignatureDeclaration(parameterDeclarations, this.convertType(indexSignatureDeclaration.type));
};
AstConverter.prototype.convertTypeElementToInterfaceMemberDeclarations = function (member) {
if (ts.isMethodSignature(member)) {
var methodDeclaration = this.convertMethodSignatureDeclaration(member);
if (methodDeclaration) {
return methodDeclaration;
}
}
else if (ts.isPropertySignature(member)) {
var propertySignatureDeclaration = this.convertPropertySignature(member);
if (propertySignatureDeclaration !== null) {
return propertySignatureDeclaration;
}
}
else if (ts.isIndexSignatureDeclaration(member)) {
return this.convertIndexSignature(member);
}
else if (ts.isCallSignatureDeclaration(member)) {
return this.astFactory.createCallSignatureDeclaration(this.convertParameterDeclarations(member.parameters), member.type ? this.convertType(member.type) : this.createTypeDeclaration("Unit"), this.convertTypeParams(member.typeParameters));
}
return null;
};
AstConverter.prototype.convertMembersToInterfaceMemberDeclarations = function (members) {
var e_4, _a;
var res = [];
try {
for (var members_1 = __values(members), members_1_1 = members_1.next(); !members_1_1.done; members_1_1 = members_1.next()) {
var member = members_1_1.value;
var memberDeclaration = this.convertTypeElementToInterfaceMemberDeclarations(member);
if (memberDeclaration) {
res.push(memberDeclaration);
}
}
}
catch (e_4_1) { e_4 = { error: e_4_1 }; }
finally {
try {
if (members_1_1 && !members_1_1.done && (_a = members_1.return)) _a.call(members_1);
}
finally { if (e_4) throw e_4.error; }
}
return res;
};
AstConverter.prototype.convertClassElementsToMembers = function (classDeclarationMembers) {
var e_5, _a;
if (classDeclarationMembers == null) {
return [];
}
var members = [];
try {
for (var classDeclarationMembers_1 = __values(classDeclarationMembers), classDeclarationMembers_1_1 = classDeclarationMembers_1.next(); !classDeclarationMembers_1_1.done; classDeclarationMembers_1_1 = classDeclarationMembers_1.next()) {
var memberDeclaration = classDeclarationMembers_1_1.value;
if (ts.isIndexSignatureDeclaration(memberDeclaration)) {
members.push(this.convertIndexSignature(memberDeclaration));
}
else if (ts.isPropertyDeclaration(memberDeclaration)) {
var propertyDeclaration = this.convertPropertyDeclaration(memberDeclaration);
if (propertyDeclaration != null) {
members.push(propertyDeclaration);
}
}
else if (ts.isMethodDeclaration(memberDeclaration)) {
var convertedMethodDeclaration = this.convertMethodDeclaration(memberDeclaration);
if (convertedMethodDeclaration != null) {
members.push(convertedMethodDeclaration);
}
}
else if (memberDeclaration.kind == ts.SyntaxKind.Constructor) {
members.push.apply(members, __spread(this.convertConstructorDeclaration(memberDeclaration)));
}
}
}
catch (e_5_1) { e_5 = { error: e_5_1 }; }
finally {
try {
if (classDeclarationMembers_1_1 && !classDeclarationMembers_1_1.done && (_a = classDeclarationMembers_1.return)) _a.call(classDeclarationMembers_1);
}
finally { if (e_5) throw e_5.error; }
}
return members;
};
AstConverter.prototype.convertTypeAliasWithTypeLiteralToInterfaceDeclaration = function (statement) {
var uid = this.exportContext.getUID(statement);
return this.astFactory.createInterfaceDeclaration(this.astFactory.createIdentifierDeclarationAsNameEntity(statement.name.getText()), this.convertMembersToInterfaceMemberDeclarations(statement.type.members), this.convertTypeParams(statement.typeParameters), [], [], [this.astFactory.createDefinitionInfoDeclaration(uid, statement.getSourceFile().fileName)], uid);
};
AstConverter.prototype.convertTypeLiteralToObjectLiteralDeclaration = function (typeLiteral) {
return this.astFactory.createObjectLiteral(this.convertMembersToInterfaceMemberDeclarations(typeLiteral.members), this.exportContext.getUID(typeLiteral));
};
AstConverter.prototype.convertConstructorDeclaration = function (constructorDeclaration) {
var _this = this;
var params = [];
var res = [];
constructorDeclaration.parameters.forEach(function (parameter, count) {
if (parameter.modifiers) {
var isField = parameter.modifiers.some(function (modifier) { return modifier.kind == ts.SyntaxKind.PublicKeyword; });
if (isField) {
var convertedVariable = _this.convertPropertyDeclaration(parameter);
if (convertedVariable != null) {
res.push(convertedVariable);
}
}
}
params.push(_this.convertParameterDeclaration(parameter, count));
});
res.push(this.astFactory.createConstructorDeclaration(params, this.convertTypeParams(constructorDeclaration.typeParameters), this.convertModifiers(constructorDeclaration.modifiers), this.convertBlock(constructorDeclaration.body)));
return res;
};
AstConverter.prototype.convertTypeAliasDeclaration = function (declaration) {
return this.astFactory.createTypeAliasDeclaration(this.convertEntityName(declaration.name), this.convertTypeParams(declaration.typeParameters), this.convertType(declaration.type), this.exportContext.getUID(declaration));
};
AstConverter.prototype.convertPropertyAccessExpression = function (propertyAccessExpression) {
var convertedExpression;
var name = this.astFactory.createIdentifierDeclaration(propertyAccessExpression.name.text);
if (ts.isIdentifier(propertyAccess