diff --git a/.gitignore b/.gitignore index 0badfe0cf61..4fff675801f 100644 --- a/.gitignore +++ b/.gitignore @@ -9,12 +9,14 @@ test-args.txt \#*\# .\#* tests/baselines/local/* +tests/baselines/local.old/* tests/services/baselines/local/* tests/baselines/prototyping/local/* tests/baselines/rwc/* tests/baselines/test262/* tests/baselines/reference/projectOutput/* tests/baselines/local/projectOutput/* +tests/baselines/reference/testresults.tap tests/services/baselines/prototyping/local/* tests/services/browser/typescriptServices.js scripts/authors.js @@ -52,3 +54,4 @@ internal/ !tests/cases/projects/projectOption/**/node_modules !tests/cases/projects/NodeModulesSearch/**/* !tests/baselines/reference/project/nodeModules*/**/* +.idea diff --git a/.travis.yml b/.travis.yml index bfc07e2b510..efbd00d5034 100644 --- a/.travis.yml +++ b/.travis.yml @@ -23,7 +23,7 @@ matrix: branches: only: - master - - transforms + - release-2.0 install: - npm uninstall typescript diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5cde901a576..1c242022979 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -40,10 +40,6 @@ In general, things we find useful when reviewing suggestions are: # Instructions for Contributing Code -## Code of Conduct - -This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. - ## Contributing bug fixes TypeScript is currently accepting contributions in the form of bug fixes. A bug must have an issue tracking it in the issue tracker that has been approved ("Milestone == Community") by the TypeScript team. Your pull request should include a link to the bug that you are fixing. If you've submitted a PR for a bug, please post a comment in the bug to avoid duplication of effort. diff --git a/Gulpfile.ts b/Gulpfile.ts index 28a465c47d4..72766de0857 100644 --- a/Gulpfile.ts +++ b/Gulpfile.ts @@ -39,9 +39,11 @@ const gulp = helpMaker(originalGulp); const mochaParallel = require("./scripts/mocha-parallel.js"); const {runTestsInParallel} = mochaParallel; +Error.stackTraceLimit = 1000; + const cmdLineOptions = minimist(process.argv.slice(2), { boolean: ["debug", "light", "colors", "lint", "soft"], - string: ["browser", "tests", "host", "reporter"], + string: ["browser", "tests", "host", "reporter", "stackTraceLimit"], alias: { d: "debug", t: "tests", @@ -584,6 +586,7 @@ function runConsoleTests(defaultReporter: string, runInParallel: boolean, done: const debug = cmdLineOptions["debug"]; const tests = cmdLineOptions["tests"]; const light = cmdLineOptions["light"]; + const stackTraceLimit = cmdLineOptions["stackTraceLimit"]; const testConfigFile = "test.config"; if (fs.existsSync(testConfigFile)) { fs.unlinkSync(testConfigFile); @@ -603,7 +606,7 @@ function runConsoleTests(defaultReporter: string, runInParallel: boolean, done: } if (tests || light || taskConfigsFolder) { - writeTestConfigFile(tests, light, taskConfigsFolder, workerCount); + writeTestConfigFile(tests, light, taskConfigsFolder, workerCount, stackTraceLimit); } if (tests && tests.toLocaleLowerCase() === "rwc") { @@ -752,6 +755,7 @@ gulp.task("browserify", "Runs browserify on run.js to produce a file suitable fo sourcemaps: { "built/local/_stream_0.js": originalMap, "built/local/bundle.js": maps, + "node_modules/source-map-support/source-map-support.js": undefined, } }); const finalMap = chain.apply(); @@ -781,8 +785,8 @@ function cleanTestDirs(done: (e?: any) => void) { } // used to pass data from jake command line directly to run.js -function writeTestConfigFile(tests: string, light: boolean, taskConfigsFolder?: string, workerCount?: number) { - const testConfigContents = JSON.stringify({ test: tests ? [tests] : undefined, light: light, workerCount: workerCount, taskConfigsFolder: taskConfigsFolder }); +function writeTestConfigFile(tests: string, light: boolean, taskConfigsFolder?: string, workerCount?: number, stackTraceLimit?: string) { + const testConfigContents = JSON.stringify({ test: tests ? [tests] : undefined, light, workerCount, stackTraceLimit, taskConfigsFolder }); console.log("Running tests with config: " + testConfigContents); fs.writeFileSync("test.config", testConfigContents); } @@ -912,7 +916,7 @@ gulp.task(loggedIOJsPath, false, [], (done) => { const temp = path.join(builtLocalDirectory, "temp"); mkdirP(temp, (err) => { if (err) { console.error(err); done(err); process.exit(1); }; - exec(host, [LKGCompiler, "--outdir", temp, loggedIOpath], () => { + exec(host, [LKGCompiler, "--types --outdir", temp, loggedIOpath], () => { fs.renameSync(path.join(temp, "/harness/loggedIO.js"), loggedIOJsPath); del(temp).then(() => done(), done); }, done); @@ -933,8 +937,8 @@ gulp.task(instrumenterJsPath, false, [servicesFile], () => { .pipe(gulp.dest(".")); }); -gulp.task("tsc-instrumented", "Builds an instrumented tsc.js", [loggedIOJsPath, instrumenterJsPath, servicesFile], (done) => { - exec(host, [instrumenterJsPath, "record", "iocapture", builtLocalDirectory, compilerFilename], done, done); +gulp.task("tsc-instrumented", "Builds an instrumented tsc.js", ["local", loggedIOJsPath, instrumenterJsPath, servicesFile], (done) => { + exec(host, [instrumenterJsPath, "record", "iocapture", builtLocalCompiler], done, done); }); gulp.task("update-sublime", "Updates the sublime plugin's tsserver", ["local", serverFile], () => { diff --git a/Jakefile.js b/Jakefile.js index 94358ab5429..64a8553ef39 100644 --- a/Jakefile.js +++ b/Jakefile.js @@ -66,7 +66,20 @@ var compilerSources = [ "utilities.ts", "binder.ts", "checker.ts", + "factory.ts", + "visitor.ts", + "transformers/destructuring.ts", + "transformers/ts.ts", + "transformers/module/es6.ts", + "transformers/module/system.ts", + "transformers/module/module.ts", + "transformers/jsx.ts", + "transformers/es7.ts", + "transformers/generators.ts", + "transformers/es6.ts", + "transformer.ts", "sourcemap.ts", + "comments.ts", "declarationEmitter.ts", "emitter.ts", "program.ts", @@ -87,7 +100,20 @@ var servicesSources = [ "utilities.ts", "binder.ts", "checker.ts", + "factory.ts", + "visitor.ts", + "transformers/destructuring.ts", + "transformers/ts.ts", + "transformers/module/es6.ts", + "transformers/module/system.ts", + "transformers/module/module.ts", + "transformers/jsx.ts", + "transformers/es7.ts", + "transformers/generators.ts", + "transformers/es6.ts", + "transformer.ts", "sourcemap.ts", + "comments.ts", "declarationEmitter.ts", "emitter.ts", "program.ts", @@ -96,15 +122,29 @@ var servicesSources = [ ].map(function (f) { return path.join(compilerDirectory, f); }).concat([ + "types.ts", + "utilities.ts", "breakpoints.ts", + "classifier.ts", + "completions.ts", + "documentHighlights.ts", + "documentRegistry.ts", + "findAllReferences.ts", + "goToDefinition.ts", + "goToImplementation.ts", + "jsDoc.ts", + "jsTyping.ts", "navigateTo.ts", "navigationBar.ts", "outliningElementsCollector.ts", "patternMatcher.ts", + "preProcess.ts", + "rename.ts", "services.ts", "shims.ts", "signatureHelp.ts", - "utilities.ts", + "symbolDisplay.ts", + "transpile.ts", "formatting/formatting.ts", "formatting/formattingContext.ts", "formatting/formattingRequestKind.ts", @@ -207,6 +247,7 @@ var harnessSources = harnessCoreSources.concat([ "moduleResolution.ts", "tsconfigParsing.ts", "commandLineParsing.ts", + "configurationExtension.ts", "convertCompilerOptionsFromJson.ts", "convertTypingOptionsFromJson.ts", "tsserverProjectSystem.ts", @@ -346,7 +387,10 @@ var builtLocalCompiler = path.join(builtLocalDirectory, compilerFilename); * @param callback: a function to execute after the compilation process ends */ function compileFile(outFile, sources, prereqs, prefixes, useBuiltCompiler, opts, callback) { - file(outFile, prereqs, function () { + file(outFile, prereqs, function() { + if (process.env.USE_TRANSFORMS === "false") { + useBuiltCompiler = false; + } var startCompileTime = mark(); opts = opts || {}; var compilerPath = useBuiltCompiler ? builtLocalCompiler : LKGCompiler; @@ -790,8 +834,14 @@ function cleanTestDirs() { } // used to pass data from jake command line directly to run.js -function writeTestConfigFile(tests, light, taskConfigsFolder, workerCount) { - var testConfigContents = JSON.stringify({ test: tests ? [tests] : undefined, light: light, workerCount: workerCount, taskConfigsFolder: taskConfigsFolder }); +function writeTestConfigFile(tests, light, taskConfigsFolder, workerCount, stackTraceLimit) { + var testConfigContents = JSON.stringify({ + test: tests ? [tests] : undefined, + light: light, + workerCount: workerCount, + taskConfigsFolder: taskConfigsFolder, + stackTraceLimit: stackTraceLimit + }); fs.writeFileSync('test.config', testConfigContents); } @@ -802,10 +852,15 @@ function deleteTemporaryProjectOutput() { } function runConsoleTests(defaultReporter, runInParallel) { - cleanTestDirs(); + var dirty = process.env.dirty; + if (!dirty) { + cleanTestDirs(); + } + var debug = process.env.debug || process.env.d; tests = process.env.test || process.env.tests || process.env.t; var light = process.env.light || false; + var stackTraceLimit = process.env.stackTraceLimit; var testConfigFile = 'test.config'; if (fs.existsSync(testConfigFile)) { fs.unlinkSync(testConfigFile); @@ -825,7 +880,7 @@ function runConsoleTests(defaultReporter, runInParallel) { } if (tests || light || taskConfigsFolder) { - writeTestConfigFile(tests, light, taskConfigsFolder, workerCount); + writeTestConfigFile(tests, light, taskConfigsFolder, workerCount, stackTraceLimit); } if (tests && tests.toLocaleLowerCase() === "rwc") { @@ -894,7 +949,7 @@ function runConsoleTests(defaultReporter, runInParallel) { } } function runLinter() { - if (!lintFlag) { + if (!lintFlag || dirty) { return; } var lint = jake.Task['lint']; @@ -911,8 +966,8 @@ task("runtests-parallel", ["build-rules", "tests", builtLocalDirectory], functio runConsoleTests('min', /*runInParallel*/ true); }, { async: true }); -desc("Runs the tests using the built run.js file. Optional arguments are: t[ests]=regex r[eporter]=[list|spec|json|] d[ebug]=true color[s]=false lint=true bail=false."); -task("runtests", ["build-rules", "tests", builtLocalDirectory], function () { +desc("Runs the tests using the built run.js file. Optional arguments are: t[ests]=regex r[eporter]=[list|spec|json|] d[ebug]=true color[s]=false lint=true bail=false dirty=false."); +task("runtests", ["build-rules", "tests", builtLocalDirectory], function() { runConsoleTests('mocha-fivemat-progress-reporter', /*runInParallel*/ false); }, { async: true }); @@ -929,8 +984,8 @@ var nodeServerInFile = "tests/webTestServer.ts"; compileFile(nodeServerOutFile, [nodeServerInFile], [builtLocalDirectory, tscFile], [], /*useBuiltCompiler:*/ true, { noOutFile: true }); desc("Runs browserify on run.js to produce a file suitable for running tests in the browser"); -task("browserify", ["tests", builtLocalDirectory, nodeServerOutFile], function () { - var cmd = 'browserify built/local/run.js -d -o built/local/bundle.js'; +task("browserify", ["tests", builtLocalDirectory, nodeServerOutFile], function() { + var cmd = 'browserify built/local/run.js -t ./scripts/browserify-optional -d -o built/local/bundle.js'; exec(cmd); }, { async: true }); @@ -996,15 +1051,18 @@ function acceptBaseline(containerFolder) { var deleteEnding = '.delete'; for (var i in files) { var filename = files[i]; - if (filename.substr(filename.length - deleteEnding.length) === deleteEnding) { - filename = filename.substr(0, filename.length - deleteEnding.length); - fs.unlinkSync(path.join(targetFolder, filename)); - } else { - var target = path.join(targetFolder, filename); - if (fs.existsSync(target)) { - fs.unlinkSync(target); + var fullLocalPath = path.join(sourceFolder, filename); + if (fs.statSync(fullLocalPath).isFile()) { + if (filename.substr(filename.length - deleteEnding.length) === deleteEnding) { + filename = filename.substr(0, filename.length - deleteEnding.length); + fs.unlinkSync(path.join(targetFolder, filename)); + } else { + var target = path.join(targetFolder, filename); + if (fs.existsSync(target)) { + fs.unlinkSync(target); + } + fs.renameSync(path.join(sourceFolder, filename), target); } - fs.renameSync(path.join(sourceFolder, filename), target); } } } @@ -1043,7 +1101,7 @@ var loggedIOJsPath = builtLocalDirectory + 'loggedIO.js'; file(loggedIOJsPath, [builtLocalDirectory, loggedIOpath], function () { var temp = builtLocalDirectory + 'temp'; jake.mkdirP(temp); - var options = "--outdir " + temp + ' ' + loggedIOpath; + var options = "--types --outdir " + temp + ' ' + loggedIOpath; var cmd = host + " " + LKGDirectory + compilerFilename + " " + options + " "; console.log(cmd + "\n"); var ex = jake.createExec([cmd]); diff --git a/README.md b/README.md index d16bc363b26..2f631439eb0 100644 --- a/README.md +++ b/README.md @@ -30,8 +30,12 @@ There are many ways to [contribute](https://github.com/Microsoft/TypeScript/blob * Engage with other TypeScript users and developers on [StackOverflow](http://stackoverflow.com/questions/tagged/typescript). * Join the [#typescript](http://twitter.com/#!/search/realtime/%23typescript) discussion on Twitter. * [Contribute bug fixes](https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md). -* Read the language specification ([docx](https://github.com/Microsoft/TypeScript/blob/master/doc/TypeScript%20Language%20Specification.docx?raw=true), [pdf](https://github.com/Microsoft/TypeScript/blob/master/doc/TypeScript%20Language%20Specification.pdf?raw=true), [md](https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md)). +* Read the language specification ([docx](https://github.com/Microsoft/TypeScript/blob/master/doc/TypeScript%20Language%20Specification.docx?raw=true), + [pdf](https://github.com/Microsoft/TypeScript/blob/master/doc/TypeScript%20Language%20Specification.pdf?raw=true), [md](https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md)). +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see +the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) +with any additional questions or comments. ## Documentation @@ -91,4 +95,4 @@ node built/local/tsc.js hello.ts ## Roadmap -For details on our planned features and future direction please refer to our [roadmap](https://github.com/Microsoft/TypeScript/wiki/Roadmap). +For details on our planned features and future direction please refer to our [roadmap](https://github.com/Microsoft/TypeScript/wiki/Roadmap). \ No newline at end of file diff --git a/lib/lib.es2015.collection.d.ts b/lib/lib.es2015.collection.d.ts index 0b23972def0..452ce388c9e 100644 --- a/lib/lib.es2015.collection.d.ts +++ b/lib/lib.es2015.collection.d.ts @@ -20,7 +20,7 @@ interface Map { forEach(callbackfn: (value: V, index: K, map: Map) => void, thisArg?: any): void; get(key: K): V | undefined; has(key: K): boolean; - set(key: K, value?: V): this; + set(key: K, value: V): this; readonly size: number; } @@ -35,7 +35,7 @@ interface WeakMap { delete(key: K): boolean; get(key: K): V | undefined; has(key: K): boolean; - set(key: K, value?: V): this; + set(key: K, value: V): this; } interface WeakMapConstructor { diff --git a/lib/lib.es2015.proxy.d.ts b/lib/lib.es2015.proxy.d.ts index 3908e97c17c..fa7527ef1c4 100644 --- a/lib/lib.es2015.proxy.d.ts +++ b/lib/lib.es2015.proxy.d.ts @@ -19,7 +19,7 @@ interface ProxyHandler { setPrototypeOf? (target: T, v: any): boolean; isExtensible? (target: T): boolean; preventExtensions? (target: T): boolean; - getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor; + getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor | undefined; has? (target: T, p: PropertyKey): boolean; get? (target: T, p: PropertyKey, receiver: any): any; set? (target: T, p: PropertyKey, value: any, receiver: any): boolean; @@ -35,4 +35,4 @@ interface ProxyConstructor { revocable(target: T, handler: ProxyHandler): { proxy: T; revoke: () => void; }; new (target: T, handler: ProxyHandler): T } -declare var Proxy: ProxyConstructor; \ No newline at end of file +declare var Proxy: ProxyConstructor; diff --git a/lib/tsc.js b/lib/tsc.js index a36f37178c4..0e3d7285ac3 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -64,87 +64,14 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); }; -})(ts || (ts = {})); -var ts; -(function (ts) { - var performance; - (function (performance) { - var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true - ? onProfilerEvent - : function (markName) { }; - var enabled = false; - var profilerStart = 0; - var counts; - var marks; - var measures; - function mark(markName) { - if (enabled) { - marks[markName] = ts.timestamp(); - counts[markName] = (counts[markName] || 0) + 1; - profilerEvent(markName); - } - } - performance.mark = mark; - function measure(measureName, startMarkName, endMarkName) { - if (enabled) { - var end = endMarkName && marks[endMarkName] || ts.timestamp(); - var start = startMarkName && marks[startMarkName] || profilerStart; - measures[measureName] = (measures[measureName] || 0) + (end - start); - } - } - performance.measure = measure; - function getCount(markName) { - return counts && counts[markName] || 0; - } - performance.getCount = getCount; - function getDuration(measureName) { - return measures && measures[measureName] || 0; - } - performance.getDuration = getDuration; - function forEachMeasure(cb) { - for (var key in measures) { - cb(key, measures[key]); - } - } - performance.forEachMeasure = forEachMeasure; - function enable() { - counts = ts.createMap(); - marks = ts.createMap(); - measures = ts.createMap(); - enabled = true; - profilerStart = ts.timestamp(); - } - performance.enable = enable; - function disable() { - enabled = false; - } - performance.disable = disable; - })(performance = ts.performance || (ts.performance = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - var createObject = Object.create; - function createMap(template) { - var map = createObject(null); - map["__"] = undefined; - delete map["__"]; - for (var key in template) - if (hasOwnProperty.call(template, key)) { - map[key] = template[key]; - } - return map; - } - ts.createMap = createMap; function createFileMap(keyMapper) { - var files = createMap(); + var files = {}; return { get: get, set: set, contains: contains, remove: remove, forEachValue: forEachValueInMap, - getKeys: getKeys, clear: clear }; function forEachValueInMap(f) { @@ -152,13 +79,6 @@ var ts; f(key, files[key]); } } - function getKeys() { - var keys = []; - for (var key in files) { - keys.push(key); - } - return keys; - } function get(path) { return files[toKey(path)]; } @@ -166,14 +86,14 @@ var ts; files[toKey(path)] = value; } function contains(path) { - return toKey(path) in files; + return hasProperty(files, toKey(path)); } function remove(path) { var key = toKey(path); delete files[key]; } function clear() { - files = createMap(); + files = {}; } function toKey(path) { return keyMapper ? keyMapper(path) : path; @@ -199,31 +119,11 @@ var ts; return undefined; } ts.forEach = forEach; - function find(array, predicate) { - for (var i = 0, len = array.length; i < len; i++) { - var value = array[i]; - if (predicate(value, i)) { - return value; - } - } - return undefined; - } - ts.find = find; - function findMap(array, callback) { - for (var i = 0, len = array.length; i < len; i++) { - var result = callback(array[i], i); - if (result) { - return result; - } - } - Debug.fail(); - } - ts.findMap = findMap; - function contains(array, value) { + function contains(array, value, areEqual) { if (array) { for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { var v = array_1[_i]; - if (v === value) { + if (areEqual ? areEqual(v, value) : v === value) { return true; } } @@ -265,43 +165,19 @@ var ts; } ts.countWhere = countWhere; function filter(array, f) { + var result; if (array) { - var len = array.length; - var i = 0; - while (i < len && f(array[i])) - i++; - if (i < len) { - var result = array.slice(0, i); - i++; - while (i < len) { - var item = array[i]; - if (f(item)) { - result.push(item); - } - i++; + result = []; + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var item = array_3[_i]; + if (f(item)) { + result.push(item); } - return result; } } - return array; + return result; } ts.filter = filter; - function removeWhere(array, f) { - var outIndex = 0; - for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { - var item = array_3[_i]; - if (!f(item)) { - array[outIndex] = item; - outIndex++; - } - } - if (outIndex !== array.length) { - array.length = outIndex; - return true; - } - return false; - } - ts.removeWhere = removeWhere; function filterMutate(array, f) { var outIndex = 0; for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { @@ -338,15 +214,11 @@ var ts; var result; if (array) { result = []; - loop: for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { var item = array_6[_i]; - for (var _a = 0, result_1 = result; _a < result_1.length; _a++) { - var res = result_1[_a]; - if (areEqual ? areEqual(res, item) : res === item) { - continue loop; - } + if (!contains(result, item, areEqual)) { + result.push(item); } - result.push(item); } } return result; @@ -387,22 +259,16 @@ var ts; return array[array.length - 1]; } ts.lastOrUndefined = lastOrUndefined; - function binarySearch(array, value, comparer) { - if (!array || array.length === 0) { - return -1; - } + function binarySearch(array, value) { var low = 0; var high = array.length - 1; - comparer = comparer !== undefined - ? comparer - : function (v1, v2) { return (v1 < v2 ? -1 : (v1 > v2 ? 1 : 0)); }; while (low <= high) { var middle = low + ((high - low) >> 1); var midValue = array[middle]; - if (comparer(midValue, value) === 0) { + if (midValue === value) { return middle; } - else if (comparer(midValue, value) > 0) { + else if (midValue > value) { high = middle - 1; } else { @@ -462,117 +328,96 @@ var ts; return hasOwnProperty.call(map, key); } ts.hasProperty = hasProperty; + function getKeys(map) { + var keys = []; + for (var key in map) { + keys.push(key); + } + return keys; + } + ts.getKeys = getKeys; function getProperty(map, key) { return hasOwnProperty.call(map, key) ? map[key] : undefined; } ts.getProperty = getProperty; - function getOwnKeys(map) { - var keys = []; - for (var key in map) - if (hasOwnProperty.call(map, key)) { - keys.push(key); + function isEmpty(map) { + for (var id in map) { + if (hasProperty(map, id)) { + return false; } - return keys; - } - ts.getOwnKeys = getOwnKeys; - function forEachProperty(map, callback) { - var result; - for (var key in map) { - if (result = callback(map[key], key)) - break; } - return result; - } - ts.forEachProperty = forEachProperty; - function someProperties(map, predicate) { - for (var key in map) { - if (!predicate || predicate(map[key], key)) - return true; - } - return false; - } - ts.someProperties = someProperties; - function copyProperties(source, target) { - for (var key in source) { - target[key] = source[key]; - } - } - ts.copyProperties = copyProperties; - function reduceProperties(map, callback, initial) { - var result = initial; - for (var key in map) { - result = callback(result, map[key], String(key)); - } - return result; - } - ts.reduceProperties = reduceProperties; - function reduceOwnProperties(map, callback, initial) { - var result = initial; - for (var key in map) - if (hasOwnProperty.call(map, key)) { - result = callback(result, map[key], String(key)); - } - return result; - } - ts.reduceOwnProperties = reduceOwnProperties; - function equalOwnProperties(left, right, equalityComparer) { - if (left === right) - return true; - if (!left || !right) - return false; - for (var key in left) - if (hasOwnProperty.call(left, key)) { - if (!hasOwnProperty.call(right, key) === undefined) - return false; - if (equalityComparer ? !equalityComparer(left[key], right[key]) : left[key] !== right[key]) - return false; - } - for (var key in right) - if (hasOwnProperty.call(right, key)) { - if (!hasOwnProperty.call(left, key)) - return false; - } return true; } - ts.equalOwnProperties = equalOwnProperties; - function arrayToMap(array, makeKey, makeValue) { - var result = createMap(); - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var value = array_8[_i]; - result[makeKey(value)] = makeValue ? makeValue(value) : value; - } - return result; - } - ts.arrayToMap = arrayToMap; - function cloneMap(map) { - var clone = createMap(); - copyProperties(map, clone); - return clone; - } - ts.cloneMap = cloneMap; + ts.isEmpty = isEmpty; function clone(object) { var result = {}; for (var id in object) { - if (hasOwnProperty.call(object, id)) { - result[id] = object[id]; - } + result[id] = object[id]; } return result; } ts.clone = clone; function extend(first, second) { var result = {}; - for (var id in second) - if (hasOwnProperty.call(second, id)) { + for (var id in first) { + result[id] = first[id]; + } + for (var id in second) { + if (!hasProperty(result, id)) { result[id] = second[id]; } - for (var id in first) - if (hasOwnProperty.call(first, id)) { - result[id] = first[id]; - } + } return result; } ts.extend = extend; + function forEachValue(map, callback) { + var result; + for (var id in map) { + if (result = callback(map[id])) + break; + } + return result; + } + ts.forEachValue = forEachValue; + function forEachKey(map, callback) { + var result; + for (var id in map) { + if (result = callback(id)) + break; + } + return result; + } + ts.forEachKey = forEachKey; + function lookUp(map, key) { + return hasProperty(map, key) ? map[key] : undefined; + } + ts.lookUp = lookUp; + function copyMap(source, target) { + for (var p in source) { + target[p] = source[p]; + } + } + ts.copyMap = copyMap; + function arrayToMap(array, makeKey) { + var result = {}; + forEach(array, function (value) { + result[makeKey(value)] = value; + }); + return result; + } + ts.arrayToMap = arrayToMap; + function reduceProperties(map, callback, initial) { + var result = initial; + if (map) { + for (var key in map) { + if (hasProperty(map, key)) { + result = callback(result, map[key], String(key)); + } + } + } + return result; + } + ts.reduceProperties = reduceProperties; function isArray(value) { return Array.isArray ? Array.isArray(value) : value instanceof Array; } @@ -594,7 +439,9 @@ var ts; } ts.localizedDiagnosticMessages = undefined; function getLocaleSpecificMessage(message) { - return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message; + return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] + ? ts.localizedDiagnosticMessages[message.key] + : message.message; } ts.getLocaleSpecificMessage = getLocaleSpecificMessage; function createFileDiagnostic(file, start, length, message) { @@ -978,17 +825,10 @@ var ts; return true; } ts.containsPath = containsPath; - function startsWith(str, prefix) { - return str.lastIndexOf(prefix, 0) === 0; - } - ts.startsWith = startsWith; - function endsWith(str, suffix) { - var expectedPos = str.length - suffix.length; - return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; - } - ts.endsWith = endsWith; function fileExtensionIs(path, extension) { - return path.length > extension.length && endsWith(path, extension); + var pathLen = path.length; + var extLen = extension.length; + return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension; } ts.fileExtensionIs = fileExtensionIs; function fileExtensionIsAny(path, extensions) { @@ -1003,15 +843,10 @@ var ts; ts.fileExtensionIsAny = fileExtensionIsAny; var reservedCharacterPattern = /[^\w\s\/]/g; var wildcardCharCodes = [42, 63]; - var singleAsteriskRegexFragmentFiles = "([^./]|(\\.(?!min\\.js$))?)*"; - var singleAsteriskRegexFragmentOther = "[^/]*"; function getRegularExpressionForWildcard(specs, basePath, usage) { if (specs === undefined || specs.length === 0) { return undefined; } - var replaceWildcardCharacter = usage === "files" ? replaceWildCardCharacterFiles : replaceWildCardCharacterOther; - var singleAsteriskRegexFragment = usage === "files" ? singleAsteriskRegexFragmentFiles : singleAsteriskRegexFragmentOther; - var doubleAsteriskRegexFragment = usage === "exclude" ? "(/.+?)?" : "(/[^/.][^/]*)*?"; var pattern = ""; var hasWrittenSubpattern = false; spec: for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { @@ -1034,7 +869,7 @@ var ts; if (hasRecursiveDirectoryWildcard) { continue spec; } - subpattern += doubleAsteriskRegexFragment; + subpattern += "(/.+?)?"; hasRecursiveDirectoryWildcard = true; hasWrittenComponent = true; } @@ -1046,16 +881,6 @@ var ts; if (hasWrittenComponent) { subpattern += ts.directorySeparator; } - if (usage !== "exclude") { - if (component.charCodeAt(0) === 42) { - subpattern += "([^./]" + singleAsteriskRegexFragment + ")?"; - component = component.substr(1); - } - else if (component.charCodeAt(0) === 63) { - subpattern += "[^./]"; - component = component.substr(1); - } - } subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); hasWrittenComponent = true; } @@ -1076,14 +901,8 @@ var ts; return "^(" + pattern + (usage === "exclude" ? ")($|/)" : ")$"); } ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; - function replaceWildCardCharacterFiles(match) { - return replaceWildcardCharacter(match, singleAsteriskRegexFragmentFiles); - } - function replaceWildCardCharacterOther(match) { - return replaceWildcardCharacter(match, singleAsteriskRegexFragmentOther); - } - function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { - return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; + function replaceWildcardCharacter(match) { + return match === "*" ? "[^/]*" : match === "?" ? "[^/]" : "\\" + match; } function getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { path = normalizePath(path); @@ -1182,21 +1001,12 @@ var ts; } ts.getScriptKindFromFileName = getScriptKindFromFileName; ts.supportedTypeScriptExtensions = [".ts", ".tsx", ".d.ts"]; - ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"]; ts.supportedJavascriptExtensions = [".js", ".jsx"]; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); function getSupportedExtensions(options) { return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } ts.getSupportedExtensions = getSupportedExtensions; - function hasJavaScriptFileExtension(fileName) { - return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); - } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); - } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; function isSupportedSourceFileName(fileName, compilerOptions) { if (!fileName) { return false; @@ -1253,13 +1063,9 @@ var ts; } ts.removeFileExtension = removeFileExtension; function tryRemoveExtension(path, extension) { - return fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined; + return fileExtensionIs(path, extension) ? path.substring(0, path.length - extension.length) : undefined; } ts.tryRemoveExtension = tryRemoveExtension; - function removeExtension(path, extension) { - return path.substring(0, path.length - extension.length); - } - ts.removeExtension = removeExtension; function isJsxOrTsxExtension(ext) { return ext === ".jsx" || ext === ".tsx"; } @@ -1287,8 +1093,6 @@ var ts; } ts.objectAllocator = { getNodeConstructor: function () { return Node; }, - getTokenConstructor: function () { return Node; }, - getIdentifierConstructor: function () { return Node; }, getSourceFileConstructor: function () { return Node; }, getSymbolConstructor: function () { return Symbol; }, getTypeConstructor: function () { return Type; }, @@ -1334,57 +1138,6 @@ var ts; : (function (fileName) { return fileName.toLowerCase(); }); } ts.createGetCanonicalFileName = createGetCanonicalFileName; - function trace(host, message) { - host.trace(formatMessage.apply(undefined, arguments)); - } - ts.trace = trace; - function isTraceEnabled(compilerOptions, host) { - return compilerOptions.traceResolution && host.trace !== undefined; - } - ts.isTraceEnabled = isTraceEnabled; - function hasZeroOrOneAsteriskCharacter(str) { - var seenAsterisk = false; - for (var i = 0; i < str.length; i++) { - if (str.charCodeAt(i) === 42) { - if (!seenAsterisk) { - seenAsterisk = true; - } - else { - return false; - } - } - } - return true; - } - ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; - } - ts.createResolvedModule = createResolvedModule; - function isExternalModuleNameRelative(moduleName) { - return /^\.\.?($|[\\/])/.test(moduleName); - } - ts.isExternalModuleNameRelative = isExternalModuleNameRelative; - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - return jsonText ? JSON.parse(jsonText) : {}; - } - catch (e) { - return {}; - } - } - ts.readJson = readJson; - function getEmitModuleKind(compilerOptions) { - return typeof compilerOptions.module === "number" ? - compilerOptions.module : - getEmitScriptTarget(compilerOptions) === 2 ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; - } - ts.getEmitModuleKind = getEmitModuleKind; - function getEmitScriptTarget(compilerOptions) { - return compilerOptions.target || 0; - } - ts.getEmitScriptTarget = getEmitScriptTarget; })(ts || (ts = {})); var ts; (function (ts) { @@ -1471,7 +1224,7 @@ var ts; function readDirectory(path, extensions, excludes, includes) { return ts.matchFiles(path, extensions, excludes, includes, false, shell.CurrentDirectory, getAccessibleFileSystemEntries); } - var wscriptSystem = { + return { args: args, newLine: "\r\n", useCaseSensitiveFileNames: false, @@ -1490,7 +1243,7 @@ var ts; return fso.FolderExists(path); }, createDirectory: function (directoryName) { - if (!wscriptSystem.directoryExists(directoryName)) { + if (!this.directoryExists(directoryName)) { fso.CreateFolder(directoryName); } }, @@ -1510,7 +1263,6 @@ var ts; } } }; - return wscriptSystem; } function getNodeSystem() { var _fs = require("fs"); @@ -1519,13 +1271,13 @@ var ts; var _crypto = require("crypto"); var useNonPollingWatchers = process.env["TSC_NONPOLLING_WATCHER"]; function createWatchedFileSet() { - var dirWatchers = ts.createMap(); - var fileWatcherCallbacks = ts.createMap(); + var dirWatchers = {}; + var fileWatcherCallbacks = {}; return { addFile: addFile, removeFile: removeFile }; function reduceDirWatcherRefCountForFile(fileName) { var dirName = ts.getDirectoryPath(fileName); - var watcher = dirWatchers[dirName]; - if (watcher) { + if (ts.hasProperty(dirWatchers, dirName)) { + var watcher = dirWatchers[dirName]; watcher.referenceCount -= 1; if (watcher.referenceCount <= 0) { watcher.close(); @@ -1534,18 +1286,23 @@ var ts; } } function addDirWatcher(dirPath) { - var watcher = dirWatchers[dirPath]; - if (watcher) { - watcher.referenceCount += 1; + if (ts.hasProperty(dirWatchers, dirPath)) { + var watcher_1 = dirWatchers[dirPath]; + watcher_1.referenceCount += 1; return; } - watcher = _fs.watch(dirPath, { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); + var watcher = _fs.watch(dirPath, { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); watcher.referenceCount = 1; dirWatchers[dirPath] = watcher; return; } function addFileWatcherCallback(filePath, callback) { - (fileWatcherCallbacks[filePath] || (fileWatcherCallbacks[filePath] = [])).push(callback); + if (ts.hasProperty(fileWatcherCallbacks, filePath)) { + fileWatcherCallbacks[filePath].push(callback); + } + else { + fileWatcherCallbacks[filePath] = [callback]; + } } function addFile(fileName, callback) { addFileWatcherCallback(fileName, callback); @@ -1557,9 +1314,8 @@ var ts; reduceDirWatcherRefCountForFile(watchedFile.fileName); } function removeFileWatcherCallback(filePath, callback) { - var callbacks = fileWatcherCallbacks[filePath]; - if (callbacks) { - var newCallbacks = ts.copyListRemovingItem(callback, callbacks); + if (ts.hasProperty(fileWatcherCallbacks, filePath)) { + var newCallbacks = ts.copyListRemovingItem(callback, fileWatcherCallbacks[filePath]); if (newCallbacks.length === 0) { delete fileWatcherCallbacks[filePath]; } @@ -1572,7 +1328,7 @@ var ts; var fileName = typeof relativeFileName !== "string" ? undefined : ts.getNormalizedAbsolutePath(relativeFileName, baseDirPath); - if ((eventName === "change" || eventName === "rename") && fileWatcherCallbacks[fileName]) { + if ((eventName === "change" || eventName === "rename") && ts.hasProperty(fileWatcherCallbacks, fileName)) { for (var _i = 0, _a = fileWatcherCallbacks[fileName]; _i < _a.length; _i++) { var fileCallback = _a[_i]; fileCallback(fileName); @@ -1679,7 +1435,7 @@ var ts; function getDirectories(path) { return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1); }); } - var nodeSystem = { + return { args: process.argv.slice(2), newLine: _os.EOL, useCaseSensitiveFileNames: useCaseSensitiveFileNames, @@ -1729,7 +1485,7 @@ var ts; fileExists: fileExists, directoryExists: directoryExists, createDirectory: function (directoryName) { - if (!nodeSystem.directoryExists(directoryName)) { + if (!this.directoryExists(directoryName)) { _fs.mkdirSync(directoryName); } }, @@ -1777,7 +1533,6 @@ var ts; return _fs.realpathSync(path); } }; - return nodeSystem; } function getChakraSystem() { var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); }); @@ -1810,37 +1565,18 @@ var ts; realpath: realpath }; } - function recursiveCreateDirectory(directoryPath, sys) { - var basePath = ts.getDirectoryPath(directoryPath); - var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath); - if (shouldCreateParent) { - recursiveCreateDirectory(basePath, sys); - } - if (shouldCreateParent || !sys.directoryExists(directoryPath)) { - sys.createDirectory(directoryPath); - } - } - var sys; if (typeof ChakraHost !== "undefined") { - sys = getChakraSystem(); + return getChakraSystem(); } else if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { - sys = getWScriptSystem(); + return getWScriptSystem(); } else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") { - sys = getNodeSystem(); + return getNodeSystem(); } - if (sys) { - var originalWriteFile_1 = sys.writeFile; - sys.writeFile = function (path, data, writeBom) { - var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path)); - if (directoryPath && !sys.directoryExists(directoryPath)) { - recursiveCreateDirectory(directoryPath, sys); - } - originalWriteFile_1.call(sys, path, data, writeBom); - }; + else { + return undefined; } - return sys; })(); })(ts || (ts = {})); var ts; @@ -2285,7 +2021,6 @@ var ts; Object_is_possibly_undefined: { code: 2532, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_undefined_2532", message: "Object is possibly 'undefined'." }, Object_is_possibly_null_or_undefined: { code: 2533, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_null_or_undefined_2533", message: "Object is possibly 'null' or 'undefined'." }, A_function_returning_never_cannot_have_a_reachable_end_point: { code: 2534, category: ts.DiagnosticCategory.Error, key: "A_function_returning_never_cannot_have_a_reachable_end_point_2534", message: "A function returning 'never' cannot have a reachable end point." }, - Enum_type_0_has_members_with_initializers_that_are_not_literals: { code: 2535, category: ts.DiagnosticCategory.Error, key: "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", message: "Enum type '{0}' has members with initializers that are not literals." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "The return type of a JSX element constructor must return an object type." }, JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -2333,9 +2068,6 @@ var ts; All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, - A_class_must_be_declared_after_its_base_class: { code: 2690, category: ts.DiagnosticCategory.Error, key: "A_class_must_be_declared_after_its_base_class_2690", message: "A class must be declared after its base class." }, - An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: { code: 2691, category: ts.DiagnosticCategory.Error, key: "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691", message: "An import path cannot end with a '{0}' extension. Consider importing '{1}' instead." }, - _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: { code: 2692, category: ts.DiagnosticCategory.Error, key: "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", message: "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible." }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -2406,7 +2138,7 @@ var ts; Parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4078, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", message: "Parameter '{0}' of exported function has or is using private name '{1}'." }, Exported_type_alias_0_has_or_is_using_private_name_1: { code: 4081, category: ts.DiagnosticCategory.Error, key: "Exported_type_alias_0_has_or_is_using_private_name_1_4081", message: "Exported type alias '{0}' has or is using private name '{1}'." }, Default_export_of_the_module_has_or_is_using_private_name_0: { code: 4082, category: ts.DiagnosticCategory.Error, key: "Default_export_of_the_module_has_or_is_using_private_name_0_4082", message: "Default export of the module has or is using private name '{0}'." }, - Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", message: "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict." }, + Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_to_resolve_this_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_t_4090", message: "Conflicting library definitions for '{0}' found at '{1}' and '{2}'. Copy the correct file to the 'typings' folder to resolve this conflict." }, The_current_host_does_not_support_the_0_option: { code: 5001, category: ts.DiagnosticCategory.Error, key: "The_current_host_does_not_support_the_0_option_5001", message: "The current host does not support the '{0}' option." }, Cannot_find_the_common_subdirectory_path_for_the_input_files: { code: 5009, category: ts.DiagnosticCategory.Error, key: "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", message: "Cannot find the common subdirectory path for the input files." }, File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5010, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", message: "File specification cannot end in a recursive directory wildcard ('**'): '{0}'." }, @@ -2434,7 +2166,6 @@ var ts; Substitutions_for_pattern_0_should_be_an_array: { code: 5063, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_should_be_an_array_5063", message: "Substitutions for pattern '{0}' should be an array." }, Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: { code: 5064, category: ts.DiagnosticCategory.Error, key: "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", message: "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'." }, File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5065, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", message: "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'." }, - Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: { code: 5066, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", message: "Substitutions for pattern '{0}' shouldn't be an empty array." }, Concatenate_and_emit_output_to_single_file: { code: 6001, category: ts.DiagnosticCategory.Message, key: "Concatenate_and_emit_output_to_single_file_6001", message: "Concatenate and emit output to single file." }, Generates_corresponding_d_ts_file: { code: 6002, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_d_ts_file_6002", message: "Generates corresponding '.d.ts' file." }, Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: ts.DiagnosticCategory.Message, key: "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", message: "Specify the location where debugger should locate map files instead of generated locations." }, @@ -2551,12 +2282,10 @@ var ts; Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." }, File_name_0_has_a_1_extension_stripping_it: { code: 6132, category: ts.DiagnosticCategory.Message, key: "File_name_0_has_a_1_extension_stripping_it_6132", message: "File name '{0}' has a '{1}' extension - stripping it" }, _0_is_declared_but_never_used: { code: 6133, category: ts.DiagnosticCategory.Error, key: "_0_is_declared_but_never_used_6133", message: "'{0}' is declared but never used." }, - Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, - Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, + Report_Errors_on_Unused_Locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Locals_6134", message: "Report Errors on Unused Locals." }, + Report_Errors_on_Unused_Parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Parameters_6135", message: "Report Errors on Unused Parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" }, No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" }, - Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, - Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6139, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6139", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -2565,6 +2294,7 @@ var ts; Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: { code: 7011, category: ts.DiagnosticCategory.Error, key: "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", message: "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type." }, Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7013, category: ts.DiagnosticCategory.Error, key: "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", message: "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type." }, Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: { code: 7015, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", message: "Element implicitly has an 'any' type because index expression is not of type 'number'." }, + Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation: { code: 7016, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation_7016", message: "Property '{0}' implicitly has type 'any', because its 'set' accessor lacks a type annotation." }, Index_signature_of_object_type_implicitly_has_an_any_type: { code: 7017, category: ts.DiagnosticCategory.Error, key: "Index_signature_of_object_type_implicitly_has_an_any_type_7017", message: "Index signature of object type implicitly has an 'any' type." }, Object_literal_s_property_0_implicitly_has_an_1_type: { code: 7018, category: ts.DiagnosticCategory.Error, key: "Object_literal_s_property_0_implicitly_has_an_1_type_7018", message: "Object literal's property '{0}' implicitly has an '{1}' type." }, Rest_parameter_0_implicitly_has_an_any_type: { code: 7019, category: ts.DiagnosticCategory.Error, key: "Rest_parameter_0_implicitly_has_an_any_type_7019", message: "Rest parameter '{0}' implicitly has an 'any[]' type." }, @@ -2579,8 +2309,6 @@ var ts; Fallthrough_case_in_switch: { code: 7029, category: ts.DiagnosticCategory.Error, key: "Fallthrough_case_in_switch_7029", message: "Fallthrough case in switch." }, Not_all_code_paths_return_a_value: { code: 7030, category: ts.DiagnosticCategory.Error, key: "Not_all_code_paths_return_a_value_7030", message: "Not all code paths return a value." }, Binding_element_0_implicitly_has_an_1_type: { code: 7031, category: ts.DiagnosticCategory.Error, key: "Binding_element_0_implicitly_has_an_1_type_7031", message: "Binding element '{0}' implicitly has an '{1}' type." }, - Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { code: 7032, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", message: "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation." }, - Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { code: 7033, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", message: "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation." }, You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, @@ -2617,7 +2345,7 @@ var ts; return token >= 69; } ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; - var textToToken = ts.createMap({ + var textToToken = { "abstract": 115, "any": 117, "as": 116, @@ -2741,7 +2469,7 @@ var ts; "|=": 67, "^=": 68, "@": 55 - }); + }; var unicodeES3IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; var unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; var unicodeES5IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6263, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516, 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7401, 7404, 7406, 7409, 7413, 7414, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11823, 11823, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42647, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43648, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; @@ -2782,7 +2510,9 @@ var ts; function makeReverseMap(source) { var result = []; for (var name_4 in source) { - result[source[name_4]] = name_4; + if (source.hasOwnProperty(name_4)) { + result[source[name_4]] = name_4; + } } return result; } @@ -4149,6 +3879,24 @@ var ts; return node.end - node.pos; } ts.getFullWidth = getFullWidth; + function mapIsEqualTo(map1, map2) { + if (!map1 || !map2) { + return map1 === map2; + } + return containsAll(map1, map2) && containsAll(map2, map1); + } + ts.mapIsEqualTo = mapIsEqualTo; + function containsAll(map, other) { + for (var key in map) { + if (!ts.hasProperty(map, key)) { + continue; + } + if (!ts.hasProperty(other, key) || map[key] !== other[key]) { + return false; + } + } + return true; + } function arrayIsEqualTo(array1, array2, equaler) { if (!array1 || !array2) { return array1 === array2; @@ -4166,7 +3914,7 @@ var ts; } ts.arrayIsEqualTo = arrayIsEqualTo; function hasResolvedModule(sourceFile, moduleNameText) { - return !!(sourceFile.resolvedModules && sourceFile.resolvedModules[moduleNameText]); + return sourceFile.resolvedModules && ts.hasProperty(sourceFile.resolvedModules, moduleNameText); } ts.hasResolvedModule = hasResolvedModule; function getResolvedModule(sourceFile, moduleNameText) { @@ -4175,14 +3923,14 @@ var ts; ts.getResolvedModule = getResolvedModule; function setResolvedModule(sourceFile, moduleNameText, resolvedModule) { if (!sourceFile.resolvedModules) { - sourceFile.resolvedModules = ts.createMap(); + sourceFile.resolvedModules = {}; } sourceFile.resolvedModules[moduleNameText] = resolvedModule; } ts.setResolvedModule = setResolvedModule; function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) { if (!sourceFile.resolvedTypeReferenceDirectiveNames) { - sourceFile.resolvedTypeReferenceDirectiveNames = ts.createMap(); + sourceFile.resolvedTypeReferenceDirectiveNames = {}; } sourceFile.resolvedTypeReferenceDirectiveNames[typeReferenceDirectiveName] = resolvedTypeReferenceDirective; } @@ -4201,7 +3949,7 @@ var ts; } for (var i = 0; i < names.length; i++) { var newResolution = newResolutions[i]; - var oldResolution = oldResolutions && oldResolutions[names[i]]; + var oldResolution = oldResolutions && ts.hasProperty(oldResolutions, names[i]) ? oldResolutions[names[i]] : undefined; var changed = oldResolution ? !newResolution || !comparer(oldResolution, newResolution) : newResolution; @@ -4301,20 +4049,16 @@ var ts; if (includeJsDocComment && node.jsDocComments && node.jsDocComments.length > 0) { return getTokenPosOfNode(node.jsDocComments[0]); } - if (node.kind === 286 && node._children.length > 0) { + if (node.kind === 282 && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDocComment); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); } ts.getTokenPosOfNode = getTokenPosOfNode; function isJSDocNode(node) { - return node.kind >= 257 && node.kind <= 282; + return node.kind >= 257 && node.kind <= 281; } ts.isJSDocNode = isJSDocNode; - function isJSDocTag(node) { - return node.kind >= 273 && node.kind <= 285; - } - ts.isJSDocTag = isJSDocTag; function getNonDecoratorTokenPosOfNode(node, sourceFile) { if (nodeIsMissing(node) || !node.decorators) { return getTokenPosOfNode(node, sourceFile); @@ -4365,13 +4109,10 @@ var ts; (node.name.kind === 9 || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; - function isShorthandAmbientModuleSymbol(moduleSymbol) { - return isShorthandAmbientModule(moduleSymbol.valueDeclaration); - } - ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; function isShorthandAmbientModule(node) { return node.kind === 225 && (!node.body); } + ts.isShorthandAmbientModule = isShorthandAmbientModule; function isBlockScopedContainerTopLevel(node) { return node.kind === 256 || node.kind === 225 || @@ -4931,7 +4672,6 @@ var ts; case 155: return node.typeName; case 194: - ts.Debug.assert(isEntityNameExpression(node.expression)); return node.expression; case 69: case 139: @@ -5095,6 +4835,10 @@ var ts; return false; } ts.isExpression = isExpression; + function isExternalModuleNameRelative(moduleName) { + return moduleName.substr(0, 2) === "./" || moduleName.substr(0, 3) === "../" || moduleName.substr(0, 2) === ".\\" || moduleName.substr(0, 3) === "..\\"; + } + ts.isExternalModuleNameRelative = isExternalModuleNameRelative; function isInstantiatedModule(node, preserveConstEnums) { var moduleState = ts.getModuleInstanceState(node); return moduleState === 1 || @@ -5357,7 +5101,7 @@ var ts; continue; } return parent_5.kind === 187 && - isAssignmentOperator(parent_5.operatorToken.kind) && + parent_5.operatorToken.kind === 56 && parent_5.left === node || (parent_5.kind === 207 || parent_5.kind === 208) && parent_5.initializer === node; @@ -5404,7 +5148,6 @@ var ts; case 146: case 225: case 232: - case 228: case 142: case 253: case 145: @@ -5521,13 +5264,9 @@ var ts; node.kind === 232 || node.kind === 234 || node.kind === 238 || - node.kind === 235 && exportAssignmentIsAlias(node); + node.kind === 235 && node.expression.kind === 69; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; - function exportAssignmentIsAlias(node) { - return isEntityNameExpression(node.expression); - } - ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getClassExtendsHeritageClauseElement(node) { var heritageClause = getHeritageClause(node.heritageClauses, 83); return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; @@ -5747,7 +5486,7 @@ var ts; ts.createSynthesizedNodeArray = createSynthesizedNodeArray; function createDiagnosticCollection() { var nonFileDiagnostics = []; - var fileDiagnostics = ts.createMap(); + var fileDiagnostics = {}; var diagnosticsModified = false; var modificationCount = 0; return { @@ -5761,12 +5500,12 @@ var ts; return modificationCount; } function reattachFileDiagnostics(newFile) { - var diagnostics = fileDiagnostics[newFile.fileName]; - if (diagnostics) { - for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { - var diagnostic = diagnostics_1[_i]; - diagnostic.file = newFile; - } + if (!ts.hasProperty(fileDiagnostics, newFile.fileName)) { + return; + } + for (var _i = 0, _a = fileDiagnostics[newFile.fileName]; _i < _a.length; _i++) { + var diagnostic = _a[_i]; + diagnostic.file = newFile; } } function add(diagnostic) { @@ -5800,7 +5539,9 @@ var ts; } ts.forEach(nonFileDiagnostics, pushDiagnostic); for (var key in fileDiagnostics) { - ts.forEach(fileDiagnostics[key], pushDiagnostic); + if (ts.hasProperty(fileDiagnostics, key)) { + ts.forEach(fileDiagnostics[key], pushDiagnostic); + } } return ts.sortAndDeduplicateDiagnostics(allDiagnostics); } @@ -5811,13 +5552,15 @@ var ts; diagnosticsModified = false; nonFileDiagnostics = ts.sortAndDeduplicateDiagnostics(nonFileDiagnostics); for (var key in fileDiagnostics) { - fileDiagnostics[key] = ts.sortAndDeduplicateDiagnostics(fileDiagnostics[key]); + if (ts.hasProperty(fileDiagnostics, key)) { + fileDiagnostics[key] = ts.sortAndDeduplicateDiagnostics(fileDiagnostics[key]); + } } } } ts.createDiagnosticCollection = createDiagnosticCollection; var escapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; - var escapedCharsMap = ts.createMap({ + var escapedCharsMap = { "\0": "\\0", "\t": "\\t", "\v": "\\v", @@ -5830,7 +5573,7 @@ var ts; "\u2028": "\\u2028", "\u2029": "\\u2029", "\u0085": "\\u0085" - }); + }; function escapeString(s) { s = escapedCharsRegExp.test(s) ? s.replace(escapedCharsRegExp, getReplacement) : s; return s; @@ -5960,13 +5703,25 @@ var ts; function getDeclarationEmitOutputFilePath(sourceFile, host) { var options = host.getCompilerOptions(); var outputDir = options.declarationDir || options.outDir; - var path = outputDir - ? getSourceFilePathInNewDir(sourceFile, host, outputDir) - : sourceFile.fileName; - return ts.removeFileExtension(path) + ".d.ts"; + if (options.declaration) { + var path = outputDir + ? getSourceFilePathInNewDir(sourceFile, host, outputDir) + : sourceFile.fileName; + return ts.removeFileExtension(path) + ".d.ts"; + } } ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; - function forEachExpectedEmitFile(host, action, targetSourceFile, emitOnlyDtsFiles) { + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return typeof compilerOptions.module === "number" ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) === 2 ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; + } + ts.getEmitModuleKind = getEmitModuleKind; + function forEachExpectedEmitFile(host, action, targetSourceFile) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { onBundledEmit(host); @@ -5993,19 +5748,18 @@ var ts; } } var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); - var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; var emitFileNames = { jsFilePath: jsFilePath, sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), - declarationFilePath: declarationFilePath + declarationFilePath: !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined }; - action(emitFileNames, [sourceFile], false, emitOnlyDtsFiles); + action(emitFileNames, [sourceFile], false); } function onBundledEmit(host) { var bundledSources = ts.filter(host.getSourceFiles(), function (sourceFile) { return !isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile) && (!ts.isExternalModule(sourceFile) || - !!ts.getEmitModuleKind(options)); }); + !!getEmitModuleKind(options)); }); if (bundledSources.length) { var jsFilePath = options.outFile || options.out; var emitFileNames = { @@ -6013,7 +5767,7 @@ var ts; sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), declarationFilePath: options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined }; - action(emitFileNames, bundledSources, true, emitOnlyDtsFiles); + action(emitFileNames, bundledSources, true); } } function getSourceMapFilePath(jsFilePath, options) { @@ -6300,11 +6054,21 @@ var ts; isClassLike(node.parent.parent); } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; - function isEntityNameExpression(node) { - return node.kind === 69 || - node.kind === 172 && isEntityNameExpression(node.expression); + function isSupportedExpressionWithTypeArguments(node) { + return isSupportedExpressionWithTypeArgumentsRest(node.expression); + } + ts.isSupportedExpressionWithTypeArguments = isSupportedExpressionWithTypeArguments; + function isSupportedExpressionWithTypeArgumentsRest(node) { + if (node.kind === 69) { + return true; + } + else if (isPropertyAccessExpression(node)) { + return isSupportedExpressionWithTypeArgumentsRest(node.expression); + } + else { + return false; + } } - ts.isEntityNameExpression = isEntityNameExpression; function isRightSideOfQualifiedNameOrPropertyAccess(node) { return (node.parent.kind === 139 && node.parent.right === node) || (node.parent.kind === 172 && node.parent.name === node); @@ -6325,10 +6089,14 @@ var ts; return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & 512) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; - function tryExtractTypeScriptExtension(fileName) { - return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function hasJavaScriptFileExtension(fileName) { + return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; + ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; + function hasTypeScriptFileExtension(fileName) { + return ts.forEach(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; function getExpandedCharCodes(input) { var output = []; var length = input.length; @@ -6385,7 +6153,7 @@ var ts; return (memo ? memo + "," : memo) + stringifyValue(value); } function stringifyObject(value) { - return "{" + ts.reduceOwnProperties(value, stringifyProperty, "") + "}"; + return "{" + ts.reduceProperties(value, stringifyProperty, "") + "}"; } function stringifyProperty(memo, value, key) { return value === undefined || typeof value === "function" || key === "__cycle" ? memo @@ -6576,23 +6344,25 @@ var ts; return node.flags & 92 && node.parent.kind === 148 && ts.isClassLike(node.parent.parent); } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; + function startsWith(str, prefix) { + return str.lastIndexOf(prefix, 0) === 0; + } + ts.startsWith = startsWith; + function endsWith(str, suffix) { + var expectedPos = str.length - suffix.length; + return str.indexOf(suffix, expectedPos) === expectedPos; + } + ts.endsWith = endsWith; })(ts || (ts = {})); var ts; (function (ts) { + ts.parseTime = 0; var NodeConstructor; - var TokenConstructor; - var IdentifierConstructor; var SourceFileConstructor; function createNode(kind, pos, end) { if (kind === 256) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); } - else if (kind === 69) { - return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); - } - else if (kind < 139) { - return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end); - } else { return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end); } @@ -6701,8 +6471,6 @@ var ts; return visitNodes(cbNodes, node.types); case 164: return visitNode(cbNode, node.type); - case 166: - return visitNode(cbNode, node.literal); case 167: case 168: return visitNodes(cbNodes, node.elements); @@ -6981,17 +6749,14 @@ var ts; case 280: return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); - case 282: - return visitNode(cbNode, node.literal); } } ts.forEachChild = forEachChild; function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { if (setParentNodes === void 0) { setParentNodes = false; } - ts.performance.mark("beforeParse"); + var start = new Date().getTime(); var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, scriptKind); - ts.performance.mark("afterParse"); - ts.performance.measure("Parse", "beforeParse", "afterParse"); + ts.parseTime += new Date().getTime() - start; return result; } ts.createSourceFile = createSourceFile; @@ -7006,7 +6771,7 @@ var ts; function parseIsolatedJSDocComment(content, start, length) { var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length); if (result && result.jsDocComment) { - fixupParentReferences(result.jsDocComment); + Parser.fixupParentReferences(result.jsDocComment); } return result; } @@ -7015,41 +6780,16 @@ var ts; return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length); } ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; - function fixupParentReferences(rootNode) { - var parent = rootNode; - forEachChild(rootNode, visitNode); - return; - function visitNode(n) { - if (n.parent !== parent) { - n.parent = parent; - var saveParent = parent; - parent = n; - forEachChild(n, visitNode); - if (n.jsDocComments) { - for (var _i = 0, _a = n.jsDocComments; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - jsDocComment.parent = n; - parent = jsDocComment; - forEachChild(jsDocComment, visitNode); - } - } - parent = saveParent; - } - } - } - ts.fixupParentReferences = fixupParentReferences; var Parser; (function (Parser) { var scanner = ts.createScanner(2, true); var disallowInAndDecoratorContext = 4194304 | 16777216; var NodeConstructor; - var TokenConstructor; - var IdentifierConstructor; var SourceFileConstructor; var sourceFile; var parseDiagnostics; var syntaxCursor; - var currentToken; + var token; var sourceText; var nodeCount; var identifiers; @@ -7070,14 +6810,12 @@ var ts; } function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind) { NodeConstructor = ts.objectAllocator.getNodeConstructor(); - TokenConstructor = ts.objectAllocator.getTokenConstructor(); - IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor(); SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor(); sourceText = _sourceText; syntaxCursor = _syntaxCursor; parseDiagnostics = []; parsingContext = 0; - identifiers = ts.createMap(); + identifiers = {}; identifierCount = 0; nodeCount = 0; contextFlags = scriptKind === 1 || scriptKind === 2 ? 134217728 : 0; @@ -7099,10 +6837,10 @@ var ts; function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) { sourceFile = createSourceFile(fileName, languageVersion, scriptKind); sourceFile.flags = contextFlags; - nextToken(); + token = nextToken(); processReferenceComments(sourceFile); sourceFile.statements = parseList(0, parseStatement); - ts.Debug.assert(token() === 1); + ts.Debug.assert(token === 1); sourceFile.endOfFileToken = parseTokenNode(); setExternalModuleIndicator(sourceFile); sourceFile.nodeCount = nodeCount; @@ -7133,6 +6871,29 @@ var ts; } return node; } + function fixupParentReferences(rootNode) { + var parent = rootNode; + forEachChild(rootNode, visitNode); + return; + function visitNode(n) { + if (n.parent !== parent) { + n.parent = parent; + var saveParent = parent; + parent = n; + forEachChild(n, visitNode); + if (n.jsDocComments) { + for (var _i = 0, _a = n.jsDocComments; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + jsDocComment.parent = n; + parent = jsDocComment; + forEachChild(jsDocComment, visitNode); + } + } + parent = saveParent; + } + } + } + Parser.fixupParentReferences = fixupParentReferences; function createSourceFile(fileName, languageVersion, scriptKind) { var sourceFile = new SourceFileConstructor(256, 0, sourceText.length); nodeCount++; @@ -7243,29 +7004,26 @@ var ts; function getNodeEnd() { return scanner.getStartPos(); } - function token() { - return currentToken; - } function nextToken() { - return currentToken = scanner.scan(); + return token = scanner.scan(); } function reScanGreaterToken() { - return currentToken = scanner.reScanGreaterToken(); + return token = scanner.reScanGreaterToken(); } function reScanSlashToken() { - return currentToken = scanner.reScanSlashToken(); + return token = scanner.reScanSlashToken(); } function reScanTemplateToken() { - return currentToken = scanner.reScanTemplateToken(); + return token = scanner.reScanTemplateToken(); } function scanJsxIdentifier() { - return currentToken = scanner.scanJsxIdentifier(); + return token = scanner.scanJsxIdentifier(); } function scanJsxText() { - return currentToken = scanner.scanJsxToken(); + return token = scanner.scanJsxToken(); } function speculationHelper(callback, isLookAhead) { - var saveToken = currentToken; + var saveToken = token; var saveParseDiagnosticsLength = parseDiagnostics.length; var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; var saveContextFlags = contextFlags; @@ -7274,7 +7032,7 @@ var ts; : scanner.tryScan(callback); ts.Debug.assert(saveContextFlags === contextFlags); if (!result || isLookAhead) { - currentToken = saveToken; + token = saveToken; parseDiagnostics.length = saveParseDiagnosticsLength; parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; } @@ -7287,20 +7045,20 @@ var ts; return speculationHelper(callback, false); } function isIdentifier() { - if (token() === 69) { + if (token === 69) { return true; } - if (token() === 114 && inYieldContext()) { + if (token === 114 && inYieldContext()) { return false; } - if (token() === 119 && inAwaitContext()) { + if (token === 119 && inAwaitContext()) { return false; } - return token() > 105; + return token > 105; } function parseExpected(kind, diagnosticMessage, shouldAdvance) { if (shouldAdvance === void 0) { shouldAdvance = true; } - if (token() === kind) { + if (token === kind) { if (shouldAdvance) { nextToken(); } @@ -7315,14 +7073,14 @@ var ts; return false; } function parseOptional(t) { - if (token() === t) { + if (token === t) { nextToken(); return true; } return false; } function parseOptionalToken(t) { - if (token() === t) { + if (token === t) { return parseTokenNode(); } return undefined; @@ -7332,19 +7090,19 @@ var ts; createMissingNode(t, reportAtCurrentPosition, diagnosticMessage, arg0); } function parseTokenNode() { - var node = createNode(token()); + var node = createNode(token); nextToken(); return finishNode(node); } function canParseSemicolon() { - if (token() === 23) { + if (token === 23) { return true; } - return token() === 16 || token() === 1 || scanner.hasPrecedingLineBreak(); + return token === 16 || token === 1 || scanner.hasPrecedingLineBreak(); } function parseSemicolon() { if (canParseSemicolon()) { - if (token() === 23) { + if (token === 23) { nextToken(); } return true; @@ -7358,9 +7116,7 @@ var ts; if (!(pos >= 0)) { pos = scanner.getStartPos(); } - return kind >= 139 ? new NodeConstructor(kind, pos, pos) : - kind === 69 ? new IdentifierConstructor(kind, pos, pos) : - new TokenConstructor(kind, pos, pos); + return new NodeConstructor(kind, pos, pos); } function finishNode(node, end) { node.end = end === undefined ? scanner.getStartPos() : end; @@ -7386,14 +7142,14 @@ var ts; } function internIdentifier(text) { text = ts.escapeIdentifier(text); - return identifiers[text] || (identifiers[text] = text); + return ts.hasProperty(identifiers, text) ? identifiers[text] : (identifiers[text] = text); } function createIdentifier(isIdentifier, diagnosticMessage) { identifierCount++; if (isIdentifier) { var node = createNode(69); - if (token() !== 69) { - node.originalKeywordKind = token(); + if (token !== 69) { + node.originalKeywordKind = token; } node.text = internIdentifier(scanner.getTokenValue()); nextToken(); @@ -7405,18 +7161,18 @@ var ts; return createIdentifier(isIdentifier(), diagnosticMessage); } function parseIdentifierName() { - return createIdentifier(ts.tokenIsIdentifierOrKeyword(token())); + return createIdentifier(ts.tokenIsIdentifierOrKeyword(token)); } function isLiteralPropertyName() { - return ts.tokenIsIdentifierOrKeyword(token()) || - token() === 9 || - token() === 8; + return ts.tokenIsIdentifierOrKeyword(token) || + token === 9 || + token === 8; } function parsePropertyNameWorker(allowComputedPropertyNames) { - if (token() === 9 || token() === 8) { + if (token === 9 || token === 8) { return parseLiteralNode(true); } - if (allowComputedPropertyNames && token() === 19) { + if (allowComputedPropertyNames && token === 19) { return parseComputedPropertyName(); } return parseIdentifierName(); @@ -7428,7 +7184,7 @@ var ts; return parsePropertyNameWorker(false); } function isSimplePropertyName() { - return token() === 9 || token() === 8 || ts.tokenIsIdentifierOrKeyword(token()); + return token === 9 || token === 8 || ts.tokenIsIdentifierOrKeyword(token); } function parseComputedPropertyName() { var node = createNode(140); @@ -7438,7 +7194,7 @@ var ts; return finishNode(node); } function parseContextualModifier(t) { - return token() === t && tryParse(nextTokenCanFollowModifier); + return token === t && tryParse(nextTokenCanFollowModifier); } function nextTokenIsOnSameLineAndCanFollowModifier() { nextToken(); @@ -7448,39 +7204,39 @@ var ts; return canFollowModifier(); } function nextTokenCanFollowModifier() { - if (token() === 74) { + if (token === 74) { return nextToken() === 81; } - if (token() === 82) { + if (token === 82) { nextToken(); - if (token() === 77) { + if (token === 77) { return lookAhead(nextTokenIsClassOrFunctionOrAsync); } - return token() !== 37 && token() !== 116 && token() !== 15 && canFollowModifier(); + return token !== 37 && token !== 116 && token !== 15 && canFollowModifier(); } - if (token() === 77) { + if (token === 77) { return nextTokenIsClassOrFunctionOrAsync(); } - if (token() === 113) { + if (token === 113) { nextToken(); return canFollowModifier(); } return nextTokenIsOnSameLineAndCanFollowModifier(); } function parseAnyContextualModifier() { - return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); + return ts.isModifierKind(token) && tryParse(nextTokenCanFollowModifier); } function canFollowModifier() { - return token() === 19 - || token() === 15 - || token() === 37 - || token() === 22 + return token === 19 + || token === 15 + || token === 37 + || token === 22 || isLiteralPropertyName(); } function nextTokenIsClassOrFunctionOrAsync() { nextToken(); - return token() === 73 || token() === 87 || - (token() === 118 && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); + return token === 73 || token === 87 || + (token === 118 && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); } function isListElement(parsingContext, inErrorRecovery) { var node = currentNode(parsingContext); @@ -7491,21 +7247,21 @@ var ts; case 0: case 1: case 3: - return !(token() === 23 && inErrorRecovery) && isStartOfStatement(); + return !(token === 23 && inErrorRecovery) && isStartOfStatement(); case 2: - return token() === 71 || token() === 77; + return token === 71 || token === 77; case 4: return lookAhead(isTypeMemberStart); case 5: - return lookAhead(isClassMemberStart) || (token() === 23 && !inErrorRecovery); + return lookAhead(isClassMemberStart) || (token === 23 && !inErrorRecovery); case 6: - return token() === 19 || isLiteralPropertyName(); + return token === 19 || isLiteralPropertyName(); case 12: - return token() === 19 || token() === 37 || isLiteralPropertyName(); + return token === 19 || token === 37 || isLiteralPropertyName(); case 9: - return token() === 19 || isLiteralPropertyName(); + return token === 19 || isLiteralPropertyName(); case 7: - if (token() === 15) { + if (token === 15) { return lookAhead(isValidHeritageClauseObjectLiteral); } if (!inErrorRecovery) { @@ -7517,23 +7273,23 @@ var ts; case 8: return isIdentifierOrPattern(); case 10: - return token() === 24 || token() === 22 || isIdentifierOrPattern(); + return token === 24 || token === 22 || isIdentifierOrPattern(); case 17: return isIdentifier(); case 11: case 15: - return token() === 24 || token() === 22 || isStartOfExpression(); + return token === 24 || token === 22 || isStartOfExpression(); case 16: return isStartOfParameter(); case 18: case 19: - return token() === 24 || isStartOfType(); + return token === 24 || isStartOfType(); case 20: return isHeritageClause(); case 21: - return ts.tokenIsIdentifierOrKeyword(token()); + return ts.tokenIsIdentifierOrKeyword(token); case 13: - return ts.tokenIsIdentifierOrKeyword(token()) || token() === 15; + return ts.tokenIsIdentifierOrKeyword(token) || token === 15; case 14: return true; case 22: @@ -7546,7 +7302,7 @@ var ts; ts.Debug.fail("Non-exhaustive case in 'isListElement'."); } function isValidHeritageClauseObjectLiteral() { - ts.Debug.assert(token() === 15); + ts.Debug.assert(token === 15); if (nextToken() === 16) { var next = nextToken(); return next === 24 || next === 15 || next === 83 || next === 106; @@ -7559,11 +7315,11 @@ var ts; } function nextTokenIsIdentifierOrKeyword() { nextToken(); - return ts.tokenIsIdentifierOrKeyword(token()); + return ts.tokenIsIdentifierOrKeyword(token); } function isHeritageClauseExtendsOrImplementsKeyword() { - if (token() === 106 || - token() === 83) { + if (token === 106 || + token === 83) { return lookAhead(nextTokenIsStartOfExpression); } return false; @@ -7573,7 +7329,7 @@ var ts; return isStartOfExpression(); } function isListTerminator(kind) { - if (token() === 1) { + if (token === 1) { return true; } switch (kind) { @@ -7585,49 +7341,49 @@ var ts; case 12: case 9: case 21: - return token() === 16; + return token === 16; case 3: - return token() === 16 || token() === 71 || token() === 77; + return token === 16 || token === 71 || token === 77; case 7: - return token() === 15 || token() === 83 || token() === 106; + return token === 15 || token === 83 || token === 106; case 8: return isVariableDeclaratorListTerminator(); case 17: - return token() === 27 || token() === 17 || token() === 15 || token() === 83 || token() === 106; + return token === 27 || token === 17 || token === 15 || token === 83 || token === 106; case 11: - return token() === 18 || token() === 23; + return token === 18 || token === 23; case 15: case 19: case 10: - return token() === 20; + return token === 20; case 16: - return token() === 18 || token() === 20; + return token === 18 || token === 20; case 18: - return token() === 27 || token() === 17; + return token === 27 || token === 17; case 20: - return token() === 15 || token() === 16; + return token === 15 || token === 16; case 13: - return token() === 27 || token() === 39; + return token === 27 || token === 39; case 14: - return token() === 25 && lookAhead(nextTokenIsSlash); + return token === 25 && lookAhead(nextTokenIsSlash); case 22: - return token() === 18 || token() === 54 || token() === 16; + return token === 18 || token === 54 || token === 16; case 23: - return token() === 27 || token() === 16; + return token === 27 || token === 16; case 25: - return token() === 20 || token() === 16; + return token === 20 || token === 16; case 24: - return token() === 16; + return token === 16; } } function isVariableDeclaratorListTerminator() { if (canParseSemicolon()) { return true; } - if (isInOrOfKeyword(token())) { + if (isInOrOfKeyword(token)) { return true; } - if (token() === 34) { + if (token === 34) { return true; } return false; @@ -7882,7 +7638,7 @@ var ts; break; } parseExpected(24); - if (considerSemicolonAsDelimiter && token() === 23 && !scanner.hasPrecedingLineBreak()) { + if (considerSemicolonAsDelimiter && token === 23 && !scanner.hasPrecedingLineBreak()) { nextToken(); } continue; @@ -7927,7 +7683,7 @@ var ts; return entity; } function parseRightSideOfDot(allowIdentifierNames) { - if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) { + if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token)) { var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); if (matchesPattern) { return createMissingNode(69, true, ts.Diagnostics.Identifier_expected); @@ -7952,7 +7708,7 @@ var ts; var span = createNode(197); span.expression = allowInAnd(parseExpression); var literal; - if (token() === 16) { + if (token === 16) { reScanTemplateToken(); literal = parseTemplateLiteralFragment(); } @@ -7962,11 +7718,14 @@ var ts; span.literal = literal; return finishNode(span); } + function parseStringLiteralTypeNode() { + return parseLiteralLikeNode(166, true); + } function parseLiteralNode(internName) { - return parseLiteralLikeNode(token(), internName); + return parseLiteralLikeNode(token, internName); } function parseTemplateLiteralFragment() { - return parseLiteralLikeNode(token(), false); + return parseLiteralLikeNode(token, false); } function parseLiteralLikeNode(kind, internName) { var node = createNode(kind); @@ -7992,7 +7751,7 @@ var ts; var typeName = parseEntityName(false, ts.Diagnostics.Type_expected); var node = createNode(155, typeName.pos); node.typeName = typeName; - if (!scanner.hasPrecedingLineBreak() && token() === 25) { + if (!scanner.hasPrecedingLineBreak() && token === 25) { node.typeArguments = parseBracketedList(18, parseType, 25, 27); } return finishNode(node); @@ -8029,7 +7788,7 @@ var ts; return finishNode(node); } function parseTypeParameters() { - if (token() === 25) { + if (token === 25) { return parseBracketedList(17, parseTypeParameter, 25, 27); } } @@ -8040,7 +7799,7 @@ var ts; return undefined; } function isStartOfParameter() { - return token() === 22 || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 55 || token() === 97; + return token === 22 || isIdentifierOrPattern() || ts.isModifierKind(token) || token === 55 || token === 97; } function setModifiers(node, modifiers) { if (modifiers) { @@ -8050,7 +7809,7 @@ var ts; } function parseParameter() { var node = createNode(142); - if (token() === 97) { + if (token === 97) { node.name = createIdentifier(true, undefined); node.type = parseParameterType(); return finishNode(node); @@ -8059,7 +7818,7 @@ var ts; setModifiers(node, parseModifiers()); node.dotDotDotToken = parseOptionalToken(22); node.name = parseIdentifierOrPattern(); - if (ts.getFullWidth(node.name) === 0 && node.flags === 0 && ts.isModifierKind(token())) { + if (ts.getFullWidth(node.name) === 0 && node.flags === 0 && ts.isModifierKind(token)) { nextToken(); } node.questionToken = parseOptionalToken(53); @@ -8117,17 +7876,17 @@ var ts; return finishNode(node); } function isIndexSignature() { - if (token() !== 19) { + if (token !== 19) { return false; } return lookAhead(isUnambiguouslyIndexSignature); } function isUnambiguouslyIndexSignature() { nextToken(); - if (token() === 22 || token() === 20) { + if (token === 22 || token === 20) { return true; } - if (ts.isModifierKind(token())) { + if (ts.isModifierKind(token)) { nextToken(); if (isIdentifier()) { return true; @@ -8139,14 +7898,14 @@ var ts; else { nextToken(); } - if (token() === 54 || token() === 24) { + if (token === 54 || token === 24) { return true; } - if (token() !== 53) { + if (token !== 53) { return false; } nextToken(); - return token() === 54 || token() === 24 || token() === 20; + return token === 54 || token === 24 || token === 20; } function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { var node = createNode(153, fullStart); @@ -8160,7 +7919,7 @@ var ts; function parsePropertyOrMethodSignature(fullStart, modifiers) { var name = parsePropertyName(); var questionToken = parseOptionalToken(53); - if (token() === 17 || token() === 25) { + if (token === 17 || token === 25) { var method = createNode(146, fullStart); setModifiers(method, modifiers); method.name = name; @@ -8175,7 +7934,7 @@ var ts; property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); - if (token() === 56) { + if (token === 56) { property.initializer = parseNonParameterInitializer(); } parseTypeMemberSemicolon(); @@ -8184,35 +7943,34 @@ var ts; } function isTypeMemberStart() { var idToken; - if (token() === 17 || token() === 25) { + if (token === 17 || token === 25) { return true; } - while (ts.isModifierKind(token())) { - idToken = token(); + while (ts.isModifierKind(token)) { + idToken = token; nextToken(); } - if (token() === 19) { + if (token === 19) { return true; } if (isLiteralPropertyName()) { - idToken = token(); + idToken = token; nextToken(); } if (idToken) { - return token() === 17 || - token() === 25 || - token() === 53 || - token() === 54 || - token() === 24 || + return token === 17 || + token === 25 || + token === 53 || + token === 54 || canParseSemicolon(); } return false; } function parseTypeMember() { - if (token() === 17 || token() === 25) { + if (token === 17 || token === 25) { return parseSignatureMember(151); } - if (token() === 92 && lookAhead(isStartOfConstructSignature)) { + if (token === 92 && lookAhead(isStartOfConstructSignature)) { return parseSignatureMember(152); } var fullStart = getNodePos(); @@ -8224,7 +7982,7 @@ var ts; } function isStartOfConstructSignature() { nextToken(); - return token() === 17 || token() === 25; + return token === 17 || token === 25; } function parseTypeLiteral() { var node = createNode(159); @@ -8264,19 +8022,10 @@ var ts; } function parseKeywordAndNoDot() { var node = parseTokenNode(); - return token() === 21 ? undefined : node; - } - function parseLiteralTypeNode() { - var node = createNode(166); - node.literal = parseSimpleUnaryExpression(); - finishNode(node); - return node; - } - function nextTokenIsNumericLiteral() { - return nextToken() === 8; + return token === 21 ? undefined : node; } function parseNonArrayType() { - switch (token()) { + switch (token) { case 117: case 132: case 130: @@ -8287,18 +8036,13 @@ var ts; var node = tryParse(parseKeywordAndNoDot); return node || parseTypeReference(); case 9: - case 8: - case 99: - case 84: - return parseLiteralTypeNode(); - case 36: - return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode() : parseTypeReference(); + return parseStringLiteralTypeNode(); case 103: case 93: return parseTokenNode(); case 97: { var thisKeyword = parseThisTypeNode(); - if (token() === 124 && !scanner.hasPrecedingLineBreak()) { + if (token === 124 && !scanner.hasPrecedingLineBreak()) { return parseThisTypePredicate(thisKeyword); } else { @@ -8318,7 +8062,7 @@ var ts; } } function isStartOfType() { - switch (token()) { + switch (token) { case 117: case 132: case 130: @@ -8335,12 +8079,7 @@ var ts; case 25: case 92: case 9: - case 8: - case 99: - case 84: return true; - case 36: - return lookAhead(nextTokenIsNumericLiteral); case 17: return lookAhead(isStartOfParenthesizedOrFunctionType); default: @@ -8349,7 +8088,7 @@ var ts; } function isStartOfParenthesizedOrFunctionType() { nextToken(); - return token() === 18 || isStartOfParameter() || isStartOfType(); + return token === 18 || isStartOfParameter() || isStartOfType(); } function parseArrayTypeOrHigher() { var type = parseNonArrayType(); @@ -8363,7 +8102,7 @@ var ts; } function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { var type = parseConstituentType(); - if (token() === operator) { + if (token === operator) { var types = [type]; types.pos = type.pos; while (parseOptional(operator)) { @@ -8383,20 +8122,20 @@ var ts; return parseUnionOrIntersectionType(162, parseIntersectionTypeOrHigher, 47); } function isStartOfFunctionType() { - if (token() === 25) { + if (token === 25) { return true; } - return token() === 17 && lookAhead(isUnambiguouslyStartOfFunctionType); + return token === 17 && lookAhead(isUnambiguouslyStartOfFunctionType); } function skipParameterStart() { - if (ts.isModifierKind(token())) { + if (ts.isModifierKind(token)) { parseModifiers(); } - if (isIdentifier() || token() === 97) { + if (isIdentifier() || token === 97) { nextToken(); return true; } - if (token() === 19 || token() === 15) { + if (token === 19 || token === 15) { var previousErrorCount = parseDiagnostics.length; parseIdentifierOrPattern(); return previousErrorCount === parseDiagnostics.length; @@ -8405,17 +8144,17 @@ var ts; } function isUnambiguouslyStartOfFunctionType() { nextToken(); - if (token() === 18 || token() === 22) { + if (token === 18 || token === 22) { return true; } if (skipParameterStart()) { - if (token() === 54 || token() === 24 || - token() === 53 || token() === 56) { + if (token === 54 || token === 24 || + token === 53 || token === 56) { return true; } - if (token() === 18) { + if (token === 18) { nextToken(); - if (token() === 34) { + if (token === 34) { return true; } } @@ -8437,7 +8176,7 @@ var ts; } function parseTypePredicatePrefix() { var id = parseIdentifier(); - if (token() === 124 && !scanner.hasPrecedingLineBreak()) { + if (token === 124 && !scanner.hasPrecedingLineBreak()) { nextToken(); return id; } @@ -8449,7 +8188,7 @@ var ts; if (isStartOfFunctionType()) { return parseFunctionOrConstructorType(156); } - if (token() === 92) { + if (token === 92) { return parseFunctionOrConstructorType(157); } return parseUnionTypeOrHigher(); @@ -8458,7 +8197,7 @@ var ts; return parseOptional(54) ? parseType() : undefined; } function isStartOfLeftHandSideExpression() { - switch (token()) { + switch (token) { case 97: case 95: case 93: @@ -8486,7 +8225,7 @@ var ts; if (isStartOfLeftHandSideExpression()) { return true; } - switch (token()) { + switch (token) { case 35: case 36: case 50: @@ -8508,10 +8247,10 @@ var ts; } } function isStartOfExpressionStatement() { - return token() !== 15 && - token() !== 87 && - token() !== 73 && - token() !== 55 && + return token !== 15 && + token !== 87 && + token !== 73 && + token !== 55 && isStartOfExpression(); } function parseExpression() { @@ -8530,8 +8269,8 @@ var ts; return expr; } function parseInitializer(inParameter) { - if (token() !== 56) { - if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 15) || !isStartOfExpression()) { + if (token !== 56) { + if (scanner.hasPrecedingLineBreak() || (inParameter && token === 15) || !isStartOfExpression()) { return undefined; } } @@ -8547,7 +8286,7 @@ var ts; return arrowExpression; } var expr = parseBinaryExpressionOrHigher(0); - if (expr.kind === 69 && token() === 34) { + if (expr.kind === 69 && token === 34) { return parseSimpleArrowFunctionExpression(expr); } if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { @@ -8556,7 +8295,7 @@ var ts; return parseConditionalExpressionRest(expr); } function isYieldExpression() { - if (token() === 114) { + if (token === 114) { if (inYieldContext()) { return true; } @@ -8572,7 +8311,7 @@ var ts; var node = createNode(190); nextToken(); if (!scanner.hasPrecedingLineBreak() && - (token() === 37 || isStartOfExpression())) { + (token === 37 || isStartOfExpression())) { node.asteriskToken = parseOptionalToken(37); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); @@ -8582,7 +8321,7 @@ var ts; } } function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { - ts.Debug.assert(token() === 34, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + ts.Debug.assert(token === 34, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); var node; if (asyncModifier) { node = createNode(180, asyncModifier.pos); @@ -8613,7 +8352,7 @@ var ts; return undefined; } var isAsync = !!(arrowFunction.flags & 256); - var lastToken = token(); + var lastToken = token; arrowFunction.equalsGreaterThanToken = parseExpectedToken(34, false, ts.Diagnostics._0_expected, "=>"); arrowFunction.body = (lastToken === 34 || lastToken === 15) ? parseArrowFunctionExpressionBody(isAsync) @@ -8621,25 +8360,25 @@ var ts; return finishNode(arrowFunction); } function isParenthesizedArrowFunctionExpression() { - if (token() === 17 || token() === 25 || token() === 118) { + if (token === 17 || token === 25 || token === 118) { return lookAhead(isParenthesizedArrowFunctionExpressionWorker); } - if (token() === 34) { + if (token === 34) { return 1; } return 0; } function isParenthesizedArrowFunctionExpressionWorker() { - if (token() === 118) { + if (token === 118) { nextToken(); if (scanner.hasPrecedingLineBreak()) { return 0; } - if (token() !== 17 && token() !== 25) { + if (token !== 17 && token !== 25) { return 0; } } - var first = token(); + var first = token; var second = nextToken(); if (first === 17) { if (second === 18) { @@ -8702,7 +8441,7 @@ var ts; return parseParenthesizedArrowFunctionExpressionHead(false); } function tryParseAsyncSimpleArrowFunctionExpression() { - if (token() === 118) { + if (token === 118) { var isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker); if (isUnParenthesizedAsyncArrowFunction === 1) { var asyncModifier = parseModifiersForArrowFunction(); @@ -8713,13 +8452,13 @@ var ts; return undefined; } function isUnParenthesizedAsyncArrowFunctionWorker() { - if (token() === 118) { + if (token === 118) { nextToken(); - if (scanner.hasPrecedingLineBreak() || token() === 34) { + if (scanner.hasPrecedingLineBreak() || token === 34) { return 0; } var expr = parseBinaryExpressionOrHigher(0); - if (!scanner.hasPrecedingLineBreak() && expr.kind === 69 && token() === 34) { + if (!scanner.hasPrecedingLineBreak() && expr.kind === 69 && token === 34) { return 1; } } @@ -8733,18 +8472,18 @@ var ts; if (!node.parameters) { return undefined; } - if (!allowAmbiguity && token() !== 34 && token() !== 15) { + if (!allowAmbiguity && token !== 34 && token !== 15) { return undefined; } return node; } function parseArrowFunctionExpressionBody(isAsync) { - if (token() === 15) { + if (token === 15) { return parseFunctionBlock(false, isAsync, false); } - if (token() !== 23 && - token() !== 87 && - token() !== 73 && + if (token !== 23 && + token !== 87 && + token !== 73 && isStartOfStatement() && !isStartOfExpressionStatement()) { return parseFunctionBlock(false, isAsync, true); @@ -8777,16 +8516,16 @@ var ts; while (true) { reScanGreaterToken(); var newPrecedence = getBinaryOperatorPrecedence(); - var consumeCurrentOperator = token() === 38 ? + var consumeCurrentOperator = token === 38 ? newPrecedence >= precedence : newPrecedence > precedence; if (!consumeCurrentOperator) { break; } - if (token() === 90 && inDisallowInContext()) { + if (token === 90 && inDisallowInContext()) { break; } - if (token() === 116) { + if (token === 116) { if (scanner.hasPrecedingLineBreak()) { break; } @@ -8802,13 +8541,13 @@ var ts; return leftOperand; } function isBinaryOperator() { - if (inDisallowInContext() && token() === 90) { + if (inDisallowInContext() && token === 90) { return false; } return getBinaryOperatorPrecedence() > 0; } function getBinaryOperatorPrecedence() { - switch (token()) { + switch (token) { case 52: return 1; case 51: @@ -8863,7 +8602,7 @@ var ts; } function parsePrefixUnaryExpression() { var node = createNode(185); - node.operator = token(); + node.operator = token; nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); @@ -8887,7 +8626,7 @@ var ts; return finishNode(node); } function isAwaitExpression() { - if (token() === 119) { + if (token === 119) { if (inAwaitContext()) { return true; } @@ -8902,15 +8641,18 @@ var ts; return finishNode(node); } function parseUnaryExpressionOrHigher() { - if (isUpdateExpression()) { + if (isAwaitExpression()) { + return parseAwaitExpression(); + } + if (isIncrementExpression()) { var incrementExpression = parseIncrementExpression(); - return token() === 38 ? + return token === 38 ? parseBinaryExpressionRest(getBinaryOperatorPrecedence(), incrementExpression) : incrementExpression; } - var unaryOperator = token(); + var unaryOperator = token; var simpleUnaryExpression = parseSimpleUnaryExpression(); - if (token() === 38) { + if (token === 38) { var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); if (simpleUnaryExpression.kind === 177) { parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); @@ -8922,7 +8664,7 @@ var ts; return simpleUnaryExpression; } function parseSimpleUnaryExpression() { - switch (token()) { + switch (token) { case 35: case 36: case 50: @@ -8936,16 +8678,12 @@ var ts; return parseVoidExpression(); case 25: return parseTypeAssertion(); - case 119: - if (isAwaitExpression()) { - return parseAwaitExpression(); - } default: return parseIncrementExpression(); } } - function isUpdateExpression() { - switch (token()) { + function isIncrementExpression() { + switch (token) { case 35: case 36: case 50: @@ -8953,7 +8691,6 @@ var ts; case 78: case 101: case 103: - case 119: return false; case 25: if (sourceFile.languageVariant !== 1) { @@ -8964,29 +8701,29 @@ var ts; } } function parseIncrementExpression() { - if (token() === 41 || token() === 42) { + if (token === 41 || token === 42) { var node = createNode(185); - node.operator = token(); + node.operator = token; nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); return finishNode(node); } - else if (sourceFile.languageVariant === 1 && token() === 25 && lookAhead(nextTokenIsIdentifierOrKeyword)) { + else if (sourceFile.languageVariant === 1 && token === 25 && lookAhead(nextTokenIsIdentifierOrKeyword)) { return parseJsxElementOrSelfClosingElement(true); } var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); - if ((token() === 41 || token() === 42) && !scanner.hasPrecedingLineBreak()) { + if ((token === 41 || token === 42) && !scanner.hasPrecedingLineBreak()) { var node = createNode(186, expression.pos); node.operand = expression; - node.operator = token(); + node.operator = token; nextToken(); return finishNode(node); } return expression; } function parseLeftHandSideExpressionOrHigher() { - var expression = token() === 95 + var expression = token === 95 ? parseSuperExpression() : parseMemberExpressionOrHigher(); return parseCallExpressionRest(expression); @@ -8997,7 +8734,7 @@ var ts; } function parseSuperExpression() { var expression = parseTokenNode(); - if (token() === 17 || token() === 21 || token() === 19) { + if (token === 17 || token === 21 || token === 19) { return expression; } var node = createNode(172, expression.pos); @@ -9036,7 +8773,7 @@ var ts; ts.Debug.assert(opening.kind === 242); result = opening; } - if (inExpressionContext && token() === 25) { + if (inExpressionContext && token === 25) { var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); @@ -9053,11 +8790,11 @@ var ts; } function parseJsxText() { var node = createNode(244, scanner.getStartPos()); - currentToken = scanner.scanJsxToken(); + token = scanner.scanJsxToken(); return finishNode(node); } function parseJsxChild() { - switch (token()) { + switch (token) { case 244: return parseJsxText(); case 15: @@ -9065,7 +8802,7 @@ var ts; case 25: return parseJsxElementOrSelfClosingElement(false); } - ts.Debug.fail("Unknown JSX child kind " + token()); + ts.Debug.fail("Unknown JSX child kind " + token); } function parseJsxChildren(openingTagName) { var result = []; @@ -9073,11 +8810,11 @@ var ts; var saveParsingContext = parsingContext; parsingContext |= 1 << 14; while (true) { - currentToken = scanner.reScanJsxToken(); - if (token() === 26) { + token = scanner.reScanJsxToken(); + if (token === 26) { break; } - else if (token() === 1) { + else if (token === 1) { parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); break; } @@ -9093,7 +8830,7 @@ var ts; var tagName = parseJsxElementName(); var attributes = parseList(13, parseJsxAttribute); var node; - if (token() === 27) { + if (token === 27) { node = createNode(243, fullStart); scanJsxText(); } @@ -9114,7 +8851,7 @@ var ts; } function parseJsxElementName() { scanJsxIdentifier(); - var expression = token() === 97 ? + var expression = token === 97 ? parseTokenNode() : parseIdentifierName(); while (parseOptional(21)) { var propertyAccess = createNode(172, expression.pos); @@ -9127,7 +8864,7 @@ var ts; function parseJsxExpression(inExpressionContext) { var node = createNode(248); parseExpected(15); - if (token() !== 16) { + if (token !== 16) { node.expression = parseAssignmentExpressionOrHigher(); } if (inExpressionContext) { @@ -9140,14 +8877,14 @@ var ts; return finishNode(node); } function parseJsxAttribute() { - if (token() === 15) { + if (token === 15) { return parseJsxSpreadAttribute(); } scanJsxIdentifier(); var node = createNode(246); node.name = parseIdentifierName(); if (parseOptional(56)) { - switch (token()) { + switch (token) { case 9: node.initializer = parseLiteralNode(); break; @@ -9197,7 +8934,7 @@ var ts; expression = finishNode(propertyAccess); continue; } - if (token() === 49 && !scanner.hasPrecedingLineBreak()) { + if (token === 49 && !scanner.hasPrecedingLineBreak()) { nextToken(); var nonNullExpression = createNode(196, expression.pos); nonNullExpression.expression = expression; @@ -9207,7 +8944,7 @@ var ts; if (!inDecoratorContext() && parseOptional(19)) { var indexedAccess = createNode(173, expression.pos); indexedAccess.expression = expression; - if (token() !== 20) { + if (token !== 20) { indexedAccess.argumentExpression = allowInAnd(parseExpression); if (indexedAccess.argumentExpression.kind === 9 || indexedAccess.argumentExpression.kind === 8) { var literal = indexedAccess.argumentExpression; @@ -9218,10 +8955,10 @@ var ts; expression = finishNode(indexedAccess); continue; } - if (token() === 11 || token() === 12) { + if (token === 11 || token === 12) { var tagExpression = createNode(176, expression.pos); tagExpression.tag = expression; - tagExpression.template = token() === 11 + tagExpression.template = token === 11 ? parseLiteralNode() : parseTemplateExpression(); expression = finishNode(tagExpression); @@ -9233,7 +8970,7 @@ var ts; function parseCallExpressionRest(expression) { while (true) { expression = parseMemberExpressionRest(expression); - if (token() === 25) { + if (token === 25) { var typeArguments = tryParse(parseTypeArgumentsInExpression); if (!typeArguments) { return expression; @@ -9245,7 +8982,7 @@ var ts; expression = finishNode(callExpr); continue; } - else if (token() === 17) { + else if (token === 17) { var callExpr = createNode(174, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); @@ -9274,7 +9011,7 @@ var ts; : undefined; } function canFollowTypeArgumentsInExpression() { - switch (token()) { + switch (token) { case 17: case 21: case 18: @@ -9301,7 +9038,7 @@ var ts; } } function parsePrimaryExpression() { - switch (token()) { + switch (token) { case 8: case 9: case 11: @@ -9354,8 +9091,8 @@ var ts; return finishNode(node); } function parseArgumentOrArrayLiteralElement() { - return token() === 22 ? parseSpreadElement() : - token() === 24 ? createNode(193) : + return token === 22 ? parseSpreadElement() : + token === 24 ? createNode(193) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { @@ -9392,10 +9129,10 @@ var ts; var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); var questionToken = parseOptionalToken(53); - if (asteriskToken || token() === 17 || token() === 25) { + if (asteriskToken || token === 17 || token === 25) { return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); } - var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 24 || token() === 16 || token() === 56); + var isShorthandPropertyAssignment = tokenIsIdentifier && (token === 24 || token === 16 || token === 56); if (isShorthandPropertyAssignment) { var shorthandDeclaration = createNode(254, fullStart); shorthandDeclaration.name = propertyName; @@ -9458,7 +9195,7 @@ var ts; parseExpected(92); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); - if (node.typeArguments || token() === 17) { + if (node.typeArguments || token === 17) { node.arguments = parseArgumentList(); } return finishNode(node); @@ -9531,8 +9268,8 @@ var ts; parseExpected(86); parseExpected(17); var initializer = undefined; - if (token() !== 23) { - if (token() === 102 || token() === 108 || token() === 74) { + if (token !== 23) { + if (token === 102 || token === 108 || token === 74) { initializer = parseVariableDeclarationList(true); } else { @@ -9558,11 +9295,11 @@ var ts; var forStatement = createNode(206, pos); forStatement.initializer = initializer; parseExpected(23); - if (token() !== 23 && token() !== 18) { + if (token !== 23 && token !== 18) { forStatement.condition = allowInAnd(parseExpression); } parseExpected(23); - if (token() !== 18) { + if (token !== 18) { forStatement.incrementor = allowInAnd(parseExpression); } parseExpected(18); @@ -9614,7 +9351,7 @@ var ts; return finishNode(node); } function parseCaseOrDefaultClause() { - return token() === 71 ? parseCaseClause() : parseDefaultClause(); + return token === 71 ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { var node = createNode(213); @@ -9640,8 +9377,8 @@ var ts; var node = createNode(216); parseExpected(100); node.tryBlock = parseBlock(false); - node.catchClause = token() === 72 ? parseCatchClause() : undefined; - if (!node.catchClause || token() === 85) { + node.catchClause = token === 72 ? parseCatchClause() : undefined; + if (!node.catchClause || token === 85) { parseExpected(85); node.finallyBlock = parseBlock(false); } @@ -9681,19 +9418,19 @@ var ts; } function nextTokenIsIdentifierOrKeywordOnSameLine() { nextToken(); - return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak(); + return ts.tokenIsIdentifierOrKeyword(token) && !scanner.hasPrecedingLineBreak(); } function nextTokenIsFunctionKeywordOnSameLine() { nextToken(); - return token() === 87 && !scanner.hasPrecedingLineBreak(); + return token === 87 && !scanner.hasPrecedingLineBreak(); } function nextTokenIsIdentifierOrKeywordOrNumberOnSameLine() { nextToken(); - return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8) && !scanner.hasPrecedingLineBreak(); + return (ts.tokenIsIdentifierOrKeyword(token) || token === 8) && !scanner.hasPrecedingLineBreak(); } function isDeclaration() { while (true) { - switch (token()) { + switch (token) { case 102: case 108: case 74: @@ -9721,16 +9458,16 @@ var ts; continue; case 137: nextToken(); - return token() === 15 || token() === 69 || token() === 82; + return token === 15 || token === 69 || token === 82; case 89: nextToken(); - return token() === 9 || token() === 37 || - token() === 15 || ts.tokenIsIdentifierOrKeyword(token()); + return token === 9 || token === 37 || + token === 15 || ts.tokenIsIdentifierOrKeyword(token); case 82: nextToken(); - if (token() === 56 || token() === 37 || - token() === 15 || token() === 77 || - token() === 116) { + if (token === 56 || token === 37 || + token === 15 || token === 77 || + token === 116) { return true; } continue; @@ -9746,7 +9483,7 @@ var ts; return lookAhead(isDeclaration); } function isStartOfStatement() { - switch (token()) { + switch (token) { case 55: case 23: case 15: @@ -9794,13 +9531,13 @@ var ts; } function nextTokenIsIdentifierOrStartOfDestructuring() { nextToken(); - return isIdentifier() || token() === 15 || token() === 19; + return isIdentifier() || token === 15 || token === 19; } function isLetDeclaration() { return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); } function parseStatement() { - switch (token()) { + switch (token) { case 23: return parseEmptyStatement(); case 15: @@ -9872,7 +9609,7 @@ var ts; var fullStart = getNodePos(); var decorators = parseDecorators(); var modifiers = parseModifiers(); - switch (token()) { + switch (token) { case 102: case 108: case 74: @@ -9895,7 +9632,7 @@ var ts; return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); case 82: nextToken(); - switch (token()) { + switch (token) { case 77: case 56: return parseExportAssignment(fullStart, decorators, modifiers); @@ -9916,17 +9653,17 @@ var ts; } function nextTokenIsIdentifierOrStringLiteralOnSameLine() { nextToken(); - return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9); + return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token === 9); } function parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage) { - if (token() !== 15 && canParseSemicolon()) { + if (token !== 15 && canParseSemicolon()) { parseSemicolon(); return; } return parseFunctionBlock(isGenerator, isAsync, false, diagnosticMessage); } function parseArrayBindingElement() { - if (token() === 24) { + if (token === 24) { return createNode(193); } var node = createNode(169); @@ -9939,7 +9676,7 @@ var ts; var node = createNode(169); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); - if (tokenIsIdentifier && token() !== 54) { + if (tokenIsIdentifier && token !== 54) { node.name = propertyName; } else { @@ -9965,13 +9702,13 @@ var ts; return finishNode(node); } function isIdentifierOrPattern() { - return token() === 15 || token() === 19 || isIdentifier(); + return token === 15 || token === 19 || isIdentifier(); } function parseIdentifierOrPattern() { - if (token() === 19) { + if (token === 19) { return parseArrayBindingPattern(); } - if (token() === 15) { + if (token === 15) { return parseObjectBindingPattern(); } return parseIdentifier(); @@ -9980,14 +9717,14 @@ var ts; var node = createNode(218); node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); - if (!isInOrOfKeyword(token())) { + if (!isInOrOfKeyword(token)) { node.initializer = parseInitializer(false); } return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { var node = createNode(219); - switch (token()) { + switch (token) { case 102: break; case 108: @@ -10000,7 +9737,7 @@ var ts; ts.Debug.fail(); } nextToken(); - if (token() === 138 && lookAhead(canFollowContextualOfKeyword)) { + if (token === 138 && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { @@ -10074,7 +9811,7 @@ var ts; var asteriskToken = parseOptionalToken(37); var name = parsePropertyName(); var questionToken = parseOptionalToken(53); - if (asteriskToken || token() === 17 || token() === 25) { + if (asteriskToken || token === 17 || token === 25) { return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, ts.Diagnostics.or_expected); } else { @@ -10107,31 +9844,31 @@ var ts; } function isClassMemberStart() { var idToken; - if (token() === 55) { + if (token === 55) { return true; } - while (ts.isModifierKind(token())) { - idToken = token(); + while (ts.isModifierKind(token)) { + idToken = token; if (isClassMemberModifier(idToken)) { return true; } nextToken(); } - if (token() === 37) { + if (token === 37) { return true; } if (isLiteralPropertyName()) { - idToken = token(); + idToken = token; nextToken(); } - if (token() === 19) { + if (token === 19) { return true; } if (idToken !== undefined) { if (!ts.isKeyword(idToken) || idToken === 131 || idToken === 123) { return true; } - switch (token()) { + switch (token) { case 17: case 25: case 54: @@ -10169,8 +9906,8 @@ var ts; var modifiers; while (true) { var modifierStart = scanner.getStartPos(); - var modifierKind = token(); - if (token() === 74 && permitInvalidConstAsModifier) { + var modifierKind = token; + if (token === 74 && permitInvalidConstAsModifier) { if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { break; } @@ -10196,9 +9933,9 @@ var ts; function parseModifiersForArrowFunction() { var flags = 0; var modifiers; - if (token() === 118) { + if (token === 118) { var modifierStart = scanner.getStartPos(); - var modifierKind = token(); + var modifierKind = token; nextToken(); modifiers = []; modifiers.pos = modifierStart; @@ -10210,7 +9947,7 @@ var ts; return modifiers; } function parseClassElement() { - if (token() === 23) { + if (token === 23) { var result = createNode(198); nextToken(); return finishNode(result); @@ -10222,17 +9959,17 @@ var ts; if (accessor) { return accessor; } - if (token() === 121) { + if (token === 121) { return parseConstructorDeclaration(fullStart, decorators, modifiers); } if (isIndexSignature()) { return parseIndexSignatureDeclaration(fullStart, decorators, modifiers); } - if (ts.tokenIsIdentifierOrKeyword(token()) || - token() === 9 || - token() === 8 || - token() === 37 || - token() === 19) { + if (ts.tokenIsIdentifierOrKeyword(token) || + token === 9 || + token === 8 || + token === 37 || + token === 19) { return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); } if (decorators || modifiers) { @@ -10270,7 +10007,7 @@ var ts; : undefined; } function isImplementsClause() { - return token() === 106 && lookAhead(nextTokenIsIdentifierOrKeyword); + return token === 106 && lookAhead(nextTokenIsIdentifierOrKeyword); } function parseHeritageClauses(isClassHeritageClause) { if (isHeritageClause()) { @@ -10279,9 +10016,9 @@ var ts; return undefined; } function parseHeritageClause() { - if (token() === 83 || token() === 106) { + if (token === 83 || token === 106) { var node = createNode(251); - node.token = token(); + node.token = token; nextToken(); node.types = parseDelimitedList(7, parseExpressionWithTypeArguments); return finishNode(node); @@ -10291,13 +10028,13 @@ var ts; function parseExpressionWithTypeArguments() { var node = createNode(194); node.expression = parseLeftHandSideExpressionOrHigher(); - if (token() === 25) { + if (token === 25) { node.typeArguments = parseBracketedList(18, parseType, 25, 27); } return finishNode(node); } function isHeritageClause() { - return token() === 83 || token() === 106; + return token === 83 || token === 106; } function parseClassMembers() { return parseList(5, parseClassElement); @@ -10373,14 +10110,14 @@ var ts; var node = createNode(225, fullStart); node.decorators = decorators; setModifiers(node, modifiers); - if (token() === 137) { + if (token === 137) { node.name = parseIdentifier(); node.flags |= 131072; } else { node.name = parseLiteralNode(true); } - if (token() === 15) { + if (token === 15) { node.body = parseModuleBlock(); } else { @@ -10390,7 +10127,7 @@ var ts; } function parseModuleDeclaration(fullStart, decorators, modifiers) { var flags = modifiers ? modifiers.flags : 0; - if (token() === 137) { + if (token === 137) { return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } else if (parseOptional(126)) { @@ -10398,14 +10135,14 @@ var ts; } else { parseExpected(125); - if (token() === 9) { + if (token === 9) { return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } } return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); } function isExternalModuleReference() { - return token() === 129 && + return token === 129 && lookAhead(nextTokenIsOpenParen); } function nextTokenIsOpenParen() { @@ -10430,7 +10167,7 @@ var ts; var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token() !== 24 && token() !== 136) { + if (token !== 24 && token !== 136) { var importEqualsDeclaration = createNode(229, fullStart); importEqualsDeclaration.decorators = decorators; setModifiers(importEqualsDeclaration, modifiers); @@ -10445,8 +10182,8 @@ var ts; importDeclaration.decorators = decorators; setModifiers(importDeclaration, modifiers); if (identifier || - token() === 37 || - token() === 15) { + token === 37 || + token === 15) { importDeclaration.importClause = parseImportClause(identifier, afterImportPos); parseExpected(136); } @@ -10461,7 +10198,7 @@ var ts; } if (!importClause.name || parseOptional(24)) { - importClause.namedBindings = token() === 37 ? parseNamespaceImport() : parseNamedImportsOrExports(233); + importClause.namedBindings = token === 37 ? parseNamespaceImport() : parseNamedImportsOrExports(233); } return finishNode(importClause); } @@ -10479,7 +10216,7 @@ var ts; return finishNode(node); } function parseModuleSpecifier() { - if (token() === 9) { + if (token === 9) { var result = parseLiteralNode(); internIdentifier(result.text); return result; @@ -10508,14 +10245,14 @@ var ts; } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); - var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); + var checkIdentifierIsKeyword = ts.isKeyword(token) && !isIdentifier(); var checkIdentifierStart = scanner.getTokenPos(); var checkIdentifierEnd = scanner.getTextPos(); var identifierName = parseIdentifierName(); - if (token() === 116) { + if (token === 116) { node.propertyName = identifierName; parseExpected(116); - checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); + checkIdentifierIsKeyword = ts.isKeyword(token) && !isIdentifier(); checkIdentifierStart = scanner.getTokenPos(); checkIdentifierEnd = scanner.getTextPos(); node.name = parseIdentifierName(); @@ -10538,7 +10275,7 @@ var ts; } else { node.exportClause = parseNamedImportsOrExports(237); - if (token() === 136 || (token() === 9 && !scanner.hasPrecedingLineBreak())) { + if (token === 136 || (token === 9 && !scanner.hasPrecedingLineBreak())) { parseExpected(136); node.moduleSpecifier = parseModuleSpecifier(); } @@ -10637,7 +10374,7 @@ var ts; var JSDocParser; (function (JSDocParser) { function isJSDocType() { - switch (token()) { + switch (token) { case 37: case 53: case 17: @@ -10650,13 +10387,13 @@ var ts; case 97: return true; } - return ts.tokenIsIdentifierOrKeyword(token()); + return ts.tokenIsIdentifierOrKeyword(token); } JSDocParser.isJSDocType = isJSDocType; function parseJSDocTypeExpressionForTests(content, start, length) { initializeState("file.js", content, 2, undefined, 1); scanner.setText(content, start, length); - currentToken = scanner.scan(); + token = scanner.scan(); var jsDocTypeExpression = parseJSDocTypeExpression(); var diagnostics = parseDiagnostics; clearState(); @@ -10674,12 +10411,12 @@ var ts; JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression; function parseJSDocTopLevelType() { var type = parseJSDocType(); - if (token() === 47) { + if (token === 47) { var unionType = createNode(261, type.pos); unionType.types = parseJSDocTypeList(type); type = finishNode(unionType); } - if (token() === 56) { + if (token === 56) { var optionalType = createNode(268, type.pos); nextToken(); optionalType.type = type; @@ -10690,20 +10427,20 @@ var ts; function parseJSDocType() { var type = parseBasicTypeExpression(); while (true) { - if (token() === 19) { + if (token === 19) { var arrayType = createNode(260, type.pos); arrayType.elementType = type; nextToken(); parseExpected(20); type = finishNode(arrayType); } - else if (token() === 53) { + else if (token === 53) { var nullableType = createNode(263, type.pos); nullableType.type = type; nextToken(); type = finishNode(nullableType); } - else if (token() === 49) { + else if (token === 49) { var nonNullableType = createNode(264, type.pos); nonNullableType.type = type; nextToken(); @@ -10716,7 +10453,7 @@ var ts; return type; } function parseBasicTypeExpression() { - switch (token()) { + switch (token) { case 37: return parseJSDocAllType(); case 53: @@ -10743,15 +10480,7 @@ var ts; case 120: case 133: case 103: - case 93: - case 135: - case 127: return parseTokenNode(); - case 9: - case 8: - case 99: - case 84: - return parseJSDocLiteralType(); } return parseJSDocTypeReference(); } @@ -10782,7 +10511,7 @@ var ts; result.parameters = parseDelimitedList(22, parseJSDocParameter); checkForTrailingComma(result.parameters); parseExpected(18); - if (token() === 54) { + if (token === 54) { nextToken(); result.type = parseJSDocType(); } @@ -10799,12 +10528,12 @@ var ts; function parseJSDocTypeReference() { var result = createNode(267); result.name = parseSimplePropertyName(); - if (token() === 25) { + if (token === 25) { result.typeArguments = parseTypeArguments(); } else { while (parseOptional(21)) { - if (token() === 25) { + if (token === 25) { result.typeArguments = parseTypeArguments(); break; } @@ -10847,7 +10576,7 @@ var ts; function parseJSDocRecordMember() { var result = createNode(266); result.name = parseSimplePropertyName(); - if (token() === 54) { + if (token === 54) { nextToken(); result.type = parseJSDocType(); } @@ -10896,20 +10625,15 @@ var ts; nextToken(); return finishNode(result); } - function parseJSDocLiteralType() { - var result = createNode(282); - result.literal = parseLiteralTypeNode(); - return finishNode(result); - } function parseJSDocUnknownOrNullableType() { var pos = scanner.getStartPos(); nextToken(); - if (token() === 24 || - token() === 16 || - token() === 18 || - token() === 27 || - token() === 56 || - token() === 47) { + if (token === 24 || + token === 16 || + token === 18 || + token === 27 || + token === 56 || + token === 47) { var result = createNode(259, pos); return finishNode(result); } @@ -10929,14 +10653,14 @@ var ts; } JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; function parseJSDocComment(parent, start, length) { - var saveToken = currentToken; + var saveToken = token; var saveParseDiagnosticsLength = parseDiagnostics.length; var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; var comment = parseJSDocCommentWorker(start, length); if (comment) { comment.parent = parent; } - currentToken = saveToken; + token = saveToken; parseDiagnostics.length = saveParseDiagnosticsLength; parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; return comment; @@ -10960,8 +10684,8 @@ var ts; var canParseTag = true; var seenAsterisk = true; nextJSDocToken(); - while (token() !== 1) { - switch (token()) { + while (token !== 1) { + switch (token) { case 55: if (canParseTag) { parseTag(); @@ -10999,12 +10723,12 @@ var ts; return finishNode(result, end); } function skipWhitespace() { - while (token() === 5 || token() === 4) { + while (token === 5 || token === 4) { nextJSDocToken(); } } function parseTag() { - ts.Debug.assert(token() === 55); + ts.Debug.assert(token === 55); var atToken = createNode(55, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); @@ -11050,7 +10774,7 @@ var ts; } } function tryParseTypeExpression() { - if (token() !== 15) { + if (token !== 15) { return undefined; } var typeExpression = parseJSDocTypeExpression(); @@ -11069,7 +10793,7 @@ var ts; } parseExpected(20); } - else if (ts.tokenIsIdentifierOrKeyword(token())) { + else if (ts.tokenIsIdentifierOrKeyword(token)) { name = parseJSDocIdentifierName(); } if (!name) { @@ -11162,15 +10886,12 @@ var ts; var canParseTag = true; var seenAsterisk = false; var parentTagTerminated = false; - while (token() !== 1 && !parentTagTerminated) { + while (token !== 1 && !parentTagTerminated) { nextJSDocToken(); - switch (token()) { + switch (token) { case 55: if (canParseTag) { parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral); - if (!parentTagTerminated) { - resumePos = scanner.getStartPos(); - } } seenAsterisk = false; break; @@ -11196,7 +10917,7 @@ var ts; } } function tryParseChildTag(parentTag) { - ts.Debug.assert(token() === 55); + ts.Debug.assert(token === 55); var atToken = createNode(55, scanner.getStartPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); @@ -11238,7 +10959,7 @@ var ts; typeParameter.name = name_9; finishNode(typeParameter); typeParameters.push(typeParameter); - if (token() === 24) { + if (token === 24) { nextJSDocToken(); } else { @@ -11254,10 +10975,10 @@ var ts; return result; } function nextJSDocToken() { - return currentToken = scanner.scanJSDocToken(); + return token = scanner.scanJSDocToken(); } function parseJSDocIdentifierName() { - return createJSDocIdentifier(ts.tokenIsIdentifierOrKeyword(token())); + return createJSDocIdentifier(ts.tokenIsIdentifierOrKeyword(token)); } function createJSDocIdentifier(isIdentifier) { if (!isIdentifier) { @@ -11337,8 +11058,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { - var node = array_9[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } } @@ -11410,8 +11131,8 @@ var ts; array.intersectsChange = true; array._children = undefined; adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_10 = array; _i < array_10.length; _i++) { - var node = array_10[_i]; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; visitNode(node); } return; @@ -11563,434 +11284,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function tryReadTypesSection(packageJsonPath, baseDirectory, state) { - var jsonContent = ts.readJson(packageJsonPath, state.host); - function tryReadFromField(fieldName) { - if (ts.hasProperty(jsonContent, fieldName)) { - var typesFile = jsonContent[fieldName]; - if (typeof typesFile === "string") { - var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1); - } - return typesFilePath_1; - } - else { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); - } - } - } - } - var typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); - if (typesFilePath) { - return typesFilePath; - } - if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); - } - var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); - return mainFilePath; - } - return undefined; - } - function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures && state.host.fileExists(fileName)) { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); - } - return fileName; - } - else { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); - } - failedLookupLocation.push(fileName); - return undefined; - } - } - function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures) { - var directory = ts.getDirectoryPath(candidate); - if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); - } - } - return ts.forEach(extensions, function (ext) { - return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); - }); - } - function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); - if (resolvedByAddingExtension) { - return resolvedByAddingExtension; - } - if (ts.hasJavaScriptFileExtension(candidate)) { - var extensionless = ts.removeFileExtension(candidate); - if (state.traceEnabled) { - var extension = candidate.substring(extensionless.length); - ts.trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); - } - return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); - } - } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { - var packageJsonPath = pathToPackageJson(candidate); - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - if (directoryExists && state.host.fileExists(packageJsonPath)) { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); - if (typesFile) { - var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); - var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) || - tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state); - if (result) { - return result; - } - } - else { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field); - } - } - } - else { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); - } - failedLookupLocation.push(packageJsonPath); - } - return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); - } - ts.loadNodeModuleFromDirectory = loadNodeModuleFromDirectory; - function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { - var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions); - var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - } - function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state, checkOneLevel) { - directory = ts.normalizeSlashes(directory); - while (true) { - var baseName = ts.getBaseFileName(directory); - if (baseName !== "node_modules") { - var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); - if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { - return packageResult; - } - else { - var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); - if (typesResult || packageResult) { - return typesResult || packageResult; - } - } - } - var parentPath = ts.getDirectoryPath(directory); - if (parentPath === directory || checkOneLevel) { - break; - } - directory = parentPath; - } - return undefined; - } - ts.loadModuleFromNodeModules = loadModuleFromNodeModules; - function moduleHasNonRelativeName(moduleName) { - return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); - } - function classicNameResolver(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = ts.isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; - var failedLookupLocations = []; - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var containingDirectory = ts.getDirectoryPath(containingFile); - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); - if (resolvedFileName) { - return ts.createResolvedModule(resolvedFileName, false, failedLookupLocations); - } - var referencedSourceFile; - if (moduleHasNonRelativeName(moduleName)) { - while (true) { - var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state); - if (referencedSourceFile) { - break; - } - var parentPath = ts.getDirectoryPath(containingDirectory); - if (parentPath === containingDirectory) { - break; - } - containingDirectory = parentPath; - } - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, false, state); - } - return referencedSourceFile - ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } - : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; - } - ts.classicNameResolver = classicNameResolver; - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { - var containingDirectory = ts.getDirectoryPath(containingFile); - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var traceEnabled = ts.isTraceEnabled(compilerOptions, host); - var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); - var isExternalLibraryImport = false; - if (!resolvedFileName) { - if (moduleHasNonRelativeName(moduleName)) { - if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); - } - resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state, false); - isExternalLibraryImport = resolvedFileName !== undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, false, state); - } - } - if (resolvedFileName && host.realpath) { - var originalFileName = resolvedFileName; - resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName)); - if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); - } - } - return ts.createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; - function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); - } - var resolvedFileName = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); - return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); - } - function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.rootDirs) { - return undefined; - } - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); - } - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var matchedRootDir; - var matchedNormalizedPrefix; - for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { - var rootDir = _a[_i]; - var normalizedRoot = ts.normalizePath(rootDir); - if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { - normalizedRoot += ts.directorySeparator; - } - var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && - (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); - } - if (isLongestMatchingPrefix) { - matchedNormalizedPrefix = normalizedRoot; - matchedRootDir = rootDir; - } - } - if (matchedNormalizedPrefix) { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); - } - var suffix = candidate.substr(matchedNormalizedPrefix.length); - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); - } - for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { - var rootDir = _c[_b]; - if (rootDir === matchedRootDir) { - continue; - } - var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); - } - var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); - if (resolvedFileName_1) { - return resolvedFileName_1; - } - } - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); - } - } - return undefined; - } - function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.baseUrl) { - return undefined; - } - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); - } - var matchedPattern = undefined; - if (state.compilerOptions.paths) { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); - } - matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName); - var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern); - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); - } - for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) { - var subst = _a[_i]; - var path = matchedStar ? subst.replace("*", matchedStar) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - } - return undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - } - } - function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (moduleHasNonRelativeName(moduleName)) { - return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); - } - else { - return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); - } - } - function resolveModuleName(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = ts.isTraceEnabled(compilerOptions, host); - if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); - } - var moduleResolution = compilerOptions.moduleResolution; - if (moduleResolution === undefined) { - moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; - if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - else { - if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - var result; - switch (moduleResolution) { - case ts.ModuleResolutionKind.NodeJs: - result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); - break; - case ts.ModuleResolutionKind.Classic: - result = classicNameResolver(moduleName, containingFile, compilerOptions, host); - break; - } - if (traceEnabled) { - if (result.resolvedModule) { - ts.trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); - } - else { - ts.trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); - } - } - return result; - } - ts.resolveModuleName = resolveModuleName; - function matchPatternOrExact(patternStrings, candidate) { - var patterns = []; - for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { - var patternString = patternStrings_1[_i]; - var pattern = tryParsePattern(patternString); - if (pattern) { - patterns.push(pattern); - } - else if (patternString === candidate) { - return patternString; - } - } - return findBestPatternMatch(patterns, function (_) { return _; }, candidate); - } - function patternText(_a) { - var prefix = _a.prefix, suffix = _a.suffix; - return prefix + "*" + suffix; - } - function matchedText(pattern, candidate) { - ts.Debug.assert(isPatternMatch(pattern, candidate)); - return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); - } - function findBestPatternMatch(values, getPattern, candidate) { - var matchedValue = undefined; - var longestMatchPrefixLength = -1; - for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { - var v = values_1[_i]; - var pattern = getPattern(v); - if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { - longestMatchPrefixLength = pattern.prefix.length; - matchedValue = v; - } - } - return matchedValue; - } - ts.findBestPatternMatch = findBestPatternMatch; - function isPatternMatch(_a, candidate) { - var prefix = _a.prefix, suffix = _a.suffix; - return candidate.length >= prefix.length + suffix.length && - ts.startsWith(candidate, prefix) && - ts.endsWith(candidate, suffix); - } - function tryParsePattern(pattern) { - ts.Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern)); - var indexOfStar = pattern.indexOf("*"); - return indexOfStar === -1 ? undefined : { - prefix: pattern.substr(0, indexOfStar), - suffix: pattern.substr(indexOfStar + 1) - }; - } - ts.tryParsePattern = tryParsePattern; - function directoryProbablyExists(directoryName, host) { - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - ts.pathToPackageJson = pathToPackageJson; -})(ts || (ts = {})); -var ts; -(function (ts) { + ts.bindTime = 0; function getModuleInstanceState(node) { if (node.kind === 222 || node.kind === 223) { return 0; @@ -12028,10 +11322,9 @@ var ts; ts.getModuleInstanceState = getModuleInstanceState; var binder = createBinder(); function bindSourceFile(file, options) { - ts.performance.mark("beforeBind"); + var start = new Date().getTime(); binder(file, options); - ts.performance.mark("afterBind"); - ts.performance.measure("Bind", "beforeBind", "afterBind"); + ts.bindTime += new Date().getTime() - start; } ts.bindSourceFile = bindSourceFile; function createBinder() { @@ -12064,7 +11357,7 @@ var ts; options = opts; languageVersion = ts.getEmitScriptTarget(options); inStrictMode = !!file.externalModuleIndicator; - classifiableNames = ts.createMap(); + classifiableNames = {}; symbolCount = 0; Symbol = ts.objectAllocator.getSymbolConstructor(); if (!file.locals) { @@ -12103,10 +11396,10 @@ var ts; } symbol.declarations.push(node); if (symbolFlags & 1952 && !symbol.exports) { - symbol.exports = ts.createMap(); + symbol.exports = {}; } if (symbolFlags & 6240 && !symbol.members) { - symbol.members = ts.createMap(); + symbol.members = {}; } if (symbolFlags & 107455) { var valueDeclaration = symbol.valueDeclaration; @@ -12190,38 +11483,35 @@ var ts; var isDefaultExport = node.flags & 512; var name = isDefaultExport && parent ? "default" : getDeclarationName(node); var symbol; - if (name === undefined) { - symbol = createSymbol(0, "__missing"); - } - else { - symbol = symbolTable[name] || (symbolTable[name] = createSymbol(0, name)); + if (name !== undefined) { + symbol = ts.hasProperty(symbolTable, name) + ? symbolTable[name] + : (symbolTable[name] = createSymbol(0, name)); if (name && (includes & 788448)) { classifiableNames[name] = name; } if (symbol.flags & excludes) { - if (symbol.isReplaceableByMethod) { - symbol = symbolTable[name] = createSymbol(0, name); + if (node.name) { + node.name.parent = node; } - else { - if (node.name) { - node.name.parent = node; + var message_1 = symbol.flags & 2 + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + : ts.Diagnostics.Duplicate_identifier_0; + ts.forEach(symbol.declarations, function (declaration) { + if (declaration.flags & 512) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; } - var message_1 = symbol.flags & 2 - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - ts.forEach(symbol.declarations, function (declaration) { - if (declaration.flags & 512) { - message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; - } - }); - ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); - }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); - symbol = createSymbol(0, name); - } + }); + ts.forEach(symbol.declarations, function (declaration) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); + }); + file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); + symbol = createSymbol(0, name); } } + else { + symbol = createSymbol(0, "__missing"); + } addDeclarationToSymbol(symbol, node, includes); symbol.parent = parent; return symbol; @@ -12239,8 +11529,8 @@ var ts; else { if (!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 8192)) { var exportKind = (symbolFlags & 107455 ? 1048576 : 0) | - (symbolFlags & 793064 ? 2097152 : 0) | - (symbolFlags & 1920 ? 4194304 : 0); + (symbolFlags & 793056 ? 2097152 : 0) | + (symbolFlags & 1536 ? 4194304 : 0); var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; @@ -12257,7 +11547,7 @@ var ts; if (containerFlags & 1) { container = blockScopeContainer = node; if (containerFlags & 32) { - container.locals = ts.createMap(); + container.locals = {}; } addToContainerChain(container); } @@ -12432,9 +11722,15 @@ var ts; } return false; } + function isNarrowingNullCheckOperands(expr1, expr2) { + return (expr1.kind === 93 || expr1.kind === 69 && expr1.text === "undefined") && isNarrowableOperand(expr2); + } function isNarrowingTypeofOperands(expr1, expr2) { return expr1.kind === 182 && isNarrowableOperand(expr1.expression) && expr2.kind === 9; } + function isNarrowingDiscriminant(expr) { + return expr.kind === 172 && isNarrowableReference(expr.expression); + } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { case 56: @@ -12443,8 +11739,9 @@ var ts; case 31: case 32: case 33: - return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || - isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); + return isNarrowingNullCheckOperands(expr.right, expr.left) || isNarrowingNullCheckOperands(expr.left, expr.right) || + isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right) || + isNarrowingDiscriminant(expr.left) || isNarrowingDiscriminant(expr.right); case 91: return isNarrowableOperand(expr.left); case 24: @@ -12466,6 +11763,10 @@ var ts; } return isNarrowableReference(expr); } + function isNarrowingSwitchStatement(switchStatement) { + var expr = switchStatement.expression; + return expr.kind === 172 && isNarrowableReference(expr.expression); + } function createBranchLabel() { return { flags: 4, @@ -12509,7 +11810,7 @@ var ts; }; } function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { - if (!isNarrowingExpression(switchStatement.expression)) { + if (!isNarrowingSwitchStatement(switchStatement)) { return antecedent; } setFlowNodeReferenced(antecedent); @@ -13097,12 +12398,12 @@ var ts; addDeclarationToSymbol(symbol, node, 131072); var typeLiteralSymbol = createSymbol(2048, "__type"); addDeclarationToSymbol(typeLiteralSymbol, node, 2048); - typeLiteralSymbol.members = ts.createMap(); - typeLiteralSymbol.members[symbol.name] = symbol; + typeLiteralSymbol.members = (_a = {}, _a[symbol.name] = symbol, _a); + var _a; } function bindObjectLiteralExpression(node) { if (inStrictMode) { - var seen = ts.createMap(); + var seen = {}; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; if (prop.name.kind !== 69) { @@ -13141,7 +12442,7 @@ var ts; } default: if (!blockScopeContainer.locals) { - blockScopeContainer.locals = ts.createMap(); + blockScopeContainer.locals = {}; addToContainerChain(blockScopeContainer); } declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); @@ -13354,7 +12655,7 @@ var ts; case 154: return checkTypePredicate(node); case 141: - return declareSymbolAndAddToSymbolTable(node, 262144, 530920); + return declareSymbolAndAddToSymbolTable(node, 262144, 530912); case 142: return bindParameter(node); case 218: @@ -13370,7 +12671,7 @@ var ts; case 254: return bindPropertyOrMethodOrAccessor(node, 4, 0); case 255: - return bindPropertyOrMethodOrAccessor(node, 8, 900095); + return bindPropertyOrMethodOrAccessor(node, 8, 107455); case 247: emitFlags |= 1073741824; return; @@ -13412,10 +12713,10 @@ var ts; inStrictMode = true; return bindClassLikeDeclaration(node); case 222: - return bindBlockScopedDeclaration(node, 64, 792968); + return bindBlockScopedDeclaration(node, 64, 792960); case 279: case 223: - return bindBlockScopedDeclaration(node, 524288, 793064); + return bindBlockScopedDeclaration(node, 524288, 793056); case 224: return bindEnumDeclaration(node); case 225: @@ -13464,14 +12765,15 @@ var ts; bindAnonymousDeclaration(file, 512, "\"" + ts.removeFileExtension(file.fileName) + "\""); } function bindExportAssignment(node) { + var boundExpression = node.kind === 235 ? node.expression : node.right; if (!container.symbol || !container.symbol.exports) { bindAnonymousDeclaration(node, 8388608, getDeclarationName(node)); } + else if (boundExpression.kind === 69 && node.kind === 235) { + declareSymbol(container.symbol.exports, container.symbol, node, 8388608, 0 | 8388608); + } else { - var flags = node.kind === 235 && ts.exportAssignmentIsAlias(node) - ? 8388608 - : 4; - declareSymbol(container.symbol.exports, container.symbol, node, flags, 0 | 8388608); + declareSymbol(container.symbol.exports, container.symbol, node, 4, 0 | 8388608); } } function bindNamespaceExportDeclaration(node) { @@ -13493,7 +12795,7 @@ var ts; return; } } - file.symbol.globalExports = file.symbol.globalExports || ts.createMap(); + file.symbol.globalExports = file.symbol.globalExports || {}; declareSymbol(file.symbol.globalExports, file.symbol, node, 8388608, 8388608); } function bindExportDeclaration(node) { @@ -13524,20 +12826,18 @@ var ts; declareSymbol(file.symbol.exports, file.symbol, node, 4 | 7340032 | 512, 0); } function bindThisPropertyAssignment(node) { - ts.Debug.assert(ts.isInJavaScriptFile(node)); - if (container.kind === 220 || container.kind === 179) { - container.symbol.members = container.symbol.members || ts.createMap(); - declareSymbol(container.symbol.members, container.symbol, node, 4, 0 & ~4); + var assignee; + if (container.kind === 220 || container.kind === 220) { + assignee = container; } else if (container.kind === 148) { - var saveContainer = container; - container = container.parent; - var symbol = bindPropertyOrMethodOrAccessor(node, 4, 0); - if (symbol) { - symbol.isReplaceableByMethod = true; - } - container = saveContainer; + assignee = container.parent; } + else { + return; + } + assignee.symbol.members = assignee.symbol.members || {}; + declareSymbol(assignee.symbol.members, assignee.symbol, node, 4, 0 & ~4); } function bindPrototypePropertyAssignment(node) { var leftSideOfAssignment = node.left; @@ -13551,7 +12851,7 @@ var ts; return; } if (!funcSymbol.members) { - funcSymbol.members = ts.createMap(); + funcSymbol.members = {}; } declareSymbol(funcSymbol.members, funcSymbol, leftSideOfAssignment, 4, 0); } @@ -13581,7 +12881,7 @@ var ts; } var symbol = node.symbol; var prototypeSymbol = createSymbol(4 | 134217728, "prototype"); - if (symbol.exports[prototypeSymbol.name]) { + if (ts.hasProperty(symbol.exports, prototypeSymbol.name)) { if (node.name) { node.name.parent = node; } @@ -13706,7 +13006,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var ambientModuleSymbolRegex = /^".+"$/; var nextSymbolId = 1; var nextNodeId = 1; var nextMergeId = 1; @@ -13719,6 +13018,7 @@ var ts; return node.id; } ts.getNodeId = getNodeId; + ts.checkTime = 0; function getSymbolId(symbol) { if (!symbol.id) { symbol.id = nextSymbolId; @@ -13735,7 +13035,7 @@ var ts; var typeCount = 0; var symbolCount = 0; var emptyArray = []; - var emptySymbols = ts.createMap(); + var emptySymbols = {}; var compilerOptions = host.getCompilerOptions(); var languageVersion = compilerOptions.target || 0; var modulekind = ts.getEmitModuleKind(compilerOptions); @@ -13787,43 +13087,34 @@ var ts; getAliasedSymbol: resolveAlias, getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, - getAmbientModules: getAmbientModules, getJsxElementAttributesType: getJsxElementAttributesType, getJsxIntrinsicTagNames: getJsxIntrinsicTagNames, isOptionalParameter: isOptionalParameter }; - var tupleTypes = []; - var unionTypes = ts.createMap(); - var intersectionTypes = ts.createMap(); - var stringLiteralTypes = ts.createMap(); - var numericLiteralTypes = ts.createMap(); var unknownSymbol = createSymbol(4 | 67108864, "unknown"); var resolvingSymbol = createSymbol(67108864, "__resolving__"); var anyType = createIntrinsicType(1, "any"); - var unknownType = createIntrinsicType(1, "unknown"); - var undefinedType = createIntrinsicType(2048, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 | 33554432, "undefined"); - var nullType = createIntrinsicType(4096, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(4096 | 33554432, "null"); var stringType = createIntrinsicType(2, "string"); var numberType = createIntrinsicType(4, "number"); - var trueType = createIntrinsicType(128, "true"); - var falseType = createIntrinsicType(128, "false"); - var booleanType = createBooleanType([trueType, falseType]); - var esSymbolType = createIntrinsicType(512, "symbol"); - var voidType = createIntrinsicType(1024, "void"); - var neverType = createIntrinsicType(8192, "never"); + var booleanType = createIntrinsicType(8, "boolean"); + var esSymbolType = createIntrinsicType(16777216, "symbol"); + var voidType = createIntrinsicType(16, "void"); + var undefinedType = createIntrinsicType(32, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32 | 2097152, "undefined"); + var nullType = createIntrinsicType(64, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(64 | 2097152, "null"); + var unknownType = createIntrinsicType(1, "unknown"); + var neverType = createIntrinsicType(134217728, "never"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - emptyGenericType.instantiations = ts.createMap(); + emptyGenericType.instantiations = {}; var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - anyFunctionType.flags |= 134217728; + anyFunctionType.flags |= 8388608; var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var anySignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, undefined, 0, false, false); var unknownSignature = createSignature(undefined, undefined, undefined, emptyArray, unknownType, undefined, 0, false, false); - var resolvingSignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, undefined, 0, false, false); var enumNumberIndexInfo = createIndexInfo(stringType, true); - var globals = ts.createMap(); + var globals = {}; var patternAmbientModules; var getGlobalESSymbolConstructorSymbol; var getGlobalPromiseConstructorSymbol; @@ -13859,8 +13150,10 @@ var ts; var flowLoopStart = 0; var flowLoopCount = 0; var visitedFlowCount = 0; - var emptyStringType = getLiteralTypeForText(32, ""); - var zeroType = getLiteralTypeForText(64, "0"); + var tupleTypes = {}; + var unionTypes = {}; + var intersectionTypes = {}; + var stringLiteralTypes = {}; var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; @@ -13876,7 +13169,7 @@ var ts; var potentialThisCollisions = []; var awaitedTypeStack = []; var diagnostics = ts.createDiagnosticCollection(); - var typeofEQFacts = ts.createMap({ + var typeofEQFacts = { "string": 1, "number": 2, "boolean": 4, @@ -13884,8 +13177,8 @@ var ts; "undefined": 16384, "object": 16, "function": 32 - }); - var typeofNEFacts = ts.createMap({ + }; + var typeofNEFacts = { "string": 128, "number": 256, "boolean": 512, @@ -13893,16 +13186,16 @@ var ts; "undefined": 131072, "object": 2048, "function": 4096 - }); - var typeofTypesByName = ts.createMap({ + }; + var typeofTypesByName = { "string": stringType, "number": numberType, "boolean": booleanType, "symbol": esSymbolType, "undefined": undefinedType - }); + }; var jsxElementType; - var jsxTypes = ts.createMap(); + var jsxTypes = {}; var JsxNames = { JSX: "JSX", IntrinsicElements: "IntrinsicElements", @@ -13912,14 +13205,15 @@ var ts; IntrinsicAttributes: "IntrinsicAttributes", IntrinsicClassAttributes: "IntrinsicClassAttributes" }; - var subtypeRelation = ts.createMap(); - var assignableRelation = ts.createMap(); - var comparableRelation = ts.createMap(); - var identityRelation = ts.createMap(); - var enumRelation = ts.createMap(); + var subtypeRelation = {}; + var assignableRelation = {}; + var comparableRelation = {}; + var identityRelation = {}; var _displayBuilder; - var builtinGlobals = ts.createMap(); - builtinGlobals[undefinedSymbol.name] = undefinedSymbol; + var builtinGlobals = (_a = {}, + _a[undefinedSymbol.name] = undefinedSymbol, + _a + ); initializeTypeChecker(); return checker; function getEmitResolver(sourceFile, cancellationToken) { @@ -13945,13 +13239,13 @@ var ts; if (flags & 4) result |= 0; if (flags & 8) - result |= 900095; + result |= 107455; if (flags & 16) result |= 106927; if (flags & 32) result |= 899519; if (flags & 64) - result |= 792968; + result |= 792960; if (flags & 256) result |= 899327; if (flags & 128) @@ -13965,9 +13259,9 @@ var ts; if (flags & 65536) result |= 74687; if (flags & 262144) - result |= 530920; + result |= 530912; if (flags & 524288) - result |= 793064; + result |= 793056; if (flags & 8388608) result |= 8388608; return result; @@ -13988,9 +13282,9 @@ var ts; if (symbol.constEnumOnlyModule) result.constEnumOnlyModule = true; if (symbol.members) - result.members = ts.cloneMap(symbol.members); + result.members = cloneSymbolTable(symbol.members); if (symbol.exports) - result.exports = ts.cloneMap(symbol.exports); + result.exports = cloneSymbolTable(symbol.exports); recordMergedSymbol(result, symbol); return result; } @@ -14010,12 +13304,12 @@ var ts; }); if (source.members) { if (!target.members) - target.members = ts.createMap(); + target.members = {}; mergeSymbolTable(target.members, source.members); } if (source.exports) { if (!target.exports) - target.exports = ts.createMap(); + target.exports = {}; mergeSymbolTable(target.exports, source.exports); } recordMergedSymbol(target, source); @@ -14031,17 +13325,28 @@ var ts; }); } } + function cloneSymbolTable(symbolTable) { + var result = {}; + for (var id in symbolTable) { + if (ts.hasProperty(symbolTable, id)) { + result[id] = symbolTable[id]; + } + } + return result; + } function mergeSymbolTable(target, source) { for (var id in source) { - var targetSymbol = target[id]; - if (!targetSymbol) { - target[id] = source[id]; - } - else { - if (!(targetSymbol.flags & 33554432)) { - target[id] = targetSymbol = cloneSymbol(targetSymbol); + if (ts.hasProperty(source, id)) { + if (!ts.hasProperty(target, id)) { + target[id] = source[id]; + } + else { + var symbol = target[id]; + if (!(symbol.flags & 33554432)) { + target[id] = symbol = cloneSymbol(symbol); + } + mergeSymbol(symbol, source[id]); } - mergeSymbol(targetSymbol, source[id]); } } } @@ -14063,7 +13368,7 @@ var ts; return; } mainModule = resolveExternalModuleSymbol(mainModule); - if (mainModule.flags & 1920) { + if (mainModule.flags & 1536) { mainModule = mainModule.flags & 33554432 ? mainModule : cloneSymbol(mainModule); mergeSymbol(mainModule, moduleAugmentation.symbol); } @@ -14074,11 +13379,13 @@ var ts; } function addToSymbolTable(target, source, message) { for (var id in source) { - if (target[id]) { - ts.forEach(target[id].declarations, addDeclarationDiagnostic(id, message)); - } - else { - target[id] = source[id]; + if (ts.hasProperty(source, id)) { + if (ts.hasProperty(target, id)) { + ts.forEach(target[id].declarations, addDeclarationDiagnostic(id, message)); + } + else { + target[id] = source[id]; + } } } function addDeclarationDiagnostic(id, message) { @@ -14093,25 +13400,23 @@ var ts; } function getNodeLinks(node) { var nodeId = getNodeId(node); - return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); + return nodeLinks[nodeId] || (nodeLinks[nodeId] = {}); } function isGlobalSourceFile(node) { return node.kind === 256 && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { - if (meaning) { + if (meaning && ts.hasProperty(symbols, name)) { var symbol = symbols[name]; - if (symbol) { - ts.Debug.assert((symbol.flags & 16777216) === 0, "Should never get an instantiated symbol here."); - if (symbol.flags & meaning) { + ts.Debug.assert((symbol.flags & 16777216) === 0, "Should never get an instantiated symbol here."); + if (symbol.flags & meaning) { + return symbol; + } + if (symbol.flags & 8388608) { + var target = resolveAlias(symbol); + if (target === unknownSymbol || target.flags & meaning) { return symbol; } - if (symbol.flags & 8388608) { - var target = resolveAlias(symbol); - if (target === unknownSymbol || target.flags & meaning) { - return symbol; - } - } } } } @@ -14195,7 +13500,7 @@ var ts; if (result = getSymbol(location.locals, name, meaning)) { var useResult = true; if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { - if (meaning & result.flags & 793064 && lastLocation.kind !== 273) { + if (meaning & result.flags & 793056 && lastLocation.kind !== 273) { useResult = result.flags & 262144 ? lastLocation === location.type || lastLocation.kind === 142 || @@ -14232,7 +13537,7 @@ var ts; } result = undefined; } - if (moduleExports[name] && + if (ts.hasProperty(moduleExports, name) && moduleExports[name].flags === 8388608 && ts.getDeclarationOfKind(moduleExports[name], 238)) { break; @@ -14261,7 +13566,7 @@ var ts; case 221: case 192: case 222: - if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064)) { + if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056)) { if (lastLocation && lastLocation.flags & 32) { error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); return undefined; @@ -14279,7 +13584,7 @@ var ts; case 140: grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 222) { - if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793064)) { + if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793056)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -14330,9 +13635,8 @@ var ts; } if (!result) { if (nameNotFoundMessage) { - if (!errorLocation || - !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && - !checkAndReportErrorForExtendingInterface(errorLocation)) { + if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForExtendingInterface(errorLocation)) { error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); } } @@ -14350,7 +13654,7 @@ var ts; checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } - if (result && isInExternalModule && (meaning & 107455) === 107455) { + if (result && isInExternalModule) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 228) { error(errorLocation, ts.Diagnostics.Identifier_0_must_be_imported_from_a_module, name); @@ -14360,7 +13664,7 @@ var ts; return result; } function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { - if ((errorLocation.kind === 69 && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { + if (!errorLocation || (errorLocation.kind === 69 && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { return false; } var container = ts.getThisContainer(errorLocation, true); @@ -14389,30 +13693,33 @@ var ts; return false; } function checkAndReportErrorForExtendingInterface(errorLocation) { - var expression = getEntityNameForExtendingInterface(errorLocation); - var isError = !!(expression && resolveEntityName(expression, 64, true)); - if (isError) { + var parentClassExpression = errorLocation; + while (parentClassExpression) { + var kind = parentClassExpression.kind; + if (kind === 69 || kind === 172) { + parentClassExpression = parentClassExpression.parent; + continue; + } + if (kind === 194) { + break; + } + return false; + } + if (!parentClassExpression) { + return false; + } + var expression = parentClassExpression.expression; + if (resolveEntityName(expression, 64, true)) { error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); + return true; } - return isError; - } - function getEntityNameForExtendingInterface(node) { - switch (node.kind) { - case 69: - case 172: - return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; - case 194: - ts.Debug.assert(ts.isEntityNameExpression(node.expression)); - return node.expression; - default: - return undefined; - } + return false; } function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert((result.flags & 2) !== 0); var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) ? d : undefined; }); ts.Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined"); - if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 218), errorLocation)) { + if (!isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 218), errorLocation)) { error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); } } @@ -14450,7 +13757,7 @@ var ts; function getTargetOfImportClause(node) { var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { - var exportDefaultSymbol = ts.isShorthandAmbientModuleSymbol(moduleSymbol) ? + var exportDefaultSymbol = ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration) ? moduleSymbol : moduleSymbol.exports["export="] ? getPropertyOfType(getTypeOfSymbol(moduleSymbol.exports["export="]), "default") : @@ -14469,7 +13776,7 @@ var ts; return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier); } function combineValueAndTypeSymbols(valueSymbol, typeSymbol) { - if (valueSymbol.flags & (793064 | 1920)) { + if (valueSymbol.flags & (793056 | 1536)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.name); @@ -14485,9 +13792,9 @@ var ts; } function getExportOfModule(symbol, name) { if (symbol.flags & 1536) { - var exportedSymbol = getExportsOfSymbol(symbol)[name]; - if (exportedSymbol) { - return resolveSymbol(exportedSymbol); + var exports = getExportsOfSymbol(symbol); + if (ts.hasProperty(exports, name)) { + return resolveSymbol(exports[name]); } } } @@ -14505,7 +13812,7 @@ var ts; if (targetSymbol) { var name_10 = specifier.propertyName || specifier.name; if (name_10.text) { - if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + if (ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration)) { return moduleSymbol; } var symbolFromVariable = void 0; @@ -14517,9 +13824,6 @@ var ts; } symbolFromVariable = resolveSymbol(symbolFromVariable); var symbolFromModule = getExportOfModule(targetSymbol, name_10.text); - if (!symbolFromModule && allowSyntheticDefaultImports && name_10.text === "default") { - symbolFromModule = resolveExternalModuleSymbol(moduleSymbol) || resolveSymbol(moduleSymbol); - } var symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; @@ -14539,10 +13843,10 @@ var ts; function getTargetOfExportSpecifier(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 107455 | 793064 | 1920); + resolveEntityName(node.propertyName || node.name, 107455 | 793056 | 1536); } function getTargetOfExportAssignment(node) { - return resolveEntityName(node.expression, 107455 | 793064 | 1920); + return resolveEntityName(node.expression, 107455 | 793056 | 1536); } function getTargetOfAliasDeclaration(node) { switch (node.kind) { @@ -14563,7 +13867,7 @@ var ts; } } function resolveSymbol(symbol) { - return symbol && symbol.flags & 8388608 && !(symbol.flags & (107455 | 793064 | 1920)) ? resolveAlias(symbol) : symbol; + return symbol && symbol.flags & 8388608 && !(symbol.flags & (107455 | 793056 | 1536)) ? resolveAlias(symbol) : symbol; } function resolveAlias(symbol) { ts.Debug.assert((symbol.flags & 8388608) !== 0, "Should only get Alias here."); @@ -14571,7 +13875,6 @@ var ts; if (!links.target) { links.target = resolvingSymbol; var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); var target = getTargetOfAliasDeclaration(node); if (links.target === resolvingSymbol) { links.target = target || unknownSymbol; @@ -14601,7 +13904,6 @@ var ts; if (!links.referenced) { links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); if (node.kind === 235) { checkExpressionCached(node.expression); } @@ -14618,11 +13920,11 @@ var ts; entityName = entityName.parent; } if (entityName.kind === 69 || entityName.parent.kind === 139) { - return resolveEntityName(entityName, 1920, false, dontResolveAlias); + return resolveEntityName(entityName, 1536, false, dontResolveAlias); } else { ts.Debug.assert(entityName.parent.kind === 229); - return resolveEntityName(entityName, 107455 | 793064 | 1920, false, dontResolveAlias); + return resolveEntityName(entityName, 107455 | 793056 | 1536, false, dontResolveAlias); } } function getFullyQualifiedName(symbol) { @@ -14634,7 +13936,7 @@ var ts; } var symbol; if (name.kind === 69) { - var message = meaning === 1920 ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; + var message = meaning === 1536 ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; symbol = resolveName(name, name.text, meaning, ignoreErrors ? undefined : message, name); if (!symbol) { return undefined; @@ -14643,7 +13945,7 @@ var ts; else if (name.kind === 139 || name.kind === 172) { var left = name.kind === 139 ? name.left : name.expression; var right = name.kind === 139 ? name.right : name.name; - var namespace = resolveEntityName(left, 1920, ignoreErrors); + var namespace = resolveEntityName(left, 1536, ignoreErrors); if (!namespace || ts.nodeIsMissing(right)) { return undefined; } @@ -14701,14 +14003,7 @@ var ts; } } if (moduleNotFoundError) { - var tsExtension = ts.tryExtractTypeScriptExtension(moduleName); - if (tsExtension) { - var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; - error(moduleReferenceLiteral, diag, tsExtension, ts.removeExtension(moduleName, tsExtension)); - } - else { - error(moduleReferenceLiteral, moduleNotFoundError, moduleName); - } + error(moduleReferenceLiteral, moduleNotFoundError, moduleName); } return undefined; } @@ -14738,7 +14033,7 @@ var ts; } function extendExportSymbols(target, source, lookupTable, exportNode) { for (var id in source) { - if (id !== "default" && !target[id]) { + if (id !== "default" && !ts.hasProperty(target, id)) { target[id] = source[id]; if (lookupTable && exportNode) { lookupTable[id] = { @@ -14746,7 +14041,7 @@ var ts; }; } } - else if (lookupTable && exportNode && id !== "default" && target[id] && resolveSymbol(target[id]) !== resolveSymbol(source[id])) { + else if (lookupTable && exportNode && id !== "default" && ts.hasProperty(target, id) && resolveSymbol(target[id]) !== resolveSymbol(source[id])) { if (!lookupTable[id].exportsWithDuplicate) { lookupTable[id].exportsWithDuplicate = [exportNode]; } @@ -14764,11 +14059,11 @@ var ts; return; } visitedSymbols.push(symbol); - var symbols = ts.cloneMap(symbol.exports); + var symbols = cloneSymbolTable(symbol.exports); var exportStars = symbol.exports["__export"]; if (exportStars) { - var nestedSymbols = ts.createMap(); - var lookupTable = ts.createMap(); + var nestedSymbols = {}; + var lookupTable = {}; for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { var node = _a[_i]; var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); @@ -14777,7 +14072,7 @@ var ts; } for (var id in lookupTable) { var exportsWithDuplicate = lookupTable[id].exportsWithDuplicate; - if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols[id]) { + if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || ts.hasProperty(symbols, id)) { continue; } for (var _b = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _b < exportsWithDuplicate_1.length; _b++) { @@ -14828,8 +14123,8 @@ var ts; } function createType(flags) { var result = new Type(checker, flags); - typeCount++; result.id = typeCount; + typeCount++; return result; } function createIntrinsicType(kind, intrinsicName) { @@ -14837,12 +14132,6 @@ var ts; type.intrinsicName = intrinsicName; return type; } - function createBooleanType(trueFalseTypes) { - var type = getUnionType(trueFalseTypes); - type.flags |= 8; - type.intrinsicName = "boolean"; - return type; - } function createObjectType(kind, symbol) { var type = createType(kind); type.symbol = symbol; @@ -14857,12 +14146,14 @@ var ts; function getNamedMembers(members) { var result; for (var id in members) { - if (!isReservedMemberName(id)) { - if (!result) - result = []; - var symbol = members[id]; - if (symbolIsValue(symbol)) { - result.push(symbol); + if (ts.hasProperty(members, id)) { + if (!isReservedMemberName(id)) { + if (!result) + result = []; + var symbol = members[id]; + if (symbolIsValue(symbol)) { + result.push(symbol); + } } } } @@ -14880,7 +14171,7 @@ var ts; return type; } function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { - return setObjectTypeMembers(createObjectType(2097152, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + return setObjectTypeMembers(createObjectType(65536, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function forEachSymbolTableInScope(enclosingDeclaration, callback) { var result; @@ -14905,7 +14196,7 @@ var ts; return callback(globals); } function getQualifiedLeftMeaning(rightMeaning) { - return rightMeaning === 107455 ? 107455 : 1920; + return rightMeaning === 107455 ? 107455 : 1536; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { function getAccessibleSymbolChainFromSymbolTable(symbols) { @@ -14922,10 +14213,10 @@ var ts; canQualifySymbol(symbolFromSymbolTable, meaning); } } - if (isAccessible(symbols[symbol.name])) { + if (isAccessible(ts.lookUp(symbols, symbol.name))) { return [symbol]; } - return ts.forEachProperty(symbols, function (symbolFromSymbolTable) { + return ts.forEachValue(symbols, function (symbolFromSymbolTable) { if (symbolFromSymbolTable.flags & 8388608 && symbolFromSymbolTable.name !== "export=" && !ts.getDeclarationOfKind(symbolFromSymbolTable, 238)) { @@ -14952,10 +14243,10 @@ var ts; function needsQualification(symbol, enclosingDeclaration, meaning) { var qualify = false; forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { - var symbolFromSymbolTable = symbolTable[symbol.name]; - if (!symbolFromSymbolTable) { + if (!ts.hasProperty(symbolTable, symbol.name)) { return false; } + var symbolFromSymbolTable = symbolTable[symbol.name]; if (symbolFromSymbolTable === symbol) { return true; } @@ -14998,7 +14289,7 @@ var ts; return { accessibility: 1, errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920) : undefined + errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1536) : undefined }; } return hasAccessibleDeclarations; @@ -15069,10 +14360,10 @@ var ts; } else if (entityName.kind === 139 || entityName.kind === 172 || entityName.parent.kind === 229) { - meaning = 1920; + meaning = 1536; } else { - meaning = 793064; + meaning = 793056; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.text, meaning, undefined, undefined); @@ -15123,31 +14414,6 @@ var ts; ts.releaseStringWriter(writer); return result; } - function formatUnionTypes(types) { - var result = []; - var flags = 0; - for (var i = 0; i < types.length; i++) { - var t = types[i]; - flags |= t.flags; - if (!(t.flags & 6144)) { - if (t.flags & (128 | 256)) { - var baseType = t.flags & 128 ? booleanType : t.baseType; - var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { - result.push(baseType); - i += count - 1; - continue; - } - } - result.push(t); - } - } - if (flags & 4096) - result.push(nullType); - if (flags & 2048) - result.push(undefinedType); - return result || types; - } function visibilityToString(flags) { if (flags === 8) { return "private"; @@ -15270,50 +14536,35 @@ var ts; var inObjectTypeLiteral = false; return writeType(type, globalFlags); function writeType(type, flags) { - var nextFlags = flags & ~512; - if (type.flags & 16015) { + if (type.flags & 150995071) { writer.writeKeyword(!(globalFlags & 16) && isTypeAny(type) ? "any" : type.intrinsicName); } - else if (type.flags & 268435456) { + else if (type.flags & 33554432) { if (inObjectTypeLiteral) { writer.reportInaccessibleThisError(); } writer.writeKeyword("this"); } - else if (type.flags & 131072) { - writeTypeReference(type, nextFlags); + else if (type.flags & 4096) { + writeTypeReference(type, flags); + } + else if (type.flags & (1024 | 2048 | 128 | 512)) { + buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793056, 0, flags); + } + else if (type.flags & 8192) { + writeTupleType(type); + } + else if (type.flags & 49152) { + writeUnionOrIntersectionType(type, flags); + } + else if (type.flags & 65536) { + writeAnonymousType(type, flags); } else if (type.flags & 256) { - buildSymbolDisplay(getParentOfSymbol(type.symbol), writer, enclosingDeclaration, 793064, 0, nextFlags); - writePunctuation(writer, 21); - appendSymbolNameOnly(type.symbol, writer); - } - else if (type.flags & (32768 | 65536 | 16 | 16384)) { - buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); - } - else if (!(flags & 512) && type.flags & (2097152 | 1572864) && type.aliasSymbol) { - if (type.flags & 2097152 || !(flags & 1024)) { - var typeArguments = type.aliasTypeArguments; - writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); - } - else { - writeUnionOrIntersectionType(type, nextFlags); - } - } - else if (type.flags & 1572864) { - writeUnionOrIntersectionType(type, nextFlags); - } - else if (type.flags & 2097152) { - writeAnonymousType(type, nextFlags); - } - else if (type.flags & 32) { writer.writeStringLiteral("\"" + ts.escapeString(type.text) + "\""); } - else if (type.flags & 64) { - writer.writeStringLiteral(type.text); - } else { writePunctuation(writer, 15); writeSpace(writer); @@ -15336,7 +14587,7 @@ var ts; } function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { if (symbol.flags & 32 || !isReservedMemberName(symbol.name)) { - buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064, 0, flags); + buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793056, 0, flags); } if (pos < end) { writePunctuation(writer, 25); @@ -15358,11 +14609,6 @@ var ts; writePunctuation(writer, 19); writePunctuation(writer, 20); } - else if (type.target.flags & 262144) { - writePunctuation(writer, 19); - writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 24); - writePunctuation(writer, 20); - } else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; @@ -15384,16 +14630,16 @@ var ts; writeSymbolTypeReference(type.symbol, typeArguments, i, typeParameterCount, flags); } } + function writeTupleType(type) { + writePunctuation(writer, 19); + writeTypeList(type.elementTypes, 24); + writePunctuation(writer, 20); + } function writeUnionOrIntersectionType(type, flags) { if (flags & 64) { writePunctuation(writer, 17); } - if (type.flags & 524288) { - writeTypeList(formatUnionTypes(type.types), 47); - } - else { - writeTypeList(type.types, 46); - } + writeTypeList(type.types, type.flags & 16384 ? 47 : 46); if (flags & 64) { writePunctuation(writer, 18); } @@ -15410,7 +14656,7 @@ var ts; else if (ts.contains(symbolStack, symbol)) { var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { - buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793064, 0, flags); + buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793056, 0, flags); } else { writeKeyword(writer, 117); @@ -15812,13 +15058,13 @@ var ts; function collectLinkedAliases(node) { var exportSymbol; if (node.parent && node.parent.kind === 235) { - exportSymbol = resolveName(node.parent, node.text, 107455 | 793064 | 1920 | 8388608, ts.Diagnostics.Cannot_find_name_0, node); + exportSymbol = resolveName(node.parent, node.text, 107455 | 793056 | 1536 | 8388608, ts.Diagnostics.Cannot_find_name_0, node); } else if (node.parent.kind === 238) { var exportSpecifier = node.parent; exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : - resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, 107455 | 793064 | 1920 | 8388608); + resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, 107455 | 793056 | 1536 | 8388608); } var result = []; if (exportSymbol) { @@ -15835,7 +15081,7 @@ var ts; if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.text, 107455 | 793064 | 1920, undefined, undefined); + var importSymbol = resolveName(declaration, firstIdentifier.text, 107455 | 793056 | 1536, undefined, undefined); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -15876,7 +15122,7 @@ var ts; return getSymbolLinks(target).declaredType; } if (propertyName === 1) { - ts.Debug.assert(!!(target.flags & 32768)); + ts.Debug.assert(!!(target.flags & 1024)); return target.resolvedBaseConstructorType; } if (propertyName === 3) { @@ -15918,7 +15164,7 @@ var ts; return type && (type.flags & 1) !== 0; } function isTypeNever(type) { - return type && (type.flags & 8192) !== 0; + return type && (type.flags & 134217728) !== 0; } function getTypeForBindingElementParent(node) { var symbol = getSymbolOfNode(node); @@ -15980,7 +15226,7 @@ var ts; : elementType; if (!type) { if (isTupleType(parentType)) { - error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); + error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), parentType.elementTypes.length, pattern.elements.length); } else { error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), propName); @@ -15992,12 +15238,10 @@ var ts; type = createArrayType(elementType); } } - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 2048)) { + if (strictNullChecks && declaration.initializer && !(getCombinedTypeFlags(checkExpressionCached(declaration.initializer)) & 32)) { type = getTypeWithFacts(type, 131072); } - return declaration.initializer ? - getUnionType([type, checkExpressionCached(declaration.initializer)], true) : - type; + return type; } function getTypeForVariableLikeDeclarationFromJSDocComment(declaration) { var jsDocType = getJSDocTypeForVariableLikeDeclarationFromJSDocComment(declaration); @@ -16027,7 +15271,7 @@ var ts; return undefined; } function addOptionality(type, optional) { - return strictNullChecks && optional ? includeFalsyTypes(type, 2048) : type; + return strictNullChecks && optional ? addTypeKind(type, 32) : type; } function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { if (declaration.flags & 134217728) { @@ -16062,14 +15306,9 @@ var ts; return getReturnTypeOfSignature(getterSignature); } } - var type = void 0; - if (declaration.symbol.name === "this") { - var thisParameter = getContextualThisParameter(func); - type = thisParameter ? getTypeOfSymbol(thisParameter) : undefined; - } - else { - type = getContextuallyTypedParameterType(declaration); - } + var type = declaration.symbol.name === "this" + ? getContextuallyTypedThisType(func) + : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, declaration.questionToken && includeOptionality); } @@ -16081,24 +15320,26 @@ var ts; return checkIdentifier(declaration.name); } if (ts.isBindingPattern(declaration.name)) { - return getTypeFromBindingPattern(declaration.name, false, true); + return getTypeFromBindingPattern(declaration.name, false); } return undefined; } - function getTypeFromBindingElement(element, includePatternInType, reportErrors) { + function getTypeFromBindingElement(element, includePatternInType) { if (element.initializer) { - return checkExpressionCached(element.initializer); + var type = checkExpressionCached(element.initializer); + reportErrorsFromWidening(element, type); + return getWidenedType(type); } if (ts.isBindingPattern(element.name)) { - return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); + return getTypeFromBindingPattern(element.name, includePatternInType); } - if (reportErrors && compilerOptions.noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { + if (compilerOptions.noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { reportImplicitAnyError(element, anyType); } return anyType; } - function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { - var members = ts.createMap(); + function getTypeFromObjectBindingPattern(pattern, includePatternInType) { + var members = {}; var hasComputedProperties = false; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; @@ -16109,7 +15350,7 @@ var ts; var text = getTextOfPropertyName(name); var flags = 4 | 67108864 | (e.initializer ? 536870912 : 0); var symbol = createSymbol(flags, text); - symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); + symbol.type = getTypeFromBindingElement(e, includePatternInType); symbol.bindingElement = e; members[symbol.name] = symbol; }); @@ -16118,27 +15359,27 @@ var ts; result.pattern = pattern; } if (hasComputedProperties) { - result.flags |= 536870912; + result.flags |= 67108864; } return result; } - function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { + function getTypeFromArrayBindingPattern(pattern, includePatternInType) { var elements = pattern.elements; if (elements.length === 0 || elements[elements.length - 1].dotDotDotToken) { return languageVersion >= 2 ? createIterableType(anyType) : anyArrayType; } - var elementTypes = ts.map(elements, function (e) { return e.kind === 193 ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); }); - var result = createTupleType(elementTypes); + var elementTypes = ts.map(elements, function (e) { return e.kind === 193 ? anyType : getTypeFromBindingElement(e, includePatternInType); }); if (includePatternInType) { - result = cloneTypeReference(result); + var result = createNewTupleType(elementTypes); result.pattern = pattern; + return result; } - return result; + return createTupleType(elementTypes); } - function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { + function getTypeFromBindingPattern(pattern, includePatternInType) { return pattern.kind === 167 - ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) - : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); + ? getTypeFromObjectBindingPattern(pattern, includePatternInType) + : getTypeFromArrayBindingPattern(pattern, includePatternInType); } function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { var type = getTypeForVariableLikeDeclaration(declaration, true); @@ -16177,27 +15418,19 @@ var ts; if (declaration.kind === 235) { return links.type = checkExpression(declaration.expression); } - if (declaration.flags & 134217728 && declaration.kind === 280 && declaration.typeExpression) { - return links.type = getTypeFromTypeNode(declaration.typeExpression.type); - } if (!pushTypeResolution(symbol, 0)) { return unknownType; } - var type = void 0; - if (declaration.kind === 187 || - declaration.kind === 172 && declaration.parent.kind === 187) { - if (declaration.flags & 134217728) { - var typeTag = ts.getJSDocTypeTag(declaration.parent); - if (typeTag && typeTag.typeExpression) { - return links.type = getTypeFromTypeNode(typeTag.typeExpression.type); - } - } - var declaredTypes = ts.map(symbol.declarations, function (decl) { return decl.kind === 187 ? - checkExpressionCached(decl.right) : - checkExpressionCached(decl.parent.right); }); - type = getUnionType(declaredTypes, true); + var type = undefined; + if (declaration.kind === 187) { + type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); })); } - else { + else if (declaration.kind === 172) { + if (declaration.parent.kind === 187) { + type = checkExpressionCached(declaration.parent.right); + } + } + if (type === undefined) { type = getWidenedTypeForVariableLikeDeclaration(declaration, true); } if (!popTypeResolution()) { @@ -16265,13 +15498,7 @@ var ts; } else { if (compilerOptions.noImplicitAny) { - if (setter) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } + error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation, symbolToString(symbol)); } type = anyType; } @@ -16291,13 +15518,13 @@ var ts; function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbol.valueDeclaration.kind === 225 && ts.isShorthandAmbientModuleSymbol(symbol)) { + if (symbol.valueDeclaration.kind === 225 && ts.isShorthandAmbientModule(symbol.valueDeclaration)) { links.type = anyType; } else { - var type = createObjectType(2097152, symbol); + var type = createObjectType(65536, symbol); links.type = strictNullChecks && symbol.flags & 536870912 ? - includeFalsyTypes(type, 2048) : type; + addTypeKind(type, 32) : type; } } return links.type; @@ -16348,7 +15575,7 @@ var ts; return unknownType; } function getTargetType(type) { - return type.flags & 131072 ? type.target : type; + return type.flags & 4096 ? type.target : type; } function hasBaseType(type, checkBase) { return check(type); @@ -16408,7 +15635,7 @@ var ts; return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); } function isConstructorType(type) { - return type.flags & 2588672 && getSignaturesOfType(type, 1).length > 0; + return type.flags & 80896 && getSignaturesOfType(type, 1).length > 0; } function getBaseTypeNodeOfClass(type) { return ts.getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); @@ -16435,7 +15662,7 @@ var ts; return unknownType; } var baseConstructorType = checkExpression(baseTypeNode.expression); - if (baseConstructorType.flags & 2588672) { + if (baseConstructorType.flags & 80896) { resolveStructuredTypeMembers(baseConstructorType); } if (!popTypeResolution()) { @@ -16451,28 +15678,25 @@ var ts; return type.resolvedBaseConstructorType; } function getBaseTypes(type) { + var isClass = type.symbol.flags & 32; + var isInterface = type.symbol.flags & 64; if (!type.resolvedBaseTypes) { - if (type.flags & 262144) { - type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters))]; - } - else if (type.symbol.flags & (32 | 64)) { - if (type.symbol.flags & 32) { - resolveBaseTypesOfClass(type); - } - if (type.symbol.flags & 64) { - resolveBaseTypesOfInterface(type); - } - } - else { + if (!isClass && !isInterface) { ts.Debug.fail("type must be class or interface"); } + if (isClass) { + resolveBaseTypesOfClass(type); + } + if (isInterface) { + resolveBaseTypesOfInterface(type); + } } return type.resolvedBaseTypes; } function resolveBaseTypesOfClass(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; var baseConstructorType = getBaseConstructorTypeOfClass(type); - if (!(baseConstructorType.flags & 2588672)) { + if (!(baseConstructorType.flags & 80896)) { return; } var baseTypeNode = getBaseTypeNodeOfClass(type); @@ -16493,7 +15717,7 @@ var ts; if (baseType === unknownType) { return; } - if (!(getTargetType(baseType).flags & (32768 | 65536))) { + if (!(getTargetType(baseType).flags & (1024 | 2048))) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); return; } @@ -16526,7 +15750,7 @@ var ts; var node = _c[_b]; var baseType = getTypeFromTypeNode(node); if (baseType !== unknownType) { - if (getTargetType(baseType).flags & (32768 | 65536)) { + if (getTargetType(baseType).flags & (1024 | 2048)) { if (type !== baseType && !hasBaseType(baseType, type)) { if (type.resolvedBaseTypes === emptyArray) { type.resolvedBaseTypes = [baseType]; @@ -16558,8 +15782,8 @@ var ts; if (baseTypeNodes) { for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { var node = baseTypeNodes_1[_b]; - if (ts.isEntityNameExpression(node.expression)) { - var baseSymbol = resolveEntityName(node.expression, 793064, true); + if (ts.isSupportedExpressionWithTypeArguments(node)) { + var baseSymbol = resolveEntityName(node.expression, 793056, true); if (!baseSymbol || !(baseSymbol.flags & 64) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -16573,20 +15797,20 @@ var ts; function getDeclaredTypeOfClassOrInterface(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var kind = symbol.flags & 32 ? 32768 : 65536; + var kind = symbol.flags & 32 ? 1024 : 2048; var type = links.declaredType = createObjectType(kind, symbol); var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - if (outerTypeParameters || localTypeParameters || kind === 32768 || !isIndependentInterface(symbol)) { - type.flags |= 131072; + if (outerTypeParameters || localTypeParameters || kind === 1024 || !isIndependentInterface(symbol)) { + type.flags |= 4096; type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); type.outerTypeParameters = outerTypeParameters; type.localTypeParameters = localTypeParameters; - type.instantiations = ts.createMap(); + type.instantiations = {}; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 | 268435456); + type.thisType = createType(512 | 33554432); type.thisType.symbol = symbol; type.thisType.constraint = type; } @@ -16599,9 +15823,8 @@ var ts; if (!pushTypeResolution(symbol, 2)) { return unknownType; } - var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - var declaration = ts.getDeclarationOfKind(symbol, 279); var type = void 0; + var declaration = ts.getDeclarationOfKind(symbol, 279); if (declaration) { if (declaration.jsDocTypeLiteral) { type = getTypeFromTypeNode(declaration.jsDocTypeLiteral); @@ -16612,12 +15835,12 @@ var ts; } else { declaration = ts.getDeclarationOfKind(symbol, 223); - type = getTypeFromTypeNode(declaration.type, symbol, typeParameters); + type = getTypeFromTypeNode(declaration.type); } if (popTypeResolution()) { - links.typeParameters = typeParameters; - if (typeParameters) { - links.instantiations = ts.createMap(); + links.typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (links.typeParameters) { + links.instantiations = {}; links.instantiations[getTypeListId(links.typeParameters)] = type; } } @@ -16629,80 +15852,19 @@ var ts; } return links.declaredType; } - function isLiteralEnumMember(symbol, member) { - var expr = member.initializer; - if (!expr) { - return !ts.isInAmbientContext(member); - } - return expr.kind === 8 || - expr.kind === 185 && expr.operator === 36 && - expr.operand.kind === 8 || - expr.kind === 69 && !!symbol.exports[expr.text]; - } - function enumHasLiteralMembers(symbol) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 224) { - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - if (!isLiteralEnumMember(symbol, member)) { - return false; - } - } - } - } - return true; - } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var enumType = links.declaredType = createType(16); - enumType.symbol = symbol; - if (enumHasLiteralMembers(symbol)) { - var memberTypeList = []; - var memberTypes = ts.createMap(); - for (var _i = 0, _a = enumType.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 224) { - computeEnumMemberValues(declaration); - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - var memberSymbol = getSymbolOfNode(member); - var value = getEnumMemberValue(member); - if (!memberTypes[value]) { - var memberType = memberTypes[value] = createType(256); - memberType.symbol = memberSymbol; - memberType.baseType = enumType; - memberType.text = "" + value; - memberTypeList.push(memberType); - } - } - } - } - enumType.memberTypes = memberTypes; - if (memberTypeList.length > 1) { - enumType.flags |= 524288; - enumType.types = memberTypeList; - unionTypes[getTypeListId(memberTypeList)] = enumType; - } - } - } - return links.declaredType; - } - function getDeclaredTypeOfEnumMember(symbol) { - var links = getSymbolLinks(symbol); - if (!links.declaredType) { - var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); - links.declaredType = enumType.flags & 524288 ? - enumType.memberTypes[getEnumMemberValue(symbol.valueDeclaration)] : - enumType; + var type = createType(128); + type.symbol = symbol; + links.declaredType = type; } return links.declaredType; } function getDeclaredTypeOfTypeParameter(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var type = createType(16384); + var type = createType(512); type.symbol = symbol; if (!ts.getDeclarationOfKind(symbol, 141).constraint) { type.constraint = noConstraintType; @@ -16726,14 +15888,11 @@ var ts; if (symbol.flags & 524288) { return getDeclaredTypeOfTypeAlias(symbol); } - if (symbol.flags & 262144) { - return getDeclaredTypeOfTypeParameter(symbol); - } if (symbol.flags & 384) { return getDeclaredTypeOfEnum(symbol); } - if (symbol.flags & 8) { - return getDeclaredTypeOfEnumMember(symbol); + if (symbol.flags & 262144) { + return getDeclaredTypeOfTypeParameter(symbol); } if (symbol.flags & 8388608) { return getDeclaredTypeOfAlias(symbol); @@ -16804,7 +15963,7 @@ var ts; return false; } function createSymbolTable(symbols) { - var result = ts.createMap(); + var result = {}; for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { var symbol = symbols_1[_i]; result[symbol.name] = symbol; @@ -16812,7 +15971,7 @@ var ts; return result; } function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) { - var result = ts.createMap(); + var result = {}; for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { var symbol = symbols_2[_i]; result[symbol.name] = mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper); @@ -16822,7 +15981,7 @@ var ts; function addInheritedMembers(symbols, baseSymbols) { for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) { var s = baseSymbols_1[_i]; - if (!symbols[s.name]) { + if (!ts.hasProperty(symbols, s.name)) { symbols[s.name] = s; } } @@ -16839,27 +15998,19 @@ var ts; return type; } function getTypeWithThisArgument(type, thisArgument) { - if (type.flags & 131072) { + if (type.flags & 4096) { return createTypeReference(type.target, ts.concatenate(type.typeArguments, [thisArgument || type.target.thisType])); } return type; } function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { - var mapper; - var members; - var callSignatures; - var constructSignatures; - var stringIndexInfo; - var numberIndexInfo; - if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { - mapper = identityMapper; - members = source.symbol ? source.symbol.members : createSymbolTable(source.declaredProperties); - callSignatures = source.declaredCallSignatures; - constructSignatures = source.declaredConstructSignatures; - stringIndexInfo = source.declaredStringIndexInfo; - numberIndexInfo = source.declaredNumberIndexInfo; - } - else { + var mapper = identityMapper; + var members = source.symbol.members; + var callSignatures = source.declaredCallSignatures; + var constructSignatures = source.declaredConstructSignatures; + var stringIndexInfo = source.declaredStringIndexInfo; + var numberIndexInfo = source.declaredNumberIndexInfo; + if (!ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { mapper = createTypeMapper(typeParameters, typeArguments); members = createInstantiatedSymbolTable(source.declaredProperties, mapper, typeParameters.length === 1); callSignatures = instantiateList(source.declaredCallSignatures, mapper, instantiateSignature); @@ -16869,7 +16020,7 @@ var ts; } var baseTypes = getBaseTypes(source); if (baseTypes.length) { - if (source.symbol && members === source.symbol.members) { + if (members === source.symbol.members) { members = createSymbolTable(source.declaredProperties); } var thisArgument = ts.lastOrUndefined(typeArguments); @@ -16895,7 +16046,7 @@ var ts; type.typeArguments : ts.concatenate(type.typeArguments, [type]); resolveObjectTypeMembers(type, source, typeParameters, typeArguments); } - function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasStringLiterals) { var sig = new Signature(checker); sig.declaration = declaration; sig.typeParameters = typeParameters; @@ -16905,11 +16056,11 @@ var ts; sig.typePredicate = typePredicate; sig.minArgumentCount = minArgumentCount; sig.hasRestParameter = hasRestParameter; - sig.hasLiteralTypes = hasLiteralTypes; + sig.hasStringLiterals = hasStringLiterals; return sig; } function cloneSignature(sig) { - return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); + return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); } function getDefaultConstructSignatures(classType) { var baseConstructorType = getBaseConstructorTypeOfClass(classType); @@ -16933,6 +16084,22 @@ var ts; } return result; } + function createTupleTypeMemberSymbols(memberTypes) { + var members = {}; + for (var i = 0; i < memberTypes.length; i++) { + var symbol = createSymbol(4 | 67108864, "" + i); + symbol.type = memberTypes[i]; + members[i] = symbol; + } + return members; + } + function resolveTupleTypeMembers(type) { + var arrayElementType = getUnionType(type.elementTypes, true); + var arrayType = resolveStructuredTypeMembers(createTypeFromGenericGlobalType(globalArrayType, [arrayElementType, type])); + var members = createTupleTypeMemberSymbols(type.elementTypes); + addInheritedMembers(members, arrayType.properties); + setObjectTypeMembers(type, members, arrayType.callSignatures, arrayType.constructSignatures, arrayType.stringIndexInfo, arrayType.numberIndexInfo); + } function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) { for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { var s = signatureList_1[_i]; @@ -16978,7 +16145,7 @@ var ts; if (unionSignatures.length > 1) { s = cloneSignature(signature); if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { - var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; }), true); + var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; })); s.thisParameter = createTransientSymbol(signature.thisParameter, thisType); } s.resolvedReturnType = undefined; @@ -17003,7 +16170,7 @@ var ts; indexTypes.push(indexInfo.type); isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; } - return createIndexInfo(getUnionType(indexTypes, true), isAnyReadonly); + return createIndexInfo(getUnionType(indexTypes), isAnyReadonly); } function resolveUnionTypeMembers(type) { var callSignatures = getUnionSignatures(type.types, 0); @@ -17063,7 +16230,7 @@ var ts; constructSignatures = getDefaultConstructSignatures(classType); } var baseConstructorType = getBaseConstructorTypeOfClass(classType); - if (baseConstructorType.flags & 2588672) { + if (baseConstructorType.flags & 80896) { members = createSymbolTable(getNamedMembers(members)); addInheritedMembers(members, getPropertiesOfObjectType(baseConstructorType)); } @@ -17077,36 +16244,41 @@ var ts; } function resolveStructuredTypeMembers(type) { if (!type.members) { - if (type.flags & 131072) { + if (type.flags & 4096) { resolveTypeReferenceMembers(type); } - else if (type.flags & (32768 | 65536)) { + else if (type.flags & (1024 | 2048)) { resolveClassOrInterfaceMembers(type); } - else if (type.flags & 2097152) { + else if (type.flags & 65536) { resolveAnonymousTypeMembers(type); } - else if (type.flags & 524288) { + else if (type.flags & 8192) { + resolveTupleTypeMembers(type); + } + else if (type.flags & 16384) { resolveUnionTypeMembers(type); } - else if (type.flags & 1048576) { + else if (type.flags & 32768) { resolveIntersectionTypeMembers(type); } } return type; } function getPropertiesOfObjectType(type) { - if (type.flags & 2588672) { + if (type.flags & 80896) { return resolveStructuredTypeMembers(type).properties; } return emptyArray; } function getPropertyOfObjectType(type, name) { - if (type.flags & 2588672) { + if (type.flags & 80896) { var resolved = resolveStructuredTypeMembers(type); - var symbol = resolved.members[name]; - if (symbol && symbolIsValue(symbol)) { - return symbol; + if (ts.hasProperty(resolved.members, name)) { + var symbol = resolved.members[name]; + if (symbolIsValue(symbol)) { + return symbol; + } } } } @@ -17117,7 +16289,7 @@ var ts; var prop = _c[_b]; getPropertyOfUnionOrIntersectionType(type, prop.name); } - if (type.flags & 524288) { + if (type.flags & 16384) { break; } } @@ -17125,12 +16297,12 @@ var ts; } function getPropertiesOfType(type) { type = getApparentType(type); - return type.flags & 1572864 ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); + return type.flags & 49152 ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } function getApparentTypeOfTypeParameter(type) { if (!type.resolvedApparentType) { var constraintType = getConstraintOfTypeParameter(type); - while (constraintType && constraintType.flags & 16384) { + while (constraintType && constraintType.flags & 512) { constraintType = getConstraintOfTypeParameter(constraintType); } type.resolvedApparentType = getTypeWithThisArgument(constraintType || emptyObjectType, type); @@ -17138,19 +16310,19 @@ var ts; return type.resolvedApparentType; } function getApparentType(type) { - if (type.flags & 16384) { + if (type.flags & 512) { type = getApparentTypeOfTypeParameter(type); } - if (type.flags & 34) { + if (type.flags & 258) { type = globalStringType; } - else if (type.flags & 340) { + else if (type.flags & 132) { type = globalNumberType; } - else if (type.flags & 136) { + else if (type.flags & 8) { type = globalBooleanType; } - else if (type.flags & 512) { + else if (type.flags & 16777216) { type = getGlobalESSymbolType(); } return type; @@ -17158,7 +16330,7 @@ var ts; function createUnionOrIntersectionProperty(containingType, name) { var types = containingType.types; var props; - var commonFlags = (containingType.flags & 1048576) ? 536870912 : 0; + var commonFlags = (containingType.flags & 32768) ? 536870912 : 0; var isReadonly = false; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var current = types_2[_i]; @@ -17177,7 +16349,7 @@ var ts; isReadonly = true; } } - else if (containingType.flags & 524288) { + else if (containingType.flags & 16384) { return undefined; } } @@ -17190,20 +16362,11 @@ var ts; } var propTypes = []; var declarations = []; - var commonType = undefined; - var hasCommonType = true; for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { var prop = props_1[_a]; if (prop.declarations) { ts.addRange(declarations, prop.declarations); } - var type = getTypeOfSymbol(prop); - if (!commonType) { - commonType = type; - } - else if (type !== commonType) { - hasCommonType = false; - } propTypes.push(getTypeOfSymbol(prop)); } var result = createSymbol(4 | @@ -17211,46 +16374,47 @@ var ts; 268435456 | commonFlags, name); result.containingType = containingType; - result.hasCommonType = hasCommonType; result.declarations = declarations; result.isReadonly = isReadonly; - result.type = containingType.flags & 524288 ? getUnionType(propTypes) : getIntersectionType(propTypes); + result.type = containingType.flags & 16384 ? getUnionType(propTypes) : getIntersectionType(propTypes); return result; } function getPropertyOfUnionOrIntersectionType(type, name) { - var properties = type.resolvedProperties || (type.resolvedProperties = ts.createMap()); - var property = properties[name]; - if (!property) { - property = createUnionOrIntersectionProperty(type, name); - if (property) { - properties[name] = property; - } + var properties = type.resolvedProperties || (type.resolvedProperties = {}); + if (ts.hasProperty(properties, name)) { + return properties[name]; + } + var property = createUnionOrIntersectionProperty(type, name); + if (property) { + properties[name] = property; } return property; } function getPropertyOfType(type, name) { type = getApparentType(type); - if (type.flags & 2588672) { + if (type.flags & 80896) { var resolved = resolveStructuredTypeMembers(type); - var symbol = resolved.members[name]; - if (symbol && symbolIsValue(symbol)) { - return symbol; + if (ts.hasProperty(resolved.members, name)) { + var symbol = resolved.members[name]; + if (symbolIsValue(symbol)) { + return symbol; + } } if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); - if (symbol_1) { - return symbol_1; + var symbol = getPropertyOfObjectType(globalFunctionType, name); + if (symbol) { + return symbol; } } return getPropertyOfObjectType(globalObjectType, name); } - if (type.flags & 1572864) { + if (type.flags & 49152) { return getPropertyOfUnionOrIntersectionType(type, name); } return undefined; } function getSignaturesOfStructuredType(type, kind) { - if (type.flags & 4161536) { + if (type.flags & 130048) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 ? resolved.callSignatures : resolved.constructSignatures; } @@ -17260,7 +16424,7 @@ var ts; return getSignaturesOfStructuredType(getApparentType(type), kind); } function getIndexInfoOfStructuredType(type, kind) { - if (type.flags & 4161536) { + if (type.flags & 130048) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 ? resolved.stringIndexInfo : resolved.numberIndexInfo; } @@ -17285,7 +16449,7 @@ var ts; } } if (propTypes.length) { - return getUnionType(propTypes, true); + return getUnionType(propTypes); } } return undefined; @@ -17368,7 +16532,7 @@ var ts; var links = getNodeLinks(declaration); if (!links.resolvedSignature) { var parameters = []; - var hasLiteralTypes = false; + var hasStringLiterals = false; var minArgumentCount = -1; var thisParameter = undefined; var hasThisParameter = void 0; @@ -17388,7 +16552,7 @@ var ts; parameters.push(paramSymbol); } if (param.type && param.type.kind === 166) { - hasLiteralTypes = true; + hasStringLiterals = true; } if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { if (minArgumentCount < 0) { @@ -17414,9 +16578,6 @@ var ts; if (isJSConstructSignature) { minArgumentCount--; } - if (!thisParameter && ts.isObjectLiteralMethod(declaration)) { - thisParameter = getContextualThisParameter(declaration); - } var classType = declaration.kind === 148 ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; @@ -17427,7 +16588,7 @@ var ts; var typePredicate = declaration.type && declaration.type.kind === 154 ? createTypePredicateFromTypePredicateNode(declaration.type) : undefined; - links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasLiteralTypes); + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasStringLiterals); } return links.resolvedSignature; } @@ -17512,7 +16673,7 @@ var ts; type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); } else if (signature.unionSignatures) { - type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), true); + type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature)); } else { type = getReturnTypeFromBody(signature.declaration); @@ -17536,7 +16697,7 @@ var ts; function getRestTypeOfSignature(signature) { if (signature.hasRestParameter) { var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); - if (type.flags & 131072 && type.target === globalArrayType) { + if (type.flags & 4096 && type.target === globalArrayType) { return type.typeArguments[0]; } } @@ -17556,7 +16717,7 @@ var ts; function getOrCreateTypeFromSignature(signature) { if (!signature.isolatedSignatureType) { var isConstructor = signature.declaration.kind === 148 || signature.declaration.kind === 152; - var type = createObjectType(2097152); + var type = createObjectType(65536 | 262144); type.members = emptySymbols; type.properties = emptyArray; type.callSignatures = !isConstructor ? [signature] : emptyArray; @@ -17600,7 +16761,7 @@ var ts; } function hasConstraintReferenceTo(type, target) { var checked; - while (type && !(type.flags & 268435456) && type.flags & 16384 && !ts.contains(checked, type)) { + while (type && !(type.flags & 33554432) && type.flags & 512 && !ts.contains(checked, type)) { if (type === target) { return true; } @@ -17632,27 +16793,24 @@ var ts; return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 141).parent); } function getTypeListId(types) { - var result = ""; if (types) { - var length_3 = types.length; - var i = 0; - while (i < length_3) { - var startId = types[i].id; - var count = 1; - while (i + count < length_3 && types[i + count].id === startId + count) { - count++; - } - if (result.length) { - result += ","; - } - result += startId; - if (count > 1) { - result += ":" + count; - } - i += count; + switch (types.length) { + case 1: + return "" + types[0].id; + case 2: + return types[0].id + "," + types[1].id; + default: + var result = ""; + for (var i = 0; i < types.length; i++) { + if (i > 0) { + result += ","; + } + result += types[i].id; + } + return result; } } - return result; + return ""; } function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; @@ -17662,29 +16820,20 @@ var ts; result |= type.flags; } } - return result & 234881024; + return result & 14680064; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); var type = target.instantiations[id]; if (!type) { var propagatedFlags = typeArguments ? getPropagatingFlagsOfTypes(typeArguments, 0) : 0; - var flags = 131072 | propagatedFlags; + var flags = 4096 | propagatedFlags; type = target.instantiations[id] = createObjectType(flags, target.symbol); type.target = target; type.typeArguments = typeArguments; } return type; } - function cloneTypeReference(source) { - var type = createObjectType(source.flags, source.symbol); - type.target = source.target; - type.typeArguments = source.typeArguments; - return type; - } - function getTypeReferenceArity(type) { - return type.target.typeParameters ? type.target.typeParameters.length : 0; - } function getTypeFromClassOrInterfaceReference(node, symbol) { var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); var typeParameters = type.localTypeParameters; @@ -17734,9 +16883,8 @@ var ts; case 267: return node.name; case 194: - var expr = node.expression; - if (ts.isEntityNameExpression(expr)) { - return expr; + if (ts.isSupportedExpressionWithTypeArguments(node)) { + return node.expression; } } return undefined; @@ -17745,7 +16893,7 @@ var ts; if (!typeReferenceName) { return unknownSymbol; } - return resolveEntityName(typeReferenceName, 793064) || unknownSymbol; + return resolveEntityName(typeReferenceName, 793056) || unknownSymbol; } function getTypeReferenceType(node, symbol) { if (symbol === unknownSymbol) { @@ -17771,14 +16919,14 @@ var ts; var typeReferenceName = getTypeReferenceName(node); symbol = resolveTypeReferenceName(node, typeReferenceName); type = getTypeReferenceType(node, symbol); + links.resolvedSymbol = symbol; + links.resolvedType = type; } else { - var typeNameOrExpression = node.kind === 155 - ? node.typeName - : ts.isEntityNameExpression(node.expression) - ? node.expression - : undefined; - symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793064) || unknownSymbol; + var typeNameOrExpression = node.kind === 155 ? node.typeName : + ts.isSupportedExpressionWithTypeArguments(node) ? node.expression : + undefined; + symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793056) || unknownSymbol; type = symbol === unknownSymbol ? unknownType : symbol.flags & (32 | 64) ? getTypeFromClassOrInterfaceReference(node, symbol) : symbol.flags & 524288 ? getTypeFromTypeAliasReference(node, symbol) : @@ -17813,7 +16961,7 @@ var ts; return arity ? emptyGenericType : emptyObjectType; } var type = getDeclaredTypeOfSymbol(symbol); - if (!(type.flags & 2588672)) { + if (!(type.flags & 80896)) { error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbol.name); return arity ? emptyGenericType : emptyObjectType; } @@ -17827,7 +16975,7 @@ var ts; return getGlobalSymbol(name, 107455, ts.Diagnostics.Cannot_find_global_value_0); } function getGlobalTypeSymbol(name) { - return getGlobalSymbol(name, 793064, ts.Diagnostics.Cannot_find_global_type_0); + return getGlobalSymbol(name, 793056, ts.Diagnostics.Cannot_find_global_type_0); } function getGlobalSymbol(name, meaning, diagnostic) { return resolveName(undefined, name, meaning, diagnostic, name); @@ -17837,8 +16985,8 @@ var ts; return getTypeOfGlobalSymbol(getGlobalTypeSymbol(name), arity); } function getExportedTypeFromNamespace(namespace, name) { - var namespaceSymbol = getGlobalSymbol(namespace, 1920, undefined); - var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793064); + var namespaceSymbol = getGlobalSymbol(namespace, 1536, undefined); + var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793056); return typeSymbol && getDeclaredTypeOfSymbol(typeSymbol); } function createTypedPropertyDescriptorType(propertyType) { @@ -17866,38 +17014,15 @@ var ts; } return links.resolvedType; } - function createTupleTypeOfArity(arity) { - var typeParameters = []; - var properties = []; - for (var i = 0; i < arity; i++) { - var typeParameter = createType(16384); - typeParameters.push(typeParameter); - var property = createSymbol(4 | 67108864, "" + i); - property.type = typeParameter; - properties.push(property); - } - var type = createObjectType(262144 | 131072); - type.typeParameters = typeParameters; - type.outerTypeParameters = undefined; - type.localTypeParameters = typeParameters; - type.instantiations = ts.createMap(); - type.instantiations[getTypeListId(type.typeParameters)] = type; - type.target = type; - type.typeArguments = type.typeParameters; - type.thisType = createType(16384 | 268435456); - type.thisType.constraint = type; - type.declaredProperties = properties; - type.declaredCallSignatures = emptyArray; - type.declaredConstructSignatures = emptyArray; - type.declaredStringIndexInfo = undefined; - type.declaredNumberIndexInfo = undefined; - return type; - } - function getTupleTypeOfArity(arity) { - return tupleTypes[arity] || (tupleTypes[arity] = createTupleTypeOfArity(arity)); - } function createTupleType(elementTypes) { - return createTypeReference(getTupleTypeOfArity(elementTypes.length), elementTypes); + var id = getTypeListId(elementTypes); + return tupleTypes[id] || (tupleTypes[id] = createNewTupleType(elementTypes)); + } + function createNewTupleType(elementTypes) { + var propagatedFlags = getPropagatingFlagsOfTypes(elementTypes, 0); + var type = createObjectType(8192 | propagatedFlags); + type.elementTypes = elementTypes; + return type; } function getTypeFromTupleTypeNode(node) { var links = getNodeLinks(node); @@ -17906,68 +17031,30 @@ var ts; } return links.resolvedType; } - function binarySearchTypes(types, type) { - var low = 0; - var high = types.length - 1; - var typeId = type.id; - while (low <= high) { - var middle = low + ((high - low) >> 1); - var id = types[middle].id; - if (id === typeId) { - return middle; - } - else if (id > typeId) { - high = middle - 1; - } - else { - low = middle + 1; - } + function addTypeToSet(typeSet, type, typeSetKind) { + if (type.flags & typeSetKind) { + addTypesToSet(typeSet, type.types, typeSetKind); } - return ~low; - } - function containsType(types, type) { - return binarySearchTypes(types, type) >= 0; - } - function addTypeToUnion(typeSet, type) { - if (type.flags & 524288) { - addTypesToUnion(typeSet, type.types); - } - else if (type.flags & 1) { - typeSet.containsAny = true; - } - else if (!strictNullChecks && type.flags & 6144) { - if (type.flags & 2048) + else if (type.flags & (1 | 32 | 64)) { + if (type.flags & 1) + typeSet.containsAny = true; + if (type.flags & 32) typeSet.containsUndefined = true; - if (type.flags & 4096) + if (type.flags & 64) typeSet.containsNull = true; - if (!(type.flags & 33554432)) + if (!(type.flags & 2097152)) typeSet.containsNonWideningType = true; } - else if (!(type.flags & 8192)) { - var len = typeSet.length; - var index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type); - if (index < 0) { - if (!(type.flags & 2097152 && type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); - } - } + else if (type !== neverType && !ts.contains(typeSet, type)) { + typeSet.push(type); } } - function addTypesToUnion(typeSet, types) { + function addTypesToSet(typeSet, types, typeSetKind) { for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { var type = types_4[_i]; - addTypeToUnion(typeSet, type); + addTypeToSet(typeSet, type, typeSetKind); } } - function containsIdenticalType(types, type) { - for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { - var t = types_5[_i]; - if (isTypeIdenticalTo(t, type)) { - return true; - } - } - return false; - } function isSubtypeOfAny(candidate, types) { for (var i = 0, len = types.length; i < len; i++) { if (candidate !== types[i] && isTypeSubtypeOf(candidate, types[i])) { @@ -17985,7 +17072,7 @@ var ts; } } } - function getUnionType(types, subtypeReduction, aliasSymbol, aliasTypeArguments) { + function getUnionType(types, noSubtypeReduction) { if (types.length === 0) { return neverType; } @@ -17993,11 +17080,17 @@ var ts; return types[0]; } var typeSet = []; - addTypesToUnion(typeSet, types); + addTypesToSet(typeSet, types, 16384); if (typeSet.containsAny) { return anyType; } - if (subtypeReduction) { + if (strictNullChecks) { + if (typeSet.containsNull) + typeSet.push(nullType); + if (typeSet.containsUndefined) + typeSet.push(undefinedType); + } + if (!noSubtypeReduction) { removeSubtypes(typeSet); } if (typeSet.length === 0) { @@ -18005,103 +17098,78 @@ var ts; typeSet.containsUndefined ? typeSet.containsNonWideningType ? undefinedType : undefinedWideningType : neverType; } - return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments); - } - function getUnionTypeFromSortedList(types, aliasSymbol, aliasTypeArguments) { - if (types.length === 0) { - return neverType; + else if (typeSet.length === 1) { + return typeSet[0]; } - if (types.length === 1) { - return types[0]; - } - var id = getTypeListId(types); + var id = getTypeListId(typeSet); var type = unionTypes[id]; if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(types, 6144); - type = unionTypes[id] = createObjectType(524288 | propagatedFlags); - type.types = types; - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = aliasTypeArguments; + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, 96); + type = unionTypes[id] = createObjectType(16384 | propagatedFlags); + type.types = typeSet; } return type; } - function getTypeFromUnionTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getTypeFromUnionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), false, aliasSymbol, aliasTypeArguments); + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), true); } return links.resolvedType; } - function addTypeToIntersection(typeSet, type) { - if (type.flags & 1048576) { - addTypesToIntersection(typeSet, type.types); - } - else if (type.flags & 1) { - typeSet.containsAny = true; - } - else if (!(type.flags & 8192) && (strictNullChecks || !(type.flags & 6144)) && !ts.contains(typeSet, type)) { - typeSet.push(type); - } - } - function addTypesToIntersection(typeSet, types) { - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type = types_6[_i]; - addTypeToIntersection(typeSet, type); - } - } - function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { + function getIntersectionType(types) { if (types.length === 0) { return emptyObjectType; } var typeSet = []; - addTypesToIntersection(typeSet, types); + addTypesToSet(typeSet, types, 32768); if (typeSet.containsAny) { return anyType; } + if (strictNullChecks) { + if (typeSet.containsNull) + typeSet.push(nullType); + if (typeSet.containsUndefined) + typeSet.push(undefinedType); + } if (typeSet.length === 1) { return typeSet[0]; } var id = getTypeListId(typeSet); var type = intersectionTypes[id]; if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, 6144); - type = intersectionTypes[id] = createObjectType(1048576 | propagatedFlags); + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, 96); + type = intersectionTypes[id] = createObjectType(32768 | propagatedFlags); type.types = typeSet; - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = aliasTypeArguments; } return type; } - function getTypeFromIntersectionTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getTypeFromIntersectionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, aliasTypeArguments); + links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode)); } return links.resolvedType; } - function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - var type = createObjectType(2097152, node.symbol); - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = aliasTypeArguments; - links.resolvedType = type; + links.resolvedType = createObjectType(65536, node.symbol); } return links.resolvedType; } - function createLiteralType(flags, text) { - var type = createType(flags); + function getStringLiteralTypeForText(text) { + if (ts.hasProperty(stringLiteralTypes, text)) { + return stringLiteralTypes[text]; + } + var type = stringLiteralTypes[text] = createType(256); type.text = text; return type; } - function getLiteralTypeForText(flags, text) { - var map = flags & 32 ? stringLiteralTypes : numericLiteralTypes; - return map[text] || (map[text] = createLiteralType(flags, text)); - } - function getTypeFromLiteralTypeNode(node) { + function getTypeFromStringLiteralTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = checkExpression(node.literal); + links.resolvedType = getStringLiteralTypeForText(ts.unescapeIdentifier(node.text)); } return links.resolvedType; } @@ -18140,7 +17208,7 @@ var ts; } return links.resolvedType; } - function getTypeFromTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getTypeFromTypeNode(node) { switch (node.kind) { case 117: case 258: @@ -18162,19 +17230,11 @@ var ts; return nullType; case 127: return neverType; - case 283: - return nullType; - case 284: - return undefinedType; - case 285: - return neverType; case 165: case 97: return getTypeFromThisTypeNode(node); case 166: - return getTypeFromLiteralTypeNode(node); - case 282: - return getTypeFromLiteralTypeNode(node.literal); + return getTypeFromStringLiteralTypeNode(node); case 155: case 267: return getTypeFromTypeReference(node); @@ -18191,9 +17251,9 @@ var ts; return getTypeFromTupleTypeNode(node); case 162: case 261: - return getTypeFromUnionTypeNode(node, aliasSymbol, aliasTypeArguments); + return getTypeFromUnionTypeNode(node); case 163: - return getTypeFromIntersectionTypeNode(node, aliasSymbol, aliasTypeArguments); + return getTypeFromIntersectionTypeNode(node); case 164: case 263: case 264: @@ -18207,7 +17267,7 @@ var ts; case 281: case 269: case 265: - return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node, aliasSymbol, aliasTypeArguments); + return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); case 69: case 139: var symbol = getSymbolAtLocation(node); @@ -18253,7 +17313,6 @@ var ts; count == 2 ? createBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : createArrayTypeMapper(sources, targets); mapper.mappedTypes = sources; - mapper.targetTypes = targets; return mapper; } function createTypeEraser(sources) { @@ -18286,7 +17345,7 @@ var ts; return mapper; } function cloneTypeParameter(typeParameter) { - var result = createType(16384); + var result = createType(512); result.symbol = typeParameter.symbol; result.target = typeParameter; return result; @@ -18321,7 +17380,7 @@ var ts; if (signature.typePredicate) { freshTypePredicate = cloneTypePredicate(signature.typePredicate, mapper); } - var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); + var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasStringLiterals); result.target = signature; result.mapper = mapper; return result; @@ -18352,11 +17411,9 @@ var ts; else { mapper.instantiations = []; } - var result = createObjectType(2097152 | 4194304, type.symbol); + var result = createObjectType(65536 | 131072, type.symbol); result.target = type; result.mapper = mapper; - result.aliasSymbol = type.aliasSymbol; - result.aliasTypeArguments = mapper.targetTypes; mapper.instantiations[type.id] = result; return result; } @@ -18408,23 +17465,26 @@ var ts; } function instantiateType(type, mapper) { if (type && mapper !== identityMapper) { - if (type.flags & 16384) { + if (type.flags & 512) { return mapper(type); } - if (type.flags & 2097152) { + if (type.flags & 65536) { return type.symbol && type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && - (type.flags & 4194304 || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? + (type.flags & 131072 || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? instantiateAnonymousType(type, mapper) : type; } - if (type.flags & 131072) { + if (type.flags & 4096) { return createTypeReference(type.target, instantiateList(type.typeArguments, mapper, instantiateType)); } - if (type.flags & 524288 && !(type.flags & 8190)) { - return getUnionType(instantiateList(type.types, mapper, instantiateType), false, type.aliasSymbol, mapper.targetTypes); + if (type.flags & 8192) { + return createTupleType(instantiateList(type.elementTypes, mapper, instantiateType)); } - if (type.flags & 1048576) { - return getIntersectionType(instantiateList(type.types, mapper, instantiateType), type.aliasSymbol, mapper.targetTypes); + if (type.flags & 16384) { + return getUnionType(instantiateList(type.types, mapper, instantiateType), true); + } + if (type.flags & 32768) { + return getIntersectionType(instantiateList(type.types, mapper, instantiateType)); } } return type; @@ -18467,10 +17527,10 @@ var ts; return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { - if (type.flags & 2588672) { + if (type.flags & 80896) { var resolved = resolveStructuredTypeMembers(type); if (resolved.constructSignatures.length) { - var result = createObjectType(2097152, type.symbol); + var result = createObjectType(65536, type.symbol); result.members = resolved.members; result.properties = resolved.properties; result.callSignatures = emptyArray; @@ -18481,25 +17541,22 @@ var ts; return type; } function isTypeIdenticalTo(source, target) { - return isTypeRelatedTo(source, target, identityRelation); + return checkTypeRelatedTo(source, target, identityRelation, undefined); } function compareTypesIdentical(source, target) { - return isTypeRelatedTo(source, target, identityRelation) ? -1 : 0; + return checkTypeRelatedTo(source, target, identityRelation, undefined) ? -1 : 0; } function compareTypesAssignable(source, target) { - return isTypeRelatedTo(source, target, assignableRelation) ? -1 : 0; + return checkTypeRelatedTo(source, target, assignableRelation, undefined) ? -1 : 0; } function isTypeSubtypeOf(source, target) { - return isTypeRelatedTo(source, target, subtypeRelation); + return checkTypeSubtypeOf(source, target, undefined); } function isTypeAssignableTo(source, target) { - return isTypeRelatedTo(source, target, assignableRelation); - } - function isTypeInstanceOf(source, target) { - return source === target || isTypeSubtypeOf(source, target) && !isTypeIdenticalTo(source, target); + return checkTypeAssignableTo(source, target, undefined); } function isTypeComparableTo(source, target) { - return isTypeRelatedTo(source, target, comparableRelation); + return checkTypeComparableTo(source, target, undefined); } function areTypesComparable(type1, type2) { return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); @@ -18612,8 +17669,8 @@ var ts; var sourceReturnType = getReturnTypeOfSignature(erasedSource); var targetReturnType = getReturnTypeOfSignature(erasedTarget); if (targetReturnType === voidType - || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation) - || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) { + || checkTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation, undefined) + || checkTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation, undefined)) { return isSignatureAssignableTo(erasedSource, erasedTarget, true); } return false; @@ -18639,88 +17696,6 @@ var ts; sourceNonRestParamCount; } } - function isEnumTypeRelatedTo(source, target, errorReporter) { - if (source === target) { - return true; - } - var id = source.id + "," + target.id; - if (enumRelation[id] !== undefined) { - return enumRelation[id]; - } - if (source.symbol.name !== target.symbol.name || - !(source.symbol.flags & 256) || !(target.symbol.flags & 256) || - (source.flags & 524288) !== (target.flags & 524288)) { - return enumRelation[id] = false; - } - var targetEnumType = getTypeOfSymbol(target.symbol); - for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { - var property = _a[_i]; - if (property.flags & 8) { - var targetProperty = getPropertyOfType(targetEnumType, property.name); - if (!targetProperty || !(targetProperty.flags & 8)) { - if (errorReporter) { - errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, undefined, 128)); - } - return enumRelation[id] = false; - } - } - } - return enumRelation[id] = true; - } - function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { - if (target.flags & 8192) - return false; - if (target.flags & 1 || source.flags & 8192) - return true; - if (source.flags & 34 && target.flags & 2) - return true; - if (source.flags & 340 && target.flags & 4) - return true; - if (source.flags & 136 && target.flags & 8) - return true; - if (source.flags & 256 && target.flags & 16 && source.baseType === target) - return true; - if (source.flags & 16 && target.flags & 16 && isEnumTypeRelatedTo(source, target, errorReporter)) - return true; - if (source.flags & 2048 && (!strictNullChecks || target.flags & (2048 | 1024))) - return true; - if (source.flags & 4096 && (!strictNullChecks || target.flags & 4096)) - return true; - if (relation === assignableRelation || relation === comparableRelation) { - if (source.flags & 1) - return true; - if ((source.flags & 4 | source.flags & 64) && target.flags & 272) - return true; - if (source.flags & 256 && - target.flags & 256 && - source.text === target.text && - isEnumTypeRelatedTo(source.baseType, target.baseType, errorReporter)) { - return true; - } - if (source.flags & 256 && - target.flags & 16 && - isEnumTypeRelatedTo(target, source.baseType, errorReporter)) { - return true; - } - } - return false; - } - function isTypeRelatedTo(source, target, relation) { - if (source === target || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { - return true; - } - if (source.flags & 2588672 && target.flags & 2588672) { - var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; - var related = relation[id]; - if (related !== undefined) { - return related === 1; - } - } - if (source.flags & 4177920 || target.flags & 4177920) { - return checkTypeRelatedTo(source, target, relation, undefined, undefined, undefined); - } - return false; - } function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain) { var errorInfo; var sourceStack; @@ -18759,16 +17734,6 @@ var ts; } reportError(message, sourceType, targetType); } - function tryElaborateErrorsForPrimitivesAndObjects(source, target) { - var sourceType = typeToString(source); - var targetType = typeToString(target); - if ((globalStringType === source && stringType === target) || - (globalNumberType === source && numberType === target) || - (globalBooleanType === source && booleanType === target) || - (getGlobalESSymbolType() === source && esSymbolType === target)) { - reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); - } - } function isRelatedTo(source, target, reportErrors, headMessage) { var result; if (source === target) @@ -18776,50 +17741,78 @@ var ts; if (relation === identityRelation) { return isIdenticalTo(source, target); } - if (isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) - return -1; - if (source.flags & 16777216) { + if (!(target.flags & 134217728)) { + if (target.flags & 1 || source.flags & 134217728) + return -1; + if (source.flags & 32) { + if (!strictNullChecks || target.flags & (32 | 16)) + return -1; + } + if (source.flags & 64) { + if (!strictNullChecks || target.flags & 64) + return -1; + } + if (source.flags & 128 && target === numberType) + return -1; + if (source.flags & 128 && target.flags & 128) { + if (result = enumRelatedTo(source, target, reportErrors)) { + return result; + } + } + if (source.flags & 256 && target === stringType) + return -1; + if (relation === assignableRelation || relation === comparableRelation) { + if (source.flags & 1) + return -1; + if (source === numberType && target.flags & 128) + return -1; + } + if (source.flags & 8 && target.flags & 8) { + return -1; + } + } + if (source.flags & 1048576) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { reportRelationError(headMessage, source, target); } return 0; } - if (target.flags & 1572864) { + if (target.flags & 49152) { source = getRegularTypeOfObjectLiteral(source); } } var saveErrorInfo = errorInfo; - if (source.flags & 524288) { + if (source.flags & 16384) { if (relation === comparableRelation) { - result = someTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190)); + result = someTypeRelatedToType(source, target, reportErrors); } else { - result = eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190)); + result = eachTypeRelatedToType(source, target, reportErrors); } if (result) { return result; } } - else if (target.flags & 1048576) { + else if (target.flags & 32768) { result = typeRelatedToEachType(source, target, reportErrors); if (result) { return result; } } else { - if (source.flags & 1048576) { + if (source.flags & 32768) { if (result = someTypeRelatedToType(source, target, false)) { return result; } } - if (target.flags & 524288) { - if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190) && !(target.flags & 8190))) { + if (target.flags & 16384) { + if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 16777726))) { return result; } } } - if (source.flags & 16384) { + if (source.flags & 512) { var constraint = getConstraintOfTypeParameter(source); if (!constraint || constraint.flags & 1) { constraint = emptyObjectType; @@ -18832,14 +17825,14 @@ var ts; } } else { - if (source.flags & 131072 && target.flags & 131072 && source.target === target.target) { + if (source.flags & 4096 && target.flags & 4096 && source.target === target.target) { if (result = typeArgumentsRelatedTo(source, target, reportErrors)) { return result; } } var apparentSource = getApparentType(source); - if (apparentSource.flags & (2588672 | 1048576) && target.flags & 2588672) { - var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !(source.flags & 8190); + if (apparentSource.flags & (80896 | 32768) && target.flags & 80896) { + var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !(source.flags & 16777726); if (result = objectTypeRelatedTo(apparentSource, source, target, reportStructuralErrors)) { errorInfo = saveErrorInfo; return result; @@ -18847,25 +17840,22 @@ var ts; } } if (reportErrors) { - if (source.flags & 2588672 && target.flags & 8190) { - tryElaborateErrorsForPrimitivesAndObjects(source, target); - } reportRelationError(headMessage, source, target); } return 0; } function isIdenticalTo(source, target) { var result; - if (source.flags & 2588672 && target.flags & 2588672) { - if (source.flags & 131072 && target.flags & 131072 && source.target === target.target) { + if (source.flags & 80896 && target.flags & 80896) { + if (source.flags & 4096 && target.flags & 4096 && source.target === target.target) { if (result = typeArgumentsRelatedTo(source, target, false)) { return result; } } return objectTypeRelatedTo(source, source, target, false); } - if (source.flags & 524288 && target.flags & 524288 || - source.flags & 1048576 && target.flags & 1048576) { + if (source.flags & 16384 && target.flags & 16384 || + source.flags & 32768 && target.flags & 32768) { if (result = eachTypeRelatedToSomeType(source, target, false)) { if (result &= eachTypeRelatedToSomeType(target, source, false)) { return result; @@ -18875,7 +17865,7 @@ var ts; return 0; } function isKnownProperty(type, name) { - if (type.flags & 2588672) { + if (type.flags & 80896) { var resolved = resolveStructuredTypeMembers(type); if ((relation === assignableRelation || relation === comparableRelation) && (type === globalObjectType || isEmptyObjectType(resolved)) || resolved.stringIndexInfo || @@ -18884,7 +17874,7 @@ var ts; return true; } } - else if (type.flags & 1572864) { + else if (type.flags & 49152) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; if (isKnownProperty(t, name)) { @@ -18902,7 +17892,7 @@ var ts; !t.numberIndexInfo; } function hasExcessProperties(source, target, reportErrors) { - if (!(target.flags & 536870912) && maybeTypeOfKind(target, 2588672)) { + if (!(target.flags & 67108864) && maybeTypeOfKind(target, 80896)) { for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; if (!isKnownProperty(target, prop.name)) { @@ -18932,10 +17922,14 @@ var ts; } function typeRelatedToSomeType(source, target, reportErrors) { var targetTypes = target.types; - if (target.flags & 524288 && containsType(targetTypes, source)) { - return -1; - } var len = targetTypes.length; + while (len >= 2 && targetTypes[len - 1].flags & 96) { + var related = isRelatedTo(source, targetTypes[len - 1], false); + if (related) { + return related; + } + len--; + } for (var i = 0; i < len; i++) { var related = isRelatedTo(source, targetTypes[i], reportErrors && i === len - 1); if (related) { @@ -18959,10 +17953,14 @@ var ts; } function someTypeRelatedToType(source, target, reportErrors) { var sourceTypes = source.types; - if (source.flags & 524288 && containsType(sourceTypes, target)) { - return -1; - } var len = sourceTypes.length; + while (len >= 2 && sourceTypes[len - 1].flags & 96) { + var related = isRelatedTo(sourceTypes[len - 1], target, false); + if (related) { + return related; + } + len--; + } for (var i = 0; i < len; i++) { var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); if (related) { @@ -19034,7 +18032,7 @@ var ts; } sourceStack[depth] = source; targetStack[depth] = target; - maybeStack[depth] = ts.createMap(); + maybeStack[depth] = {}; maybeStack[depth][id] = 1; depth++; var saveExpandingFlags = expandingFlags; @@ -19066,7 +18064,7 @@ var ts; if (result) { var maybeCache = maybeStack[depth]; var destinationCache = (result === -1 || depth === 0) ? relation : maybeStack[depth - 1]; - ts.copyProperties(maybeCache, destinationCache); + ts.copyMap(maybeCache, destinationCache); } else { relation[id] = reportErrors ? 3 : 2; @@ -19079,7 +18077,7 @@ var ts; } var result = -1; var properties = getPropertiesOfObjectType(target); - var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 8388608); + var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 524288); for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) { var targetProp = properties_1[_i]; var sourceProp = getPropertyOfType(source, targetProp.name); @@ -19145,7 +18143,7 @@ var ts; return result; } function propertiesIdenticalTo(source, target) { - if (!(source.flags & 2588672 && target.flags & 2588672)) { + if (!(source.flags & 80896 && target.flags & 80896)) { return 0; } var sourceProperties = getPropertiesOfObjectType(source); @@ -19258,7 +18256,7 @@ var ts; return indexTypesIdenticalTo(source, target, kind); } var targetInfo = getIndexInfoOfType(target, kind); - if (!targetInfo || ((targetInfo.type.flags & 1) && !(originalSource.flags & 8190))) { + if (!targetInfo || ((targetInfo.type.flags & 1) && !(originalSource.flags & 16777726))) { return -1; } var sourceInfo = getIndexInfoOfType(source, kind) || @@ -19295,6 +18293,27 @@ var ts; } return 0; } + function enumRelatedTo(source, target, reportErrors) { + if (source.symbol.name !== target.symbol.name || + source.symbol.flags & 128 || + target.symbol.flags & 128) { + return 0; + } + var targetEnumType = getTypeOfSymbol(target.symbol); + for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { + var property = _a[_i]; + if (property.flags & 8) { + var targetProperty = getPropertyOfType(targetEnumType, property.name); + if (!targetProperty || !(targetProperty.flags & 8)) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, undefined, 128)); + } + return 0; + } + } + } + return -1; + } function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) { if (!sourceSignature.declaration || !targetSignature.declaration) { return true; @@ -19317,7 +18336,7 @@ var ts; } } function isAbstractConstructorType(type) { - if (type.flags & 2097152) { + if (type.flags & 65536) { var symbol = type.symbol; if (symbol && symbol.flags & 32) { var declaration = getClassLikeDeclarationOfSymbol(symbol); @@ -19329,12 +18348,12 @@ var ts; return false; } function isDeeplyNestedGeneric(type, stack, depth) { - if (type.flags & (131072 | 4194304) && depth >= 5) { + if (type.flags & (4096 | 131072) && depth >= 5) { var symbol = type.symbol; var count = 0; for (var i = 0; i < depth; i++) { var t = stack[i]; - if (t.flags & (131072 | 4194304) && t.symbol === symbol) { + if (t.flags & (4096 | 131072) && t.symbol === symbol) { count++; if (count >= 5) return true; @@ -19376,10 +18395,8 @@ var ts; source.hasRestParameter === target.hasRestParameter) { return true; } - var sourceRestCount = source.hasRestParameter ? 1 : 0; - var targetRestCount = target.hasRestParameter ? 1 : 0; - if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (sourceRestCount > targetRestCount || - sourceRestCount === targetRestCount && source.parameters.length >= target.parameters.length)) { + if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (source.hasRestParameter && !target.hasRestParameter || + source.hasRestParameter === target.hasRestParameter && source.parameters.length >= target.parameters.length)) { return true; } return false; @@ -19429,23 +18446,31 @@ var ts; return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } function isSupertypeOfEach(candidate, types) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var t = types_5[_i]; if (candidate !== t && !isTypeSubtypeOf(t, candidate)) return false; } return true; } + function getCombinedFlagsOfTypes(types) { + var flags = 0; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var t = types_6[_i]; + flags |= t.flags; + } + return flags; + } function getCommonSupertype(types) { if (!strictNullChecks) { return ts.forEach(types, function (t) { return isSupertypeOfEach(t, types) ? t : undefined; }); } - var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 6144); }); + var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 96); }); if (!primaryTypes.length) { - return getUnionType(types, true); + return getUnionType(types); } var supertype = ts.forEach(primaryTypes, function (t) { return isSupertypeOfEach(t, primaryTypes) ? t : undefined; }); - return supertype && includeFalsyTypes(supertype, getFalsyFlagsOfTypes(types) & 6144); + return supertype && addTypeKind(supertype, getCombinedFlagsOfTypes(types) & 96); } function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { var bestSupertype; @@ -19475,72 +18500,44 @@ var ts; checkTypeSubtypeOf(bestSupertypeDownfallType, bestSupertype, errorLocation, ts.Diagnostics.Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0, errorMessageChainHead); } function isArrayType(type) { - return type.flags & 131072 && type.target === globalArrayType; + return type.flags & 4096 && type.target === globalArrayType; } function isArrayLikeType(type) { - return type.flags & 131072 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || - !(type.flags & 6144) && isTypeAssignableTo(type, anyReadonlyArrayType); + return type.flags & 4096 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || + !(type.flags & 96) && isTypeAssignableTo(type, anyReadonlyArrayType); } function isTupleLikeType(type) { return !!getPropertyOfType(type, "0"); } - function isUnitType(type) { - return (type.flags & (480 | 2048 | 4096)) !== 0; - } - function isUnitUnionType(type) { - return type.flags & 8 ? true : - type.flags & 524288 ? type.flags & 16 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : - isUnitType(type); - } - function getBaseTypeOfUnitType(type) { - return type.flags & 32 ? stringType : - type.flags & 64 ? numberType : - type.flags & 128 ? booleanType : - type.flags & 256 ? type.baseType : - type.flags & 524288 && !(type.flags & 16) ? getUnionType(ts.map(type.types, getBaseTypeOfUnitType)) : - type; + function isStringLiteralUnionType(type) { + return type.flags & 256 ? true : + type.flags & 16384 ? ts.forEach(type.types, isStringLiteralUnionType) : + false; } function isTupleType(type) { - return !!(type.flags & 131072 && type.target.flags & 262144); + return !!(type.flags & 8192); } - function getFalsyFlagsOfTypes(types) { - var result = 0; - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var t = types_8[_i]; - result |= getFalsyFlags(t); - } - return result; + function getCombinedTypeFlags(type) { + return type.flags & 16384 ? getCombinedFlagsOfTypes(type.types) : type.flags; } - function getFalsyFlags(type) { - return type.flags & 524288 ? getFalsyFlagsOfTypes(type.types) : - type.flags & 32 ? type === emptyStringType ? 32 : 0 : - type.flags & 64 ? type === zeroType ? 64 : 0 : - type.flags & 128 ? type === falseType ? 128 : 0 : - type.flags & 7406; - } - function includeFalsyTypes(type, flags) { - if ((getFalsyFlags(type) & flags) === flags) { + function addTypeKind(type, kind) { + if ((getCombinedTypeFlags(type) & kind) === kind) { return type; } var types = [type]; - if (flags & 34) - types.push(emptyStringType); - if (flags & 340) - types.push(zeroType); - if (flags & 136) - types.push(falseType); - if (flags & 1024) + if (kind & 2) + types.push(stringType); + if (kind & 4) + types.push(numberType); + if (kind & 8) + types.push(booleanType); + if (kind & 16) types.push(voidType); - if (flags & 2048) + if (kind & 32) types.push(undefinedType); - if (flags & 4096) + if (kind & 64) types.push(nullType); - return getUnionType(types, true); - } - function removeDefinitelyFalsyTypes(type) { - return getFalsyFlags(type) & 7392 ? - filterType(type, function (t) { return !(getFalsyFlags(t) & 7392); }) : - type; + return getUnionType(types); } function getNonNullableType(type) { return strictNullChecks ? getTypeWithFacts(type, 524288) : type; @@ -19562,7 +18559,7 @@ var ts; return symbol; } function transformTypeOfMembers(type, f) { - var members = ts.createMap(); + var members = {}; for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { var property = _a[_i]; var original = getTypeOfSymbol(property); @@ -19573,7 +18570,7 @@ var ts; return members; } function getRegularTypeOfObjectLiteral(type) { - if (!(type.flags & 16777216)) { + if (!(type.flags & 1048576)) { return type; } var regularType = type.regularType; @@ -19583,7 +18580,7 @@ var ts; var resolved = type; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); - regularNew.flags = resolved.flags & ~16777216; + regularNew.flags = resolved.flags & ~1048576; type.regularType = regularNew; return regularNew; } @@ -19597,28 +18594,31 @@ var ts; return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); } function getWidenedConstituentType(type) { - return type.flags & 6144 ? type : getWidenedType(type); + return type.flags & 96 ? type : getWidenedType(type); } function getWidenedType(type) { - if (type.flags & 100663296) { - if (type.flags & 6144) { + if (type.flags & 6291456) { + if (type.flags & 96) { return anyType; } - if (type.flags & 8388608) { + if (type.flags & 524288) { return getWidenedTypeOfObjectLiteral(type); } - if (type.flags & 524288) { - return getUnionType(ts.map(type.types, getWidenedConstituentType)); + if (type.flags & 16384) { + return getUnionType(ts.map(type.types, getWidenedConstituentType), true); } - if (isArrayType(type) || isTupleType(type)) { - return createTypeReference(type.target, ts.map(type.typeArguments, getWidenedType)); + if (isArrayType(type)) { + return createArrayType(getWidenedType(type.typeArguments[0])); + } + if (isTupleType(type)) { + return createTupleType(ts.map(type.elementTypes, getWidenedType)); } } return type; } function reportWideningErrorsInType(type) { var errorReported = false; - if (type.flags & 524288) { + if (type.flags & 16384) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; if (reportWideningErrorsInType(t)) { @@ -19626,19 +18626,22 @@ var ts; } } } - if (isArrayType(type) || isTupleType(type)) { - for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) { + if (isArrayType(type)) { + return reportWideningErrorsInType(type.typeArguments[0]); + } + if (isTupleType(type)) { + for (var _b = 0, _c = type.elementTypes; _b < _c.length; _b++) { var t = _c[_b]; if (reportWideningErrorsInType(t)) { errorReported = true; } } } - if (type.flags & 8388608) { + if (type.flags & 524288) { for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); - if (t.flags & 33554432) { + if (t.flags & 2097152) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, p.name, typeToString(getWidenedType(t))); } @@ -19683,7 +18686,7 @@ var ts; error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); } function reportErrorsFromWidening(declaration, type) { - if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 33554432) { + if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 2097152) { if (!reportWideningErrorsInType(type)) { reportImplicitAnyError(declaration, type); } @@ -19725,24 +18728,12 @@ var ts; isFixed: false }; } - function couldContainTypeParameters(type) { - return !!(type.flags & 16384 || - type.flags & 131072 && ts.forEach(type.typeArguments, couldContainTypeParameters) || - type.flags & 2097152 && type.symbol && type.symbol.flags & (8192 | 2048 | 32) || - type.flags & 1572864 && couldUnionOrIntersectionContainTypeParameters(type)); - } - function couldUnionOrIntersectionContainTypeParameters(type) { - if (type.couldContainTypeParameters === undefined) { - type.couldContainTypeParameters = ts.forEach(type.types, couldContainTypeParameters); - } - return type.couldContainTypeParameters; - } function inferTypes(context, source, target) { var sourceStack; var targetStack; var depth = 0; var inferiority = 0; - var visited = ts.createMap(); + var visited = {}; inferFromTypes(source, target); function isInProcess(source, target) { for (var i = 0; i < depth; i++) { @@ -19753,21 +18744,11 @@ var ts; return false; } function inferFromTypes(source, target) { - if (!couldContainTypeParameters(target)) { - return; - } - if (source.flags & 524288 && target.flags & 524288 && !(source.flags & 16 && target.flags & 16) || - source.flags & 1048576 && target.flags & 1048576) { - if (source === target) { - for (var _i = 0, _a = source.types; _i < _a.length; _i++) { - var t = _a[_i]; - inferFromTypes(t, t); - } - return; - } + if (source.flags & 16384 && target.flags & 16384 || + source.flags & 32768 && target.flags & 32768) { var matchingTypes = void 0; - for (var _b = 0, _c = target.types; _b < _c.length; _b++) { - var t = _c[_b]; + for (var _i = 0, _a = target.types; _i < _a.length; _i++) { + var t = _a[_i]; if (typeIdenticalToSomeType(t, source.types)) { (matchingTypes || (matchingTypes = [])).push(t); inferFromTypes(t, t); @@ -19778,8 +18759,8 @@ var ts; target = removeTypesFromUnionOrIntersection(target, matchingTypes); } } - if (target.flags & 16384) { - if (source.flags & 134217728) { + if (target.flags & 512) { + if (source.flags & 8388608) { return; } var typeParameters = context.typeParameters; @@ -19798,7 +18779,7 @@ var ts; } } } - else if (source.flags & 131072 && target.flags & 131072 && source.target === target.target) { + else if (source.flags & 4096 && target.flags & 4096 && source.target === target.target) { var sourceTypes = source.typeArguments || emptyArray; var targetTypes = target.typeArguments || emptyArray; var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; @@ -19806,13 +18787,20 @@ var ts; inferFromTypes(sourceTypes[i], targetTypes[i]); } } - else if (target.flags & 1572864) { + else if (source.flags & 8192 && target.flags & 8192 && source.elementTypes.length === target.elementTypes.length) { + var sourceTypes = source.elementTypes; + var targetTypes = target.elementTypes; + for (var i = 0; i < sourceTypes.length; i++) { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } + } + else if (target.flags & 49152) { var targetTypes = target.types; var typeParameterCount = 0; var typeParameter = void 0; - for (var _d = 0, targetTypes_2 = targetTypes; _d < targetTypes_2.length; _d++) { - var t = targetTypes_2[_d]; - if (t.flags & 16384 && ts.contains(context.typeParameters, t)) { + for (var _b = 0, targetTypes_2 = targetTypes; _b < targetTypes_2.length; _b++) { + var t = targetTypes_2[_b]; + if (t.flags & 512 && ts.contains(context.typeParameters, t)) { typeParameter = t; typeParameterCount++; } @@ -19826,16 +18814,18 @@ var ts; inferiority--; } } - else if (source.flags & 1572864) { + else if (source.flags & 49152) { var sourceTypes = source.types; - for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { - var sourceType = sourceTypes_3[_e]; + for (var _c = 0, sourceTypes_3 = sourceTypes; _c < sourceTypes_3.length; _c++) { + var sourceType = sourceTypes_3[_c]; inferFromTypes(sourceType, target); } } else { source = getApparentType(source); - if (source.flags & 2588672) { + if (source.flags & 80896 && (target.flags & 4096 && target.typeArguments || + target.flags & 8192 || + target.flags & 65536 && target.symbol && target.symbol.flags & (8192 | 2048 | 32))) { if (isInProcess(source, target)) { return; } @@ -19843,7 +18833,7 @@ var ts; return; } var key = source.id + "," + target.id; - if (visited[key]) { + if (ts.hasProperty(visited, key)) { return; } visited[key] = true; @@ -19912,8 +18902,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var t = types_7[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -19928,7 +18918,7 @@ var ts; reducedTypes.push(t); } } - return type.flags & 524288 ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); + return type.flags & 16384 ? getUnionType(reducedTypes, true) : getIntersectionType(reducedTypes); } function getInferenceCandidates(context, index) { var inferences = context.inferences[index]; @@ -19940,7 +18930,7 @@ var ts; if (!inferredType) { var inferences = getInferenceCandidates(context, index); if (inferences.length) { - var unionOrSuperType = context.inferUnionTypes ? getUnionType(inferences, true) : getCommonSupertype(inferences); + var unionOrSuperType = context.inferUnionTypes ? getUnionType(inferences) : getCommonSupertype(inferences); inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType; inferenceSucceeded = !!unionOrSuperType; } @@ -20006,6 +18996,10 @@ var ts; } return undefined; } + function isNullOrUndefinedLiteral(node) { + return node.kind === 93 || + node.kind === 69 && getResolvedSymbol(node) === undefinedSymbol; + } function getLeftmostIdentifierOrThis(node) { switch (node.kind) { case 69: @@ -20017,17 +19011,16 @@ var ts; return undefined; } function isMatchingReference(source, target) { - switch (source.kind) { - case 69: - return target.kind === 69 && getResolvedSymbol(source) === getResolvedSymbol(target) || - (target.kind === 218 || target.kind === 169) && - getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); - case 97: - return target.kind === 97; - case 172: - return target.kind === 172 && - source.name.text === target.name.text && - isMatchingReference(source.expression, target.expression); + if (source.kind === target.kind) { + switch (source.kind) { + case 69: + return getResolvedSymbol(source) === getResolvedSymbol(target); + case 97: + return true; + case 172: + return source.name.text === target.name.text && + isMatchingReference(source.expression, target.expression); + } } return false; } @@ -20040,40 +19033,6 @@ var ts; } return false; } - function containsMatchingReferenceDiscriminant(source, target) { - return target.kind === 172 && - containsMatchingReference(source, target.expression) && - isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.text); - } - function getDeclaredTypeOfReference(expr) { - if (expr.kind === 69) { - return getTypeOfSymbol(getResolvedSymbol(expr)); - } - if (expr.kind === 172) { - var type = getDeclaredTypeOfReference(expr.expression); - return type && getTypeOfPropertyOfType(type, expr.name.text); - } - return undefined; - } - function isDiscriminantProperty(type, name) { - if (type && type.flags & 524288) { - var prop = getPropertyOfType(type, name); - if (!prop) { - var filteredType = getTypeWithFacts(type, 4194304); - if (filteredType !== type && filteredType.flags & 524288) { - prop = getPropertyOfType(filteredType, name); - } - } - if (prop && prop.flags & 268435456) { - if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !prop.hasCommonType && - isUnitUnionType(getTypeOfSymbol(prop)); - } - return prop.isDiscriminantProperty; - } - } - return false; - } function isOrContainsMatchingReference(source, target) { return isMatchingReference(source, target) || containsMatchingReference(source, target); } @@ -20100,7 +19059,7 @@ var ts; return flow.id; } function typeMaybeAssignableTo(source, target) { - if (!(source.flags & 524288)) { + if (!(source.flags & 16384)) { return isTypeAssignableTo(source, target); } for (var _i = 0, _a = source.types; _i < _a.length; _i++) { @@ -20112,79 +19071,70 @@ var ts; return false; } function getAssignmentReducedType(declaredType, assignedType) { - if (declaredType !== assignedType) { - var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); - if (reducedType !== neverType) { - return reducedType; + if (declaredType !== assignedType && declaredType.flags & 16384) { + var reducedTypes = ts.filter(declaredType.types, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (reducedTypes.length) { + return reducedTypes.length === 1 ? reducedTypes[0] : getUnionType(reducedTypes); } } return declaredType; } - function getTypeFactsOfTypes(types) { - var result = 0; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; - result |= getTypeFacts(t); - } - return result; - } - function isFunctionObjectType(type) { - var resolved = resolveStructuredTypeMembers(type); - return !!(resolved.callSignatures.length || resolved.constructSignatures.length || - resolved.members["bind"] && isTypeSubtypeOf(type, globalFunctionType)); - } function getTypeFacts(type) { var flags = type.flags; - if (flags & 2) { + if (flags & 258) { return strictNullChecks ? 4079361 : 4194049; } - if (flags & 32) { - return strictNullChecks ? - type === emptyStringType ? 3030785 : 1982209 : - type === emptyStringType ? 3145473 : 4194049; - } - if (flags & (4 | 16)) { + if (flags & 132) { return strictNullChecks ? 4079234 : 4193922; } - if (flags & (64 | 256)) { - var isZero = type === zeroType || type.flags & 256 && type.text === "0"; - return strictNullChecks ? - isZero ? 3030658 : 1982082 : - isZero ? 3145346 : 4193922; - } if (flags & 8) { return strictNullChecks ? 4078980 : 4193668; } - if (flags & 136) { - return strictNullChecks ? - type === falseType ? 3030404 : 1981828 : - type === falseType ? 3145092 : 4193668; + if (flags & 80896) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length || resolved.constructSignatures.length || isTypeSubtypeOf(type, globalFunctionType) ? + strictNullChecks ? 1970144 : 4181984 : + strictNullChecks ? 1972176 : 4184016; } - if (flags & 2588672) { - return isFunctionObjectType(type) ? - strictNullChecks ? 6164448 : 8376288 : - strictNullChecks ? 6166480 : 8378320; - } - if (flags & (1024 | 2048)) { + if (flags & (16 | 32)) { return 2457472; } - if (flags & 4096) { + if (flags & 64) { return 2340752; } - if (flags & 512) { + if (flags & 16777216) { return strictNullChecks ? 1981320 : 4193160; } - if (flags & 16384) { + if (flags & 512) { var constraint = getConstraintOfTypeParameter(type); - return getTypeFacts(constraint || emptyObjectType); + return constraint ? getTypeFacts(constraint) : 4194303; } - if (flags & 1572864) { - return getTypeFactsOfTypes(type.types); + if (flags & 32768) { + return ts.reduceLeft(type.types, function (flags, type) { return flags |= getTypeFacts(type); }, 0); } - return 8388607; + return 4194303; } function getTypeWithFacts(type, include) { - return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); + if (!(type.flags & 16384)) { + return getTypeFacts(type) & include ? type : neverType; + } + var firstType; + var types; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (getTypeFacts(t) & include) { + if (!firstType) { + firstType = t; + } + else { + if (!types) { + types = [firstType]; + } + types.push(t); + } + } + } + return firstType ? types ? getUnionType(types, true) : firstType : neverType; } function getTypeWithDefault(type, defaultExpression) { if (defaultExpression) { @@ -20278,86 +19228,51 @@ var ts; getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } - function getInitialOrAssignedType(node) { - return node.kind === 218 || node.kind === 169 ? - getInitialType(node) : - getAssignedType(node); - } - function getReferenceCandidate(node) { + function getReferenceFromExpression(node) { switch (node.kind) { case 178: - return getReferenceCandidate(node.expression); + return getReferenceFromExpression(node.expression); case 187: switch (node.operatorToken.kind) { case 56: - return getReferenceCandidate(node.left); + return getReferenceFromExpression(node.left); case 24: - return getReferenceCandidate(node.right); + return getReferenceFromExpression(node.right); } } return node; } function getTypeOfSwitchClause(clause) { if (clause.kind === 249) { - var caseType = checkExpression(clause.expression); - return isUnitType(caseType) ? caseType : undefined; + var expr = clause.expression; + return expr.kind === 9 ? getStringLiteralTypeForText(expr.text) : checkExpression(expr); } - return neverType; + return undefined; } function getSwitchClauseTypes(switchStatement) { var links = getNodeLinks(switchStatement); if (!links.switchTypes) { var types = ts.map(switchStatement.caseBlock.clauses, getTypeOfSwitchClause); - links.switchTypes = !ts.contains(types, undefined) ? types : emptyArray; + links.switchTypes = ts.forEach(types, function (t) { return !t || t.flags & 256; }) ? types : emptyArray; } return links.switchTypes; } function eachTypeContainedIn(source, types) { - return source.flags & 524288 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); - } - function isTypeSubsetOf(source, target) { - return source === target || target.flags & 524288 && isTypeSubsetOfUnion(source, target); - } - function isTypeSubsetOfUnion(source, target) { - if (source.flags & 524288) { - for (var _i = 0, _a = source.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (!containsType(target.types, t)) { - return false; - } - } - return true; - } - if (source.flags & 256 && target.flags & 16 && source.baseType === target) { - return true; - } - return containsType(target.types, source); + return source.flags & 16384 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } function filterType(type, f) { - if (type.flags & 524288) { - var types = type.types; - var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered); - } - return f(type) ? type : neverType; + return type.flags & 16384 ? + getUnionType(ts.filter(type.types, f)) : + f(type) ? type : neverType; } - function isIncomplete(flowType) { - return flowType.flags === 0; - } - function getTypeFromFlowType(flowType) { - return flowType.flags === 0 ? flowType.type : flowType; - } - function createFlowType(type, incomplete) { - return incomplete ? { flags: 0, type: type } : type; - } - function getFlowTypeOfReference(reference, declaredType, assumeInitialized, flowContainer) { + function getFlowTypeOfReference(reference, declaredType, assumeInitialized, includeOuterFunctions) { var key; - if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 4178943)) { + if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 16908175)) { return declaredType; } - var initialType = assumeInitialized ? declaredType : includeFalsyTypes(declaredType, 2048); + var initialType = assumeInitialized ? declaredType : addTypeKind(declaredType, 32); var visitedFlowStart = visitedFlowCount; - var result = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); + var result = getTypeAtFlowNode(reference.flowNode); visitedFlowCount = visitedFlowStart; if (reference.parent.kind === 196 && getTypeWithFacts(result, 524288) === neverType) { return declaredType; @@ -20397,7 +19312,7 @@ var ts; } else if (flow.flags & 2) { var container = flow.container; - if (container && container !== flowContainer && reference.kind !== 172) { + if (container && includeOuterFunctions) { flow = container.flowNode; continue; } @@ -20416,9 +19331,16 @@ var ts; } function getTypeAtFlowAssignment(flow) { var node = flow.node; + if ((node.kind === 218 || node.kind === 169) && + reference.kind === 69 && + getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(reference)) === getSymbolOfNode(node)) { + return declaredType.flags & 16384 ? + getAssignmentReducedType(declaredType, getInitialType(node)) : + declaredType; + } if (isMatchingReference(reference, node)) { - return declaredType.flags & 524288 ? - getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : + return declaredType.flags & 16384 ? + getAssignmentReducedType(declaredType, getAssignedType(node)) : declaredType; } if (containsMatchingReference(reference, node)) { @@ -20427,55 +19349,37 @@ var ts; return undefined; } function getTypeAtFlowCondition(flow) { - var flowType = getTypeAtFlowNode(flow.antecedent); - var type = getTypeFromFlowType(flowType); + var type = getTypeAtFlowNode(flow.antecedent); if (type !== neverType) { var assumeTrue = (flow.flags & 32) !== 0; type = narrowType(type, flow.expression, assumeTrue); - if (type === neverType && isIncomplete(flowType)) { + if (type === neverType) { type = narrowType(declaredType, flow.expression, assumeTrue); } } - return createFlowType(type, isIncomplete(flowType)); + return type; } function getTypeAtSwitchClause(flow) { - var flowType = getTypeAtFlowNode(flow.antecedent); - var type = getTypeFromFlowType(flowType); - var expr = flow.switchStatement.expression; - if (isMatchingReference(reference, expr)) { - type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); - } - else if (isMatchingReferenceDiscriminant(expr)) { - type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); - } - return createFlowType(type, isIncomplete(flowType)); + var type = getTypeAtFlowNode(flow.antecedent); + return narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } function getTypeAtFlowBranchLabel(flow) { var antecedentTypes = []; - var subtypeReduction = false; - var seenIncomplete = false; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { var antecedent = _a[_i]; - var flowType = getTypeAtFlowNode(antecedent); - var type = getTypeFromFlowType(flowType); + var type = getTypeAtFlowNode(antecedent); if (type === declaredType && declaredType === initialType) { return type; } if (!ts.contains(antecedentTypes, type)) { antecedentTypes.push(type); } - if (!isTypeSubsetOf(type, declaredType)) { - subtypeReduction = true; - } - if (isIncomplete(flowType)) { - seenIncomplete = true; - } } - return createFlowType(getUnionType(antecedentTypes, subtypeReduction), seenIncomplete); + return getUnionType(antecedentTypes); } function getTypeAtFlowLoopLabel(flow) { var id = getFlowNodeId(flow); - var cache = flowLoopCaches[id] || (flowLoopCaches[id] = ts.createMap()); + var cache = flowLoopCaches[id] || (flowLoopCaches[id] = {}); if (!key) { key = getFlowCacheKey(reference); } @@ -20484,66 +19388,32 @@ var ts; } for (var i = flowLoopStart; i < flowLoopCount; i++) { if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key) { - return createFlowType(getUnionType(flowLoopTypes[i]), true); + return getUnionType(flowLoopTypes[i]); } } var antecedentTypes = []; - var subtypeReduction = false; - var firstAntecedentType; flowLoopNodes[flowLoopCount] = flow; flowLoopKeys[flowLoopCount] = key; flowLoopTypes[flowLoopCount] = antecedentTypes; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { var antecedent = _a[_i]; flowLoopCount++; - var flowType = getTypeAtFlowNode(antecedent); + var type = getTypeAtFlowNode(antecedent); flowLoopCount--; - if (!firstAntecedentType) { - firstAntecedentType = flowType; - } - var type = getTypeFromFlowType(flowType); if (cache[key]) { return cache[key]; } if (!ts.contains(antecedentTypes, type)) { antecedentTypes.push(type); } - if (!isTypeSubsetOf(type, declaredType)) { - subtypeReduction = true; - } if (type === declaredType) { break; } } - var result = getUnionType(antecedentTypes, subtypeReduction); - if (isIncomplete(firstAntecedentType)) { - return createFlowType(result, true); - } - return cache[key] = result; - } - function isMatchingReferenceDiscriminant(expr) { - return expr.kind === 172 && - declaredType.flags & 524288 && - isMatchingReference(reference, expr.expression) && - isDiscriminantProperty(declaredType, expr.name.text); - } - function narrowTypeByDiscriminant(type, propAccess, narrowType) { - var propName = propAccess.name.text; - var propType = getTypeOfPropertyOfType(type, propName); - var narrowedPropType = propType && narrowType(propType); - return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); + return cache[key] = getUnionType(antecedentTypes); } function narrowTypeByTruthiness(type, expr, assumeTrue) { - if (isMatchingReference(reference, expr)) { - return getTypeWithFacts(type, assumeTrue ? 1048576 : 2097152); - } - if (isMatchingReferenceDiscriminant(expr)) { - return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 1048576 : 2097152); }); - } - if (containsMatchingReferenceDiscriminant(reference, expr)) { - return declaredType; - } - return type; + return isMatchingReference(reference, expr) ? getTypeWithFacts(type, assumeTrue ? 1048576 : 2097152) : type; } function narrowTypeByBinaryExpression(type, expr, assumeTrue) { switch (expr.operatorToken.kind) { @@ -20553,29 +19423,26 @@ var ts; case 31: case 32: case 33: - var operator_1 = expr.operatorToken.kind; - var left_1 = getReferenceCandidate(expr.left); - var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 182 && right_1.kind === 9) { - return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); + var left = expr.left; + var operator = expr.operatorToken.kind; + var right = expr.right; + if (isNullOrUndefinedLiteral(right)) { + return narrowTypeByNullCheck(type, left, operator, right, assumeTrue); } - if (right_1.kind === 182 && left_1.kind === 9) { - return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); + if (isNullOrUndefinedLiteral(left)) { + return narrowTypeByNullCheck(type, right, operator, left, assumeTrue); } - if (isMatchingReference(reference, left_1)) { - return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); + if (left.kind === 182 && right.kind === 9) { + return narrowTypeByTypeof(type, left, operator, right, assumeTrue); } - if (isMatchingReference(reference, right_1)) { - return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); + if (right.kind === 182 && left.kind === 9) { + return narrowTypeByTypeof(type, right, operator, left, assumeTrue); } - if (isMatchingReferenceDiscriminant(left_1)) { - return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); + if (left.kind === 172) { + return narrowTypeByDiscriminant(type, left, operator, right, assumeTrue); } - if (isMatchingReferenceDiscriminant(right_1)) { - return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); - } - if (containsMatchingReferenceDiscriminant(reference, left_1) || containsMatchingReferenceDiscriminant(reference, right_1)) { - return declaredType; + if (right.kind === 172) { + return narrowTypeByDiscriminant(type, right, operator, left, assumeTrue); } break; case 91: @@ -20585,37 +19452,23 @@ var ts; } return type; } - function narrowTypeByEquality(type, operator, value, assumeTrue) { - if (type.flags & 1) { - return type; - } + function narrowTypeByNullCheck(type, target, operator, literal, assumeTrue) { if (operator === 31 || operator === 33) { assumeTrue = !assumeTrue; } - var valueType = checkExpression(value); - if (valueType.flags & 6144) { - if (!strictNullChecks) { - return type; - } - var doubleEquals = operator === 30 || operator === 31; - var facts = doubleEquals ? - assumeTrue ? 65536 : 524288 : - value.kind === 93 ? - assumeTrue ? 32768 : 262144 : - assumeTrue ? 16384 : 131072; - return getTypeWithFacts(type, facts); - } - if (type.flags & 2589191) { + if (!strictNullChecks || !isMatchingReference(reference, getReferenceFromExpression(target))) { return type; } - if (assumeTrue) { - var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType !== neverType ? narrowedType : type; - } - return isUnitType(valueType) ? filterType(type, function (t) { return t !== valueType; }) : type; + var doubleEquals = operator === 30 || operator === 31; + var facts = doubleEquals ? + assumeTrue ? 65536 : 524288 : + literal.kind === 93 ? + assumeTrue ? 32768 : 262144 : + assumeTrue ? 16384 : 131072; + return getTypeWithFacts(type, facts); } function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { - var target = getReferenceCandidate(typeOfExpr.expression); + var target = getReferenceFromExpression(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { if (containsMatchingReference(reference, target)) { return declaredType; @@ -20625,40 +19478,76 @@ var ts; if (operator === 31 || operator === 33) { assumeTrue = !assumeTrue; } - if (assumeTrue && !(type.flags & 524288)) { - var targetType = typeofTypesByName[literal.text]; + if (assumeTrue && !(type.flags & 16384)) { + var targetType = ts.getProperty(typeofTypesByName, literal.text); if (targetType && isTypeSubtypeOf(targetType, type)) { return targetType; } } var facts = assumeTrue ? - typeofEQFacts[literal.text] || 64 : - typeofNEFacts[literal.text] || 8192; + ts.getProperty(typeofEQFacts, literal.text) || 64 : + ts.getProperty(typeofNEFacts, literal.text) || 8192; return getTypeWithFacts(type, facts); } + function narrowTypeByDiscriminant(type, propAccess, operator, value, assumeTrue) { + if (!isMatchingReference(reference, propAccess.expression)) { + return type; + } + var propName = propAccess.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return type; + } + var discriminantType = value.kind === 9 ? getStringLiteralTypeForText(value.text) : checkExpression(value); + if (!isStringLiteralUnionType(discriminantType)) { + return type; + } + if (operator === 31 || operator === 33) { + assumeTrue = !assumeTrue; + } + if (assumeTrue) { + return filterType(type, function (t) { return areTypesComparable(getTypeOfPropertyOfType(t, propName), discriminantType); }); + } + if (discriminantType.flags & 256) { + return filterType(type, function (t) { return getTypeOfPropertyOfType(t, propName) !== discriminantType; }); + } + return type; + } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { + if (!isMatchingReference(reference, switchStatement.expression.expression)) { + return type; + } + var propName = switchStatement.expression.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return type; + } var switchTypes = getSwitchClauseTypes(switchStatement); if (!switchTypes.length) { return type; } var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); - var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); - var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType === neverType ? neverType : filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }); + var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, undefined); + var caseTypes = hasDefaultClause ? ts.filter(clauseTypes, function (t) { return !!t; }) : clauseTypes; + var discriminantType = caseTypes.length ? getUnionType(caseTypes) : undefined; + var caseType = discriminantType && filterType(type, function (t) { return isTypeComparableTo(discriminantType, getTypeOfPropertyOfType(t, propName)); }); if (!hasDefaultClause) { return caseType; } - var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, t)); }); - return caseType === neverType ? defaultType : getUnionType([caseType, defaultType]); + var defaultType = filterType(type, function (t) { return !eachTypeContainedIn(getTypeOfPropertyOfType(t, propName), switchTypes); }); + return caseType ? getUnionType([caseType, defaultType]) : defaultType; } function narrowTypeByInstanceof(type, expr, assumeTrue) { - var left = getReferenceCandidate(expr.left); + var left = getReferenceFromExpression(expr.left); if (!isMatchingReference(reference, left)) { if (containsMatchingReference(reference, left)) { return declaredType; } return type; } + if (isTypeAny(type)) { + return type; + } var rightType = checkExpression(expr.right); if (!isTypeSubtypeOf(rightType, globalFunctionType)) { return type; @@ -20671,15 +19560,12 @@ var ts; targetType = prototypePropertyType; } } - if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) { - return type; - } if (!targetType) { var constructSignatures = void 0; - if (rightType.flags & 65536) { + if (rightType.flags & 2048) { constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; } - else if (rightType.flags & 2097152) { + else if (rightType.flags & 65536) { constructSignatures = getSignaturesOfType(rightType, 1); } if (constructSignatures && constructSignatures.length) { @@ -20693,22 +19579,23 @@ var ts; } function getNarrowedType(type, candidate, assumeTrue) { if (!assumeTrue) { - return filterType(type, function (t) { return !isTypeInstanceOf(t, candidate); }); + return type.flags & 16384 ? + getUnionType(ts.filter(type.types, function (t) { return !isTypeSubtypeOf(t, candidate); })) : + type; } - if (type.flags & 524288) { - var assignableType = filterType(type, function (t) { return isTypeInstanceOf(t, candidate); }); - if (assignableType !== neverType) { - return assignableType; + if (type.flags & 16384) { + var assignableConstituents = ts.filter(type.types, function (t) { return isTypeAssignableTo(t, candidate); }); + if (assignableConstituents.length) { + return getUnionType(assignableConstituents); } } - var targetType = type.flags & 16384 ? getApparentType(type) : type; - return isTypeSubtypeOf(candidate, type) ? candidate : + var targetType = type.flags & 512 ? getApparentType(type) : type; + return isTypeAssignableTo(candidate, targetType) ? candidate : isTypeAssignableTo(type, candidate) ? type : - isTypeAssignableTo(candidate, targetType) ? candidate : - getIntersectionType([type, candidate]); + getIntersectionType([type, candidate]); } function narrowTypeByTypePredicate(type, callExpression, assumeTrue) { - if (!hasMatchingArgument(callExpression, reference)) { + if (type.flags & 1 || !hasMatchingArgument(callExpression, reference)) { return type; } var signature = getResolvedSignature(callExpression); @@ -20716,9 +19603,6 @@ var ts; if (!predicate) { return type; } - if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { - return type; - } if (ts.isIdentifierTypePredicate(predicate)) { var predicateArgument = callExpression.arguments[predicate.parameterIndex]; if (predicateArgument) { @@ -20789,48 +19673,20 @@ var ts; function getControlFlowContainer(node) { while (true) { node = node.parent; - if (ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || - node.kind === 226 || - node.kind === 256 || - node.kind === 145) { + if (ts.isFunctionLike(node) || node.kind === 226 || node.kind === 256 || node.kind === 145) { return node; } } } - function isParameterAssigned(symbol) { - var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; - var links = getNodeLinks(func); - if (!(links.flags & 4194304)) { - links.flags |= 4194304; - if (!hasParentWithAssignmentsMarked(func)) { - markParameterAssignments(func); - } - } - return symbol.isAssigned || false; - } - function hasParentWithAssignmentsMarked(node) { - while (true) { - node = node.parent; - if (!node) { - return false; - } - if (ts.isFunctionLike(node) && getNodeLinks(node).flags & 4194304) { - return true; - } - } - } - function markParameterAssignments(node) { - if (node.kind === 69) { - if (ts.isAssignmentTarget(node)) { - var symbol = getResolvedSymbol(node); - if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 142) { - symbol.isAssigned = true; - } - } - } - else { - ts.forEachChild(node, markParameterAssignments); + function isDeclarationIncludedInFlow(reference, declaration, includeOuterFunctions) { + var declarationContainer = getControlFlowContainer(declaration); + var container = getControlFlowContainer(reference); + while (container !== declarationContainer && + (container.kind === 179 || container.kind === 180) && + (includeOuterFunctions || ts.getImmediatelyInvokedFunctionExpression(container))) { + container = getControlFlowContainer(container); } + return container === declarationContainer; } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); @@ -20867,23 +19723,16 @@ var ts; checkCollisionWithCapturedThisVariable(node, node); checkNestedBlockScopedBinding(node, symbol); var type = getTypeOfSymbol(localOrExportSymbol); - var declaration = localOrExportSymbol.valueDeclaration; - if (!(localOrExportSymbol.flags & 3) || ts.isAssignmentTarget(node) || !declaration) { + if (!(localOrExportSymbol.flags & 3) || ts.isAssignmentTarget(node)) { return type; } - var isParameter = ts.getRootDeclaration(declaration).kind === 142; - var declarationContainer = getControlFlowContainer(declaration); - var flowContainer = getControlFlowContainer(node); - var isOuterVariable = flowContainer !== declarationContainer; - while (flowContainer !== declarationContainer && - (flowContainer.kind === 179 || flowContainer.kind === 180) && - (isReadonlySymbol(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { - flowContainer = getControlFlowContainer(flowContainer); - } - var assumeInitialized = !strictNullChecks || (type.flags & 1) !== 0 || isParameter || - isOuterVariable || ts.isInAmbientContext(declaration); - var flowType = getFlowTypeOfReference(node, type, assumeInitialized, flowContainer); - if (!assumeInitialized && !(getFalsyFlags(type) & 2048) && getFalsyFlags(flowType) & 2048) { + var declaration = localOrExportSymbol.valueDeclaration; + var includeOuterFunctions = isReadonlySymbol(localOrExportSymbol); + var assumeInitialized = !strictNullChecks || (type.flags & 1) !== 0 || !declaration || + ts.getRootDeclaration(declaration).kind === 142 || ts.isInAmbientContext(declaration) || + !isDeclarationIncludedInFlow(node, declaration, includeOuterFunctions); + var flowType = getFlowTypeOfReference(node, type, assumeInitialized, includeOuterFunctions); + if (!assumeInitialized && !(getCombinedTypeFlags(type) & 32) && getCombinedTypeFlags(flowType) & 32) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); return type; } @@ -21046,6 +19895,10 @@ var ts; return getInferredClassType(classSymbol); } } + var type = getContextuallyTypedThisType(container); + if (type) { + return type; + } var thisType = getThisTypeOfDeclaration(container); if (thisType) { return thisType; @@ -21054,7 +19907,7 @@ var ts; if (ts.isClassLike(container.parent)) { var symbol = getSymbolOfNode(container.parent); var type = container.flags & 32 ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; - return getFlowTypeOfReference(node, type, true, undefined); + return getFlowTypeOfReference(node, type, true, true); } if (ts.isInJavaScriptFile(node)) { var type = getTypeForThisExpressionFromJSDoc(container); @@ -21187,11 +20040,11 @@ var ts; return false; } } - function getContextualThisParameter(func) { + function getContextuallyTypedThisType(func) { if (isContextSensitiveFunctionOrObjectLiteralMethod(func) && func.kind !== 180) { var contextualSignature = getContextualSignature(func); if (contextualSignature) { - return contextualSignature.thisParameter; + return getThisTypeOfSignature(contextualSignature); } } return undefined; @@ -21248,7 +20101,7 @@ var ts; } } if (ts.isBindingPattern(declaration.name)) { - return getTypeFromBindingPattern(declaration.name, true, false); + return getTypeFromBindingPattern(declaration.name, true); } if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; @@ -21331,9 +20184,6 @@ var ts; var binaryExpression = node.parent; var operator = binaryExpression.operatorToken.kind; if (operator >= 56 && operator <= 68) { - if (ts.getSpecialPropertyAssignmentKind(binaryExpression) !== 0) { - return undefined; - } if (node === binaryExpression.right) { return checkExpression(binaryExpression.left); } @@ -21353,14 +20203,14 @@ var ts; return undefined; } function applyToContextualType(type, mapper) { - if (!(type.flags & 524288)) { + if (!(type.flags & 16384)) { return mapper(type); } var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var current = types_11[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var current = types_8[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -21378,7 +20228,7 @@ var ts; } function getTypeOfPropertyOfContextualType(type, name) { return applyToContextualType(type, function (t) { - var prop = t.flags & 4161536 ? getPropertyOfType(t, name) : undefined; + var prop = t.flags & 130048 ? getPropertyOfType(t, name) : undefined; return prop ? getTypeOfSymbol(prop) : undefined; }); } @@ -21386,7 +20236,7 @@ var ts; return applyToContextualType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); } function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 524288 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); + return !!(type.flags & 16384 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); } function getContextualTypeForObjectLiteralMethod(node) { ts.Debug.assert(ts.isObjectLiteralMethod(node)); @@ -21492,30 +20342,6 @@ var ts; } return undefined; } - function isLiteralTypeLocation(node) { - var parent = node.parent; - switch (parent.kind) { - case 187: - switch (parent.operatorToken.kind) { - case 32: - case 33: - case 30: - case 31: - return true; - } - break; - case 188: - return (node === parent.whenTrue || - node === parent.whenFalse) && - isLiteralTypeLocation(parent); - case 178: - return isLiteralTypeLocation(parent); - case 249: - case 166: - return true; - } - return false; - } function getNonGenericSignature(type) { var signatures = getSignaturesOfStructuredType(type, 0); if (signatures.length === 1) { @@ -21544,13 +20370,13 @@ var ts; if (!type) { return undefined; } - if (!(type.flags & 524288)) { + if (!(type.flags & 16384)) { return getNonGenericSignature(type); } var signatureList; var types = type.types; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var current = types_12[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var current = types_9[_i]; var signature = getNonGenericSignature(current); if (signature) { if (!signatureList) { @@ -21606,7 +20432,7 @@ var ts; } if (!hasSpreadElement) { if (inDestructuringPattern && elementTypes.length) { - var type = cloneTypeReference(createTupleType(elementTypes)); + var type = createNewTupleType(elementTypes); type.pattern = node; return type; } @@ -21618,7 +20444,7 @@ var ts; for (var i = elementTypes.length; i < patternElements.length; i++) { var patternElement = patternElements[i]; if (hasDefaultValue(patternElement)) { - elementTypes.push(contextualType.typeArguments[i]); + elementTypes.push(contextualType.elementTypes[i]); } else { if (patternElement.kind !== 193) { @@ -21633,15 +20459,13 @@ var ts; } } } - return createArrayType(elementTypes.length ? - getUnionType(elementTypes, true) : - strictNullChecks ? neverType : undefinedWideningType); + return createArrayType(elementTypes.length ? getUnionType(elementTypes) : strictNullChecks ? neverType : undefinedWideningType); } function isNumericName(name) { return name.kind === 140 ? isNumericComputedName(name) : isNumericLiteralName(name.text); } function isNumericComputedName(name) { - return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 340); + return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 132); } function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { return isTypeAny(type) || isTypeOfKind(type, kind); @@ -21653,7 +20477,7 @@ var ts; var links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); - if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 340 | 34 | 512)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 132 | 258 | 16777216)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -21669,13 +20493,13 @@ var ts; propTypes.push(getTypeOfSymbol(properties[i])); } } - var unionType = propTypes.length ? getUnionType(propTypes, true) : undefinedType; + var unionType = propTypes.length ? getUnionType(propTypes) : undefinedType; return createIndexInfo(unionType, false); } function checkObjectLiteral(node, contextualMapper) { var inDestructuringPattern = ts.isAssignmentTarget(node); checkGrammarObjectLiteralExpression(node, inDestructuringPattern); - var propertiesTable = ts.createMap(); + var propertiesTable = {}; var propertiesArray = []; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && @@ -21713,7 +20537,7 @@ var ts; patternWithComputedProperties = true; } } - else if (contextualTypeHasPattern && !(contextualType.flags & 536870912)) { + else if (contextualTypeHasPattern && !(contextualType.flags & 67108864)) { var impliedProp = getPropertyOfType(contextualType, member.name); if (impliedProp) { prop.flags |= impliedProp.flags & 536870912; @@ -21751,7 +20575,7 @@ var ts; if (contextualTypeHasPattern) { for (var _b = 0, _c = getPropertiesOfType(contextualType); _b < _c.length; _b++) { var prop = _c[_b]; - if (!propertiesTable[prop.name]) { + if (!ts.hasProperty(propertiesTable, prop.name)) { if (!(prop.flags & 536870912)) { error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } @@ -21763,8 +20587,8 @@ var ts; var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 0) : undefined; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 1) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16777216; - result.flags |= 8388608 | 67108864 | freshObjectLiteralFlag | (typeFlags & 234881024) | (patternWithComputedProperties ? 536870912 : 0); + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576; + result.flags |= 524288 | 4194304 | freshObjectLiteralFlag | (typeFlags & 14680064) | (patternWithComputedProperties ? 67108864 : 0); if (inDestructuringPattern) { result.pattern = node; } @@ -21818,9 +20642,9 @@ var ts; var correspondingPropSymbol = getPropertyOfType(elementAttributesType, node.name.text); correspondingPropType = correspondingPropSymbol && getTypeOfSymbol(correspondingPropSymbol); if (isUnhyphenatedJsxName(node.name.text)) { - var attributeType = getTypeOfPropertyOfType(elementAttributesType, getTextOfPropertyName(node.name)) || getIndexTypeOfType(elementAttributesType, 0); - if (attributeType) { - correspondingPropType = attributeType; + var indexerType = getIndexTypeOfType(elementAttributesType, 0); + if (indexerType) { + correspondingPropType = indexerType; } else { if (!correspondingPropType) { @@ -21893,7 +20717,7 @@ var ts; return links.resolvedSymbol; } function getJsxElementInstanceType(node, valueType) { - ts.Debug.assert(!(valueType.flags & 524288)); + ts.Debug.assert(!(valueType.flags & 16384)); if (isTypeAny(valueType)) { return anyType; } @@ -21905,11 +20729,11 @@ var ts; return unknownType; } } - return getUnionType(signatures.map(getReturnTypeOfSignature), true); + return getUnionType(signatures.map(getReturnTypeOfSignature)); } function getJsxElementPropertiesName() { - var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920, undefined); - var attribsPropTypeSym = jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.ElementAttributesPropertyNameContainer, 793064); + var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1536, undefined); + var attribsPropTypeSym = jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.ElementAttributesPropertyNameContainer, 793056); var attribPropType = attribsPropTypeSym && getDeclaredTypeOfSymbol(attribsPropTypeSym); var attribProperties = attribPropType && getPropertiesOfType(attribPropType); if (attribProperties) { @@ -21932,16 +20756,16 @@ var ts; if (!elemType) { elemType = checkExpression(node.tagName); } - if (elemType.flags & 524288) { + if (elemType.flags & 16384) { var types = elemType.types; return getUnionType(types.map(function (type) { return getResolvedJsxType(node, type, elemClassType); - }), true); + })); } if (elemType.flags & 2) { return anyType; } - else if (elemType.flags & 32) { + else if (elemType.flags & 256) { var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { var stringLiteralTypeName = elemType.text; @@ -21994,7 +20818,7 @@ var ts; else if (isTypeAny(attributesType) || (attributesType === unknownType)) { return attributesType; } - else if (attributesType.flags & 524288) { + else if (attributesType.flags & 16384) { error(node.tagName, ts.Diagnostics.JSX_element_attributes_type_0_may_not_be_a_union_type, typeToString(attributesType)); return anyType; } @@ -22077,7 +20901,7 @@ var ts; getSymbolLinks(reactSym).referenced = true; } var targetAttributesType = getJsxElementAttributesType(node); - var nameTable = ts.createMap(); + var nameTable = {}; var sawSpreadedAny = false; for (var i = node.attributes.length - 1; i >= 0; i--) { if (node.attributes[i].kind === 246) { @@ -22095,7 +20919,7 @@ var ts; var targetProperties = getPropertiesOfType(targetAttributesType); for (var i = 0; i < targetProperties.length; i++) { if (!(targetProperties[i].flags & 536870912) && - !nameTable[targetProperties[i].name]) { + nameTable[targetProperties[i].name] === undefined) { error(node, ts.Diagnostics.Property_0_is_missing_in_type_1, targetProperties[i].name, typeToString(targetAttributesType)); } } @@ -22156,10 +20980,10 @@ var ts; if (flags & 32) { return true; } - if (type.flags & 268435456) { + if (type.flags & 33554432) { type = getConstraintOfTypeParameter(type); } - if (!(getTargetType(type).flags & (32768 | 65536) && hasBaseType(type, enclosingClass))) { + if (!(getTargetType(type).flags & (1024 | 2048) && hasBaseType(type, enclosingClass))) { error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); return false; } @@ -22168,9 +20992,9 @@ var ts; function checkNonNullExpression(node) { var type = checkExpression(node); if (strictNullChecks) { - var kind = getFalsyFlags(type) & 6144; + var kind = getCombinedTypeFlags(type) & 96; if (kind) { - error(node, kind & 2048 ? kind & 4096 ? + error(node, kind & 32 ? kind & 64 ? ts.Diagnostics.Object_is_possibly_null_or_undefined : ts.Diagnostics.Object_is_possibly_undefined : ts.Diagnostics.Object_is_possibly_null); @@ -22191,13 +21015,13 @@ var ts; return type; } var apparentType = getApparentType(getWidenedType(type)); - if (apparentType === unknownType || (type.flags & 16384 && isTypeAny(apparentType))) { + if (apparentType === unknownType || (type.flags & 512 && isTypeAny(apparentType))) { return apparentType; } var prop = getPropertyOfType(apparentType, right.text); if (!prop) { if (right.text && !checkAndReportErrorForExtendingInterface(node)) { - error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type.flags & 268435456 ? apparentType : type)); + error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type.flags & 33554432 ? apparentType : type)); } return unknownType; } @@ -22216,15 +21040,12 @@ var ts; checkClassPropertyAccess(node, left, apparentType, prop); } var propType = getTypeOfSymbol(prop); - if (prop.flags & 8 && isLiteralContextForType(node, propType)) { - propType = getDeclaredTypeOfSymbol(prop); - } if (node.kind !== 172 || ts.isAssignmentTarget(node) || !(prop.flags & (3 | 4 | 98304)) && - !(prop.flags & 8192 && propType.flags & 524288)) { + !(prop.flags & 8192 && propType.flags & 16384)) { return propType; } - return getFlowTypeOfReference(node, propType, true, undefined); + return getFlowTypeOfReference(node, propType, true, false); } function isValidPropertyAccess(node, propertyName) { var left = node.kind === 172 @@ -22315,9 +21136,8 @@ var ts; } } } - var allowedNullableFlags = strictNullChecks ? 0 : 6144; - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 34 | 340 | 512 | allowedNullableFlags)) { - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 | allowedNullableFlags) || isForInVariableForNumericPropertyNames(node.argumentExpression)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 258 | 132 | 16777216)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 132) || isForInVariableForNumericPropertyNames(node.argumentExpression)) { var numberIndexInfo = getIndexInfoOfType(objectType, 1); if (numberIndexInfo) { getNodeLinks(node).resolvedIndexInfo = numberIndexInfo; @@ -22362,7 +21182,7 @@ var ts; if (!ts.isWellKnownSymbolSyntactically(expression)) { return false; } - if ((expressionType.flags & 512) === 0) { + if ((expressionType.flags & 16777216) === 0) { if (reportError) { error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); } @@ -22426,7 +21246,7 @@ var ts; lastParent = parent_9; } lastSymbol = symbol; - if (signature.hasLiteralTypes) { + if (signature.hasStringLiterals) { specializedIndex++; spliceIndex = specializedIndex; cutoffIndex++; @@ -22500,7 +21320,7 @@ var ts; return callIsIncomplete || hasEnoughArguments; } function getSingleCallSignature(type) { - if (type.flags & 2588672) { + if (type.flags & 80896) { var resolved = resolveStructuredTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -22600,7 +21420,9 @@ var ts; var paramType = getTypeAtPosition(signature, i); var argType = getEffectiveArgumentType(node, i, arg); if (argType === undefined) { - argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + argType = arg.kind === 9 && !reportErrors + ? getStringLiteralTypeForText(arg.text) + : checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); } var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; if (!checkTypeRelatedTo(argType, paramType, relation, errorNode, headMessage)) { @@ -22704,10 +21526,10 @@ var ts; case 69: case 8: case 9: - return getLiteralTypeForText(32, element.name.text); + return getStringLiteralTypeForText(element.name.text); case 140: var nameType = checkComputedPropertyName(element.name); - if (isTypeOfKind(nameType, 512)) { + if (isTypeOfKind(nameType, 16777216)) { return nameType; } else { @@ -22947,7 +21769,9 @@ var ts; } var callSignatures = getSignaturesOfType(apparentType, 0); var constructSignatures = getSignaturesOfType(apparentType, 1); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + if (isTypeAny(funcType) || + (isTypeAny(apparentType) && funcType.flags & 512) || + (!callSignatures.length && !constructSignatures.length && !(funcType.flags & 16384) && isTypeAssignableTo(funcType, globalFunctionType))) { if (funcType !== unknownType && node.typeArguments) { error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); } @@ -22964,21 +21788,6 @@ var ts; } return resolveCall(node, callSignatures, candidatesOutArray); } - function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { - if (isTypeAny(funcType)) { - return true; - } - if (isTypeAny(apparentFuncType) && funcType.flags & 16384) { - return true; - } - if (!numCallSignatures && !numConstructSignatures) { - if (funcType.flags & 524288) { - return false; - } - return isTypeAssignableTo(funcType, globalFunctionType); - } - return false; - } function resolveNewExpression(node, candidatesOutArray) { if (node.arguments && languageVersion < 1) { var spreadIndex = getSpreadArgumentIndex(node.arguments); @@ -23035,18 +21844,6 @@ var ts; var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); if (!isNodeWithinClass(node, declaringClassDeclaration)) { - var containingClass = ts.getContainingClass(node); - if (containingClass) { - var containingType = getTypeOfNode(containingClass); - var baseTypes = getBaseTypes(containingType); - if (baseTypes.length) { - var baseType = baseTypes[0]; - if (flags & 16 && - baseType.symbol === declaration.parent.symbol) { - return true; - } - } - } if (flags & 8) { error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); } @@ -23064,8 +21861,7 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0); - var constructSignatures = getSignaturesOfType(apparentType, 1); - if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { + if (isTypeAny(tagType) || (!callSignatures.length && !(tagType.flags & 16384) && isTypeAssignableTo(tagType, globalFunctionType))) { return resolveUntypedCall(node); } if (!callSignatures.length) { @@ -23096,8 +21892,7 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0); - var constructSignatures = getSignaturesOfType(apparentType, 1); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + if (funcType === anyType || (!callSignatures.length && !(funcType.flags & 16384) && isTypeAssignableTo(funcType, globalFunctionType))) { return resolveUntypedCall(node); } var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); @@ -23126,21 +21921,21 @@ var ts; function getResolvedSignature(node, candidatesOutArray) { var links = getNodeLinks(node); var cached = links.resolvedSignature; - if (cached && cached !== resolvingSignature && !candidatesOutArray) { + if (cached && cached !== anySignature && !candidatesOutArray) { return cached; } - links.resolvedSignature = resolvingSignature; + links.resolvedSignature = anySignature; var result = resolveSignature(node, candidatesOutArray); links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached; return result; } function getResolvedOrAnySignature(node) { - return getNodeLinks(node).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(node); + return getNodeLinks(node).resolvedSignature === anySignature ? anySignature : getResolvedSignature(node); } function getInferredClassType(symbol) { var links = getSymbolLinks(symbol); if (!links.inferredClassType) { - links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, undefined, undefined); + links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, undefined, undefined); } return links.inferredClassType; } @@ -23197,7 +21992,7 @@ var ts; if (strictNullChecks) { var declaration = symbol.valueDeclaration; if (declaration && declaration.initializer) { - return includeFalsyTypes(type, 2048); + return addTypeKind(type, 32); } } return type; @@ -23209,12 +22004,6 @@ var ts; } function assignContextualParameterTypes(signature, context, mapper) { var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); - if (context.thisParameter) { - if (!signature.thisParameter) { - signature.thisParameter = createTransientSymbol(context.thisParameter, undefined); - } - assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter), mapper); - } for (var i = 0; i < len; i++) { var parameter = signature.parameters[i]; var contextualParameterType = getTypeAtPosition(context, i); @@ -23312,7 +22101,7 @@ var ts; return isAsync ? createPromiseReturnType(func, voidType) : voidType; } } - type = contextualSignature ? getUnionType(types, true) : getCommonSupertype(types); + type = contextualSignature ? getUnionType(types) : getCommonSupertype(types); if (!type) { if (funcIsGenerator) { error(func, ts.Diagnostics.No_best_common_type_exists_among_yield_expressions); @@ -23320,7 +22109,7 @@ var ts; } else { error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); - return isAsync ? createPromiseReturnType(func, getUnionType(types, true)) : getUnionType(types, true); + return isAsync ? createPromiseReturnType(func, getUnionType(types)) : getUnionType(types); } } if (funcIsGenerator) { @@ -23350,18 +22139,24 @@ var ts; return aggregatedTypes; } function isExhaustiveSwitchStatement(node) { - if (!node.possiblyExhaustive) { + var expr = node.expression; + if (!node.possiblyExhaustive || expr.kind !== 172) { return false; } - var type = checkExpression(node.expression); - if (!isUnitUnionType(type)) { + var type = checkExpression(expr.expression); + if (!(type.flags & 16384)) { + return false; + } + var propName = expr.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { return false; } var switchTypes = getSwitchClauseTypes(node); if (!switchTypes.length) { return false; } - return eachTypeContainedIn(type, switchTypes); + return eachTypeContainedIn(propType, switchTypes); } function functionHasImplicitReturn(func) { if (!(func.flags & 32768)) { @@ -23411,7 +22206,7 @@ var ts; if (!produceDiagnostics) { return; } - if (returnType && maybeTypeOfKind(returnType, 1 | 1024)) { + if (returnType && maybeTypeOfKind(returnType, 1 | 16)) { return; } if (ts.nodeIsMissing(func.body) || func.body.kind !== 199 || !functionHasImplicitReturn(func)) { @@ -23513,7 +22308,7 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 340)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 132)) { error(operand, diagnostic); return false; } @@ -23607,22 +22402,16 @@ var ts; } function checkPrefixUnaryExpression(node) { var operandType = checkExpression(node.operand); - if (node.operator === 36 && node.operand.kind === 8 && isLiteralContextForType(node, numberType)) { - return getLiteralTypeForText(64, "" + -node.operand.text); - } switch (node.operator) { case 35: case 36: case 50: - if (maybeTypeOfKind(operandType, 512)) { + if (maybeTypeOfKind(operandType, 16777216)) { error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } return numberType; case 49: - var facts = getTypeFacts(operandType) & (1048576 | 2097152); - return facts === 1048576 ? falseType : - facts === 2097152 ? trueType : - booleanType; + return booleanType; case 41: case 42: var ok = checkArithmeticOperandType(node.operand, getNonNullableType(operandType), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); @@ -23645,10 +22434,10 @@ var ts; if (type.flags & kind) { return true; } - if (type.flags & 1572864) { + if (type.flags & 49152) { var types = type.types; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -23660,20 +22449,20 @@ var ts; if (type.flags & kind) { return true; } - if (type.flags & 524288) { + if (type.flags & 16384) { var types = type.types; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; if (!isTypeOfKind(t, kind)) { return false; } } return true; } - if (type.flags & 1048576) { + if (type.flags & 32768) { var types = type.types; - for (var _a = 0, types_15 = types; _a < types_15.length; _a++) { - var t = types_15[_a]; + for (var _a = 0, types_12 = types; _a < types_12.length; _a++) { + var t = types_12[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -23682,13 +22471,13 @@ var ts; return false; } function isConstEnumObjectType(type) { - return type.flags & (2588672 | 2097152) && type.symbol && isConstEnumSymbol(type.symbol); + return type.flags & (80896 | 65536) && type.symbol && isConstEnumSymbol(type.symbol); } function isConstEnumSymbol(symbol) { return (symbol.flags & 128) !== 0; } function checkInstanceOfExpression(left, right, leftType, rightType) { - if (isTypeOfKind(leftType, 8190)) { + if (isTypeOfKind(leftType, 16777726)) { error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } if (!(isTypeAny(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) { @@ -23697,10 +22486,10 @@ var ts; return booleanType; } function checkInExpression(left, right, leftType, rightType) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 34 | 340 | 512)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258 | 132 | 16777216)) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 2588672 | 16384)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 80896 | 512)) { error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; @@ -23767,9 +22556,8 @@ var ts; return checkDestructuringAssignment(element, type, contextualMapper); } else { - checkExpression(element); if (isTupleType(sourceType)) { - error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); + error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), sourceType.elementTypes.length, elements.length); } else { error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); @@ -23799,7 +22587,7 @@ var ts; var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { if (strictNullChecks && - !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 2048)) { + !(getCombinedTypeFlags(checkExpression(prop.objectAssignmentInitializer)) & 32)) { sourceType = getTypeWithFacts(sourceType, 131072); } checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, contextualMapper); @@ -23829,14 +22617,7 @@ var ts; return sourceType; } function isTypeEqualityComparableTo(source, target) { - return (target.flags & 6144) !== 0 || isTypeComparableTo(source, target); - } - function getBestChoiceType(type1, type2) { - var firstAssignableToSecond = isTypeAssignableTo(type1, type2); - var secondAssignableToFirst = isTypeAssignableTo(type2, type1); - return secondAssignableToFirst && !firstAssignableToSecond ? type1 : - firstAssignableToSecond && !secondAssignableToFirst ? type2 : - getUnionType([type1, type2], true); + return (target.flags & 96) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, contextualMapper) { return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, contextualMapper, node); @@ -23871,15 +22652,15 @@ var ts; case 68: case 46: case 66: - if (leftType.flags & 6144) + if (leftType.flags & 96) leftType = rightType; - if (rightType.flags & 6144) + if (rightType.flags & 96) rightType = leftType; leftType = getNonNullableType(leftType); rightType = getNonNullableType(rightType); var suggestedOperator = void 0; - if ((leftType.flags & 136) && - (rightType.flags & 136) && + if ((leftType.flags & 8) && + (rightType.flags & 8) && (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator)); } @@ -23893,18 +22674,18 @@ var ts; return numberType; case 35: case 57: - if (leftType.flags & 6144) + if (leftType.flags & 96) leftType = rightType; - if (rightType.flags & 6144) + if (rightType.flags & 96) rightType = leftType; leftType = getNonNullableType(leftType); rightType = getNonNullableType(rightType); var resultType = void 0; - if (isTypeOfKind(leftType, 340) && isTypeOfKind(rightType, 340)) { + if (isTypeOfKind(leftType, 132) && isTypeOfKind(rightType, 132)) { resultType = numberType; } else { - if (isTypeOfKind(leftType, 34) || isTypeOfKind(rightType, 34)) { + if (isTypeOfKind(leftType, 258) || isTypeOfKind(rightType, 258)) { resultType = stringType; } else if (isTypeAny(leftType) || isTypeAny(rightType)) { @@ -23936,12 +22717,6 @@ var ts; case 31: case 32: case 33: - var leftIsUnit = isUnitUnionType(leftType); - var rightIsUnit = isUnitUnionType(rightType); - if (!leftIsUnit || !rightIsUnit) { - leftType = leftIsUnit ? getBaseTypeOfUnitType(leftType) : leftType; - rightType = rightIsUnit ? getBaseTypeOfUnitType(rightType) : rightType; - } if (!isTypeEqualityComparableTo(leftType, rightType) && !isTypeEqualityComparableTo(rightType, leftType)) { reportOperatorError(); } @@ -23951,13 +22726,9 @@ var ts; case 90: return checkInExpression(left, right, leftType, rightType); case 51: - return getTypeFacts(leftType) & 1048576 ? - includeFalsyTypes(rightType, getFalsyFlags(strictNullChecks ? leftType : getBaseTypeOfUnitType(rightType))) : - leftType; + return strictNullChecks ? addTypeKind(rightType, getCombinedTypeFlags(leftType) & 112) : rightType; case 52: - return getTypeFacts(leftType) & 2097152 ? - getBestChoiceType(removeDefinitelyFalsyTypes(leftType), rightType) : - leftType; + return getUnionType([getNonNullableType(leftType), rightType]); case 56: checkAssignmentOperator(rightType); return getRegularTypeOfObjectLiteral(rightType); @@ -23965,8 +22736,8 @@ var ts; return rightType; } function checkForDisallowedESSymbolOperand(operator) { - var offendingSymbolOperand = maybeTypeOfKind(leftType, 512) ? left : - maybeTypeOfKind(rightType, 512) ? right : + var offendingSymbolOperand = maybeTypeOfKind(leftType, 16777216) ? left : + maybeTypeOfKind(rightType, 16777216) ? right : undefined; if (offendingSymbolOperand) { error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); @@ -24051,63 +22822,14 @@ var ts; checkExpression(node.condition); var type1 = checkExpression(node.whenTrue, contextualMapper); var type2 = checkExpression(node.whenFalse, contextualMapper); - return getBestChoiceType(type1, type2); + return getUnionType([type1, type2]); } - function typeContainsLiteralFromEnum(type, enumType) { - if (type.flags & 524288) { - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (t.flags & 256 && t.baseType === enumType) { - return true; - } - } - } - if (type.flags & 256) { - return type.baseType === enumType; - } - return false; - } - function isLiteralContextForType(node, type) { - if (isLiteralTypeLocation(node)) { - return true; - } + function checkStringLiteralExpression(node) { var contextualType = getContextualType(node); - if (contextualType) { - if (contextualType.flags & 16384) { - var apparentType = getApparentTypeOfTypeParameter(contextualType); - if (type === apparentType) { - return true; - } - contextualType = apparentType; - } - if (type.flags & 2) { - return maybeTypeOfKind(contextualType, 32); - } - if (type.flags & 4) { - return maybeTypeOfKind(contextualType, (64 | 256)); - } - if (type.flags & 8) { - return maybeTypeOfKind(contextualType, 128); - } - if (type.flags & 16) { - return typeContainsLiteralFromEnum(contextualType, type); - } - } - return false; - } - function checkLiteralExpression(node) { - if (node.kind === 8) { - checkGrammarNumericLiteral(node); - } - switch (node.kind) { - case 9: - return isLiteralContextForType(node, stringType) ? getLiteralTypeForText(32, node.text) : stringType; - case 8: - return isLiteralContextForType(node, numberType) ? getLiteralTypeForText(64, node.text) : numberType; - case 99: - case 84: - return isLiteralContextForType(node, booleanType) ? node.kind === 99 ? trueType : falseType : booleanType; + if (contextualType && isStringLiteralUnionType(contextualType)) { + return getStringLiteralTypeForText(node.text); } + return stringType; } function checkTemplateExpression(node) { ts.forEach(node.templateSpans, function (templateSpan) { @@ -24180,6 +22902,10 @@ var ts; } return type; } + function checkNumericLiteral(node) { + checkGrammarNumericLiteral(node); + return numberType; + } function checkExpressionWorker(node, contextualMapper) { switch (node.kind) { case 69: @@ -24190,13 +22916,15 @@ var ts; return checkSuperExpression(node); case 93: return nullWideningType; - case 9: - case 8: case 99: case 84: - return checkLiteralExpression(node); + return booleanType; + case 8: + return checkNumericLiteral(node); case 189: return checkTemplateExpression(node); + case 9: + return checkStringLiteralExpression(node); case 11: return stringType; case 10: @@ -24427,21 +23155,22 @@ var ts; checkAsyncFunctionReturnType(node); } } - if (noUnusedIdentifiers && !node.body) { + if (!node.body) { checkUnusedTypeParameters(node); } } } function checkClassForDuplicateDeclarations(node) { - var instanceNames = ts.createMap(); - var staticNames = ts.createMap(); + var getter = 1, setter = 2, property = getter | setter; + var instanceNames = {}; + var staticNames = {}; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; if (member.kind === 148) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var param = _c[_b]; if (ts.isParameterPropertyDeclaration(param)) { - addName(instanceNames, param.name, param.name.text, 3); + addName(instanceNames, param.name, param.name.text, property); } } } @@ -24452,21 +23181,21 @@ var ts; if (memberName) { switch (member.kind) { case 149: - addName(names, member.name, memberName, 1); + addName(names, member.name, memberName, getter); break; case 150: - addName(names, member.name, memberName, 2); + addName(names, member.name, memberName, setter); break; case 145: - addName(names, member.name, memberName, 3); + addName(names, member.name, memberName, property); break; } } } } function addName(names, location, name, meaning) { - var prev = names[name]; - if (prev) { + if (ts.hasProperty(names, name)) { + var prev = names[name]; if (prev & meaning) { error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); } @@ -24480,7 +23209,7 @@ var ts; } } function checkObjectTypeForDuplicateDeclarations(node) { - var names = ts.createMap(); + var names = {}; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; if (member.kind == 144) { @@ -24494,7 +23223,7 @@ var ts; default: continue; } - if (names[memberName]) { + if (ts.hasProperty(names, memberName)) { error(member.symbol.valueDeclaration.name, ts.Diagnostics.Duplicate_identifier_0, memberName); error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); } @@ -24636,7 +23365,12 @@ var ts; checkSignatureDeclaration(node); if (node.kind === 149) { if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 32768)) { - if (!(node.flags & 65536)) { + if (node.flags & 65536) { + if (compilerOptions.noImplicitReturns) { + error(node.name, ts.Diagnostics.Not_all_code_paths_return_a_value); + } + } + else { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); } } @@ -24658,10 +23392,7 @@ var ts; checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type); } } - var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 149) { - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); - } + getTypeOfAccessors(getSymbolOfNode(node)); } if (node.parent.kind !== 171) { checkSourceElement(node.body); @@ -24714,9 +23445,6 @@ var ts; checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } - if (type.flags & 16 && !type.memberTypes && getNodeLinks(node).resolvedSymbol.flags & 8) { - error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); - } } } function checkTypeQuery(node) { @@ -24986,10 +23714,10 @@ var ts; case 224: return 2097152 | 1048576; case 229: - var result_2 = 0; + var result_1 = 0; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_2 |= getDeclarationSpaces(d); }); - return result_2; + ts.forEach(target.declarations, function (d) { result_1 |= getDeclarationSpaces(d); }); + return result_1; default: return 1048576; } @@ -25012,7 +23740,7 @@ var ts; if (isTypeAny(promise)) { return undefined; } - if (promise.flags & 131072) { + if (promise.flags & 4096) { if (promise.target === tryGetGlobalPromiseType() || promise.target === getGlobalPromiseLikeType()) { return promise.typeArguments[0]; @@ -25038,7 +23766,7 @@ var ts; if (onfulfilledParameterSignatures.length === 0) { return undefined; } - return getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), true); + return getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); } function getTypeOfFirstParameterOfSignature(signature) { return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType; @@ -25049,13 +23777,13 @@ var ts; function checkAwaitedType(type, location, message) { return checkAwaitedTypeWorker(type); function checkAwaitedTypeWorker(type) { - if (type.flags & 524288) { + if (type.flags & 16384) { var types = []; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var constituentType = _a[_i]; types.push(checkAwaitedTypeWorker(constituentType)); } - return getUnionType(types, true); + return getUnionType(types); } else { var promisedType = getPromisedType(type); @@ -25160,7 +23888,7 @@ var ts; function checkTypeNodeAsExpression(node) { if (node && node.kind === 155) { var root = getFirstIdentifier(node.typeName); - var meaning = root.parent.kind === 155 ? 793064 : 1920; + var meaning = root.parent.kind === 155 ? 793056 : 1536; var rootSymbol = resolveName(root, root.text, meaning | 8388608, undefined, undefined); if (rootSymbol && rootSymbol.flags & 8388608) { var aliasTarget = resolveAlias(rootSymbol); @@ -25316,19 +24044,20 @@ var ts; function checkUnusedLocalsAndParameters(node) { if (node.parent.kind !== 222 && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { var _loop_1 = function(key) { - var local = node.locals[key]; - if (!local.isReferenced) { - if (local.valueDeclaration && local.valueDeclaration.kind === 142) { - var parameter = local.valueDeclaration; - if (compilerOptions.noUnusedParameters && - !ts.isParameterPropertyDeclaration(parameter) && - !parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(parameter)) { - error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); + if (ts.hasProperty(node.locals, key)) { + var local_1 = node.locals[key]; + if (!local_1.isReferenced) { + if (local_1.valueDeclaration && local_1.valueDeclaration.kind === 142) { + var parameter = local_1.valueDeclaration; + if (compilerOptions.noUnusedParameters && + !ts.isParameterPropertyDeclaration(parameter) && + !parameterNameStartsWithUnderscore(parameter)) { + error(local_1.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local_1.name); + } + } + else if (compilerOptions.noUnusedLocals) { + ts.forEach(local_1.declarations, function (d) { return error(d.name || d, ts.Diagnostics._0_is_declared_but_never_used, local_1.name); }); } - } - else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return error(d.name || d, ts.Diagnostics._0_is_declared_but_never_used, local.name); }); } } }; @@ -25337,9 +24066,6 @@ var ts; } } } - function parameterIsThisKeyword(parameter) { - return parameter.name && parameter.name.originalKeywordKind === 97; - } function parameterNameStartsWithUnderscore(parameter) { return parameter.name && parameter.name.kind === 69 && parameter.name.text.charCodeAt(0) === 95; } @@ -25357,7 +24083,7 @@ var ts; for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; if (!parameter.symbol.isReferenced && parameter.flags & 8) { - error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_never_used, parameter.symbol.name); + error(parameter.name, ts.Diagnostics._0_is_declared_but_never_used, parameter.symbol.name); } } } @@ -25368,14 +24094,9 @@ var ts; function checkUnusedTypeParameters(node) { if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { if (node.typeParameters) { - var symbol = getSymbolOfNode(node); - var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations); - if (lastDeclaration !== node) { - return; - } for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { var typeParameter = _a[_i]; - if (!getMergedSymbol(typeParameter.symbol).isReferenced) { + if (!typeParameter.symbol.isReferenced) { error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name); } } @@ -25385,12 +24106,14 @@ var ts; function checkUnusedModuleMembers(node) { if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { for (var key in node.locals) { - var local = node.locals[key]; - if (!local.isReferenced && !local.exportSymbol) { - for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (!ts.isAmbientModule(declaration)) { - error(declaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); + if (ts.hasProperty(node.locals, key)) { + var local = node.locals[key]; + if (!local.isReferenced && !local.exportSymbol) { + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (!ts.isAmbientModule(declaration)) { + error(declaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); + } } } } @@ -25772,7 +24495,7 @@ var ts; if (varExpr.kind === 170 || varExpr.kind === 171) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } - else if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 34)) { + else if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258)) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); } else { @@ -25780,7 +24503,7 @@ var ts; } } var rightType = checkNonNullExpression(node.expression); - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 2588672 | 16384)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 80896 | 512)) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); } checkSourceElement(node.statement); @@ -25833,7 +24556,7 @@ var ts; } var typeAsIterable = type; if (!typeAsIterable.iterableElementType) { - if ((type.flags & 131072) && type.target === getGlobalIterableType()) { + if ((type.flags & 4096) && type.target === getGlobalIterableType()) { typeAsIterable.iterableElementType = type.typeArguments[0]; } else { @@ -25848,7 +24571,7 @@ var ts; } return undefined; } - typeAsIterable.iterableElementType = getElementTypeOfIterator(getUnionType(ts.map(iteratorFunctionSignatures, getReturnTypeOfSignature), true), errorNode); + typeAsIterable.iterableElementType = getElementTypeOfIterator(getUnionType(ts.map(iteratorFunctionSignatures, getReturnTypeOfSignature)), errorNode); } } return typeAsIterable.iterableElementType; @@ -25859,7 +24582,7 @@ var ts; } var typeAsIterator = type; if (!typeAsIterator.iteratorElementType) { - if ((type.flags & 131072) && type.target === getGlobalIteratorType()) { + if ((type.flags & 4096) && type.target === getGlobalIteratorType()) { typeAsIterator.iteratorElementType = type.typeArguments[0]; } else { @@ -25874,7 +24597,7 @@ var ts; } return undefined; } - var iteratorNextResult = getUnionType(ts.map(iteratorNextFunctionSignatures, getReturnTypeOfSignature), true); + var iteratorNextResult = getUnionType(ts.map(iteratorNextFunctionSignatures, getReturnTypeOfSignature)); if (isTypeAny(iteratorNextResult)) { return undefined; } @@ -25894,7 +24617,7 @@ var ts; if (isTypeAny(type)) { return undefined; } - if ((type.flags & 131072) && type.target === getGlobalIterableIteratorType()) { + if ((type.flags & 4096) && type.target === getGlobalIterableIteratorType()) { return type.typeArguments[0]; } return getElementTypeOfIterable(type, undefined) || @@ -25903,10 +24626,10 @@ var ts; function checkElementTypeOfArrayOrString(arrayOrStringType, errorNode) { ts.Debug.assert(languageVersion < 2); var arrayType = arrayOrStringType; - if (arrayOrStringType.flags & 524288) { - arrayType = getUnionType(ts.filter(arrayOrStringType.types, function (t) { return !(t.flags & 34); }), true); + if (arrayOrStringType.flags & 16384) { + arrayType = getUnionType(ts.filter(arrayOrStringType.types, function (t) { return !(t.flags & 258); })); } - else if (arrayOrStringType.flags & 34) { + else if (arrayOrStringType.flags & 258) { arrayType = neverType; } var hasStringConstituent = arrayOrStringType !== arrayType; @@ -25931,10 +24654,10 @@ var ts; } var arrayElementType = getIndexTypeOfType(arrayType, 1) || unknownType; if (hasStringConstituent) { - if (arrayElementType.flags & 34) { + if (arrayElementType.flags & 258) { return stringType; } - return getUnionType([arrayElementType, stringType], true); + return getUnionType([arrayElementType, stringType]); } return arrayElementType; } @@ -25946,7 +24669,7 @@ var ts; } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { var unwrappedReturnType = ts.isAsyncFunctionLike(func) ? getPromisedType(returnType) : returnType; - return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 1024 | 1); + return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16 | 1); } function checkReturnStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { @@ -26077,7 +24800,7 @@ var ts; else { var identifierName = catchClause.variableDeclaration.name.text; var locals = catchClause.block.locals; - if (locals) { + if (locals && ts.hasProperty(locals, identifierName)) { var localSymbol = locals[identifierName]; if (localSymbol && (localSymbol.flags & 2) !== 0) { grammarErrorOnNode(localSymbol.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, identifierName); @@ -26102,7 +24825,7 @@ var ts; checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1); }); - if (type.flags & 32768 && ts.isClassLike(type.symbol.valueDeclaration)) { + if (type.flags & 1024 && ts.isClassLike(type.symbol.valueDeclaration)) { var classDeclaration = type.symbol.valueDeclaration; for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; @@ -26117,7 +24840,7 @@ var ts; var errorNode; if (stringIndexType && numberIndexType) { errorNode = declaredNumberIndexer || declaredStringIndexer; - if (!errorNode && (type.flags & 65536)) { + if (!errorNode && (type.flags & 2048)) { var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0) && getIndexTypeOfType(base, 1); }); errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; } @@ -26139,7 +24862,7 @@ var ts; else if (indexDeclaration) { errorNode = indexDeclaration; } - else if (containingType.flags & 65536) { + else if (containingType.flags & 2048) { var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.name) && getIndexTypeOfType(base, indexKind); }); errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; } @@ -26247,11 +24970,6 @@ var ts; } checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); - if (baseType_1.symbol.valueDeclaration && !ts.isInAmbientContext(baseType_1.symbol.valueDeclaration)) { - if (!isBlockScopedNameDeclaredBeforeUse(baseType_1.symbol.valueDeclaration, node)) { - error(baseTypeNode, ts.Diagnostics.A_class_must_be_declared_after_its_base_class); - } - } if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32)) { var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments); if (ts.forEach(constructors, function (sig) { return getReturnTypeOfSignature(sig) !== baseType_1; })) { @@ -26265,15 +24983,15 @@ var ts; if (implementedTypeNodes) { for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { var typeRefNode = implementedTypeNodes_1[_b]; - if (!ts.isEntityNameExpression(typeRefNode.expression)) { + if (!ts.isSupportedExpressionWithTypeArguments(typeRefNode)) { error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); } checkTypeReferenceNode(typeRefNode); if (produceDiagnostics) { var t = getTypeFromTypeNode(typeRefNode); if (t !== unknownType) { - var declaredType = (t.flags & 131072) ? t.target : t; - if (declaredType.flags & (32768 | 65536)) { + var declaredType = (t.flags & 4096) ? t.target : t; + if (declaredType.flags & (1024 | 2048)) { checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_implements_interface_1); } else { @@ -26397,7 +25115,7 @@ var ts; if (baseTypes.length < 2) { return true; } - var seen = ts.createMap(); + var seen = {}; ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen[p.name] = { prop: p, containingType: type }; }); var ok = true; for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { @@ -26405,11 +25123,11 @@ var ts; var properties = getPropertiesOfObjectType(getTypeWithThisArgument(base, type.thisType)); for (var _a = 0, properties_4 = properties; _a < properties_4.length; _a++) { var prop = properties_4[_a]; - var existing = seen[prop.name]; - if (!existing) { + if (!ts.hasProperty(seen, prop.name)) { seen[prop.name] = { prop: prop, containingType: base }; } else { + var existing = seen[prop.name]; var isInheritedProperty = existing.containingType !== type; if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) { ok = false; @@ -26447,7 +25165,7 @@ var ts; checkObjectTypeForDuplicateDeclarations(node); } ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) { - if (!ts.isEntityNameExpression(heritageElement.expression)) { + if (!ts.isSupportedExpressionWithTypeArguments(heritageElement)) { error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); } checkTypeReferenceNode(heritageElement); @@ -26455,7 +25173,7 @@ var ts; ts.forEach(node.members, checkSourceElement); if (produceDiagnostics) { checkTypeForDuplicateIndexSignatures(node); - registerForUnusedIdentifiersCheck(node); + checkUnusedTypeParameters(node); } } function checkTypeAliasDeclaration(node) { @@ -26770,6 +25488,9 @@ var ts; } } } + if (compilerOptions.noImplicitAny && !node.body) { + reportImplicitAnyError(node, anyType); + } if (node.body) { checkSourceElement(node.body); if (!ts.isGlobalScopeAugmentation(node)) { @@ -26823,20 +25544,19 @@ var ts; } } function getFirstIdentifier(node) { - switch (node.kind) { - case 69: - return node; - case 139: - do { - node = node.left; - } while (node.kind !== 69); - return node; - case 172: - do { - node = node.expression; - } while (node.kind !== 69); - return node; + while (true) { + if (node.kind === 139) { + node = node.left; + } + else if (node.kind === 172) { + node = node.expression; + } + else { + break; + } } + ts.Debug.assert(node.kind === 69); + return node; } function checkExternalImportOrExportDeclaration(node) { var moduleName = ts.getExternalModuleName(node); @@ -26864,8 +25584,8 @@ var ts; var target = resolveAlias(symbol); if (target !== unknownSymbol) { var excludedMeanings = (symbol.flags & (107455 | 1048576) ? 107455 : 0) | - (symbol.flags & 793064 ? 793064 : 0) | - (symbol.flags & 1920 ? 1920 : 0); + (symbol.flags & 793056 ? 793056 : 0) | + (symbol.flags & 1536 ? 1536 : 0); if (target.flags & excludedMeanings) { var message = node.kind === 238 ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : @@ -26919,11 +25639,11 @@ var ts; if (target !== unknownSymbol) { if (target.flags & 107455) { var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 107455 | 1920).flags & 1920)) { + if (!(resolveEntityName(moduleName, 107455 | 1536).flags & 1536)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 793064) { + if (target.flags & 793056) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -26967,7 +25687,7 @@ var ts; checkAliasSymbol(node); if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; - var symbol = resolveName(exportedName, exportedName.text, 107455 | 793064 | 1920 | 8388608, undefined, undefined); + var symbol = resolveName(exportedName, exportedName.text, 107455 | 793056 | 1536 | 8388608, undefined, undefined); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, exportedName.text); } @@ -27029,7 +25749,7 @@ var ts; continue; } var _a = exports[id], declarations = _a.declarations, flags = _a.flags; - if (flags & (1920 | 64 | 384)) { + if (flags & (1536 | 64 | 384)) { continue; } var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverload); @@ -27199,10 +25919,9 @@ var ts; } } function checkSourceFile(node) { - ts.performance.mark("beforeCheck"); + var start = new Date().getTime(); checkSourceFileWorker(node); - ts.performance.mark("afterCheck"); - ts.performance.measure("Check", "beforeCheck", "afterCheck"); + ts.checkTime += new Date().getTime() - start; } function checkSourceFileWorker(node) { var links = getNodeLinks(node); @@ -27273,7 +25992,7 @@ var ts; return false; } function getSymbolsInScope(location, meaning) { - var symbols = ts.createMap(); + var symbols = {}; var memberFlags = 0; if (isInsideWithStatementBody(location)) { return []; @@ -27304,7 +26023,7 @@ var ts; case 221: case 222: if (!(memberFlags & 32)) { - copySymbols(getSymbolOfNode(location).members, meaning & 793064); + copySymbols(getSymbolOfNode(location).members, meaning & 793056); } break; case 179: @@ -27325,7 +26044,7 @@ var ts; function copySymbol(symbol, meaning) { if (symbol.flags & meaning) { var id = symbol.name; - if (!symbols[id]) { + if (!ts.hasProperty(symbols, id)) { symbols[id] = symbol; } } @@ -27413,13 +26132,15 @@ var ts; default: } } - if (entityName.parent.kind === 235 && ts.isEntityNameExpression(entityName)) { - return resolveEntityName(entityName, 107455 | 793064 | 1920 | 8388608); + if (entityName.parent.kind === 235) { + return resolveEntityName(entityName, 107455 | 793056 | 1536 | 8388608); } - if (entityName.kind !== 172 && isInRightSideOfImportOrExportAssignment(entityName)) { - var importEqualsDeclaration = ts.getAncestor(entityName, 229); - ts.Debug.assert(importEqualsDeclaration !== undefined); - return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importEqualsDeclaration, true); + if (entityName.kind !== 172) { + if (isInRightSideOfImportOrExportAssignment(entityName)) { + var importEqualsDeclaration = ts.getAncestor(entityName, 229); + ts.Debug.assert(importEqualsDeclaration !== undefined); + return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importEqualsDeclaration, true); + } } if (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; @@ -27427,13 +26148,13 @@ var ts; if (isHeritageClauseElementIdentifier(entityName)) { var meaning = 0; if (entityName.parent.kind === 194) { - meaning = 793064; + meaning = 793056; if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { meaning |= 107455; } } else { - meaning = 1920; + meaning = 1536; } meaning |= 8388608; return resolveEntityName(entityName, meaning); @@ -27464,7 +26185,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = (entityName.parent.kind === 155 || entityName.parent.kind === 267) ? 793064 : 1920; + var meaning = (entityName.parent.kind === 155 || entityName.parent.kind === 267) ? 793056 : 1536; return resolveEntityName(entityName, meaning, false, true); } else if (entityName.parent.kind === 246) { @@ -27556,7 +26277,7 @@ var ts; function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 107455 | 793064 | 1920 | 8388608); + resolveEntityName(node.propertyName || node.name, 107455 | 793056 | 1536 | 8388608); } function getTypeOfNode(node) { if (isInsideWithStatementBody(node)) { @@ -27637,7 +26358,7 @@ var ts; var propsByName = createSymbolTable(getPropertiesOfType(type)); if (getSignaturesOfType(type, 0).length || getSignaturesOfType(type, 1).length) { ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { - if (!propsByName[p.name]) { + if (!ts.hasProperty(propsByName, p.name)) { propsByName[p.name] = p; } }); @@ -27673,7 +26394,7 @@ var ts; } function moduleExportsSomeValue(moduleReferenceExpression) { var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); - if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + if (!moduleSymbol) { return true; } var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol); @@ -27682,7 +26403,7 @@ var ts; if (symbolLinks.exportsSomeValue === undefined) { symbolLinks.exportsSomeValue = hasExportAssignment ? !!(moduleSymbol.flags & 107455) - : ts.forEachProperty(getExportsOfModule(moduleSymbol), isValue); + : ts.forEachValue(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { @@ -27826,7 +26547,7 @@ var ts; return undefined; } function isFunctionType(type) { - return type.flags & 2588672 && getSignaturesOfType(type, 0).length > 0; + return type.flags & 80896 && getSignaturesOfType(type, 0).length > 0; } function getTypeReferenceSerializationKind(typeName) { var valueSymbol = resolveEntityName(typeName, 107455, true); @@ -27834,7 +26555,7 @@ var ts; if (constructorType && isConstructorType(constructorType)) { return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue; } - var typeSymbol = resolveEntityName(typeName, 793064, true); + var typeSymbol = resolveEntityName(typeName, 793056, true); if (!typeSymbol) { return ts.TypeReferenceSerializationKind.ObjectType; } @@ -27845,22 +26566,22 @@ var ts; else if (type.flags & 1) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (isTypeOfKind(type, 1024)) { + else if (isTypeOfKind(type, 16)) { return ts.TypeReferenceSerializationKind.VoidType; } - else if (isTypeOfKind(type, 136)) { + else if (isTypeOfKind(type, 8)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeOfKind(type, 340)) { + else if (isTypeOfKind(type, 132)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (isTypeOfKind(type, 34)) { + else if (isTypeOfKind(type, 258)) { return ts.TypeReferenceSerializationKind.StringLikeType; } - else if (isTupleType(type)) { + else if (isTypeOfKind(type, 8192)) { return ts.TypeReferenceSerializationKind.ArrayLikeType; } - else if (isTypeOfKind(type, 512)) { + else if (isTypeOfKind(type, 16777216)) { return ts.TypeReferenceSerializationKind.ESSymbolType; } else if (isFunctionType(type)) { @@ -27895,7 +26616,7 @@ var ts; getSymbolDisplayBuilder().buildTypeDisplay(baseType, writer, enclosingDeclaration, flags); } function hasGlobalName(name) { - return !!globals[name]; + return ts.hasProperty(globals, name); } function getReferencedValueSymbol(reference) { return getNodeLinks(reference).resolvedSymbol || @@ -27912,14 +26633,14 @@ var ts; if (resolvedTypeReferenceDirectives) { fileToDirective = ts.createFileMap(); for (var key in resolvedTypeReferenceDirectives) { + if (!ts.hasProperty(resolvedTypeReferenceDirectives, key)) { + continue; + } var resolvedDirective = resolvedTypeReferenceDirectives[key]; if (!resolvedDirective) { continue; } var file = host.getSourceFile(resolvedDirective.resolvedFileName); - if (!file) { - continue; - } fileToDirective.set(file.path, key); } } @@ -27958,7 +26679,7 @@ var ts; } var meaning = (node.kind === 172) || (node.kind === 69 && isInTypeQuery(node)) ? 107455 | 1048576 - : 793064 | 1920; + : 793056 | 1536; var symbol = resolveEntityName(node, meaning, true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; } @@ -28033,12 +26754,7 @@ var ts; (augmentations || (augmentations = [])).push(file.moduleAugmentations); } if (file.symbol && file.symbol.globalExports) { - var source = file.symbol.globalExports; - for (var id in source) { - if (!(id in globals)) { - globals[id] = source[id]; - } - } + mergeSymbolTable(globals, file.symbol.globalExports); } }); if (augmentations) { @@ -28069,7 +26785,7 @@ var ts; getGlobalTypedPropertyDescriptorType = ts.memoize(function () { return getGlobalType("TypedPropertyDescriptor", 1); }); getGlobalESSymbolConstructorSymbol = ts.memoize(function () { return getGlobalValueSymbol("Symbol"); }); getGlobalPromiseType = ts.memoize(function () { return getGlobalType("Promise", 1); }); - tryGetGlobalPromiseType = ts.memoize(function () { return getGlobalSymbol("Promise", 793064, undefined) && getGlobalPromiseType(); }); + tryGetGlobalPromiseType = ts.memoize(function () { return getGlobalSymbol("Promise", 793056, undefined) && getGlobalPromiseType(); }); getGlobalPromiseLikeType = ts.memoize(function () { return getGlobalType("PromiseLike", 1); }); getInstantiatedGlobalPromiseLikeType = ts.memoize(createInstantiatedPromiseLikeType); getGlobalPromiseConstructorSymbol = ts.memoize(function () { return getGlobalValueSymbol("Promise"); }); @@ -28089,7 +26805,7 @@ var ts; getGlobalIterableIteratorType = ts.memoize(function () { return emptyGenericType; }); } anyArrayType = createArrayType(anyType); - var symbol = getGlobalSymbol("ReadonlyArray", 793064, undefined); + var symbol = getGlobalSymbol("ReadonlyArray", 793056, undefined); globalReadonlyArrayType = symbol && getTypeOfGlobalSymbol(symbol, 1); anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; } @@ -28103,7 +26819,7 @@ var ts; function createThenableType() { var thenPropertySymbol = createSymbol(67108864 | 4, "then"); getSymbolLinks(thenPropertySymbol).type = globalFunctionType; - var thenableType = createObjectType(2097152); + var thenableType = createObjectType(65536); thenableType.properties = [thenPropertySymbol]; thenableType.members = createSymbolTable(thenableType.properties); thenableType.callSignatures = []; @@ -28131,9 +26847,49 @@ var ts; return false; } function checkGrammarModifiers(node) { - var quickResult = reportObviousModifierErrors(node); - if (quickResult !== undefined) { - return quickResult; + switch (node.kind) { + case 149: + case 150: + case 148: + case 145: + case 144: + case 147: + case 146: + case 153: + case 225: + case 230: + case 229: + case 236: + case 235: + case 179: + case 180: + case 142: + break; + case 220: + if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 118) && + node.parent.kind !== 226 && node.parent.kind !== 256) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + break; + case 221: + case 222: + case 200: + case 223: + if (node.modifiers && node.parent.kind !== 226 && node.parent.kind !== 256) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + break; + case 224: + if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 74) && + node.parent.kind !== 226 && node.parent.kind !== 256) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + break; + default: + return false; + } + if (!node.modifiers) { + return; } var lastStatic, lastPrivate, lastProtected, lastDeclare, lastAsync, lastReadonly; var flags = 0; @@ -28326,56 +27082,6 @@ var ts; return checkGrammarAsyncModifier(node, lastAsync); } } - function reportObviousModifierErrors(node) { - return !node.modifiers - ? false - : shouldReportBadModifier(node) - ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here) - : undefined; - } - function shouldReportBadModifier(node) { - switch (node.kind) { - case 149: - case 150: - case 148: - case 145: - case 144: - case 147: - case 146: - case 153: - case 225: - case 230: - case 229: - case 236: - case 235: - case 179: - case 180: - case 142: - return false; - default: - if (node.parent.kind === 226 || node.parent.kind === 256) { - return false; - } - switch (node.kind) { - case 220: - return nodeHasAnyModifiersExcept(node, 118); - case 221: - return nodeHasAnyModifiersExcept(node, 115); - case 222: - case 200: - case 223: - return true; - case 224: - return nodeHasAnyModifiersExcept(node, 74); - default: - ts.Debug.fail(); - return false; - } - } - } - function nodeHasAnyModifiersExcept(node, allowedModifier) { - return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier; - } function checkGrammarAsyncModifier(node, asyncModifier) { if (languageVersion < 2) { return grammarErrorOnNode(asyncModifier, ts.Diagnostics.Async_functions_are_only_available_when_targeting_ECMAScript_2015_or_higher); @@ -28608,7 +27314,7 @@ var ts; } } function checkGrammarObjectLiteralExpression(node, inDestructuring) { - var seen = ts.createMap(); + var seen = {}; var Property = 1; var GetAccessor = 2; var SetAccessor = 4; @@ -28651,7 +27357,7 @@ var ts; if (effectiveName === undefined) { return "continue"; } - if (!seen[effectiveName]) { + if (!ts.hasProperty(seen, effectiveName)) { seen[effectiveName] = currentKind; } else { @@ -28679,7 +27385,7 @@ var ts; } } function checkGrammarJsxElement(node) { - var seen = ts.createMap(); + var seen = {}; for (var _i = 0, _a = node.attributes; _i < _a.length; _i++) { var attr = _a[_i]; if (attr.kind === 247) { @@ -28687,7 +27393,7 @@ var ts; } var jsxAttr = attr; var name_22 = jsxAttr.name; - if (!seen[name_22.text]) { + if (!ts.hasProperty(seen, name_22.text)) { seen[name_22.text] = true; } else { @@ -29015,7 +27721,6 @@ var ts; node.kind === 229 || node.kind === 236 || node.kind === 235 || - node.kind === 228 || (node.flags & 2) || (node.flags & (1 | 512))) { return false; @@ -29067,15 +27772,7 @@ var ts; return true; } } - function getAmbientModules() { - var result = []; - for (var sym in globals) { - if (ambientModuleSymbolRegex.test(sym)) { - result.push(globals[sym]); - } - } - return result; - } + var _a; } ts.createTypeChecker = createTypeChecker; })(ts || (ts = {})); @@ -29109,7 +27806,6 @@ var ts; ts.getNullSourceMapWriter = getNullSourceMapWriter; function createSourceMapWriter(host, writer) { var compilerOptions = host.getCompilerOptions(); - var extendedDiagnostics = compilerOptions.extendedDiagnostics; var currentSourceFile; var sourceMapDir; var stopOverridingSpan = false; @@ -29238,9 +27934,6 @@ var ts; if (pos === -1) { return; } - if (extendedDiagnostics) { - ts.performance.mark("beforeSourcemap"); - } var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos); sourceLinePos.line++; sourceLinePos.character++; @@ -29268,10 +27961,6 @@ var ts; lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; } updateLastEncodedAndRecordedSpans(); - if (extendedDiagnostics) { - ts.performance.mark("afterSourcemap"); - ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); - } } function getStartPos(range) { var rangeHasDecorators = !!range.decorators; @@ -29359,11 +28048,11 @@ var ts; return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined); function getDeclarationDiagnosticsFromFile(_a, sources, isBundledEmit) { var declarationFilePath = _a.declarationFilePath; - emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit, false); + emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit); } } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles) { + function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit) { var newLine = host.getNewLine(); var compilerOptions = host.getCompilerOptions(); var write; @@ -29399,7 +28088,7 @@ var ts; ts.forEach(sourceFile.referencedFiles, function (fileReference) { var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); if (referencedFile && !ts.contains(emittedReferencedFiles, referencedFile)) { - if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference, emitOnlyDtsFiles)) { + if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference)) { addedGlobalFileReference = true; } emittedReferencedFiles.push(referencedFile); @@ -29449,7 +28138,9 @@ var ts; }); if (usedTypeDirectiveReferences) { for (var directive in usedTypeDirectiveReferences) { - referencesOutput += "/// " + newLine; + if (ts.hasProperty(usedTypeDirectiveReferences, directive)) { + referencesOutput += "/// " + newLine; + } } } return { @@ -29538,11 +28229,11 @@ var ts; return; } if (!usedTypeDirectiveReferences) { - usedTypeDirectiveReferences = ts.createMap(); + usedTypeDirectiveReferences = {}; } for (var _i = 0, typeReferenceDirectives_1 = typeReferenceDirectives; _i < typeReferenceDirectives_1.length; _i++) { var directive = typeReferenceDirectives_1[_i]; - if (!(directive in usedTypeDirectiveReferences)) { + if (!ts.hasProperty(usedTypeDirectiveReferences, directive)) { usedTypeDirectiveReferences[directive] = directive; } } @@ -29584,7 +28275,7 @@ var ts; } else { errorNameNode = declaration.name; - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 | 1024, writer); + resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2, writer); errorNameNode = undefined; } } @@ -29596,7 +28287,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 | 1024, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2, writer); errorNameNode = undefined; } } @@ -29694,7 +28385,7 @@ var ts; writeEntityName(entityName); } function emitExpressionWithTypeArguments(node) { - if (ts.isEntityNameExpression(node.expression)) { + if (ts.isSupportedExpressionWithTypeArguments(node)) { ts.Debug.assert(node.expression.kind === 69 || node.expression.kind === 172); emitEntityName(node.expression); if (node.typeArguments) { @@ -29763,14 +28454,14 @@ var ts; } function getExportDefaultTempVariableName() { var baseName = "_default"; - if (!(baseName in currentIdentifiers)) { + if (!ts.hasProperty(currentIdentifiers, baseName)) { return baseName; } var count = 0; while (true) { count++; var name_23 = baseName + "_" + count; - if (!(name_23 in currentIdentifiers)) { + if (!ts.hasProperty(currentIdentifiers, name_23)) { return name_23; } } @@ -29789,7 +28480,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 | 1024, writer); + resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2, writer); write(";"); writeLine(); write(node.isExportEquals ? "export = " : "export default "); @@ -30186,7 +28877,7 @@ var ts; emitCommaList(typeReferences, emitTypeOfTypeReference); } function emitTypeOfTypeReference(node) { - if (ts.isEntityNameExpression(node.expression)) { + if (ts.isSupportedExpressionWithTypeArguments(node)) { emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError); } else if (!isImplementsList && node.expression.kind === 93) { @@ -30194,7 +28885,7 @@ var ts; } else { writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 | 1024, writer); + resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2, writer); } function getHeritageClauseVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; @@ -30284,8 +28975,7 @@ var ts; } else { writeTextOfNode(currentText, node.name); - if ((node.kind === 145 || node.kind === 144 || - (node.kind === 142 && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { + if ((node.kind === 145 || node.kind === 144 || node.kind === 142) && ts.hasQuestionToken(node)) { write("?"); } if ((node.kind === 145 || node.kind === 144) && node.parent.kind === 159) { @@ -30758,14 +29448,14 @@ var ts; return emitSourceFile(node); } } - function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { + function writeReferencePath(referencedFile, addBundledFileReference) { var declFileName; var addedBundledEmitReference = false; if (ts.isDeclarationFile(referencedFile)) { declFileName = referencedFile.fileName; } else { - ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile, emitOnlyDtsFiles); + ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile); } if (declFileName) { declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, false); @@ -30782,8 +29472,8 @@ var ts; } } } - function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) { - var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles); + function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) { + var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit); var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; if (!emitSkipped) { var declarationOutput = emitDeclarationResult.referencesOutput @@ -30821,7 +29511,7 @@ var ts; return getResolvedExternalModuleName(host, file); } ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; - var entities = ts.createMap({ + var entities = { "quot": 0x0022, "amp": 0x0026, "apos": 0x0027, @@ -31075,8 +29765,8 @@ var ts; "clubs": 0x2663, "hearts": 0x2665, "diams": 0x2666 - }); - function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles) { + }; + function emitFiles(resolver, host, targetSourceFile) { var extendsHelper = "\nvar __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n};"; var assignHelper = "\nvar __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n};"; var decorateHelper = "\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};"; @@ -31092,7 +29782,7 @@ var ts; var emitSkipped = false; var newLine = host.getNewLine(); var emitJavaScript = createFileEmitter(); - ts.forEachExpectedEmitFile(host, emitFile, targetSourceFile, emitOnlyDtsFiles); + ts.forEachExpectedEmitFile(host, emitFile, targetSourceFile); return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -31101,7 +29791,7 @@ var ts; }; function isUniqueLocalName(name, container) { for (var node = container; ts.isNodeDescendentOf(node, container); node = node.nextContainer) { - if (node.locals && name in node.locals) { + if (node.locals && ts.hasProperty(node.locals, name)) { if (node.locals[name].flags & (107455 | 1048576 | 8388608)) { return false; } @@ -31112,13 +29802,13 @@ var ts; function setLabeledJump(state, isBreak, labelText, labelMarker) { if (isBreak) { if (!state.labeledNonLocalBreaks) { - state.labeledNonLocalBreaks = ts.createMap(); + state.labeledNonLocalBreaks = {}; } state.labeledNonLocalBreaks[labelText] = labelMarker; } else { if (!state.labeledNonLocalContinues) { - state.labeledNonLocalContinues = ts.createMap(); + state.labeledNonLocalContinues = {}; } state.labeledNonLocalContinues[labelText] = labelMarker; } @@ -31176,26 +29866,26 @@ var ts; var isOwnFileEmit; var emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos) { } : emitLeadingCommentsOfPositionWorker; var setSourceMapWriterEmit = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? changeSourceMapEmit : function (writer) { }; - var moduleEmitDelegates = ts.createMap((_a = {}, + var moduleEmitDelegates = (_a = {}, _a[ts.ModuleKind.ES6] = emitES6Module, _a[ts.ModuleKind.AMD] = emitAMDModule, _a[ts.ModuleKind.System] = emitSystemModule, _a[ts.ModuleKind.UMD] = emitUMDModule, _a[ts.ModuleKind.CommonJS] = emitCommonJSModule, _a - )); - var bundleEmitDelegates = ts.createMap((_b = {}, + ); + var bundleEmitDelegates = (_b = {}, _b[ts.ModuleKind.ES6] = function () { }, _b[ts.ModuleKind.AMD] = emitAMDModule, _b[ts.ModuleKind.System] = emitSystemModule, _b[ts.ModuleKind.UMD] = function () { }, _b[ts.ModuleKind.CommonJS] = function () { }, _b - )); + ); return doEmit; function doEmit(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit) { sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); - generatedNameSet = ts.createMap(); + generatedNameSet = {}; nodeToGeneratedName = []; decoratedClassAliases = []; isOwnFileEmit = !isBundledEmit; @@ -31206,7 +29896,7 @@ var ts; writeLine(); var sourceMappingURL = sourceMap.getSourceMappingURL(); if (sourceMappingURL) { - write("//# " + "sourceMappingURL" + "=" + sourceMappingURL); + write("//# sourceMappingURL=" + sourceMappingURL); } writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, compilerOptions.emitBOM, sourceFiles); sourceMap.reset(); @@ -31254,8 +29944,8 @@ var ts; } function isUniqueName(name) { return !resolver.hasGlobalName(name) && - !(name in currentFileIdentifiers) && - !(name in generatedNameSet); + !ts.hasProperty(currentFileIdentifiers, name) && + !ts.hasProperty(generatedNameSet, name); } function makeTempVariableName(flags) { if (flags && !(tempFlags & flags)) { @@ -32152,10 +30842,6 @@ var ts; else if (node.parent.kind === 188 && node.parent.condition === node) { return true; } - else if (node.parent.kind === 185 || node.parent.kind === 181 || - node.parent.kind === 182 || node.parent.kind === 183) { - return true; - } return false; } function needsParenthesisForPropertyAccessOrInvocation(node) { @@ -32742,7 +31428,6 @@ var ts; operand.kind !== 181 && operand.kind !== 186 && operand.kind !== 175 && - !(operand.kind === 187 && node.expression.kind === 195) && !(operand.kind === 174 && node.parent.kind === 175) && !(operand.kind === 179 && node.parent.kind === 174) && !(operand.kind === 8 && node.parent.kind === 172)) { @@ -32784,7 +31469,7 @@ var ts; if (modulekind === ts.ModuleKind.System || node.kind !== 69 || ts.nodeIsSynthesized(node)) { return false; } - return !exportEquals && exportSpecifiers && node.text in exportSpecifiers; + return !exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, node.text); } function emitPrefixUnaryExpression(node) { var isPlusPlusOrMinusMinus = (node.operator === 41 @@ -33245,12 +31930,12 @@ var ts; for (var _c = 0, _d = convertedLoopState.hoistedLocalVariables; _c < _d.length; _c++) { var id = _d[_c]; if (!seen) { - seen = ts.createMap(); + seen = {}; } else { write(", "); } - if (!(id.text in seen)) { + if (!ts.hasProperty(seen, id.text)) { emit(id); seen[id.text] = id.text; } @@ -33703,7 +32388,7 @@ var ts; } if (convertedLoopState) { if (!convertedLoopState.labels) { - convertedLoopState.labels = ts.createMap(); + convertedLoopState.labels = {}; } convertedLoopState.labels[node.label.text] = node.label.text; } @@ -33801,7 +32486,7 @@ var ts; if (modulekind === ts.ModuleKind.System) { return; } - if (!exportEquals && exportSpecifiers && name.text in exportSpecifiers) { + if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { for (var _a = 0, _b = exportSpecifiers[name.text]; _a < _b.length; _a++) { var specifier = _b[_a]; writeLine(); @@ -34234,12 +32919,11 @@ var ts; } function emitRestParameter(node) { if (languageVersion < 2 && ts.hasDeclaredRestParameter(node)) { - var restParam = node.parameters[node.parameters.length - 1]; + var restIndex = node.parameters.length - 1; + var restParam = node.parameters[restIndex]; if (ts.isBindingPattern(restParam.name)) { return; } - var skipThisCount = node.parameters.length && node.parameters[0].name.originalKeywordKind === 97 ? 1 : 0; - var restIndex = node.parameters.length - 1 - skipThisCount; var tempName = createTempVariable(268435456).text; writeLine(); emitLeadingComments(restParam); @@ -34352,7 +33036,7 @@ var ts; write("("); if (node) { var parameters = node.parameters; - var skipCount = node.parameters.length && node.parameters[0].name.originalKeywordKind === 97 ? 1 : 0; + var skipCount = node.parameters.length && node.parameters[0].name.text === "this" ? 1 : 0; var omitCount = languageVersion < 2 && ts.hasDeclaredRestParameter(node) ? 1 : 0; emitList(parameters, skipCount, parameters.length - omitCount - skipCount, false, false); } @@ -34769,7 +33453,12 @@ var ts; emitSignatureParameters(ctor); } else { - write("()"); + if (baseTypeElement) { + write("(...args)"); + } + else { + write("()"); + } } } var startIndex = 0; @@ -34801,7 +33490,7 @@ var ts; write("_super.apply(this, arguments);"); } else { - write("super(...arguments);"); + write("super(...args);"); } emitEnd(baseTypeElement); } @@ -34857,13 +33546,13 @@ var ts; if (isES6ExportedDeclaration(node) && !(node.flags & 512) && decoratedClassAlias === undefined) { write("export "); } + if (!isHoistedDeclarationInSystemModule) { + write("let "); + } if (decoratedClassAlias !== undefined) { - write("let " + decoratedClassAlias); + write("" + decoratedClassAlias); } else { - if (!isHoistedDeclarationInSystemModule) { - write("let "); - } emitDeclarationName(node); } write(" = "); @@ -34879,7 +33568,7 @@ var ts; var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 192; var generatedName; if (isClassExpressionWithStaticProperties) { - generatedName = node.name ? getGeneratedNameForNode(node.name) : makeUniqueName("classExpression"); + generatedName = getGeneratedNameForNode(node.name); var synthesizedNode = ts.createSynthesizedNode(69); synthesizedNode.text = generatedName; recordTempDeclaration(synthesizedNode); @@ -35329,11 +34018,10 @@ var ts; } if (valueDeclaration) { var parameters = valueDeclaration.parameters; - var skipThisCount = parameters.length && parameters[0].name.originalKeywordKind === 97 ? 1 : 0; var parameterCount = parameters.length; - if (parameterCount > skipThisCount) { - for (var i = skipThisCount; i < parameterCount; i++) { - if (i > skipThisCount) { + if (parameterCount > 0) { + for (var i = 0; i < parameterCount; i++) { + if (i > 0) { write(", "); } if (parameters[i].dotDotDotToken) { @@ -35588,7 +34276,7 @@ var ts; } } function tryRenameExternalModule(moduleName) { - if (renamedDependencies && moduleName.text in renamedDependencies) { + if (renamedDependencies && ts.hasProperty(renamedDependencies, moduleName.text)) { return "\"" + renamedDependencies[moduleName.text] + "\""; } return undefined; @@ -35689,7 +34377,7 @@ var ts; write(" = "); } else { - var isNakedImport = node.kind === 230 && !node.importClause; + var isNakedImport = 230 && !node.importClause; if (!isNakedImport) { write(varOrConst); write(getGeneratedNameForNode(node)); @@ -35888,7 +34576,7 @@ var ts; } function collectExternalModuleInfo(sourceFile) { externalImports = []; - exportSpecifiers = ts.createMap(); + exportSpecifiers = {}; exportEquals = undefined; hasExportStarsToExportValues = false; for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) { @@ -36000,7 +34688,7 @@ var ts; if (!hasExportStarsToExportValues) { return undefined; } - if (!exportedDeclarations && !ts.someProperties(exportSpecifiers)) { + if (!exportedDeclarations && ts.isEmpty(exportSpecifiers)) { var hasExportDeclarationWithExportClause = false; for (var _a = 0, externalImports_2 = externalImports; _a < externalImports_2.length; _a++) { var externalImport = externalImports_2[_a]; @@ -36104,7 +34792,7 @@ var ts; if (hoistedVars) { writeLine(); write("var "); - var seen = ts.createMap(); + var seen = {}; for (var i = 0; i < hoistedVars.length; i++) { var local = hoistedVars[i]; var name_32 = local.kind === 69 @@ -36112,7 +34800,7 @@ var ts; : local.name; if (name_32) { var text = ts.unescapeIdentifier(name_32.text); - if (text in seen) { + if (ts.hasProperty(seen, text)) { continue; } else { @@ -36355,7 +35043,7 @@ var ts; write("System.register("); writeModuleName(node, emitRelativePathAsModuleName); write("["); - var groupIndices = ts.createMap(); + var groupIndices = {}; var dependencyGroups = []; for (var i = 0; i < externalImports.length; i++) { var text = getExternalModuleNameText(externalImports[i], emitRelativePathAsModuleName); @@ -36363,7 +35051,7 @@ var ts; continue; } var key = text.substr(1, text.length - 2); - if (key in groupIndices) { + if (ts.hasProperty(groupIndices, key)) { var groupIndex = groupIndices[key]; dependencyGroups[groupIndex].push(externalImports[i]); continue; @@ -37078,25 +35766,21 @@ var ts; } var _a, _b; } - function emitFile(_a, sourceFiles, isBundledEmit, emitOnlyDtsFiles) { + function emitFile(_a, sourceFiles, isBundledEmit) { var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath; - if (!emitOnlyDtsFiles) { - if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { - emitJavaScript(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); - } - else { - emitSkipped = true; - } + if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { + emitJavaScript(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + } + else { + emitSkipped = true; } if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; + emitSkipped = ts.writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; } if (!emitSkipped && emittedFilesList) { - if (!emitOnlyDtsFiles) { - emittedFilesList.push(jsFilePath); - if (sourceMapFilePath) { - emittedFilesList.push(sourceMapFilePath); - } + emittedFilesList.push(jsFilePath); + if (sourceMapFilePath) { + emittedFilesList.push(sourceMapFilePath); } if (declarationFilePath) { emittedFilesList.push(declarationFilePath); @@ -37108,12 +35792,16 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.version = "2.0.5"; + ts.programTime = 0; + ts.emitTime = 0; + ts.ioReadTime = 0; + ts.ioWriteTime = 0; + ts.version = "2.0.0"; var emptyArray = []; - function findConfigFile(searchPath, fileExists, configName) { - if (configName === void 0) { configName = "tsconfig.json"; } + var defaultTypeRoots = ["node_modules/@types"]; + function findConfigFile(searchPath, fileExists) { while (true) { - var fileName = ts.combinePaths(searchPath, configName); + var fileName = ts.combinePaths(searchPath, "tsconfig.json"); if (fileExists(fileName)) { return fileName; } @@ -37163,6 +35851,87 @@ var ts; return ts.getNormalizedPathFromPathComponents(commonPathComponents); } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; + function trace(host, message) { + host.trace(ts.formatMessage.apply(undefined, arguments)); + } + function isTraceEnabled(compilerOptions, host) { + return compilerOptions.traceResolution && host.trace !== undefined; + } + function hasZeroOrOneAsteriskCharacter(str) { + var seenAsterisk = false; + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) === 42) { + if (!seenAsterisk) { + seenAsterisk = true; + } + else { + return false; + } + } + } + return true; + } + ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; + function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { + return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; + } + function moduleHasNonRelativeName(moduleName) { + if (ts.isRootedDiskPath(moduleName)) { + return false; + } + var i = moduleName.lastIndexOf("./", 1); + var startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === 46); + return !startsWithDotSlashOrDotDotSlash; + } + function tryReadTypesSection(packageJsonPath, baseDirectory, state) { + var jsonContent; + try { + var jsonText = state.host.readFile(packageJsonPath); + jsonContent = jsonText ? JSON.parse(jsonText) : {}; + } + catch (e) { + jsonContent = {}; + } + var typesFile; + var fieldName; + if (jsonContent.typings) { + if (typeof jsonContent.typings === "string") { + fieldName = "typings"; + typesFile = jsonContent.typings; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, "typings", typeof jsonContent.typings); + } + } + } + if (!typesFile && jsonContent.types) { + if (typeof jsonContent.types === "string") { + fieldName = "types"; + typesFile = jsonContent.types; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, "types", typeof jsonContent.types); + } + } + } + if (typesFile) { + var typesFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath); + } + return typesFilePath; + } + if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); + } + var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); + return mainFilePath; + } + return undefined; + } var typeReferenceExtensions = [".d.ts"]; function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { @@ -37175,30 +35944,13 @@ var ts; else if (host.getCurrentDirectory) { currentDirectory = host.getCurrentDirectory(); } - return currentDirectory && getDefaultTypeRoots(currentDirectory, host); - } - ts.getEffectiveTypeRoots = getEffectiveTypeRoots; - function getDefaultTypeRoots(currentDirectory, host) { - if (!host.directoryExists) { - return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + if (!currentDirectory) { + return undefined; } - var typeRoots; - while (true) { - var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes); - if (host.directoryExists(atTypes)) { - (typeRoots || (typeRoots = [])).push(atTypes); - } - var parent_15 = ts.getDirectoryPath(currentDirectory); - if (parent_15 === currentDirectory) { - break; - } - currentDirectory = parent_15; - } - return typeRoots; + return ts.map(defaultTypeRoots, function (d) { return ts.combinePaths(currentDirectory, d); }); } - var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { - var traceEnabled = ts.isTraceEnabled(options, host); + var traceEnabled = isTraceEnabled(options, host); var moduleResolutionState = { compilerOptions: options, host: host, @@ -37209,35 +35961,35 @@ var ts; if (traceEnabled) { if (containingFile === undefined) { if (typeRoots === undefined) { - ts.trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); } else { - ts.trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); } } else { if (typeRoots === undefined) { - ts.trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); } else { - ts.trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); } } } var failedLookupLocations = []; if (typeRoots && typeRoots.length) { if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); } var primarySearchPaths = typeRoots; for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) { var typeRoot = primarySearchPaths_1[_i]; var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); - var resolvedFile_1 = ts.loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !ts.directoryProbablyExists(candidateDirectory, host), moduleResolutionState); + var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState); if (resolvedFile_1) { if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true); + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true); } return { resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 }, @@ -37248,7 +36000,7 @@ var ts; } else { if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); + trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); } } var resolvedFile; @@ -37258,21 +36010,21 @@ var ts; } if (initialLocationForSecondaryLookup !== undefined) { if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); + trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - resolvedFile = ts.loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, false); + resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState); if (traceEnabled) { if (resolvedFile) { - ts.trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); } else { - ts.trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); } } } else { if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); + trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); } } return { @@ -37283,8 +36035,398 @@ var ts; }; } ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; + function resolveModuleName(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + } + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + if (traceEnabled) { + trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + var result; + switch (moduleResolution) { + case ts.ModuleResolutionKind.NodeJs: + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); + break; + case ts.ModuleResolutionKind.Classic: + result = classicNameResolver(moduleName, containingFile, compilerOptions, host); + break; + } + if (traceEnabled) { + if (result.resolvedModule) { + trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); + } + else { + trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); + } + } + return result; + } + ts.resolveModuleName = resolveModuleName; + function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (moduleHasNonRelativeName(moduleName)) { + return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); + } + else { + return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); + } + } + function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.rootDirs) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var matchedRootDir; + var matchedNormalizedPrefix; + for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { + var rootDir = _a[_i]; + var normalizedRoot = ts.normalizePath(rootDir); + if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { + normalizedRoot += ts.directorySeparator; + } + var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && + (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); + } + if (isLongestMatchingPrefix) { + matchedNormalizedPrefix = normalizedRoot; + matchedRootDir = rootDir; + } + } + if (matchedNormalizedPrefix) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); + } + var suffix = candidate.substr(matchedNormalizedPrefix.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); + } + for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { + var rootDir = _c[_b]; + if (rootDir === matchedRootDir) { + continue; + } + var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); + } + var baseDirectory = ts.getDirectoryPath(candidate_1); + var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + if (resolvedFileName_1) { + return resolvedFileName_1; + } + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); + } + } + return undefined; + } + function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.baseUrl) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + } + var matchedPattern = undefined; + if (state.compilerOptions.paths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + matchedPattern = matchPatternOrExact(ts.getKeys(state.compilerOptions.paths), moduleName); + } + if (matchedPattern) { + var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName); + var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) { + var subst = _a[_i]; + var path = matchedStar ? subst.replace("*", matchedStar) : subst; + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + } + return undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); + } + return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + } + } + function matchPatternOrExact(patternStrings, candidate) { + var patterns = []; + for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { + var patternString = patternStrings_1[_i]; + var pattern = tryParsePattern(patternString); + if (pattern) { + patterns.push(pattern); + } + else if (patternString === candidate) { + return patternString; + } + } + return findBestPatternMatch(patterns, function (_) { return _; }, candidate); + } + function patternText(_a) { + var prefix = _a.prefix, suffix = _a.suffix; + return prefix + "*" + suffix; + } + function matchedText(pattern, candidate) { + ts.Debug.assert(isPatternMatch(pattern, candidate)); + return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); + } + function findBestPatternMatch(values, getPattern, candidate) { + var matchedValue = undefined; + var longestMatchPrefixLength = -1; + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var v = values_1[_i]; + var pattern = getPattern(v); + if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { + longestMatchPrefixLength = pattern.prefix.length; + matchedValue = v; + } + } + return matchedValue; + } + ts.findBestPatternMatch = findBestPatternMatch; + function isPatternMatch(_a, candidate) { + var prefix = _a.prefix, suffix = _a.suffix; + return candidate.length >= prefix.length + suffix.length && + ts.startsWith(candidate, prefix) && + ts.endsWith(candidate, suffix); + } + function tryParsePattern(pattern) { + ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); + var indexOfStar = pattern.indexOf("*"); + return indexOfStar === -1 ? undefined : { + prefix: pattern.substr(0, indexOfStar), + suffix: pattern.substr(indexOfStar + 1) + }; + } + ts.tryParsePattern = tryParsePattern; + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { + var containingDirectory = ts.getDirectoryPath(containingFile); + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var traceEnabled = isTraceEnabled(compilerOptions, host); + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); + var isExternalLibraryImport = false; + if (!resolvedFileName) { + if (moduleHasNonRelativeName(moduleName)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); + } + resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state); + isExternalLibraryImport = resolvedFileName !== undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, false, state); + } + } + if (resolvedFileName && host.realpath) { + var originalFileName = resolvedFileName; + resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName)); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); + } + } + return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; + function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); + } + var resolvedFileName = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); + return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); + } + function directoryProbablyExists(directoryName, host) { + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + var resolvedByAddingOrKeepingExtension = loadModuleFromFileWorker(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); + if (resolvedByAddingOrKeepingExtension) { + return resolvedByAddingOrKeepingExtension; + } + if (ts.hasJavaScriptFileExtension(candidate)) { + var extensionless = ts.removeFileExtension(candidate); + if (state.traceEnabled) { + var extension = candidate.substring(extensionless.length); + trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); + } + return loadModuleFromFileWorker(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); + } + } + function loadModuleFromFileWorker(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + var directory = ts.getDirectoryPath(candidate); + if (directory) { + onlyRecordFailures = !directoryProbablyExists(directory, state.host); + } + } + return ts.forEach(extensions, tryLoad); + function tryLoad(ext) { + if (state.skipTsx && ts.isJsxOrTsxExtension(ext)) { + return undefined; + } + var fileName = ts.fileExtensionIs(candidate, ext) ? candidate : candidate + ext; + if (!onlyRecordFailures && state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); + } + return fileName; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); + } + failedLookupLocation.push(fileName); + return undefined; + } + } + } + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { + var packageJsonPath = ts.combinePaths(candidate, "package.json"); + var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); + if (directoryExists && state.host.fileExists(packageJsonPath)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); + if (typesFile) { + var result = loadModuleFromFile(typesFile, extensions, failedLookupLocation, !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host), state); + if (result) { + return result; + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field); + } + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); + } + failedLookupLocation.push(packageJsonPath); + } + return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); + } + function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { + var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); + var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions); + var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); + if (result) { + return result; + } + result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); + if (result) { + return result; + } + } + function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state) { + directory = ts.normalizeSlashes(directory); + while (true) { + var baseName = ts.getBaseFileName(directory); + if (baseName !== "node_modules") { + var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); + if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { + return packageResult; + } + else { + var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); + if (typesResult || packageResult) { + return typesResult || packageResult; + } + } + } + var parentPath = ts.getDirectoryPath(directory); + if (parentPath === directory) { + break; + } + directory = parentPath; + } + return undefined; + } + function classicNameResolver(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; + var failedLookupLocations = []; + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var containingDirectory = ts.getDirectoryPath(containingFile); + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); + if (resolvedFileName) { + return createResolvedModule(resolvedFileName, false, failedLookupLocations); + } + var referencedSourceFile; + if (moduleHasNonRelativeName(moduleName)) { + while (true) { + var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state); + if (referencedSourceFile) { + break; + } + var parentPath = ts.getDirectoryPath(containingDirectory); + if (parentPath === containingDirectory) { + break; + } + containingDirectory = parentPath; + } + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, false, state); + } + return referencedSourceFile + ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } + : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; + } + ts.classicNameResolver = classicNameResolver; + ts.defaultInitCompilerOptions = { + module: ts.ModuleKind.CommonJS, + target: 1, + noImplicitAny: false, + sourceMap: false + }; function createCompilerHost(options, setParentNodes) { - var existingDirectories = ts.createMap(); + var existingDirectories = {}; function getCanonicalFileName(fileName) { return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } @@ -37292,10 +36434,9 @@ var ts; function getSourceFile(fileName, languageVersion, onError) { var text; try { - ts.performance.mark("beforeIORead"); + var start = new Date().getTime(); text = ts.sys.readFile(fileName, options.charset); - ts.performance.mark("afterIORead"); - ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); + ts.ioReadTime += new Date().getTime() - start; } catch (e) { if (onError) { @@ -37308,7 +36449,7 @@ var ts; return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined; } function directoryExists(directoryPath) { - if (directoryPath in existingDirectories) { + if (ts.hasProperty(existingDirectories, directoryPath)) { return true; } if (ts.sys.directoryExists(directoryPath)) { @@ -37327,11 +36468,11 @@ var ts; var outputFingerprints; function writeFileIfUpdated(fileName, data, writeByteOrderMark) { if (!outputFingerprints) { - outputFingerprints = ts.createMap(); + outputFingerprints = {}; } var hash = ts.sys.createHash(data); var mtimeBefore = ts.sys.getModifiedTime(fileName); - if (mtimeBefore && fileName in outputFingerprints) { + if (mtimeBefore && ts.hasProperty(outputFingerprints, fileName)) { var fingerprint = outputFingerprints[fileName]; if (fingerprint.byteOrderMark === writeByteOrderMark && fingerprint.hash === hash && @@ -37349,7 +36490,7 @@ var ts; } function writeFile(fileName, data, writeByteOrderMark, onError) { try { - ts.performance.mark("beforeIOWrite"); + var start = new Date().getTime(); ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { writeFileIfUpdated(fileName, data, writeByteOrderMark); @@ -37357,8 +36498,7 @@ var ts; else { ts.sys.writeFile(fileName, data, writeByteOrderMark); } - ts.performance.mark("afterIOWrite"); - ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + ts.ioWriteTime += new Date().getTime() - start; } catch (e) { if (onError) { @@ -37397,22 +36537,6 @@ var ts; return ts.sortAndDeduplicateDiagnostics(diagnostics); } ts.getPreEmitDiagnostics = getPreEmitDiagnostics; - function formatDiagnostics(diagnostics, host) { - var output = ""; - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; - if (diagnostic.file) { - var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; - var fileName = diagnostic.file.fileName; - var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }); - output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): "; - } - var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); - output += category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine(); - } - return output; - } - ts.formatDiagnostics = formatDiagnostics; function flattenDiagnosticMessageText(messageText, newLine) { if (typeof messageText === "string") { return messageText; @@ -37441,17 +36565,25 @@ var ts; return []; } var resolutions = []; - var cache = ts.createMap(); + var cache = {}; for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { var name_34 = names_1[_i]; - var result = name_34 in cache - ? cache[name_34] - : cache[name_34] = loader(name_34, containingFile); + var result = void 0; + if (ts.hasProperty(cache, name_34)) { + result = cache[name_34]; + } + else { + result = loader(name_34, containingFile); + cache[name_34] = result; + } resolutions.push(result); } return resolutions; } - function getAutomaticTypeDirectiveNames(options, host) { + function getInferredTypesRoot(options, rootFiles, host) { + return computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + function getAutomaticTypeDirectiveNames(options, rootFiles, host) { if (options.types) { return options.types; } @@ -37462,15 +36594,7 @@ var ts; for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { var root = typeRoots_1[_i]; if (host.directoryExists(root)) { - for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { - var typeDirectivePath = _b[_a]; - var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = ts.pathToPackageJson(ts.combinePaths(root, normalized)); - var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null; - if (!isNotNeededPackage) { - result.push(ts.getBaseFileName(normalized)); - } - } + result = result.concat(host.getDirectories(root)); } } } @@ -37485,13 +36609,13 @@ var ts; var diagnosticsProducingTypeChecker; var noDiagnosticsTypeChecker; var classifiableNames; - var resolvedTypeReferenceDirectives = ts.createMap(); + var resolvedTypeReferenceDirectives = {}; var fileProcessingDiagnostics = ts.createDiagnosticCollection(); - var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; - var currentNodeModulesDepth = 0; - var modulesWithElidedImports = ts.createMap(); - var sourceFilesFoundSearchingNodeModules = ts.createMap(); - ts.performance.mark("beforeProgram"); + var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 2; + var currentNodeModulesJsDepth = 0; + var modulesWithElidedImports = {}; + var sourceFilesFoundSearchingNodeModules = {}; + var start = new Date().getTime(); host = host || createCompilerHost(options); var skipDefaultLib = options.noLib; var programDiagnostics = ts.createDiagnosticCollection(); @@ -37503,7 +36627,7 @@ var ts; resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }; } else { - var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; + var loader_1 = function (moduleName, containingFile) { return resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(moduleNames, containingFile, loader_1); }; } var resolveTypeReferenceDirectiveNamesWorker; @@ -37518,9 +36642,10 @@ var ts; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; if (!tryReuseStructureFromOldProgram()) { ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); - var typeReferences = getAutomaticTypeDirectiveNames(options, host); + var typeReferences = getAutomaticTypeDirectiveNames(options, rootNames, host); if (typeReferences) { - var containingFilename = ts.combinePaths(host.getCurrentDirectory(), "__inferred type names__.ts"); + var inferredRoot = getInferredTypesRoot(options, rootNames, host); + var containingFilename = ts.combinePaths(inferredRoot, "__inferred type names__.ts"); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i]); @@ -37561,12 +36686,10 @@ var ts; getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, - getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, - dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker + getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; } }; verifyCompilerOptions(); - ts.performance.mark("afterProgram"); - ts.performance.measure("Program", "beforeProgram", "afterProgram"); + ts.programTime += new Date().getTime() - start; return program; function getCommonSourceDirectory() { if (typeof commonSourceDirectory === "undefined") { @@ -37585,10 +36708,10 @@ var ts; function getClassifiableNames() { if (!classifiableNames) { getTypeChecker(); - classifiableNames = ts.createMap(); + classifiableNames = {}; for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { var sourceFile = files_2[_i]; - ts.copyProperties(sourceFile.classifiableNames, classifiableNames); + ts.copyMap(sourceFile.classifiableNames, classifiableNames); } } return classifiableNames; @@ -37611,7 +36734,7 @@ var ts; (oldOptions.maxNodeModuleJsDepth !== options.maxNodeModuleJsDepth) || !ts.arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) || !ts.arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) || - !ts.equalOwnProperties(oldOptions.paths, options.paths)) { + !ts.mapIsEqualTo(oldOptions.paths, options.paths)) { return false; } ts.Debug.assert(!oldProgram.structureIsReused); @@ -37701,7 +36824,7 @@ var ts; getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, - isSourceFileFromExternalLibrary: function (file) { return !!sourceFilesFoundSearchingNodeModules[file.path]; }, + isSourceFileFromExternalLibrary: function (file) { return !!ts.lookUp(sourceFilesFoundSearchingNodeModules, file.path); }, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked }; @@ -37709,19 +36832,17 @@ var ts; function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, true)); } - function dropDiagnosticsProducingTypeChecker() { - diagnosticsProducingTypeChecker = undefined; - } function getTypeChecker() { return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, false)); } - function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { - return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles); }); + function emit(sourceFile, writeFileCallback, cancellationToken) { + var _this = this; + return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); }); } function isEmitBlocked(emitFileName) { return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); } - function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { + function emitWorker(program, sourceFile, writeFileCallback, cancellationToken) { var declarationDiagnostics = []; if (options.noEmit) { return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; @@ -37741,10 +36862,9 @@ var ts; } } var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); - ts.performance.mark("beforeEmit"); - var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles); - ts.performance.mark("afterEmit"); - ts.performance.measure("Emit", "beforeEmit", "afterEmit"); + var start = new Date().getTime(); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile); + ts.emitTime += new Date().getTime() - start; return emitResult; } function getSourceFile(fileName) { @@ -37883,16 +37003,16 @@ var ts; case 175: var expression = node; if (expression.typeArguments && expression.typeArguments.length > 0) { - var start = expression.typeArguments.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, expression.typeArguments.end - start, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); + var start_2 = expression.typeArguments.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start_2, expression.typeArguments.end - start_2, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); return true; } break; case 142: var parameter = node; if (parameter.modifiers) { - var start = parameter.modifiers.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, parameter.modifiers.end - start, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); + var start_3 = parameter.modifiers.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start_3, parameter.modifiers.end - start_3, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); return true; } if (parameter.questionToken) { @@ -37936,8 +37056,8 @@ var ts; } function checkTypeParameters(typeParameters) { if (typeParameters) { - var start = typeParameters.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, typeParameters.end - start, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); + var start_4 = typeParameters.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start_4, typeParameters.end - start_4, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); return true; } return false; @@ -38124,17 +37244,8 @@ var ts; if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); } - if (file_1 && sourceFilesFoundSearchingNodeModules[file_1.path] && currentNodeModulesDepth == 0) { - sourceFilesFoundSearchingNodeModules[file_1.path] = false; - if (!options.noResolve) { - processReferencedFiles(file_1, ts.getDirectoryPath(fileName), isDefaultLib); - processTypeReferenceDirectives(file_1); - } - modulesWithElidedImports[file_1.path] = false; - processImportedModules(file_1, ts.getDirectoryPath(fileName)); - } - else if (file_1 && modulesWithElidedImports[file_1.path]) { - if (currentNodeModulesDepth < maxNodeModulesJsDepth) { + if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) { + if (currentNodeModulesJsDepth < maxNodeModulesJsDepth) { modulesWithElidedImports[file_1.path] = false; processImportedModules(file_1, ts.getDirectoryPath(fileName)); } @@ -38151,7 +37262,6 @@ var ts; }); filesByName.set(path, file); if (file) { - sourceFilesFoundSearchingNodeModules[path] = (currentNodeModulesDepth > 0); file.path = path; if (host.useCaseSensitiveFileNames()) { var existingFile = filesByNameIgnoreCase.get(path); @@ -38185,14 +37295,13 @@ var ts; }); } function processTypeReferenceDirectives(file) { - var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); + var typeDirectives = ts.map(file.typeReferenceDirectives, function (l) { return l.fileName; }); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; var resolvedTypeReferenceDirective = resolutions[i]; - var fileName = ref.fileName.toLocaleLowerCase(); - ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective); - processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end); + ts.setResolvedTypeReferenceDirective(file, ref.fileName, resolvedTypeReferenceDirective); + processTypeReferenceDirective(ref.fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end); } } function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, refFile, refPos, refEnd) { @@ -38209,7 +37318,7 @@ var ts; if (previousResolution) { var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) { - fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_to_resolve_this_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); } saveResolution = false; } @@ -38243,7 +37352,7 @@ var ts; function processImportedModules(file, basePath) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { - file.resolvedModules = ts.createMap(); + file.resolvedModules = {}; var moduleNames = ts.map(ts.concatenate(file.imports, file.moduleAugmentations), getTextOfLiteral); var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory)); for (var i = 0; i < moduleNames.length; i++) { @@ -38253,9 +37362,12 @@ var ts; var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport; var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName); if (isFromNodeModulesSearch) { - currentNodeModulesDepth++; + sourceFilesFoundSearchingNodeModules[resolvedPath] = true; } - var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth; + if (isJsFileFromNodeModules) { + currentNodeModulesJsDepth++; + } + var elideImport = isJsFileFromNodeModules && currentNodeModulesJsDepth > maxNodeModulesJsDepth; var shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport; if (elideImport) { modulesWithElidedImports[file.path] = true; @@ -38263,8 +37375,8 @@ var ts; else if (shouldAddFile) { findSourceFile(resolution.resolvedFileName, resolvedPath, false, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); } - if (isFromNodeModulesSearch) { - currentNodeModulesDepth--; + if (isJsFileFromNodeModules) { + currentNodeModulesJsDepth--; } } } @@ -38331,18 +37443,15 @@ var ts; if (!ts.hasProperty(options.paths, key)) { continue; } - if (!ts.hasZeroOrOneAsteriskCharacter(key)) { + if (!hasZeroOrOneAsteriskCharacter(key)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); } if (ts.isArray(options.paths[key])) { - if (options.paths[key].length === 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key)); - } for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { var subst = _a[_i]; var typeOfSubst = typeof subst; if (typeOfSubst === "string") { - if (!ts.hasZeroOrOneAsteriskCharacter(subst)) { + if (!hasZeroOrOneAsteriskCharacter(subst)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key)); } } @@ -38383,7 +37492,7 @@ var ts; } var languageVersion = options.target || 0; var outFile = options.outFile || options.out; - var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); + var firstExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) ? f : undefined; }); if (options.isolatedModules) { if (options.module === ts.ModuleKind.None && languageVersion < 2) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); @@ -38394,17 +37503,17 @@ var ts; programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); } } - else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 && options.module === ts.ModuleKind.None) { - var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); + else if (firstExternalModuleSourceFile && languageVersion < 2 && options.module === ts.ModuleKind.None) { + var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } if (outFile) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); } - else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) { - var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); + else if (options.module === undefined && firstExternalModuleSourceFile) { + var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); } } if (options.outDir || @@ -38457,13 +37566,11 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; ts.optionDeclarations = [ { name: "charset", type: "string" }, - ts.compileOnSaveCommandLineOption, { name: "declaration", shortName: "d", @@ -38480,10 +37587,6 @@ var ts; name: "diagnostics", type: "boolean" }, - { - name: "extendedDiagnostics", - type: "boolean" - }, { name: "emitBOM", type: "boolean" @@ -38514,10 +37617,10 @@ var ts; }, { name: "jsx", - type: ts.createMap({ + type: { "preserve": 1, "react": 2 - }), + }, paramType: ts.Diagnostics.KIND, description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react }, @@ -38544,7 +37647,7 @@ var ts; { name: "module", shortName: "m", - type: ts.createMap({ + type: { "none": ts.ModuleKind.None, "commonjs": ts.ModuleKind.CommonJS, "amd": ts.ModuleKind.AMD, @@ -38552,16 +37655,16 @@ var ts; "umd": ts.ModuleKind.UMD, "es6": ts.ModuleKind.ES6, "es2015": ts.ModuleKind.ES2015 - }), + }, description: ts.Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015, paramType: ts.Diagnostics.KIND }, { name: "newLine", - type: ts.createMap({ + type: { "crlf": 0, "lf": 1 - }), + }, description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix, paramType: ts.Diagnostics.NEWLINE }, @@ -38579,10 +37682,6 @@ var ts; type: "boolean", description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported }, - { - name: "noErrorTruncation", - type: "boolean" - }, { name: "noImplicitAny", type: "boolean", @@ -38596,12 +37695,12 @@ var ts; { name: "noUnusedLocals", type: "boolean", - description: ts.Diagnostics.Report_errors_on_unused_locals + description: ts.Diagnostics.Report_Errors_on_Unused_Locals }, { name: "noUnusedParameters", type: "boolean", - description: ts.Diagnostics.Report_errors_on_unused_parameters + description: ts.Diagnostics.Report_Errors_on_Unused_Parameters }, { name: "noLib", @@ -38706,12 +37805,12 @@ var ts; { name: "target", shortName: "t", - type: ts.createMap({ + type: { "es3": 0, "es5": 1, "es6": 2, "es2015": 2 - }), + }, description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015, paramType: ts.Diagnostics.VERSION }, @@ -38740,10 +37839,10 @@ var ts; }, { name: "moduleResolution", - type: ts.createMap({ + type: { "node": ts.ModuleResolutionKind.NodeJs, "classic": ts.ModuleResolutionKind.Classic - }), + }, description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6 }, { @@ -38844,7 +37943,7 @@ var ts; type: "list", element: { name: "lib", - type: ts.createMap({ + type: { "es5": "lib.es5.d.ts", "es6": "lib.es2015.d.ts", "es2015": "lib.es2015.d.ts", @@ -38866,7 +37965,7 @@ var ts; "es2016.array.include": "lib.es2016.array.include.d.ts", "es2017.object": "lib.es2017.object.d.ts", "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts" - }) + } }, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon }, @@ -38902,19 +38001,13 @@ var ts; } } ]; - ts.defaultInitCompilerOptions = { - module: ts.ModuleKind.CommonJS, - target: 1, - noImplicitAny: false, - sourceMap: false - }; var optionNameMapCache; function getOptionNameMap() { if (optionNameMapCache) { return optionNameMapCache; } - var optionNameMap = ts.createMap(); - var shortOptionNames = ts.createMap(); + var optionNameMap = {}; + var shortOptionNames = {}; ts.forEach(ts.optionDeclarations, function (option) { optionNameMap[option.name.toLowerCase()] = option; if (option.shortName) { @@ -38927,16 +38020,16 @@ var ts; ts.getOptionNameMap = getOptionNameMap; function createCompilerDiagnosticForInvalidCustomType(opt) { var namesOfType = []; - for (var key in opt.type) { + ts.forEachKey(opt.type, function (key) { namesOfType.push(" '" + key + "'"); - } + }); return ts.createCompilerDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); } ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; function parseCustomTypeOption(opt, value, errors) { var key = trimString((value || "")).toLowerCase(); var map = opt.type; - if (key in map) { + if (ts.hasProperty(map, key)) { return map[key]; } else { @@ -38985,10 +38078,10 @@ var ts; } else if (s.charCodeAt(0) === 45) { s = s.slice(s.charCodeAt(1) === 45 ? 2 : 1).toLowerCase(); - if (s in shortOptionNames) { + if (ts.hasProperty(shortOptionNames, s)) { s = shortOptionNames[s]; } - if (s in optionNameMap) { + if (ts.hasProperty(optionNameMap, s)) { var opt = optionNameMap[s]; if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -39079,87 +38172,16 @@ var ts; return parseConfigFileTextToJson(fileName, text); } ts.readConfigFile = readConfigFile; - function parseConfigFileTextToJson(fileName, jsonText, stripComments) { - if (stripComments === void 0) { stripComments = true; } + function parseConfigFileTextToJson(fileName, jsonText) { try { - var jsonTextToParse = stripComments ? removeComments(jsonText) : jsonText; - return { config: /\S/.test(jsonTextToParse) ? JSON.parse(jsonTextToParse) : {} }; + var jsonTextWithoutComments = removeComments(jsonText); + return { config: /\S/.test(jsonTextWithoutComments) ? JSON.parse(jsonTextWithoutComments) : {} }; } catch (e) { return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) }; } } ts.parseConfigFileTextToJson = parseConfigFileTextToJson; - function generateTSConfig(options, fileNames) { - var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); - var configurations = { - compilerOptions: serializeCompilerOptions(compilerOptions) - }; - if (fileNames && fileNames.length) { - configurations.files = fileNames; - } - return configurations; - function getCustomTypeMapOfCommandLineOption(optionDefinition) { - if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { - return undefined; - } - else if (optionDefinition.type === "list") { - return getCustomTypeMapOfCommandLineOption(optionDefinition.element); - } - else { - return optionDefinition.type; - } - } - function getNameOfCompilerOptionValue(value, customTypeMap) { - for (var key in customTypeMap) { - if (customTypeMap[key] === value) { - return key; - } - } - return undefined; - } - function serializeCompilerOptions(options) { - var result = ts.createMap(); - var optionsNameMap = getOptionNameMap().optionNameMap; - for (var name_35 in options) { - if (ts.hasProperty(options, name_35)) { - switch (name_35) { - case "init": - case "watch": - case "version": - case "help": - case "project": - break; - default: - var value = options[name_35]; - var optionDefinition = optionsNameMap[name_35.toLowerCase()]; - if (optionDefinition) { - var customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition); - if (!customTypeMap) { - result[name_35] = value; - } - else { - if (optionDefinition.type === "list") { - var convertedValue = []; - for (var _i = 0, _a = value; _i < _a.length; _i++) { - var element = _a[_i]; - convertedValue.push(getNameOfCompilerOptionValue(element, customTypeMap)); - } - result[name_35] = convertedValue; - } - else { - result[name_35] = getNameOfCompilerOptionValue(value, customTypeMap); - } - } - } - break; - } - } - } - return result; - } - } - ts.generateTSConfig = generateTSConfig; function removeComments(jsonText) { var output = ""; var scanner = ts.createScanner(1, false, 0, jsonText); @@ -39177,6 +38199,7 @@ var ts; } return output; } + var ignoreFileNamePattern = /(\.min\.js$)|([\\/]\.[\w.])/; function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName) { if (existingOptions === void 0) { existingOptions = {}; } var errors = []; @@ -39185,15 +38208,13 @@ var ts; var typingOptions = convertTypingOptionsFromJsonWorker(json["typingOptions"], basePath, errors, configFileName); options.configFilePath = configFileName; var _a = getFileNames(errors), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; - var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); return { options: options, fileNames: fileNames, typingOptions: typingOptions, raw: json, errors: errors, - wildcardDirectories: wildcardDirectories, - compileOnSave: compileOnSave + wildcardDirectories: wildcardDirectories }; function getFileNames(errors) { var fileNames; @@ -39240,17 +38261,6 @@ var ts; } } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; - function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { - if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { - return false; - } - var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); - if (typeof result === "boolean" && result) { - return result; - } - return false; - } - ts.convertCompileOnSaveOptionFromJson = convertCompileOnSaveOptionFromJson; function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { var errors = []; var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); @@ -39264,7 +38274,7 @@ var ts; } ts.convertTypingOptionsFromJson = convertTypingOptionsFromJson; function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2 } : {}; + var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true } : {}; convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); return options; } @@ -39281,7 +38291,7 @@ var ts; } var optionNameMap = ts.arrayToMap(optionDeclarations, function (opt) { return opt.name; }); for (var id in jsonOptions) { - if (id in optionNameMap) { + if (ts.hasProperty(optionNameMap, id)) { var opt = optionNameMap[id]; defaultOptions[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors); } @@ -39316,7 +38326,7 @@ var ts; } function convertJsonOptionOfCustomType(opt, value, errors) { var key = value.toLowerCase(); - if (key in opt.type) { + if (ts.hasProperty(opt.type, key)) { return opt.type[key]; } else { @@ -39337,8 +38347,8 @@ var ts; function matchFileNames(fileNames, include, exclude, basePath, options, host, errors) { basePath = ts.normalizePath(basePath); var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; - var literalFileMap = ts.createMap(); - var wildcardFileMap = ts.createMap(); + var literalFileMap = {}; + var wildcardFileMap = {}; if (include) { include = validateSpecs(include, errors, false); } @@ -39360,9 +38370,12 @@ var ts; if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { continue; } + if (ignoreFileNamePattern.test(file)) { + continue; + } removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); var key = keyMapper(file); - if (!(key in literalFileMap) && !(key in wildcardFileMap)) { + if (!ts.hasProperty(literalFileMap, key) && !ts.hasProperty(wildcardFileMap, key)) { wildcardFileMap[key] = file; } } @@ -39397,20 +38410,20 @@ var ts; function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) { var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); - var wildcardDirectories = ts.createMap(); + var wildcardDirectories = {}; if (include !== undefined) { var recursiveKeys = []; for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { var file = include_1[_i]; - var name_36 = ts.normalizePath(ts.combinePaths(path, file)); - if (excludeRegex && excludeRegex.test(name_36)) { + var name_35 = ts.normalizePath(ts.combinePaths(path, file)); + if (excludeRegex && excludeRegex.test(name_35)) { continue; } - var match = wildcardDirectoryPattern.exec(name_36); + var match = wildcardDirectoryPattern.exec(name_35); if (match) { var key = useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(); - var flags = watchRecursivePattern.test(name_36) ? 1 : 0; - var existingFlags = wildcardDirectories[key]; + var flags = watchRecursivePattern.test(name_35) ? 1 : 0; + var existingFlags = ts.getProperty(wildcardDirectories, key); if (existingFlags === undefined || existingFlags < flags) { wildcardDirectories[key] = flags; if (flags === 1) { @@ -39420,10 +38433,12 @@ var ts; } } for (var key in wildcardDirectories) { - for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { - var recursiveKey = recursiveKeys_1[_a]; - if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { - delete wildcardDirectories[key]; + if (ts.hasProperty(wildcardDirectories, key)) { + for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { + var recursiveKey = recursiveKeys_1[_a]; + if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { + delete wildcardDirectories[key]; + } } } } @@ -39436,7 +38451,7 @@ var ts; for (var i = 0; i < adjustedExtensionPriority; i++) { var higherPriorityExtension = extensions[i]; var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); - if (higherPriorityPath in literalFiles || higherPriorityPath in wildcardFiles) { + if (ts.hasProperty(literalFiles, higherPriorityPath) || ts.hasProperty(wildcardFiles, higherPriorityPath)) { return true; } } @@ -39464,18 +38479,10 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var defaultFormatDiagnosticsHost = { - getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); }, - getNewLine: function () { return ts.sys.newLine; }, - getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames) - }; - var reportDiagnosticWorker = reportDiagnosticSimply; - function reportDiagnostic(diagnostic, host) { - reportDiagnosticWorker(diagnostic, host || defaultFormatDiagnosticsHost); - } + var reportDiagnostic = reportDiagnosticSimply; function reportDiagnostics(diagnostics, host) { - for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { - var diagnostic = diagnostics_3[_i]; + for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { + var diagnostic = diagnostics_1[_i]; reportDiagnostic(diagnostic, host); } } @@ -39546,8 +38553,19 @@ var ts; var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments); return diagnostic.messageText; } + function getRelativeFileName(fileName, host) { + return host ? ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : fileName; + } function reportDiagnosticSimply(diagnostic, host) { - ts.sys.write(ts.formatDiagnostics([diagnostic], host)); + var output = ""; + if (diagnostic.file) { + var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; + var relativeFileName = getRelativeFileName(diagnostic.file.fileName, host); + output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): "; + } + var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); + output += category + " TS" + diagnostic.code + ": " + ts.flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine) + ts.sys.newLine; + ts.sys.write(output); } var redForegroundEscapeSequence = "\u001b[91m"; var yellowForegroundEscapeSequence = "\u001b[93m"; @@ -39556,23 +38574,23 @@ var ts; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; - var categoryFormatMap = ts.createMap((_a = {}, + var categoryFormatMap = (_a = {}, _a[ts.DiagnosticCategory.Warning] = yellowForegroundEscapeSequence, _a[ts.DiagnosticCategory.Error] = redForegroundEscapeSequence, _a[ts.DiagnosticCategory.Message] = blueForegroundEscapeSequence, _a - )); + ); function formatAndReset(text, formatStyle) { return formatStyle + text + resetEscapeSequence; } function reportDiagnosticWithColorAndContext(diagnostic, host) { var output = ""; if (diagnostic.file) { - var start = diagnostic.start, length_4 = diagnostic.length, file = diagnostic.file; + var start = diagnostic.start, length_3 = diagnostic.length, file = diagnostic.file; var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; - var _b = ts.getLineAndCharacterOfPosition(file, start + length_4), lastLine = _b.line, lastLineChar = _b.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length_3), lastLine = _b.line, lastLineChar = _b.character; var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; - var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; + var relativeFileName = getRelativeFileName(file.fileName, host); var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; var gutterWidth = (lastLine + 1 + "").length; if (hasMoreThanFiveLines) { @@ -39761,8 +38779,7 @@ var ts; ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); return; } - var cwd = ts.sys.getCurrentDirectory(); - var configParseResult = ts.parseJsonConfigFileContent(configObject, ts.sys, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), commandLine.options, ts.getNormalizedAbsolutePath(configFileName, cwd)); + var configParseResult = ts.parseJsonConfigFileContent(configObject, ts.sys, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), ts.sys.getCurrentDirectory()), commandLine.options, configFileName); if (configParseResult.errors.length > 0) { reportDiagnostics(configParseResult.errors, undefined); ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); @@ -39799,9 +38816,9 @@ var ts; compilerHost.fileExists = cachedFileExists; } if (compilerOptions.pretty) { - reportDiagnosticWorker = reportDiagnosticWithColorAndContext; + reportDiagnostic = reportDiagnosticWithColorAndContext; } - cachedExistingFiles = ts.createMap(); + cachedExistingFiles = {}; var compileResult = compile(rootFileNames, compilerOptions, compilerHost); if (!ts.isWatchSet(compilerOptions)) { return ts.sys.exit(compileResult.exitStatus); @@ -39810,9 +38827,10 @@ var ts; reportWatchDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Compilation_complete_Watching_for_file_changes)); } function cachedFileExists(fileName) { - return fileName in cachedExistingFiles - ? cachedExistingFiles[fileName] - : cachedExistingFiles[fileName] = hostFileExists(fileName); + if (ts.hasProperty(cachedExistingFiles, fileName)) { + return cachedExistingFiles[fileName]; + } + return cachedExistingFiles[fileName] = hostFileExists(fileName); } function getSourceFile(fileName, languageVersion, onError) { if (cachedProgram) { @@ -39892,9 +38910,12 @@ var ts; } ts.executeCommandLine = executeCommandLine; function compile(fileNames, compilerOptions, compilerHost) { - var hasDiagnostics = compilerOptions.diagnostics || compilerOptions.extendedDiagnostics; - if (hasDiagnostics) - ts.performance.enable(); + ts.ioReadTime = 0; + ts.ioWriteTime = 0; + ts.programTime = 0; + ts.bindTime = 0; + ts.checkTime = 0; + ts.emitTime = 0; var program = ts.createProgram(fileNames, compilerOptions, compilerHost); var exitStatus = compileProgram(); if (compilerOptions.listFiles) { @@ -39902,7 +38923,7 @@ var ts; ts.sys.write(file.fileName + ts.sys.newLine); }); } - if (hasDiagnostics) { + if (compilerOptions.diagnostics) { var memoryUsed = ts.sys.getMemoryUsage ? ts.sys.getMemoryUsage() : -1; reportCountStatistic("Files", program.getSourceFiles().length); reportCountStatistic("Lines", countLines(program)); @@ -39913,23 +38934,13 @@ var ts; if (memoryUsed >= 0) { reportStatisticalValue("Memory used", Math.round(memoryUsed / 1000) + "K"); } - var programTime = ts.performance.getDuration("Program"); - var bindTime = ts.performance.getDuration("Bind"); - var checkTime = ts.performance.getDuration("Check"); - var emitTime = ts.performance.getDuration("Emit"); - if (compilerOptions.extendedDiagnostics) { - ts.performance.forEachMeasure(function (name, duration) { return reportTimeStatistic(name + " time", duration); }); - } - else { - reportTimeStatistic("I/O read", ts.performance.getDuration("I/O Read")); - reportTimeStatistic("I/O write", ts.performance.getDuration("I/O Write")); - reportTimeStatistic("Parse time", programTime); - reportTimeStatistic("Bind time", bindTime); - reportTimeStatistic("Check time", checkTime); - reportTimeStatistic("Emit time", emitTime); - } - reportTimeStatistic("Total time", programTime + bindTime + checkTime + emitTime); - ts.performance.disable(); + reportTimeStatistic("I/O read", ts.ioReadTime); + reportTimeStatistic("I/O write", ts.ioWriteTime); + reportTimeStatistic("Parse time", ts.programTime); + reportTimeStatistic("Bind time", ts.bindTime); + reportTimeStatistic("Check time", ts.checkTime); + reportTimeStatistic("Emit time", ts.emitTime); + reportTimeStatistic("Total time", ts.programTime + ts.bindTime + ts.checkTime + ts.emitTime); } return { program: program, exitStatus: exitStatus }; function compileProgram() { @@ -39968,7 +38979,7 @@ var ts; output += ts.sys.newLine + ts.sys.newLine; var padding = makePadding(marginLength); output += getDiagnosticText(ts.Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + ts.sys.newLine; - output += padding + "tsc --outFile file.js file.ts" + ts.sys.newLine; + output += padding + "tsc --out file.js file.ts" + ts.sys.newLine; output += padding + "tsc @args.txt" + ts.sys.newLine; output += ts.sys.newLine; output += getDiagnosticText(ts.Diagnostics.Options_Colon) + ts.sys.newLine; @@ -39977,11 +38988,11 @@ var ts; marginLength = 0; var usageColumn = []; var descriptionColumn = []; - var optionsDescriptionMap = ts.createMap(); - for (var i = 0; i < optsList.length; i++) { + var optionsDescriptionMap = {}; + var _loop_3 = function(i) { var option = optsList[i]; if (!option.description) { - continue; + return "continue"; } var usageText_1 = " "; if (option.shortName) { @@ -39995,19 +39006,21 @@ var ts; var description = void 0; if (option.name === "lib") { description = getDiagnosticText(option.description); - var options = []; + var options_1 = []; var element = option.element; - var typeMap = element.type; - for (var key in typeMap) { - options.push("'" + key + "'"); - } - optionsDescriptionMap[description] = options; + ts.forEachKey(element.type, function (key) { + options_1.push("'" + key + "'"); + }); + optionsDescriptionMap[description] = options_1; } else { description = getDiagnosticText(option.description); } descriptionColumn.push(description); marginLength = Math.max(usageText_1.length, marginLength); + }; + for (var i = 0; i < optsList.length; i++) { + _loop_3(i); } var usageText = " @<" + getDiagnosticText(ts.Diagnostics.file) + ">"; usageColumn.push(usageText); @@ -40046,10 +39059,58 @@ var ts; reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.A_tsconfig_json_file_is_already_defined_at_Colon_0, file), undefined); } else { - ts.sys.writeFile(file, JSON.stringify(ts.generateTSConfig(options, fileNames), undefined, 4)); + var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); + var configurations = { + compilerOptions: serializeCompilerOptions(compilerOptions) + }; + if (fileNames && fileNames.length) { + configurations.files = fileNames; + } + else { + configurations.exclude = ["node_modules"]; + if (compilerOptions.outDir) { + configurations.exclude.push(compilerOptions.outDir); + } + } + ts.sys.writeFile(file, JSON.stringify(configurations, undefined, 4)); reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Successfully_created_a_tsconfig_json_file), undefined); } return; + function serializeCompilerOptions(options) { + var result = {}; + var optionsNameMap = ts.getOptionNameMap().optionNameMap; + for (var name_36 in options) { + if (ts.hasProperty(options, name_36)) { + var value = options[name_36]; + switch (name_36) { + case "init": + case "watch": + case "version": + case "help": + case "project": + break; + default: + var optionDefinition = optionsNameMap[name_36.toLowerCase()]; + if (optionDefinition) { + if (typeof optionDefinition.type === "string") { + result[name_36] = value; + } + else { + var typeMap = optionDefinition.type; + for (var key in typeMap) { + if (ts.hasProperty(typeMap, key)) { + if (typeMap[key] === value) + result[name_36] = key; + } + } + } + } + break; + } + } + } + return result; + } } var _a; })(ts || (ts = {})); diff --git a/lib/tsserver.js b/lib/tsserver.js index 5cd35272b5c..af6ee897902 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -69,87 +69,14 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); }; -})(ts || (ts = {})); -var ts; -(function (ts) { - var performance; - (function (performance) { - var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true - ? onProfilerEvent - : function (markName) { }; - var enabled = false; - var profilerStart = 0; - var counts; - var marks; - var measures; - function mark(markName) { - if (enabled) { - marks[markName] = ts.timestamp(); - counts[markName] = (counts[markName] || 0) + 1; - profilerEvent(markName); - } - } - performance.mark = mark; - function measure(measureName, startMarkName, endMarkName) { - if (enabled) { - var end = endMarkName && marks[endMarkName] || ts.timestamp(); - var start = startMarkName && marks[startMarkName] || profilerStart; - measures[measureName] = (measures[measureName] || 0) + (end - start); - } - } - performance.measure = measure; - function getCount(markName) { - return counts && counts[markName] || 0; - } - performance.getCount = getCount; - function getDuration(measureName) { - return measures && measures[measureName] || 0; - } - performance.getDuration = getDuration; - function forEachMeasure(cb) { - for (var key in measures) { - cb(key, measures[key]); - } - } - performance.forEachMeasure = forEachMeasure; - function enable() { - counts = ts.createMap(); - marks = ts.createMap(); - measures = ts.createMap(); - enabled = true; - profilerStart = ts.timestamp(); - } - performance.enable = enable; - function disable() { - enabled = false; - } - performance.disable = disable; - })(performance = ts.performance || (ts.performance = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - var createObject = Object.create; - function createMap(template) { - var map = createObject(null); - map["__"] = undefined; - delete map["__"]; - for (var key in template) - if (hasOwnProperty.call(template, key)) { - map[key] = template[key]; - } - return map; - } - ts.createMap = createMap; function createFileMap(keyMapper) { - var files = createMap(); + var files = {}; return { get: get, set: set, contains: contains, remove: remove, forEachValue: forEachValueInMap, - getKeys: getKeys, clear: clear }; function forEachValueInMap(f) { @@ -157,13 +84,6 @@ var ts; f(key, files[key]); } } - function getKeys() { - var keys = []; - for (var key in files) { - keys.push(key); - } - return keys; - } function get(path) { return files[toKey(path)]; } @@ -171,14 +91,14 @@ var ts; files[toKey(path)] = value; } function contains(path) { - return toKey(path) in files; + return hasProperty(files, toKey(path)); } function remove(path) { var key = toKey(path); delete files[key]; } function clear() { - files = createMap(); + files = {}; } function toKey(path) { return keyMapper ? keyMapper(path) : path; @@ -204,31 +124,11 @@ var ts; return undefined; } ts.forEach = forEach; - function find(array, predicate) { - for (var i = 0, len = array.length; i < len; i++) { - var value = array[i]; - if (predicate(value, i)) { - return value; - } - } - return undefined; - } - ts.find = find; - function findMap(array, callback) { - for (var i = 0, len = array.length; i < len; i++) { - var result = callback(array[i], i); - if (result) { - return result; - } - } - Debug.fail(); - } - ts.findMap = findMap; - function contains(array, value) { + function contains(array, value, areEqual) { if (array) { for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { var v = array_1[_i]; - if (v === value) { + if (areEqual ? areEqual(v, value) : v === value) { return true; } } @@ -270,43 +170,19 @@ var ts; } ts.countWhere = countWhere; function filter(array, f) { + var result; if (array) { - var len = array.length; - var i = 0; - while (i < len && f(array[i])) - i++; - if (i < len) { - var result = array.slice(0, i); - i++; - while (i < len) { - var item = array[i]; - if (f(item)) { - result.push(item); - } - i++; + result = []; + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var item = array_3[_i]; + if (f(item)) { + result.push(item); } - return result; } } - return array; + return result; } ts.filter = filter; - function removeWhere(array, f) { - var outIndex = 0; - for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { - var item = array_3[_i]; - if (!f(item)) { - array[outIndex] = item; - outIndex++; - } - } - if (outIndex !== array.length) { - array.length = outIndex; - return true; - } - return false; - } - ts.removeWhere = removeWhere; function filterMutate(array, f) { var outIndex = 0; for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { @@ -343,15 +219,11 @@ var ts; var result; if (array) { result = []; - loop: for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { var item = array_6[_i]; - for (var _a = 0, result_1 = result; _a < result_1.length; _a++) { - var res = result_1[_a]; - if (areEqual ? areEqual(res, item) : res === item) { - continue loop; - } + if (!contains(result, item, areEqual)) { + result.push(item); } - result.push(item); } } return result; @@ -392,22 +264,16 @@ var ts; return array[array.length - 1]; } ts.lastOrUndefined = lastOrUndefined; - function binarySearch(array, value, comparer) { - if (!array || array.length === 0) { - return -1; - } + function binarySearch(array, value) { var low = 0; var high = array.length - 1; - comparer = comparer !== undefined - ? comparer - : function (v1, v2) { return (v1 < v2 ? -1 : (v1 > v2 ? 1 : 0)); }; while (low <= high) { var middle = low + ((high - low) >> 1); var midValue = array[middle]; - if (comparer(midValue, value) === 0) { + if (midValue === value) { return middle; } - else if (comparer(midValue, value) > 0) { + else if (midValue > value) { high = middle - 1; } else { @@ -467,117 +333,96 @@ var ts; return hasOwnProperty.call(map, key); } ts.hasProperty = hasProperty; + function getKeys(map) { + var keys = []; + for (var key in map) { + keys.push(key); + } + return keys; + } + ts.getKeys = getKeys; function getProperty(map, key) { return hasOwnProperty.call(map, key) ? map[key] : undefined; } ts.getProperty = getProperty; - function getOwnKeys(map) { - var keys = []; - for (var key in map) - if (hasOwnProperty.call(map, key)) { - keys.push(key); + function isEmpty(map) { + for (var id in map) { + if (hasProperty(map, id)) { + return false; } - return keys; - } - ts.getOwnKeys = getOwnKeys; - function forEachProperty(map, callback) { - var result; - for (var key in map) { - if (result = callback(map[key], key)) - break; } - return result; - } - ts.forEachProperty = forEachProperty; - function someProperties(map, predicate) { - for (var key in map) { - if (!predicate || predicate(map[key], key)) - return true; - } - return false; - } - ts.someProperties = someProperties; - function copyProperties(source, target) { - for (var key in source) { - target[key] = source[key]; - } - } - ts.copyProperties = copyProperties; - function reduceProperties(map, callback, initial) { - var result = initial; - for (var key in map) { - result = callback(result, map[key], String(key)); - } - return result; - } - ts.reduceProperties = reduceProperties; - function reduceOwnProperties(map, callback, initial) { - var result = initial; - for (var key in map) - if (hasOwnProperty.call(map, key)) { - result = callback(result, map[key], String(key)); - } - return result; - } - ts.reduceOwnProperties = reduceOwnProperties; - function equalOwnProperties(left, right, equalityComparer) { - if (left === right) - return true; - if (!left || !right) - return false; - for (var key in left) - if (hasOwnProperty.call(left, key)) { - if (!hasOwnProperty.call(right, key) === undefined) - return false; - if (equalityComparer ? !equalityComparer(left[key], right[key]) : left[key] !== right[key]) - return false; - } - for (var key in right) - if (hasOwnProperty.call(right, key)) { - if (!hasOwnProperty.call(left, key)) - return false; - } return true; } - ts.equalOwnProperties = equalOwnProperties; - function arrayToMap(array, makeKey, makeValue) { - var result = createMap(); - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var value = array_8[_i]; - result[makeKey(value)] = makeValue ? makeValue(value) : value; - } - return result; - } - ts.arrayToMap = arrayToMap; - function cloneMap(map) { - var clone = createMap(); - copyProperties(map, clone); - return clone; - } - ts.cloneMap = cloneMap; + ts.isEmpty = isEmpty; function clone(object) { var result = {}; for (var id in object) { - if (hasOwnProperty.call(object, id)) { - result[id] = object[id]; - } + result[id] = object[id]; } return result; } ts.clone = clone; function extend(first, second) { var result = {}; - for (var id in second) - if (hasOwnProperty.call(second, id)) { + for (var id in first) { + result[id] = first[id]; + } + for (var id in second) { + if (!hasProperty(result, id)) { result[id] = second[id]; } - for (var id in first) - if (hasOwnProperty.call(first, id)) { - result[id] = first[id]; - } + } return result; } ts.extend = extend; + function forEachValue(map, callback) { + var result; + for (var id in map) { + if (result = callback(map[id])) + break; + } + return result; + } + ts.forEachValue = forEachValue; + function forEachKey(map, callback) { + var result; + for (var id in map) { + if (result = callback(id)) + break; + } + return result; + } + ts.forEachKey = forEachKey; + function lookUp(map, key) { + return hasProperty(map, key) ? map[key] : undefined; + } + ts.lookUp = lookUp; + function copyMap(source, target) { + for (var p in source) { + target[p] = source[p]; + } + } + ts.copyMap = copyMap; + function arrayToMap(array, makeKey) { + var result = {}; + forEach(array, function (value) { + result[makeKey(value)] = value; + }); + return result; + } + ts.arrayToMap = arrayToMap; + function reduceProperties(map, callback, initial) { + var result = initial; + if (map) { + for (var key in map) { + if (hasProperty(map, key)) { + result = callback(result, map[key], String(key)); + } + } + } + return result; + } + ts.reduceProperties = reduceProperties; function isArray(value) { return Array.isArray ? Array.isArray(value) : value instanceof Array; } @@ -599,7 +444,9 @@ var ts; } ts.localizedDiagnosticMessages = undefined; function getLocaleSpecificMessage(message) { - return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message; + return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] + ? ts.localizedDiagnosticMessages[message.key] + : message.message; } ts.getLocaleSpecificMessage = getLocaleSpecificMessage; function createFileDiagnostic(file, start, length, message) { @@ -983,17 +830,10 @@ var ts; return true; } ts.containsPath = containsPath; - function startsWith(str, prefix) { - return str.lastIndexOf(prefix, 0) === 0; - } - ts.startsWith = startsWith; - function endsWith(str, suffix) { - var expectedPos = str.length - suffix.length; - return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; - } - ts.endsWith = endsWith; function fileExtensionIs(path, extension) { - return path.length > extension.length && endsWith(path, extension); + var pathLen = path.length; + var extLen = extension.length; + return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension; } ts.fileExtensionIs = fileExtensionIs; function fileExtensionIsAny(path, extensions) { @@ -1008,15 +848,10 @@ var ts; ts.fileExtensionIsAny = fileExtensionIsAny; var reservedCharacterPattern = /[^\w\s\/]/g; var wildcardCharCodes = [42, 63]; - var singleAsteriskRegexFragmentFiles = "([^./]|(\\.(?!min\\.js$))?)*"; - var singleAsteriskRegexFragmentOther = "[^/]*"; function getRegularExpressionForWildcard(specs, basePath, usage) { if (specs === undefined || specs.length === 0) { return undefined; } - var replaceWildcardCharacter = usage === "files" ? replaceWildCardCharacterFiles : replaceWildCardCharacterOther; - var singleAsteriskRegexFragment = usage === "files" ? singleAsteriskRegexFragmentFiles : singleAsteriskRegexFragmentOther; - var doubleAsteriskRegexFragment = usage === "exclude" ? "(/.+?)?" : "(/[^/.][^/]*)*?"; var pattern = ""; var hasWrittenSubpattern = false; spec: for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { @@ -1039,7 +874,7 @@ var ts; if (hasRecursiveDirectoryWildcard) { continue spec; } - subpattern += doubleAsteriskRegexFragment; + subpattern += "(/.+?)?"; hasRecursiveDirectoryWildcard = true; hasWrittenComponent = true; } @@ -1051,16 +886,6 @@ var ts; if (hasWrittenComponent) { subpattern += ts.directorySeparator; } - if (usage !== "exclude") { - if (component.charCodeAt(0) === 42) { - subpattern += "([^./]" + singleAsteriskRegexFragment + ")?"; - component = component.substr(1); - } - else if (component.charCodeAt(0) === 63) { - subpattern += "[^./]"; - component = component.substr(1); - } - } subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); hasWrittenComponent = true; } @@ -1081,14 +906,8 @@ var ts; return "^(" + pattern + (usage === "exclude" ? ")($|/)" : ")$"); } ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; - function replaceWildCardCharacterFiles(match) { - return replaceWildcardCharacter(match, singleAsteriskRegexFragmentFiles); - } - function replaceWildCardCharacterOther(match) { - return replaceWildcardCharacter(match, singleAsteriskRegexFragmentOther); - } - function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { - return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; + function replaceWildcardCharacter(match) { + return match === "*" ? "[^/]*" : match === "?" ? "[^/]" : "\\" + match; } function getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { path = normalizePath(path); @@ -1187,21 +1006,12 @@ var ts; } ts.getScriptKindFromFileName = getScriptKindFromFileName; ts.supportedTypeScriptExtensions = [".ts", ".tsx", ".d.ts"]; - ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"]; ts.supportedJavascriptExtensions = [".js", ".jsx"]; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); function getSupportedExtensions(options) { return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } ts.getSupportedExtensions = getSupportedExtensions; - function hasJavaScriptFileExtension(fileName) { - return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); - } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); - } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; function isSupportedSourceFileName(fileName, compilerOptions) { if (!fileName) { return false; @@ -1258,13 +1068,9 @@ var ts; } ts.removeFileExtension = removeFileExtension; function tryRemoveExtension(path, extension) { - return fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined; + return fileExtensionIs(path, extension) ? path.substring(0, path.length - extension.length) : undefined; } ts.tryRemoveExtension = tryRemoveExtension; - function removeExtension(path, extension) { - return path.substring(0, path.length - extension.length); - } - ts.removeExtension = removeExtension; function isJsxOrTsxExtension(ext) { return ext === ".jsx" || ext === ".tsx"; } @@ -1292,8 +1098,6 @@ var ts; } ts.objectAllocator = { getNodeConstructor: function () { return Node; }, - getTokenConstructor: function () { return Node; }, - getIdentifierConstructor: function () { return Node; }, getSourceFileConstructor: function () { return Node; }, getSymbolConstructor: function () { return Symbol; }, getTypeConstructor: function () { return Type; }, @@ -1339,57 +1143,6 @@ var ts; : (function (fileName) { return fileName.toLowerCase(); }); } ts.createGetCanonicalFileName = createGetCanonicalFileName; - function trace(host, message) { - host.trace(formatMessage.apply(undefined, arguments)); - } - ts.trace = trace; - function isTraceEnabled(compilerOptions, host) { - return compilerOptions.traceResolution && host.trace !== undefined; - } - ts.isTraceEnabled = isTraceEnabled; - function hasZeroOrOneAsteriskCharacter(str) { - var seenAsterisk = false; - for (var i = 0; i < str.length; i++) { - if (str.charCodeAt(i) === 42) { - if (!seenAsterisk) { - seenAsterisk = true; - } - else { - return false; - } - } - } - return true; - } - ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; - } - ts.createResolvedModule = createResolvedModule; - function isExternalModuleNameRelative(moduleName) { - return /^\.\.?($|[\\/])/.test(moduleName); - } - ts.isExternalModuleNameRelative = isExternalModuleNameRelative; - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - return jsonText ? JSON.parse(jsonText) : {}; - } - catch (e) { - return {}; - } - } - ts.readJson = readJson; - function getEmitModuleKind(compilerOptions) { - return typeof compilerOptions.module === "number" ? - compilerOptions.module : - getEmitScriptTarget(compilerOptions) === 2 ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; - } - ts.getEmitModuleKind = getEmitModuleKind; - function getEmitScriptTarget(compilerOptions) { - return compilerOptions.target || 0; - } - ts.getEmitScriptTarget = getEmitScriptTarget; })(ts || (ts = {})); var ts; (function (ts) { @@ -1476,7 +1229,7 @@ var ts; function readDirectory(path, extensions, excludes, includes) { return ts.matchFiles(path, extensions, excludes, includes, false, shell.CurrentDirectory, getAccessibleFileSystemEntries); } - var wscriptSystem = { + return { args: args, newLine: "\r\n", useCaseSensitiveFileNames: false, @@ -1495,7 +1248,7 @@ var ts; return fso.FolderExists(path); }, createDirectory: function (directoryName) { - if (!wscriptSystem.directoryExists(directoryName)) { + if (!this.directoryExists(directoryName)) { fso.CreateFolder(directoryName); } }, @@ -1515,7 +1268,6 @@ var ts; } } }; - return wscriptSystem; } function getNodeSystem() { var _fs = require("fs"); @@ -1524,13 +1276,13 @@ var ts; var _crypto = require("crypto"); var useNonPollingWatchers = process.env["TSC_NONPOLLING_WATCHER"]; function createWatchedFileSet() { - var dirWatchers = ts.createMap(); - var fileWatcherCallbacks = ts.createMap(); + var dirWatchers = {}; + var fileWatcherCallbacks = {}; return { addFile: addFile, removeFile: removeFile }; function reduceDirWatcherRefCountForFile(fileName) { var dirName = ts.getDirectoryPath(fileName); - var watcher = dirWatchers[dirName]; - if (watcher) { + if (ts.hasProperty(dirWatchers, dirName)) { + var watcher = dirWatchers[dirName]; watcher.referenceCount -= 1; if (watcher.referenceCount <= 0) { watcher.close(); @@ -1539,18 +1291,23 @@ var ts; } } function addDirWatcher(dirPath) { - var watcher = dirWatchers[dirPath]; - if (watcher) { - watcher.referenceCount += 1; + if (ts.hasProperty(dirWatchers, dirPath)) { + var watcher_1 = dirWatchers[dirPath]; + watcher_1.referenceCount += 1; return; } - watcher = _fs.watch(dirPath, { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); + var watcher = _fs.watch(dirPath, { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); watcher.referenceCount = 1; dirWatchers[dirPath] = watcher; return; } function addFileWatcherCallback(filePath, callback) { - (fileWatcherCallbacks[filePath] || (fileWatcherCallbacks[filePath] = [])).push(callback); + if (ts.hasProperty(fileWatcherCallbacks, filePath)) { + fileWatcherCallbacks[filePath].push(callback); + } + else { + fileWatcherCallbacks[filePath] = [callback]; + } } function addFile(fileName, callback) { addFileWatcherCallback(fileName, callback); @@ -1562,9 +1319,8 @@ var ts; reduceDirWatcherRefCountForFile(watchedFile.fileName); } function removeFileWatcherCallback(filePath, callback) { - var callbacks = fileWatcherCallbacks[filePath]; - if (callbacks) { - var newCallbacks = ts.copyListRemovingItem(callback, callbacks); + if (ts.hasProperty(fileWatcherCallbacks, filePath)) { + var newCallbacks = ts.copyListRemovingItem(callback, fileWatcherCallbacks[filePath]); if (newCallbacks.length === 0) { delete fileWatcherCallbacks[filePath]; } @@ -1577,7 +1333,7 @@ var ts; var fileName = typeof relativeFileName !== "string" ? undefined : ts.getNormalizedAbsolutePath(relativeFileName, baseDirPath); - if ((eventName === "change" || eventName === "rename") && fileWatcherCallbacks[fileName]) { + if ((eventName === "change" || eventName === "rename") && ts.hasProperty(fileWatcherCallbacks, fileName)) { for (var _i = 0, _a = fileWatcherCallbacks[fileName]; _i < _a.length; _i++) { var fileCallback = _a[_i]; fileCallback(fileName); @@ -1684,7 +1440,7 @@ var ts; function getDirectories(path) { return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1); }); } - var nodeSystem = { + return { args: process.argv.slice(2), newLine: _os.EOL, useCaseSensitiveFileNames: useCaseSensitiveFileNames, @@ -1734,7 +1490,7 @@ var ts; fileExists: fileExists, directoryExists: directoryExists, createDirectory: function (directoryName) { - if (!nodeSystem.directoryExists(directoryName)) { + if (!this.directoryExists(directoryName)) { _fs.mkdirSync(directoryName); } }, @@ -1782,7 +1538,6 @@ var ts; return _fs.realpathSync(path); } }; - return nodeSystem; } function getChakraSystem() { var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); }); @@ -1815,37 +1570,18 @@ var ts; realpath: realpath }; } - function recursiveCreateDirectory(directoryPath, sys) { - var basePath = ts.getDirectoryPath(directoryPath); - var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath); - if (shouldCreateParent) { - recursiveCreateDirectory(basePath, sys); - } - if (shouldCreateParent || !sys.directoryExists(directoryPath)) { - sys.createDirectory(directoryPath); - } - } - var sys; if (typeof ChakraHost !== "undefined") { - sys = getChakraSystem(); + return getChakraSystem(); } else if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { - sys = getWScriptSystem(); + return getWScriptSystem(); } else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") { - sys = getNodeSystem(); + return getNodeSystem(); } - if (sys) { - var originalWriteFile_1 = sys.writeFile; - sys.writeFile = function (path, data, writeBom) { - var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path)); - if (directoryPath && !sys.directoryExists(directoryPath)) { - recursiveCreateDirectory(directoryPath, sys); - } - originalWriteFile_1.call(sys, path, data, writeBom); - }; + else { + return undefined; } - return sys; })(); })(ts || (ts = {})); var ts; @@ -2290,7 +2026,6 @@ var ts; Object_is_possibly_undefined: { code: 2532, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_undefined_2532", message: "Object is possibly 'undefined'." }, Object_is_possibly_null_or_undefined: { code: 2533, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_null_or_undefined_2533", message: "Object is possibly 'null' or 'undefined'." }, A_function_returning_never_cannot_have_a_reachable_end_point: { code: 2534, category: ts.DiagnosticCategory.Error, key: "A_function_returning_never_cannot_have_a_reachable_end_point_2534", message: "A function returning 'never' cannot have a reachable end point." }, - Enum_type_0_has_members_with_initializers_that_are_not_literals: { code: 2535, category: ts.DiagnosticCategory.Error, key: "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", message: "Enum type '{0}' has members with initializers that are not literals." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "The return type of a JSX element constructor must return an object type." }, JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -2338,9 +2073,6 @@ var ts; All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, - A_class_must_be_declared_after_its_base_class: { code: 2690, category: ts.DiagnosticCategory.Error, key: "A_class_must_be_declared_after_its_base_class_2690", message: "A class must be declared after its base class." }, - An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: { code: 2691, category: ts.DiagnosticCategory.Error, key: "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691", message: "An import path cannot end with a '{0}' extension. Consider importing '{1}' instead." }, - _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: { code: 2692, category: ts.DiagnosticCategory.Error, key: "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", message: "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible." }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -2411,7 +2143,7 @@ var ts; Parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4078, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", message: "Parameter '{0}' of exported function has or is using private name '{1}'." }, Exported_type_alias_0_has_or_is_using_private_name_1: { code: 4081, category: ts.DiagnosticCategory.Error, key: "Exported_type_alias_0_has_or_is_using_private_name_1_4081", message: "Exported type alias '{0}' has or is using private name '{1}'." }, Default_export_of_the_module_has_or_is_using_private_name_0: { code: 4082, category: ts.DiagnosticCategory.Error, key: "Default_export_of_the_module_has_or_is_using_private_name_0_4082", message: "Default export of the module has or is using private name '{0}'." }, - Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", message: "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict." }, + Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_to_resolve_this_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_t_4090", message: "Conflicting library definitions for '{0}' found at '{1}' and '{2}'. Copy the correct file to the 'typings' folder to resolve this conflict." }, The_current_host_does_not_support_the_0_option: { code: 5001, category: ts.DiagnosticCategory.Error, key: "The_current_host_does_not_support_the_0_option_5001", message: "The current host does not support the '{0}' option." }, Cannot_find_the_common_subdirectory_path_for_the_input_files: { code: 5009, category: ts.DiagnosticCategory.Error, key: "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", message: "Cannot find the common subdirectory path for the input files." }, File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5010, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", message: "File specification cannot end in a recursive directory wildcard ('**'): '{0}'." }, @@ -2439,7 +2171,6 @@ var ts; Substitutions_for_pattern_0_should_be_an_array: { code: 5063, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_should_be_an_array_5063", message: "Substitutions for pattern '{0}' should be an array." }, Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: { code: 5064, category: ts.DiagnosticCategory.Error, key: "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", message: "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'." }, File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5065, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", message: "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'." }, - Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: { code: 5066, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", message: "Substitutions for pattern '{0}' shouldn't be an empty array." }, Concatenate_and_emit_output_to_single_file: { code: 6001, category: ts.DiagnosticCategory.Message, key: "Concatenate_and_emit_output_to_single_file_6001", message: "Concatenate and emit output to single file." }, Generates_corresponding_d_ts_file: { code: 6002, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_d_ts_file_6002", message: "Generates corresponding '.d.ts' file." }, Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: ts.DiagnosticCategory.Message, key: "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", message: "Specify the location where debugger should locate map files instead of generated locations." }, @@ -2556,12 +2287,10 @@ var ts; Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." }, File_name_0_has_a_1_extension_stripping_it: { code: 6132, category: ts.DiagnosticCategory.Message, key: "File_name_0_has_a_1_extension_stripping_it_6132", message: "File name '{0}' has a '{1}' extension - stripping it" }, _0_is_declared_but_never_used: { code: 6133, category: ts.DiagnosticCategory.Error, key: "_0_is_declared_but_never_used_6133", message: "'{0}' is declared but never used." }, - Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, - Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, + Report_Errors_on_Unused_Locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Locals_6134", message: "Report Errors on Unused Locals." }, + Report_Errors_on_Unused_Parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Parameters_6135", message: "Report Errors on Unused Parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" }, No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" }, - Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, - Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6139, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6139", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -2570,6 +2299,7 @@ var ts; Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: { code: 7011, category: ts.DiagnosticCategory.Error, key: "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", message: "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type." }, Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7013, category: ts.DiagnosticCategory.Error, key: "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", message: "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type." }, Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: { code: 7015, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", message: "Element implicitly has an 'any' type because index expression is not of type 'number'." }, + Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation: { code: 7016, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation_7016", message: "Property '{0}' implicitly has type 'any', because its 'set' accessor lacks a type annotation." }, Index_signature_of_object_type_implicitly_has_an_any_type: { code: 7017, category: ts.DiagnosticCategory.Error, key: "Index_signature_of_object_type_implicitly_has_an_any_type_7017", message: "Index signature of object type implicitly has an 'any' type." }, Object_literal_s_property_0_implicitly_has_an_1_type: { code: 7018, category: ts.DiagnosticCategory.Error, key: "Object_literal_s_property_0_implicitly_has_an_1_type_7018", message: "Object literal's property '{0}' implicitly has an '{1}' type." }, Rest_parameter_0_implicitly_has_an_any_type: { code: 7019, category: ts.DiagnosticCategory.Error, key: "Rest_parameter_0_implicitly_has_an_any_type_7019", message: "Rest parameter '{0}' implicitly has an 'any[]' type." }, @@ -2584,8 +2314,6 @@ var ts; Fallthrough_case_in_switch: { code: 7029, category: ts.DiagnosticCategory.Error, key: "Fallthrough_case_in_switch_7029", message: "Fallthrough case in switch." }, Not_all_code_paths_return_a_value: { code: 7030, category: ts.DiagnosticCategory.Error, key: "Not_all_code_paths_return_a_value_7030", message: "Not all code paths return a value." }, Binding_element_0_implicitly_has_an_1_type: { code: 7031, category: ts.DiagnosticCategory.Error, key: "Binding_element_0_implicitly_has_an_1_type_7031", message: "Binding element '{0}' implicitly has an '{1}' type." }, - Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { code: 7032, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", message: "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation." }, - Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { code: 7033, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", message: "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation." }, You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, @@ -2622,7 +2350,7 @@ var ts; return token >= 69; } ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; - var textToToken = ts.createMap({ + var textToToken = { "abstract": 115, "any": 117, "as": 116, @@ -2746,7 +2474,7 @@ var ts; "|=": 67, "^=": 68, "@": 55 - }); + }; var unicodeES3IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; var unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; var unicodeES5IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6263, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516, 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7401, 7404, 7406, 7409, 7413, 7414, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11823, 11823, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42647, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43648, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; @@ -2787,7 +2515,9 @@ var ts; function makeReverseMap(source) { var result = []; for (var name_4 in source) { - result[source[name_4]] = name_4; + if (source.hasOwnProperty(name_4)) { + result[source[name_4]] = name_4; + } } return result; } @@ -4107,13 +3837,11 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; ts.optionDeclarations = [ { name: "charset", type: "string" }, - ts.compileOnSaveCommandLineOption, { name: "declaration", shortName: "d", @@ -4130,10 +3858,6 @@ var ts; name: "diagnostics", type: "boolean" }, - { - name: "extendedDiagnostics", - type: "boolean" - }, { name: "emitBOM", type: "boolean" @@ -4164,10 +3888,10 @@ var ts; }, { name: "jsx", - type: ts.createMap({ + type: { "preserve": 1, "react": 2 - }), + }, paramType: ts.Diagnostics.KIND, description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react }, @@ -4194,7 +3918,7 @@ var ts; { name: "module", shortName: "m", - type: ts.createMap({ + type: { "none": ts.ModuleKind.None, "commonjs": ts.ModuleKind.CommonJS, "amd": ts.ModuleKind.AMD, @@ -4202,16 +3926,16 @@ var ts; "umd": ts.ModuleKind.UMD, "es6": ts.ModuleKind.ES6, "es2015": ts.ModuleKind.ES2015 - }), + }, description: ts.Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015, paramType: ts.Diagnostics.KIND }, { name: "newLine", - type: ts.createMap({ + type: { "crlf": 0, "lf": 1 - }), + }, description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix, paramType: ts.Diagnostics.NEWLINE }, @@ -4229,10 +3953,6 @@ var ts; type: "boolean", description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported }, - { - name: "noErrorTruncation", - type: "boolean" - }, { name: "noImplicitAny", type: "boolean", @@ -4246,12 +3966,12 @@ var ts; { name: "noUnusedLocals", type: "boolean", - description: ts.Diagnostics.Report_errors_on_unused_locals + description: ts.Diagnostics.Report_Errors_on_Unused_Locals }, { name: "noUnusedParameters", type: "boolean", - description: ts.Diagnostics.Report_errors_on_unused_parameters + description: ts.Diagnostics.Report_Errors_on_Unused_Parameters }, { name: "noLib", @@ -4356,12 +4076,12 @@ var ts; { name: "target", shortName: "t", - type: ts.createMap({ + type: { "es3": 0, "es5": 1, "es6": 2, "es2015": 2 - }), + }, description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015, paramType: ts.Diagnostics.VERSION }, @@ -4390,10 +4110,10 @@ var ts; }, { name: "moduleResolution", - type: ts.createMap({ + type: { "node": ts.ModuleResolutionKind.NodeJs, "classic": ts.ModuleResolutionKind.Classic - }), + }, description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6 }, { @@ -4494,7 +4214,7 @@ var ts; type: "list", element: { name: "lib", - type: ts.createMap({ + type: { "es5": "lib.es5.d.ts", "es6": "lib.es2015.d.ts", "es2015": "lib.es2015.d.ts", @@ -4516,7 +4236,7 @@ var ts; "es2016.array.include": "lib.es2016.array.include.d.ts", "es2017.object": "lib.es2017.object.d.ts", "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts" - }) + } }, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon }, @@ -4552,19 +4272,13 @@ var ts; } } ]; - ts.defaultInitCompilerOptions = { - module: ts.ModuleKind.CommonJS, - target: 1, - noImplicitAny: false, - sourceMap: false - }; var optionNameMapCache; function getOptionNameMap() { if (optionNameMapCache) { return optionNameMapCache; } - var optionNameMap = ts.createMap(); - var shortOptionNames = ts.createMap(); + var optionNameMap = {}; + var shortOptionNames = {}; ts.forEach(ts.optionDeclarations, function (option) { optionNameMap[option.name.toLowerCase()] = option; if (option.shortName) { @@ -4577,16 +4291,16 @@ var ts; ts.getOptionNameMap = getOptionNameMap; function createCompilerDiagnosticForInvalidCustomType(opt) { var namesOfType = []; - for (var key in opt.type) { + ts.forEachKey(opt.type, function (key) { namesOfType.push(" '" + key + "'"); - } + }); return ts.createCompilerDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); } ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; function parseCustomTypeOption(opt, value, errors) { var key = trimString((value || "")).toLowerCase(); var map = opt.type; - if (key in map) { + if (ts.hasProperty(map, key)) { return map[key]; } else { @@ -4635,10 +4349,10 @@ var ts; } else if (s.charCodeAt(0) === 45) { s = s.slice(s.charCodeAt(1) === 45 ? 2 : 1).toLowerCase(); - if (s in shortOptionNames) { + if (ts.hasProperty(shortOptionNames, s)) { s = shortOptionNames[s]; } - if (s in optionNameMap) { + if (ts.hasProperty(optionNameMap, s)) { var opt = optionNameMap[s]; if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -4729,87 +4443,16 @@ var ts; return parseConfigFileTextToJson(fileName, text); } ts.readConfigFile = readConfigFile; - function parseConfigFileTextToJson(fileName, jsonText, stripComments) { - if (stripComments === void 0) { stripComments = true; } + function parseConfigFileTextToJson(fileName, jsonText) { try { - var jsonTextToParse = stripComments ? removeComments(jsonText) : jsonText; - return { config: /\S/.test(jsonTextToParse) ? JSON.parse(jsonTextToParse) : {} }; + var jsonTextWithoutComments = removeComments(jsonText); + return { config: /\S/.test(jsonTextWithoutComments) ? JSON.parse(jsonTextWithoutComments) : {} }; } catch (e) { return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) }; } } ts.parseConfigFileTextToJson = parseConfigFileTextToJson; - function generateTSConfig(options, fileNames) { - var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); - var configurations = { - compilerOptions: serializeCompilerOptions(compilerOptions) - }; - if (fileNames && fileNames.length) { - configurations.files = fileNames; - } - return configurations; - function getCustomTypeMapOfCommandLineOption(optionDefinition) { - if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { - return undefined; - } - else if (optionDefinition.type === "list") { - return getCustomTypeMapOfCommandLineOption(optionDefinition.element); - } - else { - return optionDefinition.type; - } - } - function getNameOfCompilerOptionValue(value, customTypeMap) { - for (var key in customTypeMap) { - if (customTypeMap[key] === value) { - return key; - } - } - return undefined; - } - function serializeCompilerOptions(options) { - var result = ts.createMap(); - var optionsNameMap = getOptionNameMap().optionNameMap; - for (var name_5 in options) { - if (ts.hasProperty(options, name_5)) { - switch (name_5) { - case "init": - case "watch": - case "version": - case "help": - case "project": - break; - default: - var value = options[name_5]; - var optionDefinition = optionsNameMap[name_5.toLowerCase()]; - if (optionDefinition) { - var customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition); - if (!customTypeMap) { - result[name_5] = value; - } - else { - if (optionDefinition.type === "list") { - var convertedValue = []; - for (var _i = 0, _a = value; _i < _a.length; _i++) { - var element = _a[_i]; - convertedValue.push(getNameOfCompilerOptionValue(element, customTypeMap)); - } - result[name_5] = convertedValue; - } - else { - result[name_5] = getNameOfCompilerOptionValue(value, customTypeMap); - } - } - } - break; - } - } - } - return result; - } - } - ts.generateTSConfig = generateTSConfig; function removeComments(jsonText) { var output = ""; var scanner = ts.createScanner(1, false, 0, jsonText); @@ -4827,6 +4470,7 @@ var ts; } return output; } + var ignoreFileNamePattern = /(\.min\.js$)|([\\/]\.[\w.])/; function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName) { if (existingOptions === void 0) { existingOptions = {}; } var errors = []; @@ -4835,15 +4479,13 @@ var ts; var typingOptions = convertTypingOptionsFromJsonWorker(json["typingOptions"], basePath, errors, configFileName); options.configFilePath = configFileName; var _a = getFileNames(errors), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; - var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); return { options: options, fileNames: fileNames, typingOptions: typingOptions, raw: json, errors: errors, - wildcardDirectories: wildcardDirectories, - compileOnSave: compileOnSave + wildcardDirectories: wildcardDirectories }; function getFileNames(errors) { var fileNames; @@ -4890,17 +4532,6 @@ var ts; } } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; - function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { - if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { - return false; - } - var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); - if (typeof result === "boolean" && result) { - return result; - } - return false; - } - ts.convertCompileOnSaveOptionFromJson = convertCompileOnSaveOptionFromJson; function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { var errors = []; var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); @@ -4914,7 +4545,7 @@ var ts; } ts.convertTypingOptionsFromJson = convertTypingOptionsFromJson; function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2 } : {}; + var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true } : {}; convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); return options; } @@ -4931,7 +4562,7 @@ var ts; } var optionNameMap = ts.arrayToMap(optionDeclarations, function (opt) { return opt.name; }); for (var id in jsonOptions) { - if (id in optionNameMap) { + if (ts.hasProperty(optionNameMap, id)) { var opt = optionNameMap[id]; defaultOptions[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors); } @@ -4966,7 +4597,7 @@ var ts; } function convertJsonOptionOfCustomType(opt, value, errors) { var key = value.toLowerCase(); - if (key in opt.type) { + if (ts.hasProperty(opt.type, key)) { return opt.type[key]; } else { @@ -4987,8 +4618,8 @@ var ts; function matchFileNames(fileNames, include, exclude, basePath, options, host, errors) { basePath = ts.normalizePath(basePath); var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; - var literalFileMap = ts.createMap(); - var wildcardFileMap = ts.createMap(); + var literalFileMap = {}; + var wildcardFileMap = {}; if (include) { include = validateSpecs(include, errors, false); } @@ -5010,9 +4641,12 @@ var ts; if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { continue; } + if (ignoreFileNamePattern.test(file)) { + continue; + } removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); var key = keyMapper(file); - if (!(key in literalFileMap) && !(key in wildcardFileMap)) { + if (!ts.hasProperty(literalFileMap, key) && !ts.hasProperty(wildcardFileMap, key)) { wildcardFileMap[key] = file; } } @@ -5047,20 +4681,20 @@ var ts; function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) { var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); - var wildcardDirectories = ts.createMap(); + var wildcardDirectories = {}; if (include !== undefined) { var recursiveKeys = []; for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { var file = include_1[_i]; - var name_6 = ts.normalizePath(ts.combinePaths(path, file)); - if (excludeRegex && excludeRegex.test(name_6)) { + var name_5 = ts.normalizePath(ts.combinePaths(path, file)); + if (excludeRegex && excludeRegex.test(name_5)) { continue; } - var match = wildcardDirectoryPattern.exec(name_6); + var match = wildcardDirectoryPattern.exec(name_5); if (match) { var key = useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(); - var flags = watchRecursivePattern.test(name_6) ? 1 : 0; - var existingFlags = wildcardDirectories[key]; + var flags = watchRecursivePattern.test(name_5) ? 1 : 0; + var existingFlags = ts.getProperty(wildcardDirectories, key); if (existingFlags === undefined || existingFlags < flags) { wildcardDirectories[key] = flags; if (flags === 1) { @@ -5070,10 +4704,12 @@ var ts; } } for (var key in wildcardDirectories) { - for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { - var recursiveKey = recursiveKeys_1[_a]; - if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { - delete wildcardDirectories[key]; + if (ts.hasProperty(wildcardDirectories, key)) { + for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { + var recursiveKey = recursiveKeys_1[_a]; + if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { + delete wildcardDirectories[key]; + } } } } @@ -5086,7 +4722,7 @@ var ts; for (var i = 0; i < adjustedExtensionPriority; i++) { var higherPriorityExtension = extensions[i]; var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); - if (higherPriorityPath in literalFiles || higherPriorityPath in wildcardFiles) { + if (ts.hasProperty(literalFiles, higherPriorityPath) || ts.hasProperty(wildcardFiles, higherPriorityPath)) { return true; } } @@ -5113,378 +4749,6 @@ var ts; } })(ts || (ts = {})); var ts; -(function (ts) { - var JsTyping; - (function (JsTyping) { - ; - ; - var safeList; - var EmptySafeList = ts.createMap(); - function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typingOptions, compilerOptions) { - var inferredTypings = ts.createMap(); - if (!typingOptions || !typingOptions.enableAutoDiscovery) { - return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; - } - fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { - var kind = ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)); - return kind === 1 || kind === 2; - }); - if (!safeList) { - var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); - safeList = result.config ? ts.createMap(result.config) : EmptySafeList; - } - var filesToWatch = []; - var searchDirs = []; - var exclude = []; - mergeTypings(typingOptions.include); - exclude = typingOptions.exclude || []; - var possibleSearchDirs = ts.map(fileNames, ts.getDirectoryPath); - if (projectRootPath !== undefined) { - possibleSearchDirs.push(projectRootPath); - } - searchDirs = ts.deduplicate(possibleSearchDirs); - for (var _i = 0, searchDirs_1 = searchDirs; _i < searchDirs_1.length; _i++) { - var searchDir = searchDirs_1[_i]; - var packageJsonPath = ts.combinePaths(searchDir, "package.json"); - getTypingNamesFromJson(packageJsonPath, filesToWatch); - var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); - getTypingNamesFromJson(bowerJsonPath, filesToWatch); - var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); - getTypingNamesFromNodeModuleFolder(nodeModulesPath); - } - getTypingNamesFromSourceFileNames(fileNames); - for (var name_7 in packageNameToTypingLocation) { - if (name_7 in inferredTypings && !inferredTypings[name_7]) { - inferredTypings[name_7] = packageNameToTypingLocation[name_7]; - } - } - for (var _a = 0, exclude_1 = exclude; _a < exclude_1.length; _a++) { - var excludeTypingName = exclude_1[_a]; - delete inferredTypings[excludeTypingName]; - } - var newTypingNames = []; - var cachedTypingPaths = []; - for (var typing in inferredTypings) { - if (inferredTypings[typing] !== undefined) { - cachedTypingPaths.push(inferredTypings[typing]); - } - else { - newTypingNames.push(typing); - } - } - return { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; - function mergeTypings(typingNames) { - if (!typingNames) { - return; - } - for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) { - var typing = typingNames_1[_i]; - if (!(typing in inferredTypings)) { - inferredTypings[typing] = undefined; - } - } - } - function getTypingNamesFromJson(jsonPath, filesToWatch) { - var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }); - if (result.config) { - var jsonConfig = result.config; - filesToWatch.push(jsonPath); - if (jsonConfig.dependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.dependencies)); - } - if (jsonConfig.devDependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.devDependencies)); - } - if (jsonConfig.optionalDependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.optionalDependencies)); - } - if (jsonConfig.peerDependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.peerDependencies)); - } - } - } - function getTypingNamesFromSourceFileNames(fileNames) { - var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension); - var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); }); - var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); }); - if (safeList !== EmptySafeList) { - mergeTypings(ts.filter(cleanedTypingNames, function (f) { return f in safeList; })); - } - var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)) === 2; }); - if (hasJsxFile) { - mergeTypings(["react"]); - } - } - function getTypingNamesFromNodeModuleFolder(nodeModulesPath) { - if (!host.directoryExists(nodeModulesPath)) { - return; - } - var typingNames = []; - var fileNames = host.readDirectory(nodeModulesPath, [".json"], undefined, undefined, 2); - for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { - var fileName = fileNames_2[_i]; - var normalizedFileName = ts.normalizePath(fileName); - if (ts.getBaseFileName(normalizedFileName) !== "package.json") { - continue; - } - var result = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - if (!result.config) { - continue; - } - var packageJson = result.config; - if (packageJson._requiredBy && - ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { - continue; - } - if (!packageJson.name) { - continue; - } - if (packageJson.typings) { - var absolutePath = ts.getNormalizedAbsolutePath(packageJson.typings, ts.getDirectoryPath(normalizedFileName)); - inferredTypings[packageJson.name] = absolutePath; - } - else { - typingNames.push(packageJson.name); - } - } - mergeTypings(typingNames); - } - } - JsTyping.discoverTypings = discoverTypings; - })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - var server; - (function (server) { - (function (LogLevel) { - LogLevel[LogLevel["terse"] = 0] = "terse"; - LogLevel[LogLevel["normal"] = 1] = "normal"; - LogLevel[LogLevel["requestTime"] = 2] = "requestTime"; - LogLevel[LogLevel["verbose"] = 3] = "verbose"; - })(server.LogLevel || (server.LogLevel = {})); - var LogLevel = server.LogLevel; - server.emptyArray = []; - var Msg; - (function (Msg) { - Msg.Err = "Err"; - Msg.Info = "Info"; - Msg.Perf = "Perf"; - })(Msg = server.Msg || (server.Msg = {})); - function getProjectRootPath(project) { - switch (project.projectKind) { - case server.ProjectKind.Configured: - return ts.getDirectoryPath(project.getProjectName()); - case server.ProjectKind.Inferred: - return ""; - case server.ProjectKind.External: - var projectName = ts.normalizeSlashes(project.getProjectName()); - return project.projectService.host.fileExists(projectName) ? ts.getDirectoryPath(projectName) : projectName; - } - } - function createInstallTypingsRequest(project, typingOptions, cachePath) { - return { - projectName: project.getProjectName(), - fileNames: project.getFileNames(), - compilerOptions: project.getCompilerOptions(), - typingOptions: typingOptions, - projectRootPath: getProjectRootPath(project), - cachePath: cachePath, - kind: "discover" - }; - } - server.createInstallTypingsRequest = createInstallTypingsRequest; - var Errors; - (function (Errors) { - function ThrowNoProject() { - throw new Error("No Project."); - } - Errors.ThrowNoProject = ThrowNoProject; - function ThrowProjectLanguageServiceDisabled() { - throw new Error("The project's language service is disabled."); - } - Errors.ThrowProjectLanguageServiceDisabled = ThrowProjectLanguageServiceDisabled; - function ThrowProjectDoesNotContainDocument(fileName, project) { - throw new Error("Project '" + project.getProjectName() + "' does not contain document '" + fileName + "'"); - } - Errors.ThrowProjectDoesNotContainDocument = ThrowProjectDoesNotContainDocument; - })(Errors = server.Errors || (server.Errors = {})); - function getDefaultFormatCodeSettings(host) { - return { - indentSize: 4, - tabSize: 4, - newLineCharacter: host.newLine || "\n", - convertTabsToSpaces: true, - indentStyle: ts.IndentStyle.Smart, - insertSpaceAfterCommaDelimiter: true, - insertSpaceAfterSemicolonInForStatements: true, - insertSpaceBeforeAndAfterBinaryOperators: true, - insertSpaceAfterKeywordsInControlFlowStatements: true, - insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, - insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, - insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, - placeOpenBraceOnNewLineForFunctions: false, - placeOpenBraceOnNewLineForControlBlocks: false - }; - } - server.getDefaultFormatCodeSettings = getDefaultFormatCodeSettings; - function mergeMaps(target, source) { - for (var key in source) { - if (ts.hasProperty(source, key)) { - target[key] = source[key]; - } - } - } - server.mergeMaps = mergeMaps; - function removeItemFromSet(items, itemToRemove) { - if (items.length === 0) { - return; - } - var index = items.indexOf(itemToRemove); - if (index < 0) { - return; - } - if (index === items.length - 1) { - items.pop(); - } - else { - items[index] = items.pop(); - } - } - server.removeItemFromSet = removeItemFromSet; - function toNormalizedPath(fileName) { - return ts.normalizePath(fileName); - } - server.toNormalizedPath = toNormalizedPath; - function normalizedPathToPath(normalizedPath, currentDirectory, getCanonicalFileName) { - var f = ts.isRootedDiskPath(normalizedPath) ? normalizedPath : ts.getNormalizedAbsolutePath(normalizedPath, currentDirectory); - return getCanonicalFileName(f); - } - server.normalizedPathToPath = normalizedPathToPath; - function asNormalizedPath(fileName) { - return fileName; - } - server.asNormalizedPath = asNormalizedPath; - function createNormalizedPathMap() { - var map = Object.create(null); - return { - get: function (path) { - return map[path]; - }, - set: function (path, value) { - map[path] = value; - }, - contains: function (path) { - return ts.hasProperty(map, path); - }, - remove: function (path) { - delete map[path]; - } - }; - } - server.createNormalizedPathMap = createNormalizedPathMap; - function throwLanguageServiceIsDisabledError() { - throw new Error("LanguageService is disabled"); - } - server.nullLanguageService = { - cleanupSemanticCache: function () { return throwLanguageServiceIsDisabledError(); }, - getSyntacticDiagnostics: function () { return throwLanguageServiceIsDisabledError(); }, - getSemanticDiagnostics: function () { return throwLanguageServiceIsDisabledError(); }, - getCompilerOptionsDiagnostics: function () { return throwLanguageServiceIsDisabledError(); }, - getSyntacticClassifications: function () { return throwLanguageServiceIsDisabledError(); }, - getEncodedSyntacticClassifications: function () { return throwLanguageServiceIsDisabledError(); }, - getSemanticClassifications: function () { return throwLanguageServiceIsDisabledError(); }, - getEncodedSemanticClassifications: function () { return throwLanguageServiceIsDisabledError(); }, - getCompletionsAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - findReferences: function () { return throwLanguageServiceIsDisabledError(); }, - getCompletionEntryDetails: function () { return throwLanguageServiceIsDisabledError(); }, - getQuickInfoAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - findRenameLocations: function () { return throwLanguageServiceIsDisabledError(); }, - getNameOrDottedNameSpan: function () { return throwLanguageServiceIsDisabledError(); }, - getBreakpointStatementAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - getBraceMatchingAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - getSignatureHelpItems: function () { return throwLanguageServiceIsDisabledError(); }, - getDefinitionAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - getRenameInfo: function () { return throwLanguageServiceIsDisabledError(); }, - getTypeDefinitionAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - getReferencesAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - getDocumentHighlights: function () { return throwLanguageServiceIsDisabledError(); }, - getOccurrencesAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - getNavigateToItems: function () { return throwLanguageServiceIsDisabledError(); }, - getNavigationBarItems: function () { return throwLanguageServiceIsDisabledError(); }, - getOutliningSpans: function () { return throwLanguageServiceIsDisabledError(); }, - getTodoComments: function () { return throwLanguageServiceIsDisabledError(); }, - getIndentationAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - getFormattingEditsForRange: function () { return throwLanguageServiceIsDisabledError(); }, - getFormattingEditsForDocument: function () { return throwLanguageServiceIsDisabledError(); }, - getFormattingEditsAfterKeystroke: function () { return throwLanguageServiceIsDisabledError(); }, - getDocCommentTemplateAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - isValidBraceCompletionAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - getEmitOutput: function () { return throwLanguageServiceIsDisabledError(); }, - getProgram: function () { return throwLanguageServiceIsDisabledError(); }, - getNonBoundSourceFile: function () { return throwLanguageServiceIsDisabledError(); }, - dispose: function () { return throwLanguageServiceIsDisabledError(); } - }; - server.nullLanguageServiceHost = { - setCompilationSettings: function () { return undefined; }, - notifyFileRemoved: function () { return undefined; } - }; - function isInferredProjectName(name) { - return /dev\/null\/inferredProject\d+\*/.test(name); - } - server.isInferredProjectName = isInferredProjectName; - function makeInferredProjectName(counter) { - return "/dev/null/inferredProject" + counter + "*"; - } - server.makeInferredProjectName = makeInferredProjectName; - var ThrottledOperations = (function () { - function ThrottledOperations(host) { - this.host = host; - this.pendingTimeouts = ts.createMap(); - } - ThrottledOperations.prototype.schedule = function (operationId, delay, cb) { - if (ts.hasProperty(this.pendingTimeouts, operationId)) { - this.host.clearTimeout(this.pendingTimeouts[operationId]); - } - this.pendingTimeouts[operationId] = this.host.setTimeout(ThrottledOperations.run, delay, this, operationId, cb); - }; - ThrottledOperations.run = function (self, operationId, cb) { - delete self.pendingTimeouts[operationId]; - cb(); - }; - return ThrottledOperations; - }()); - server.ThrottledOperations = ThrottledOperations; - var GcTimer = (function () { - function GcTimer(host, delay, logger) { - this.host = host; - this.delay = delay; - this.logger = logger; - } - GcTimer.prototype.scheduleCollect = function () { - if (!this.host.gc || this.timerId != undefined) { - return; - } - this.timerId = this.host.setTimeout(GcTimer.run, this.delay, this); - }; - GcTimer.run = function (self) { - self.timerId = undefined; - var log = self.logger.hasLevel(LogLevel.requestTime); - var before = log && self.host.getMemoryUsage(); - self.host.gc(); - if (log) { - var after = self.host.getMemoryUsage(); - self.logger.perftrc("GC::before " + before + ", after " + after); - } - }; - return GcTimer; - }()); - server.GcTimer = GcTimer; - })(server = ts.server || (ts.server = {})); -})(ts || (ts = {})); -var ts; (function (ts) { function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; @@ -5533,6 +4797,24 @@ var ts; return node.end - node.pos; } ts.getFullWidth = getFullWidth; + function mapIsEqualTo(map1, map2) { + if (!map1 || !map2) { + return map1 === map2; + } + return containsAll(map1, map2) && containsAll(map2, map1); + } + ts.mapIsEqualTo = mapIsEqualTo; + function containsAll(map, other) { + for (var key in map) { + if (!ts.hasProperty(map, key)) { + continue; + } + if (!ts.hasProperty(other, key) || map[key] !== other[key]) { + return false; + } + } + return true; + } function arrayIsEqualTo(array1, array2, equaler) { if (!array1 || !array2) { return array1 === array2; @@ -5550,7 +4832,7 @@ var ts; } ts.arrayIsEqualTo = arrayIsEqualTo; function hasResolvedModule(sourceFile, moduleNameText) { - return !!(sourceFile.resolvedModules && sourceFile.resolvedModules[moduleNameText]); + return sourceFile.resolvedModules && ts.hasProperty(sourceFile.resolvedModules, moduleNameText); } ts.hasResolvedModule = hasResolvedModule; function getResolvedModule(sourceFile, moduleNameText) { @@ -5559,14 +4841,14 @@ var ts; ts.getResolvedModule = getResolvedModule; function setResolvedModule(sourceFile, moduleNameText, resolvedModule) { if (!sourceFile.resolvedModules) { - sourceFile.resolvedModules = ts.createMap(); + sourceFile.resolvedModules = {}; } sourceFile.resolvedModules[moduleNameText] = resolvedModule; } ts.setResolvedModule = setResolvedModule; function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) { if (!sourceFile.resolvedTypeReferenceDirectiveNames) { - sourceFile.resolvedTypeReferenceDirectiveNames = ts.createMap(); + sourceFile.resolvedTypeReferenceDirectiveNames = {}; } sourceFile.resolvedTypeReferenceDirectiveNames[typeReferenceDirectiveName] = resolvedTypeReferenceDirective; } @@ -5585,7 +4867,7 @@ var ts; } for (var i = 0; i < names.length; i++) { var newResolution = newResolutions[i]; - var oldResolution = oldResolutions && oldResolutions[names[i]]; + var oldResolution = oldResolutions && ts.hasProperty(oldResolutions, names[i]) ? oldResolutions[names[i]] : undefined; var changed = oldResolution ? !newResolution || !comparer(oldResolution, newResolution) : newResolution; @@ -5685,20 +4967,16 @@ var ts; if (includeJsDocComment && node.jsDocComments && node.jsDocComments.length > 0) { return getTokenPosOfNode(node.jsDocComments[0]); } - if (node.kind === 286 && node._children.length > 0) { + if (node.kind === 282 && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDocComment); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); } ts.getTokenPosOfNode = getTokenPosOfNode; function isJSDocNode(node) { - return node.kind >= 257 && node.kind <= 282; + return node.kind >= 257 && node.kind <= 281; } ts.isJSDocNode = isJSDocNode; - function isJSDocTag(node) { - return node.kind >= 273 && node.kind <= 285; - } - ts.isJSDocTag = isJSDocTag; function getNonDecoratorTokenPosOfNode(node, sourceFile) { if (nodeIsMissing(node) || !node.decorators) { return getTokenPosOfNode(node, sourceFile); @@ -5749,13 +5027,10 @@ var ts; (node.name.kind === 9 || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; - function isShorthandAmbientModuleSymbol(moduleSymbol) { - return isShorthandAmbientModule(moduleSymbol.valueDeclaration); - } - ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; function isShorthandAmbientModule(node) { return node.kind === 225 && (!node.body); } + ts.isShorthandAmbientModule = isShorthandAmbientModule; function isBlockScopedContainerTopLevel(node) { return node.kind === 256 || node.kind === 225 || @@ -6084,9 +5359,9 @@ var ts; return; default: if (isFunctionLike(node)) { - var name_8 = node.name; - if (name_8 && name_8.kind === 140) { - traverse(name_8.expression); + var name_6 = node.name; + if (name_6 && name_6.kind === 140) { + traverse(name_6.expression); return; } } @@ -6315,7 +5590,6 @@ var ts; case 155: return node.typeName; case 194: - ts.Debug.assert(isEntityNameExpression(node.expression)); return node.expression; case 69: case 139: @@ -6479,6 +5753,10 @@ var ts; return false; } ts.isExpression = isExpression; + function isExternalModuleNameRelative(moduleName) { + return moduleName.substr(0, 2) === "./" || moduleName.substr(0, 3) === "../" || moduleName.substr(0, 2) === ".\\" || moduleName.substr(0, 3) === "..\\"; + } + ts.isExternalModuleNameRelative = isExternalModuleNameRelative; function isInstantiatedModule(node, preserveConstEnums) { var moduleState = ts.getModuleInstanceState(node); return moduleState === 1 || @@ -6673,8 +5951,8 @@ var ts; var tag = _b[_a]; if (tag.kind === 275) { var parameterTag = tag; - var name_9 = parameterTag.preParameterName || parameterTag.postParameterName; - if (name_9.text === parameterName) { + var name_7 = parameterTag.preParameterName || parameterTag.postParameterName; + if (name_7.text === parameterName) { return parameterTag; } } @@ -6741,7 +6019,7 @@ var ts; continue; } return parent_5.kind === 187 && - isAssignmentOperator(parent_5.operatorToken.kind) && + parent_5.operatorToken.kind === 56 && parent_5.left === node || (parent_5.kind === 207 || parent_5.kind === 208) && parent_5.initializer === node; @@ -6788,7 +6066,6 @@ var ts; case 146: case 225: case 232: - case 228: case 142: case 253: case 145: @@ -6905,13 +6182,9 @@ var ts; node.kind === 232 || node.kind === 234 || node.kind === 238 || - node.kind === 235 && exportAssignmentIsAlias(node); + node.kind === 235 && node.expression.kind === 69; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; - function exportAssignmentIsAlias(node) { - return isEntityNameExpression(node.expression); - } - ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getClassExtendsHeritageClauseElement(node) { var heritageClause = getHeritageClause(node.heritageClauses, 83); return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; @@ -7131,7 +6404,7 @@ var ts; ts.createSynthesizedNodeArray = createSynthesizedNodeArray; function createDiagnosticCollection() { var nonFileDiagnostics = []; - var fileDiagnostics = ts.createMap(); + var fileDiagnostics = {}; var diagnosticsModified = false; var modificationCount = 0; return { @@ -7145,12 +6418,12 @@ var ts; return modificationCount; } function reattachFileDiagnostics(newFile) { - var diagnostics = fileDiagnostics[newFile.fileName]; - if (diagnostics) { - for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { - var diagnostic = diagnostics_1[_i]; - diagnostic.file = newFile; - } + if (!ts.hasProperty(fileDiagnostics, newFile.fileName)) { + return; + } + for (var _i = 0, _a = fileDiagnostics[newFile.fileName]; _i < _a.length; _i++) { + var diagnostic = _a[_i]; + diagnostic.file = newFile; } } function add(diagnostic) { @@ -7184,7 +6457,9 @@ var ts; } ts.forEach(nonFileDiagnostics, pushDiagnostic); for (var key in fileDiagnostics) { - ts.forEach(fileDiagnostics[key], pushDiagnostic); + if (ts.hasProperty(fileDiagnostics, key)) { + ts.forEach(fileDiagnostics[key], pushDiagnostic); + } } return ts.sortAndDeduplicateDiagnostics(allDiagnostics); } @@ -7195,13 +6470,15 @@ var ts; diagnosticsModified = false; nonFileDiagnostics = ts.sortAndDeduplicateDiagnostics(nonFileDiagnostics); for (var key in fileDiagnostics) { - fileDiagnostics[key] = ts.sortAndDeduplicateDiagnostics(fileDiagnostics[key]); + if (ts.hasProperty(fileDiagnostics, key)) { + fileDiagnostics[key] = ts.sortAndDeduplicateDiagnostics(fileDiagnostics[key]); + } } } } ts.createDiagnosticCollection = createDiagnosticCollection; var escapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; - var escapedCharsMap = ts.createMap({ + var escapedCharsMap = { "\0": "\\0", "\t": "\\t", "\v": "\\v", @@ -7214,7 +6491,7 @@ var ts; "\u2028": "\\u2028", "\u2029": "\\u2029", "\u0085": "\\u0085" - }); + }; function escapeString(s) { s = escapedCharsRegExp.test(s) ? s.replace(escapedCharsRegExp, getReplacement) : s; return s; @@ -7344,13 +6621,25 @@ var ts; function getDeclarationEmitOutputFilePath(sourceFile, host) { var options = host.getCompilerOptions(); var outputDir = options.declarationDir || options.outDir; - var path = outputDir - ? getSourceFilePathInNewDir(sourceFile, host, outputDir) - : sourceFile.fileName; - return ts.removeFileExtension(path) + ".d.ts"; + if (options.declaration) { + var path = outputDir + ? getSourceFilePathInNewDir(sourceFile, host, outputDir) + : sourceFile.fileName; + return ts.removeFileExtension(path) + ".d.ts"; + } } ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; - function forEachExpectedEmitFile(host, action, targetSourceFile, emitOnlyDtsFiles) { + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return typeof compilerOptions.module === "number" ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) === 2 ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; + } + ts.getEmitModuleKind = getEmitModuleKind; + function forEachExpectedEmitFile(host, action, targetSourceFile) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { onBundledEmit(host); @@ -7377,19 +6666,18 @@ var ts; } } var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); - var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; var emitFileNames = { jsFilePath: jsFilePath, sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), - declarationFilePath: declarationFilePath + declarationFilePath: !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined }; - action(emitFileNames, [sourceFile], false, emitOnlyDtsFiles); + action(emitFileNames, [sourceFile], false); } function onBundledEmit(host) { var bundledSources = ts.filter(host.getSourceFiles(), function (sourceFile) { return !isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile) && (!ts.isExternalModule(sourceFile) || - !!ts.getEmitModuleKind(options)); }); + !!getEmitModuleKind(options)); }); if (bundledSources.length) { var jsFilePath = options.outFile || options.out; var emitFileNames = { @@ -7397,7 +6685,7 @@ var ts; sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), declarationFilePath: options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined }; - action(emitFileNames, bundledSources, true, emitOnlyDtsFiles); + action(emitFileNames, bundledSources, true); } } function getSourceMapFilePath(jsFilePath, options) { @@ -7684,11 +6972,21 @@ var ts; isClassLike(node.parent.parent); } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; - function isEntityNameExpression(node) { - return node.kind === 69 || - node.kind === 172 && isEntityNameExpression(node.expression); + function isSupportedExpressionWithTypeArguments(node) { + return isSupportedExpressionWithTypeArgumentsRest(node.expression); + } + ts.isSupportedExpressionWithTypeArguments = isSupportedExpressionWithTypeArguments; + function isSupportedExpressionWithTypeArgumentsRest(node) { + if (node.kind === 69) { + return true; + } + else if (isPropertyAccessExpression(node)) { + return isSupportedExpressionWithTypeArgumentsRest(node.expression); + } + else { + return false; + } } - ts.isEntityNameExpression = isEntityNameExpression; function isRightSideOfQualifiedNameOrPropertyAccess(node) { return (node.parent.kind === 139 && node.parent.right === node) || (node.parent.kind === 172 && node.parent.name === node); @@ -7709,10 +7007,14 @@ var ts; return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & 512) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; - function tryExtractTypeScriptExtension(fileName) { - return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function hasJavaScriptFileExtension(fileName) { + return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; + ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; + function hasTypeScriptFileExtension(fileName) { + return ts.forEach(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; function getExpandedCharCodes(input) { var output = []; var length = input.length; @@ -7769,7 +7071,7 @@ var ts; return (memo ? memo + "," : memo) + stringifyValue(value); } function stringifyObject(value) { - return "{" + ts.reduceOwnProperties(value, stringifyProperty, "") + "}"; + return "{" + ts.reduceProperties(value, stringifyProperty, "") + "}"; } function stringifyProperty(memo, value, key) { return value === undefined || typeof value === "function" || key === "__cycle" ? memo @@ -7960,451 +7262,25 @@ var ts; return node.flags & 92 && node.parent.kind === 148 && ts.isClassLike(node.parent.parent); } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; + function startsWith(str, prefix) { + return str.lastIndexOf(prefix, 0) === 0; + } + ts.startsWith = startsWith; + function endsWith(str, suffix) { + var expectedPos = str.length - suffix.length; + return str.indexOf(suffix, expectedPos) === expectedPos; + } + ts.endsWith = endsWith; })(ts || (ts = {})); var ts; (function (ts) { - function tryReadTypesSection(packageJsonPath, baseDirectory, state) { - var jsonContent = ts.readJson(packageJsonPath, state.host); - function tryReadFromField(fieldName) { - if (ts.hasProperty(jsonContent, fieldName)) { - var typesFile = jsonContent[fieldName]; - if (typeof typesFile === "string") { - var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1); - } - return typesFilePath_1; - } - else { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); - } - } - } - } - var typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); - if (typesFilePath) { - return typesFilePath; - } - if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); - } - var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); - return mainFilePath; - } - return undefined; - } - function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures && state.host.fileExists(fileName)) { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); - } - return fileName; - } - else { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); - } - failedLookupLocation.push(fileName); - return undefined; - } - } - function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures) { - var directory = ts.getDirectoryPath(candidate); - if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); - } - } - return ts.forEach(extensions, function (ext) { - return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); - }); - } - function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); - if (resolvedByAddingExtension) { - return resolvedByAddingExtension; - } - if (ts.hasJavaScriptFileExtension(candidate)) { - var extensionless = ts.removeFileExtension(candidate); - if (state.traceEnabled) { - var extension = candidate.substring(extensionless.length); - ts.trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); - } - return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); - } - } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { - var packageJsonPath = pathToPackageJson(candidate); - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - if (directoryExists && state.host.fileExists(packageJsonPath)) { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); - if (typesFile) { - var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); - var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) || - tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state); - if (result) { - return result; - } - } - else { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field); - } - } - } - else { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); - } - failedLookupLocation.push(packageJsonPath); - } - return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); - } - ts.loadNodeModuleFromDirectory = loadNodeModuleFromDirectory; - function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { - var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions); - var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - } - function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state, checkOneLevel) { - directory = ts.normalizeSlashes(directory); - while (true) { - var baseName = ts.getBaseFileName(directory); - if (baseName !== "node_modules") { - var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); - if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { - return packageResult; - } - else { - var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); - if (typesResult || packageResult) { - return typesResult || packageResult; - } - } - } - var parentPath = ts.getDirectoryPath(directory); - if (parentPath === directory || checkOneLevel) { - break; - } - directory = parentPath; - } - return undefined; - } - ts.loadModuleFromNodeModules = loadModuleFromNodeModules; - function moduleHasNonRelativeName(moduleName) { - return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); - } - function classicNameResolver(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = ts.isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; - var failedLookupLocations = []; - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var containingDirectory = ts.getDirectoryPath(containingFile); - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); - if (resolvedFileName) { - return ts.createResolvedModule(resolvedFileName, false, failedLookupLocations); - } - var referencedSourceFile; - if (moduleHasNonRelativeName(moduleName)) { - while (true) { - var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state); - if (referencedSourceFile) { - break; - } - var parentPath = ts.getDirectoryPath(containingDirectory); - if (parentPath === containingDirectory) { - break; - } - containingDirectory = parentPath; - } - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, false, state); - } - return referencedSourceFile - ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } - : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; - } - ts.classicNameResolver = classicNameResolver; - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { - var containingDirectory = ts.getDirectoryPath(containingFile); - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var traceEnabled = ts.isTraceEnabled(compilerOptions, host); - var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); - var isExternalLibraryImport = false; - if (!resolvedFileName) { - if (moduleHasNonRelativeName(moduleName)) { - if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); - } - resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state, false); - isExternalLibraryImport = resolvedFileName !== undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, false, state); - } - } - if (resolvedFileName && host.realpath) { - var originalFileName = resolvedFileName; - resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName)); - if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); - } - } - return ts.createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; - function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); - } - var resolvedFileName = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); - return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); - } - function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.rootDirs) { - return undefined; - } - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); - } - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var matchedRootDir; - var matchedNormalizedPrefix; - for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { - var rootDir = _a[_i]; - var normalizedRoot = ts.normalizePath(rootDir); - if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { - normalizedRoot += ts.directorySeparator; - } - var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && - (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); - } - if (isLongestMatchingPrefix) { - matchedNormalizedPrefix = normalizedRoot; - matchedRootDir = rootDir; - } - } - if (matchedNormalizedPrefix) { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); - } - var suffix = candidate.substr(matchedNormalizedPrefix.length); - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); - } - for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { - var rootDir = _c[_b]; - if (rootDir === matchedRootDir) { - continue; - } - var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); - } - var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); - if (resolvedFileName_1) { - return resolvedFileName_1; - } - } - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); - } - } - return undefined; - } - function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.baseUrl) { - return undefined; - } - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); - } - var matchedPattern = undefined; - if (state.compilerOptions.paths) { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); - } - matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName); - var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern); - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); - } - for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) { - var subst = _a[_i]; - var path = matchedStar ? subst.replace("*", matchedStar) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - } - return undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - } - } - function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (moduleHasNonRelativeName(moduleName)) { - return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); - } - else { - return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); - } - } - function resolveModuleName(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = ts.isTraceEnabled(compilerOptions, host); - if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); - } - var moduleResolution = compilerOptions.moduleResolution; - if (moduleResolution === undefined) { - moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; - if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - else { - if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - var result; - switch (moduleResolution) { - case ts.ModuleResolutionKind.NodeJs: - result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); - break; - case ts.ModuleResolutionKind.Classic: - result = classicNameResolver(moduleName, containingFile, compilerOptions, host); - break; - } - if (traceEnabled) { - if (result.resolvedModule) { - ts.trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); - } - else { - ts.trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); - } - } - return result; - } - ts.resolveModuleName = resolveModuleName; - function matchPatternOrExact(patternStrings, candidate) { - var patterns = []; - for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { - var patternString = patternStrings_1[_i]; - var pattern = tryParsePattern(patternString); - if (pattern) { - patterns.push(pattern); - } - else if (patternString === candidate) { - return patternString; - } - } - return findBestPatternMatch(patterns, function (_) { return _; }, candidate); - } - function patternText(_a) { - var prefix = _a.prefix, suffix = _a.suffix; - return prefix + "*" + suffix; - } - function matchedText(pattern, candidate) { - ts.Debug.assert(isPatternMatch(pattern, candidate)); - return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); - } - function findBestPatternMatch(values, getPattern, candidate) { - var matchedValue = undefined; - var longestMatchPrefixLength = -1; - for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { - var v = values_1[_i]; - var pattern = getPattern(v); - if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { - longestMatchPrefixLength = pattern.prefix.length; - matchedValue = v; - } - } - return matchedValue; - } - ts.findBestPatternMatch = findBestPatternMatch; - function isPatternMatch(_a, candidate) { - var prefix = _a.prefix, suffix = _a.suffix; - return candidate.length >= prefix.length + suffix.length && - ts.startsWith(candidate, prefix) && - ts.endsWith(candidate, suffix); - } - function tryParsePattern(pattern) { - ts.Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern)); - var indexOfStar = pattern.indexOf("*"); - return indexOfStar === -1 ? undefined : { - prefix: pattern.substr(0, indexOfStar), - suffix: pattern.substr(indexOfStar + 1) - }; - } - ts.tryParsePattern = tryParsePattern; - function directoryProbablyExists(directoryName, host) { - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - ts.pathToPackageJson = pathToPackageJson; -})(ts || (ts = {})); -var ts; -(function (ts) { + ts.parseTime = 0; var NodeConstructor; - var TokenConstructor; - var IdentifierConstructor; var SourceFileConstructor; function createNode(kind, pos, end) { if (kind === 256) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); } - else if (kind === 69) { - return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); - } - else if (kind < 139) { - return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end); - } else { return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end); } @@ -8513,8 +7389,6 @@ var ts; return visitNodes(cbNodes, node.types); case 164: return visitNode(cbNode, node.type); - case 166: - return visitNode(cbNode, node.literal); case 167: case 168: return visitNodes(cbNodes, node.elements); @@ -8793,17 +7667,14 @@ var ts; case 280: return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); - case 282: - return visitNode(cbNode, node.literal); } } ts.forEachChild = forEachChild; function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { if (setParentNodes === void 0) { setParentNodes = false; } - ts.performance.mark("beforeParse"); + var start = new Date().getTime(); var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, scriptKind); - ts.performance.mark("afterParse"); - ts.performance.measure("Parse", "beforeParse", "afterParse"); + ts.parseTime += new Date().getTime() - start; return result; } ts.createSourceFile = createSourceFile; @@ -8818,7 +7689,7 @@ var ts; function parseIsolatedJSDocComment(content, start, length) { var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length); if (result && result.jsDocComment) { - fixupParentReferences(result.jsDocComment); + Parser.fixupParentReferences(result.jsDocComment); } return result; } @@ -8827,41 +7698,16 @@ var ts; return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length); } ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; - function fixupParentReferences(rootNode) { - var parent = rootNode; - forEachChild(rootNode, visitNode); - return; - function visitNode(n) { - if (n.parent !== parent) { - n.parent = parent; - var saveParent = parent; - parent = n; - forEachChild(n, visitNode); - if (n.jsDocComments) { - for (var _i = 0, _a = n.jsDocComments; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - jsDocComment.parent = n; - parent = jsDocComment; - forEachChild(jsDocComment, visitNode); - } - } - parent = saveParent; - } - } - } - ts.fixupParentReferences = fixupParentReferences; var Parser; (function (Parser) { var scanner = ts.createScanner(2, true); var disallowInAndDecoratorContext = 4194304 | 16777216; var NodeConstructor; - var TokenConstructor; - var IdentifierConstructor; var SourceFileConstructor; var sourceFile; var parseDiagnostics; var syntaxCursor; - var currentToken; + var token; var sourceText; var nodeCount; var identifiers; @@ -8882,14 +7728,12 @@ var ts; } function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind) { NodeConstructor = ts.objectAllocator.getNodeConstructor(); - TokenConstructor = ts.objectAllocator.getTokenConstructor(); - IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor(); SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor(); sourceText = _sourceText; syntaxCursor = _syntaxCursor; parseDiagnostics = []; parsingContext = 0; - identifiers = ts.createMap(); + identifiers = {}; identifierCount = 0; nodeCount = 0; contextFlags = scriptKind === 1 || scriptKind === 2 ? 134217728 : 0; @@ -8911,10 +7755,10 @@ var ts; function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) { sourceFile = createSourceFile(fileName, languageVersion, scriptKind); sourceFile.flags = contextFlags; - nextToken(); + token = nextToken(); processReferenceComments(sourceFile); sourceFile.statements = parseList(0, parseStatement); - ts.Debug.assert(token() === 1); + ts.Debug.assert(token === 1); sourceFile.endOfFileToken = parseTokenNode(); setExternalModuleIndicator(sourceFile); sourceFile.nodeCount = nodeCount; @@ -8945,6 +7789,29 @@ var ts; } return node; } + function fixupParentReferences(rootNode) { + var parent = rootNode; + forEachChild(rootNode, visitNode); + return; + function visitNode(n) { + if (n.parent !== parent) { + n.parent = parent; + var saveParent = parent; + parent = n; + forEachChild(n, visitNode); + if (n.jsDocComments) { + for (var _i = 0, _a = n.jsDocComments; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + jsDocComment.parent = n; + parent = jsDocComment; + forEachChild(jsDocComment, visitNode); + } + } + parent = saveParent; + } + } + } + Parser.fixupParentReferences = fixupParentReferences; function createSourceFile(fileName, languageVersion, scriptKind) { var sourceFile = new SourceFileConstructor(256, 0, sourceText.length); nodeCount++; @@ -9055,29 +7922,26 @@ var ts; function getNodeEnd() { return scanner.getStartPos(); } - function token() { - return currentToken; - } function nextToken() { - return currentToken = scanner.scan(); + return token = scanner.scan(); } function reScanGreaterToken() { - return currentToken = scanner.reScanGreaterToken(); + return token = scanner.reScanGreaterToken(); } function reScanSlashToken() { - return currentToken = scanner.reScanSlashToken(); + return token = scanner.reScanSlashToken(); } function reScanTemplateToken() { - return currentToken = scanner.reScanTemplateToken(); + return token = scanner.reScanTemplateToken(); } function scanJsxIdentifier() { - return currentToken = scanner.scanJsxIdentifier(); + return token = scanner.scanJsxIdentifier(); } function scanJsxText() { - return currentToken = scanner.scanJsxToken(); + return token = scanner.scanJsxToken(); } function speculationHelper(callback, isLookAhead) { - var saveToken = currentToken; + var saveToken = token; var saveParseDiagnosticsLength = parseDiagnostics.length; var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; var saveContextFlags = contextFlags; @@ -9086,7 +7950,7 @@ var ts; : scanner.tryScan(callback); ts.Debug.assert(saveContextFlags === contextFlags); if (!result || isLookAhead) { - currentToken = saveToken; + token = saveToken; parseDiagnostics.length = saveParseDiagnosticsLength; parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; } @@ -9099,20 +7963,20 @@ var ts; return speculationHelper(callback, false); } function isIdentifier() { - if (token() === 69) { + if (token === 69) { return true; } - if (token() === 114 && inYieldContext()) { + if (token === 114 && inYieldContext()) { return false; } - if (token() === 119 && inAwaitContext()) { + if (token === 119 && inAwaitContext()) { return false; } - return token() > 105; + return token > 105; } function parseExpected(kind, diagnosticMessage, shouldAdvance) { if (shouldAdvance === void 0) { shouldAdvance = true; } - if (token() === kind) { + if (token === kind) { if (shouldAdvance) { nextToken(); } @@ -9127,14 +7991,14 @@ var ts; return false; } function parseOptional(t) { - if (token() === t) { + if (token === t) { nextToken(); return true; } return false; } function parseOptionalToken(t) { - if (token() === t) { + if (token === t) { return parseTokenNode(); } return undefined; @@ -9144,19 +8008,19 @@ var ts; createMissingNode(t, reportAtCurrentPosition, diagnosticMessage, arg0); } function parseTokenNode() { - var node = createNode(token()); + var node = createNode(token); nextToken(); return finishNode(node); } function canParseSemicolon() { - if (token() === 23) { + if (token === 23) { return true; } - return token() === 16 || token() === 1 || scanner.hasPrecedingLineBreak(); + return token === 16 || token === 1 || scanner.hasPrecedingLineBreak(); } function parseSemicolon() { if (canParseSemicolon()) { - if (token() === 23) { + if (token === 23) { nextToken(); } return true; @@ -9170,9 +8034,7 @@ var ts; if (!(pos >= 0)) { pos = scanner.getStartPos(); } - return kind >= 139 ? new NodeConstructor(kind, pos, pos) : - kind === 69 ? new IdentifierConstructor(kind, pos, pos) : - new TokenConstructor(kind, pos, pos); + return new NodeConstructor(kind, pos, pos); } function finishNode(node, end) { node.end = end === undefined ? scanner.getStartPos() : end; @@ -9198,14 +8060,14 @@ var ts; } function internIdentifier(text) { text = ts.escapeIdentifier(text); - return identifiers[text] || (identifiers[text] = text); + return ts.hasProperty(identifiers, text) ? identifiers[text] : (identifiers[text] = text); } function createIdentifier(isIdentifier, diagnosticMessage) { identifierCount++; if (isIdentifier) { var node = createNode(69); - if (token() !== 69) { - node.originalKeywordKind = token(); + if (token !== 69) { + node.originalKeywordKind = token; } node.text = internIdentifier(scanner.getTokenValue()); nextToken(); @@ -9217,18 +8079,18 @@ var ts; return createIdentifier(isIdentifier(), diagnosticMessage); } function parseIdentifierName() { - return createIdentifier(ts.tokenIsIdentifierOrKeyword(token())); + return createIdentifier(ts.tokenIsIdentifierOrKeyword(token)); } function isLiteralPropertyName() { - return ts.tokenIsIdentifierOrKeyword(token()) || - token() === 9 || - token() === 8; + return ts.tokenIsIdentifierOrKeyword(token) || + token === 9 || + token === 8; } function parsePropertyNameWorker(allowComputedPropertyNames) { - if (token() === 9 || token() === 8) { + if (token === 9 || token === 8) { return parseLiteralNode(true); } - if (allowComputedPropertyNames && token() === 19) { + if (allowComputedPropertyNames && token === 19) { return parseComputedPropertyName(); } return parseIdentifierName(); @@ -9240,7 +8102,7 @@ var ts; return parsePropertyNameWorker(false); } function isSimplePropertyName() { - return token() === 9 || token() === 8 || ts.tokenIsIdentifierOrKeyword(token()); + return token === 9 || token === 8 || ts.tokenIsIdentifierOrKeyword(token); } function parseComputedPropertyName() { var node = createNode(140); @@ -9250,7 +8112,7 @@ var ts; return finishNode(node); } function parseContextualModifier(t) { - return token() === t && tryParse(nextTokenCanFollowModifier); + return token === t && tryParse(nextTokenCanFollowModifier); } function nextTokenIsOnSameLineAndCanFollowModifier() { nextToken(); @@ -9260,39 +8122,39 @@ var ts; return canFollowModifier(); } function nextTokenCanFollowModifier() { - if (token() === 74) { + if (token === 74) { return nextToken() === 81; } - if (token() === 82) { + if (token === 82) { nextToken(); - if (token() === 77) { + if (token === 77) { return lookAhead(nextTokenIsClassOrFunctionOrAsync); } - return token() !== 37 && token() !== 116 && token() !== 15 && canFollowModifier(); + return token !== 37 && token !== 116 && token !== 15 && canFollowModifier(); } - if (token() === 77) { + if (token === 77) { return nextTokenIsClassOrFunctionOrAsync(); } - if (token() === 113) { + if (token === 113) { nextToken(); return canFollowModifier(); } return nextTokenIsOnSameLineAndCanFollowModifier(); } function parseAnyContextualModifier() { - return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); + return ts.isModifierKind(token) && tryParse(nextTokenCanFollowModifier); } function canFollowModifier() { - return token() === 19 - || token() === 15 - || token() === 37 - || token() === 22 + return token === 19 + || token === 15 + || token === 37 + || token === 22 || isLiteralPropertyName(); } function nextTokenIsClassOrFunctionOrAsync() { nextToken(); - return token() === 73 || token() === 87 || - (token() === 118 && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); + return token === 73 || token === 87 || + (token === 118 && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); } function isListElement(parsingContext, inErrorRecovery) { var node = currentNode(parsingContext); @@ -9303,21 +8165,21 @@ var ts; case 0: case 1: case 3: - return !(token() === 23 && inErrorRecovery) && isStartOfStatement(); + return !(token === 23 && inErrorRecovery) && isStartOfStatement(); case 2: - return token() === 71 || token() === 77; + return token === 71 || token === 77; case 4: return lookAhead(isTypeMemberStart); case 5: - return lookAhead(isClassMemberStart) || (token() === 23 && !inErrorRecovery); + return lookAhead(isClassMemberStart) || (token === 23 && !inErrorRecovery); case 6: - return token() === 19 || isLiteralPropertyName(); + return token === 19 || isLiteralPropertyName(); case 12: - return token() === 19 || token() === 37 || isLiteralPropertyName(); + return token === 19 || token === 37 || isLiteralPropertyName(); case 9: - return token() === 19 || isLiteralPropertyName(); + return token === 19 || isLiteralPropertyName(); case 7: - if (token() === 15) { + if (token === 15) { return lookAhead(isValidHeritageClauseObjectLiteral); } if (!inErrorRecovery) { @@ -9329,23 +8191,23 @@ var ts; case 8: return isIdentifierOrPattern(); case 10: - return token() === 24 || token() === 22 || isIdentifierOrPattern(); + return token === 24 || token === 22 || isIdentifierOrPattern(); case 17: return isIdentifier(); case 11: case 15: - return token() === 24 || token() === 22 || isStartOfExpression(); + return token === 24 || token === 22 || isStartOfExpression(); case 16: return isStartOfParameter(); case 18: case 19: - return token() === 24 || isStartOfType(); + return token === 24 || isStartOfType(); case 20: return isHeritageClause(); case 21: - return ts.tokenIsIdentifierOrKeyword(token()); + return ts.tokenIsIdentifierOrKeyword(token); case 13: - return ts.tokenIsIdentifierOrKeyword(token()) || token() === 15; + return ts.tokenIsIdentifierOrKeyword(token) || token === 15; case 14: return true; case 22: @@ -9358,7 +8220,7 @@ var ts; ts.Debug.fail("Non-exhaustive case in 'isListElement'."); } function isValidHeritageClauseObjectLiteral() { - ts.Debug.assert(token() === 15); + ts.Debug.assert(token === 15); if (nextToken() === 16) { var next = nextToken(); return next === 24 || next === 15 || next === 83 || next === 106; @@ -9371,11 +8233,11 @@ var ts; } function nextTokenIsIdentifierOrKeyword() { nextToken(); - return ts.tokenIsIdentifierOrKeyword(token()); + return ts.tokenIsIdentifierOrKeyword(token); } function isHeritageClauseExtendsOrImplementsKeyword() { - if (token() === 106 || - token() === 83) { + if (token === 106 || + token === 83) { return lookAhead(nextTokenIsStartOfExpression); } return false; @@ -9385,7 +8247,7 @@ var ts; return isStartOfExpression(); } function isListTerminator(kind) { - if (token() === 1) { + if (token === 1) { return true; } switch (kind) { @@ -9397,49 +8259,49 @@ var ts; case 12: case 9: case 21: - return token() === 16; + return token === 16; case 3: - return token() === 16 || token() === 71 || token() === 77; + return token === 16 || token === 71 || token === 77; case 7: - return token() === 15 || token() === 83 || token() === 106; + return token === 15 || token === 83 || token === 106; case 8: return isVariableDeclaratorListTerminator(); case 17: - return token() === 27 || token() === 17 || token() === 15 || token() === 83 || token() === 106; + return token === 27 || token === 17 || token === 15 || token === 83 || token === 106; case 11: - return token() === 18 || token() === 23; + return token === 18 || token === 23; case 15: case 19: case 10: - return token() === 20; + return token === 20; case 16: - return token() === 18 || token() === 20; + return token === 18 || token === 20; case 18: - return token() === 27 || token() === 17; + return token === 27 || token === 17; case 20: - return token() === 15 || token() === 16; + return token === 15 || token === 16; case 13: - return token() === 27 || token() === 39; + return token === 27 || token === 39; case 14: - return token() === 25 && lookAhead(nextTokenIsSlash); + return token === 25 && lookAhead(nextTokenIsSlash); case 22: - return token() === 18 || token() === 54 || token() === 16; + return token === 18 || token === 54 || token === 16; case 23: - return token() === 27 || token() === 16; + return token === 27 || token === 16; case 25: - return token() === 20 || token() === 16; + return token === 20 || token === 16; case 24: - return token() === 16; + return token === 16; } } function isVariableDeclaratorListTerminator() { if (canParseSemicolon()) { return true; } - if (isInOrOfKeyword(token())) { + if (isInOrOfKeyword(token)) { return true; } - if (token() === 34) { + if (token === 34) { return true; } return false; @@ -9694,7 +8556,7 @@ var ts; break; } parseExpected(24); - if (considerSemicolonAsDelimiter && token() === 23 && !scanner.hasPrecedingLineBreak()) { + if (considerSemicolonAsDelimiter && token === 23 && !scanner.hasPrecedingLineBreak()) { nextToken(); } continue; @@ -9739,7 +8601,7 @@ var ts; return entity; } function parseRightSideOfDot(allowIdentifierNames) { - if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) { + if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token)) { var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); if (matchesPattern) { return createMissingNode(69, true, ts.Diagnostics.Identifier_expected); @@ -9764,7 +8626,7 @@ var ts; var span = createNode(197); span.expression = allowInAnd(parseExpression); var literal; - if (token() === 16) { + if (token === 16) { reScanTemplateToken(); literal = parseTemplateLiteralFragment(); } @@ -9774,11 +8636,14 @@ var ts; span.literal = literal; return finishNode(span); } + function parseStringLiteralTypeNode() { + return parseLiteralLikeNode(166, true); + } function parseLiteralNode(internName) { - return parseLiteralLikeNode(token(), internName); + return parseLiteralLikeNode(token, internName); } function parseTemplateLiteralFragment() { - return parseLiteralLikeNode(token(), false); + return parseLiteralLikeNode(token, false); } function parseLiteralLikeNode(kind, internName) { var node = createNode(kind); @@ -9804,7 +8669,7 @@ var ts; var typeName = parseEntityName(false, ts.Diagnostics.Type_expected); var node = createNode(155, typeName.pos); node.typeName = typeName; - if (!scanner.hasPrecedingLineBreak() && token() === 25) { + if (!scanner.hasPrecedingLineBreak() && token === 25) { node.typeArguments = parseBracketedList(18, parseType, 25, 27); } return finishNode(node); @@ -9841,7 +8706,7 @@ var ts; return finishNode(node); } function parseTypeParameters() { - if (token() === 25) { + if (token === 25) { return parseBracketedList(17, parseTypeParameter, 25, 27); } } @@ -9852,7 +8717,7 @@ var ts; return undefined; } function isStartOfParameter() { - return token() === 22 || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 55 || token() === 97; + return token === 22 || isIdentifierOrPattern() || ts.isModifierKind(token) || token === 55 || token === 97; } function setModifiers(node, modifiers) { if (modifiers) { @@ -9862,7 +8727,7 @@ var ts; } function parseParameter() { var node = createNode(142); - if (token() === 97) { + if (token === 97) { node.name = createIdentifier(true, undefined); node.type = parseParameterType(); return finishNode(node); @@ -9871,7 +8736,7 @@ var ts; setModifiers(node, parseModifiers()); node.dotDotDotToken = parseOptionalToken(22); node.name = parseIdentifierOrPattern(); - if (ts.getFullWidth(node.name) === 0 && node.flags === 0 && ts.isModifierKind(token())) { + if (ts.getFullWidth(node.name) === 0 && node.flags === 0 && ts.isModifierKind(token)) { nextToken(); } node.questionToken = parseOptionalToken(53); @@ -9929,17 +8794,17 @@ var ts; return finishNode(node); } function isIndexSignature() { - if (token() !== 19) { + if (token !== 19) { return false; } return lookAhead(isUnambiguouslyIndexSignature); } function isUnambiguouslyIndexSignature() { nextToken(); - if (token() === 22 || token() === 20) { + if (token === 22 || token === 20) { return true; } - if (ts.isModifierKind(token())) { + if (ts.isModifierKind(token)) { nextToken(); if (isIdentifier()) { return true; @@ -9951,14 +8816,14 @@ var ts; else { nextToken(); } - if (token() === 54 || token() === 24) { + if (token === 54 || token === 24) { return true; } - if (token() !== 53) { + if (token !== 53) { return false; } nextToken(); - return token() === 54 || token() === 24 || token() === 20; + return token === 54 || token === 24 || token === 20; } function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { var node = createNode(153, fullStart); @@ -9972,7 +8837,7 @@ var ts; function parsePropertyOrMethodSignature(fullStart, modifiers) { var name = parsePropertyName(); var questionToken = parseOptionalToken(53); - if (token() === 17 || token() === 25) { + if (token === 17 || token === 25) { var method = createNode(146, fullStart); setModifiers(method, modifiers); method.name = name; @@ -9987,7 +8852,7 @@ var ts; property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); - if (token() === 56) { + if (token === 56) { property.initializer = parseNonParameterInitializer(); } parseTypeMemberSemicolon(); @@ -9996,35 +8861,34 @@ var ts; } function isTypeMemberStart() { var idToken; - if (token() === 17 || token() === 25) { + if (token === 17 || token === 25) { return true; } - while (ts.isModifierKind(token())) { - idToken = token(); + while (ts.isModifierKind(token)) { + idToken = token; nextToken(); } - if (token() === 19) { + if (token === 19) { return true; } if (isLiteralPropertyName()) { - idToken = token(); + idToken = token; nextToken(); } if (idToken) { - return token() === 17 || - token() === 25 || - token() === 53 || - token() === 54 || - token() === 24 || + return token === 17 || + token === 25 || + token === 53 || + token === 54 || canParseSemicolon(); } return false; } function parseTypeMember() { - if (token() === 17 || token() === 25) { + if (token === 17 || token === 25) { return parseSignatureMember(151); } - if (token() === 92 && lookAhead(isStartOfConstructSignature)) { + if (token === 92 && lookAhead(isStartOfConstructSignature)) { return parseSignatureMember(152); } var fullStart = getNodePos(); @@ -10036,7 +8900,7 @@ var ts; } function isStartOfConstructSignature() { nextToken(); - return token() === 17 || token() === 25; + return token === 17 || token === 25; } function parseTypeLiteral() { var node = createNode(159); @@ -10076,19 +8940,10 @@ var ts; } function parseKeywordAndNoDot() { var node = parseTokenNode(); - return token() === 21 ? undefined : node; - } - function parseLiteralTypeNode() { - var node = createNode(166); - node.literal = parseSimpleUnaryExpression(); - finishNode(node); - return node; - } - function nextTokenIsNumericLiteral() { - return nextToken() === 8; + return token === 21 ? undefined : node; } function parseNonArrayType() { - switch (token()) { + switch (token) { case 117: case 132: case 130: @@ -10099,18 +8954,13 @@ var ts; var node = tryParse(parseKeywordAndNoDot); return node || parseTypeReference(); case 9: - case 8: - case 99: - case 84: - return parseLiteralTypeNode(); - case 36: - return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode() : parseTypeReference(); + return parseStringLiteralTypeNode(); case 103: case 93: return parseTokenNode(); case 97: { var thisKeyword = parseThisTypeNode(); - if (token() === 124 && !scanner.hasPrecedingLineBreak()) { + if (token === 124 && !scanner.hasPrecedingLineBreak()) { return parseThisTypePredicate(thisKeyword); } else { @@ -10130,7 +8980,7 @@ var ts; } } function isStartOfType() { - switch (token()) { + switch (token) { case 117: case 132: case 130: @@ -10147,12 +8997,7 @@ var ts; case 25: case 92: case 9: - case 8: - case 99: - case 84: return true; - case 36: - return lookAhead(nextTokenIsNumericLiteral); case 17: return lookAhead(isStartOfParenthesizedOrFunctionType); default: @@ -10161,7 +9006,7 @@ var ts; } function isStartOfParenthesizedOrFunctionType() { nextToken(); - return token() === 18 || isStartOfParameter() || isStartOfType(); + return token === 18 || isStartOfParameter() || isStartOfType(); } function parseArrayTypeOrHigher() { var type = parseNonArrayType(); @@ -10175,7 +9020,7 @@ var ts; } function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { var type = parseConstituentType(); - if (token() === operator) { + if (token === operator) { var types = [type]; types.pos = type.pos; while (parseOptional(operator)) { @@ -10195,20 +9040,20 @@ var ts; return parseUnionOrIntersectionType(162, parseIntersectionTypeOrHigher, 47); } function isStartOfFunctionType() { - if (token() === 25) { + if (token === 25) { return true; } - return token() === 17 && lookAhead(isUnambiguouslyStartOfFunctionType); + return token === 17 && lookAhead(isUnambiguouslyStartOfFunctionType); } function skipParameterStart() { - if (ts.isModifierKind(token())) { + if (ts.isModifierKind(token)) { parseModifiers(); } - if (isIdentifier() || token() === 97) { + if (isIdentifier() || token === 97) { nextToken(); return true; } - if (token() === 19 || token() === 15) { + if (token === 19 || token === 15) { var previousErrorCount = parseDiagnostics.length; parseIdentifierOrPattern(); return previousErrorCount === parseDiagnostics.length; @@ -10217,17 +9062,17 @@ var ts; } function isUnambiguouslyStartOfFunctionType() { nextToken(); - if (token() === 18 || token() === 22) { + if (token === 18 || token === 22) { return true; } if (skipParameterStart()) { - if (token() === 54 || token() === 24 || - token() === 53 || token() === 56) { + if (token === 54 || token === 24 || + token === 53 || token === 56) { return true; } - if (token() === 18) { + if (token === 18) { nextToken(); - if (token() === 34) { + if (token === 34) { return true; } } @@ -10249,7 +9094,7 @@ var ts; } function parseTypePredicatePrefix() { var id = parseIdentifier(); - if (token() === 124 && !scanner.hasPrecedingLineBreak()) { + if (token === 124 && !scanner.hasPrecedingLineBreak()) { nextToken(); return id; } @@ -10261,7 +9106,7 @@ var ts; if (isStartOfFunctionType()) { return parseFunctionOrConstructorType(156); } - if (token() === 92) { + if (token === 92) { return parseFunctionOrConstructorType(157); } return parseUnionTypeOrHigher(); @@ -10270,7 +9115,7 @@ var ts; return parseOptional(54) ? parseType() : undefined; } function isStartOfLeftHandSideExpression() { - switch (token()) { + switch (token) { case 97: case 95: case 93: @@ -10298,7 +9143,7 @@ var ts; if (isStartOfLeftHandSideExpression()) { return true; } - switch (token()) { + switch (token) { case 35: case 36: case 50: @@ -10320,10 +9165,10 @@ var ts; } } function isStartOfExpressionStatement() { - return token() !== 15 && - token() !== 87 && - token() !== 73 && - token() !== 55 && + return token !== 15 && + token !== 87 && + token !== 73 && + token !== 55 && isStartOfExpression(); } function parseExpression() { @@ -10342,8 +9187,8 @@ var ts; return expr; } function parseInitializer(inParameter) { - if (token() !== 56) { - if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 15) || !isStartOfExpression()) { + if (token !== 56) { + if (scanner.hasPrecedingLineBreak() || (inParameter && token === 15) || !isStartOfExpression()) { return undefined; } } @@ -10359,7 +9204,7 @@ var ts; return arrowExpression; } var expr = parseBinaryExpressionOrHigher(0); - if (expr.kind === 69 && token() === 34) { + if (expr.kind === 69 && token === 34) { return parseSimpleArrowFunctionExpression(expr); } if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { @@ -10368,7 +9213,7 @@ var ts; return parseConditionalExpressionRest(expr); } function isYieldExpression() { - if (token() === 114) { + if (token === 114) { if (inYieldContext()) { return true; } @@ -10384,7 +9229,7 @@ var ts; var node = createNode(190); nextToken(); if (!scanner.hasPrecedingLineBreak() && - (token() === 37 || isStartOfExpression())) { + (token === 37 || isStartOfExpression())) { node.asteriskToken = parseOptionalToken(37); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); @@ -10394,7 +9239,7 @@ var ts; } } function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { - ts.Debug.assert(token() === 34, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + ts.Debug.assert(token === 34, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); var node; if (asyncModifier) { node = createNode(180, asyncModifier.pos); @@ -10425,7 +9270,7 @@ var ts; return undefined; } var isAsync = !!(arrowFunction.flags & 256); - var lastToken = token(); + var lastToken = token; arrowFunction.equalsGreaterThanToken = parseExpectedToken(34, false, ts.Diagnostics._0_expected, "=>"); arrowFunction.body = (lastToken === 34 || lastToken === 15) ? parseArrowFunctionExpressionBody(isAsync) @@ -10433,25 +9278,25 @@ var ts; return finishNode(arrowFunction); } function isParenthesizedArrowFunctionExpression() { - if (token() === 17 || token() === 25 || token() === 118) { + if (token === 17 || token === 25 || token === 118) { return lookAhead(isParenthesizedArrowFunctionExpressionWorker); } - if (token() === 34) { + if (token === 34) { return 1; } return 0; } function isParenthesizedArrowFunctionExpressionWorker() { - if (token() === 118) { + if (token === 118) { nextToken(); if (scanner.hasPrecedingLineBreak()) { return 0; } - if (token() !== 17 && token() !== 25) { + if (token !== 17 && token !== 25) { return 0; } } - var first = token(); + var first = token; var second = nextToken(); if (first === 17) { if (second === 18) { @@ -10514,7 +9359,7 @@ var ts; return parseParenthesizedArrowFunctionExpressionHead(false); } function tryParseAsyncSimpleArrowFunctionExpression() { - if (token() === 118) { + if (token === 118) { var isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker); if (isUnParenthesizedAsyncArrowFunction === 1) { var asyncModifier = parseModifiersForArrowFunction(); @@ -10525,13 +9370,13 @@ var ts; return undefined; } function isUnParenthesizedAsyncArrowFunctionWorker() { - if (token() === 118) { + if (token === 118) { nextToken(); - if (scanner.hasPrecedingLineBreak() || token() === 34) { + if (scanner.hasPrecedingLineBreak() || token === 34) { return 0; } var expr = parseBinaryExpressionOrHigher(0); - if (!scanner.hasPrecedingLineBreak() && expr.kind === 69 && token() === 34) { + if (!scanner.hasPrecedingLineBreak() && expr.kind === 69 && token === 34) { return 1; } } @@ -10545,18 +9390,18 @@ var ts; if (!node.parameters) { return undefined; } - if (!allowAmbiguity && token() !== 34 && token() !== 15) { + if (!allowAmbiguity && token !== 34 && token !== 15) { return undefined; } return node; } function parseArrowFunctionExpressionBody(isAsync) { - if (token() === 15) { + if (token === 15) { return parseFunctionBlock(false, isAsync, false); } - if (token() !== 23 && - token() !== 87 && - token() !== 73 && + if (token !== 23 && + token !== 87 && + token !== 73 && isStartOfStatement() && !isStartOfExpressionStatement()) { return parseFunctionBlock(false, isAsync, true); @@ -10589,16 +9434,16 @@ var ts; while (true) { reScanGreaterToken(); var newPrecedence = getBinaryOperatorPrecedence(); - var consumeCurrentOperator = token() === 38 ? + var consumeCurrentOperator = token === 38 ? newPrecedence >= precedence : newPrecedence > precedence; if (!consumeCurrentOperator) { break; } - if (token() === 90 && inDisallowInContext()) { + if (token === 90 && inDisallowInContext()) { break; } - if (token() === 116) { + if (token === 116) { if (scanner.hasPrecedingLineBreak()) { break; } @@ -10614,13 +9459,13 @@ var ts; return leftOperand; } function isBinaryOperator() { - if (inDisallowInContext() && token() === 90) { + if (inDisallowInContext() && token === 90) { return false; } return getBinaryOperatorPrecedence() > 0; } function getBinaryOperatorPrecedence() { - switch (token()) { + switch (token) { case 52: return 1; case 51: @@ -10675,7 +9520,7 @@ var ts; } function parsePrefixUnaryExpression() { var node = createNode(185); - node.operator = token(); + node.operator = token; nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); @@ -10699,7 +9544,7 @@ var ts; return finishNode(node); } function isAwaitExpression() { - if (token() === 119) { + if (token === 119) { if (inAwaitContext()) { return true; } @@ -10714,15 +9559,18 @@ var ts; return finishNode(node); } function parseUnaryExpressionOrHigher() { - if (isUpdateExpression()) { + if (isAwaitExpression()) { + return parseAwaitExpression(); + } + if (isIncrementExpression()) { var incrementExpression = parseIncrementExpression(); - return token() === 38 ? + return token === 38 ? parseBinaryExpressionRest(getBinaryOperatorPrecedence(), incrementExpression) : incrementExpression; } - var unaryOperator = token(); + var unaryOperator = token; var simpleUnaryExpression = parseSimpleUnaryExpression(); - if (token() === 38) { + if (token === 38) { var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); if (simpleUnaryExpression.kind === 177) { parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); @@ -10734,7 +9582,7 @@ var ts; return simpleUnaryExpression; } function parseSimpleUnaryExpression() { - switch (token()) { + switch (token) { case 35: case 36: case 50: @@ -10748,16 +9596,12 @@ var ts; return parseVoidExpression(); case 25: return parseTypeAssertion(); - case 119: - if (isAwaitExpression()) { - return parseAwaitExpression(); - } default: return parseIncrementExpression(); } } - function isUpdateExpression() { - switch (token()) { + function isIncrementExpression() { + switch (token) { case 35: case 36: case 50: @@ -10765,7 +9609,6 @@ var ts; case 78: case 101: case 103: - case 119: return false; case 25: if (sourceFile.languageVariant !== 1) { @@ -10776,29 +9619,29 @@ var ts; } } function parseIncrementExpression() { - if (token() === 41 || token() === 42) { + if (token === 41 || token === 42) { var node = createNode(185); - node.operator = token(); + node.operator = token; nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); return finishNode(node); } - else if (sourceFile.languageVariant === 1 && token() === 25 && lookAhead(nextTokenIsIdentifierOrKeyword)) { + else if (sourceFile.languageVariant === 1 && token === 25 && lookAhead(nextTokenIsIdentifierOrKeyword)) { return parseJsxElementOrSelfClosingElement(true); } var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); - if ((token() === 41 || token() === 42) && !scanner.hasPrecedingLineBreak()) { + if ((token === 41 || token === 42) && !scanner.hasPrecedingLineBreak()) { var node = createNode(186, expression.pos); node.operand = expression; - node.operator = token(); + node.operator = token; nextToken(); return finishNode(node); } return expression; } function parseLeftHandSideExpressionOrHigher() { - var expression = token() === 95 + var expression = token === 95 ? parseSuperExpression() : parseMemberExpressionOrHigher(); return parseCallExpressionRest(expression); @@ -10809,7 +9652,7 @@ var ts; } function parseSuperExpression() { var expression = parseTokenNode(); - if (token() === 17 || token() === 21 || token() === 19) { + if (token === 17 || token === 21 || token === 19) { return expression; } var node = createNode(172, expression.pos); @@ -10848,7 +9691,7 @@ var ts; ts.Debug.assert(opening.kind === 242); result = opening; } - if (inExpressionContext && token() === 25) { + if (inExpressionContext && token === 25) { var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); @@ -10865,11 +9708,11 @@ var ts; } function parseJsxText() { var node = createNode(244, scanner.getStartPos()); - currentToken = scanner.scanJsxToken(); + token = scanner.scanJsxToken(); return finishNode(node); } function parseJsxChild() { - switch (token()) { + switch (token) { case 244: return parseJsxText(); case 15: @@ -10877,7 +9720,7 @@ var ts; case 25: return parseJsxElementOrSelfClosingElement(false); } - ts.Debug.fail("Unknown JSX child kind " + token()); + ts.Debug.fail("Unknown JSX child kind " + token); } function parseJsxChildren(openingTagName) { var result = []; @@ -10885,11 +9728,11 @@ var ts; var saveParsingContext = parsingContext; parsingContext |= 1 << 14; while (true) { - currentToken = scanner.reScanJsxToken(); - if (token() === 26) { + token = scanner.reScanJsxToken(); + if (token === 26) { break; } - else if (token() === 1) { + else if (token === 1) { parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); break; } @@ -10905,7 +9748,7 @@ var ts; var tagName = parseJsxElementName(); var attributes = parseList(13, parseJsxAttribute); var node; - if (token() === 27) { + if (token === 27) { node = createNode(243, fullStart); scanJsxText(); } @@ -10926,7 +9769,7 @@ var ts; } function parseJsxElementName() { scanJsxIdentifier(); - var expression = token() === 97 ? + var expression = token === 97 ? parseTokenNode() : parseIdentifierName(); while (parseOptional(21)) { var propertyAccess = createNode(172, expression.pos); @@ -10939,7 +9782,7 @@ var ts; function parseJsxExpression(inExpressionContext) { var node = createNode(248); parseExpected(15); - if (token() !== 16) { + if (token !== 16) { node.expression = parseAssignmentExpressionOrHigher(); } if (inExpressionContext) { @@ -10952,14 +9795,14 @@ var ts; return finishNode(node); } function parseJsxAttribute() { - if (token() === 15) { + if (token === 15) { return parseJsxSpreadAttribute(); } scanJsxIdentifier(); var node = createNode(246); node.name = parseIdentifierName(); if (parseOptional(56)) { - switch (token()) { + switch (token) { case 9: node.initializer = parseLiteralNode(); break; @@ -11009,7 +9852,7 @@ var ts; expression = finishNode(propertyAccess); continue; } - if (token() === 49 && !scanner.hasPrecedingLineBreak()) { + if (token === 49 && !scanner.hasPrecedingLineBreak()) { nextToken(); var nonNullExpression = createNode(196, expression.pos); nonNullExpression.expression = expression; @@ -11019,7 +9862,7 @@ var ts; if (!inDecoratorContext() && parseOptional(19)) { var indexedAccess = createNode(173, expression.pos); indexedAccess.expression = expression; - if (token() !== 20) { + if (token !== 20) { indexedAccess.argumentExpression = allowInAnd(parseExpression); if (indexedAccess.argumentExpression.kind === 9 || indexedAccess.argumentExpression.kind === 8) { var literal = indexedAccess.argumentExpression; @@ -11030,10 +9873,10 @@ var ts; expression = finishNode(indexedAccess); continue; } - if (token() === 11 || token() === 12) { + if (token === 11 || token === 12) { var tagExpression = createNode(176, expression.pos); tagExpression.tag = expression; - tagExpression.template = token() === 11 + tagExpression.template = token === 11 ? parseLiteralNode() : parseTemplateExpression(); expression = finishNode(tagExpression); @@ -11045,7 +9888,7 @@ var ts; function parseCallExpressionRest(expression) { while (true) { expression = parseMemberExpressionRest(expression); - if (token() === 25) { + if (token === 25) { var typeArguments = tryParse(parseTypeArgumentsInExpression); if (!typeArguments) { return expression; @@ -11057,7 +9900,7 @@ var ts; expression = finishNode(callExpr); continue; } - else if (token() === 17) { + else if (token === 17) { var callExpr = createNode(174, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); @@ -11086,7 +9929,7 @@ var ts; : undefined; } function canFollowTypeArgumentsInExpression() { - switch (token()) { + switch (token) { case 17: case 21: case 18: @@ -11113,7 +9956,7 @@ var ts; } } function parsePrimaryExpression() { - switch (token()) { + switch (token) { case 8: case 9: case 11: @@ -11166,8 +10009,8 @@ var ts; return finishNode(node); } function parseArgumentOrArrayLiteralElement() { - return token() === 22 ? parseSpreadElement() : - token() === 24 ? createNode(193) : + return token === 22 ? parseSpreadElement() : + token === 24 ? createNode(193) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { @@ -11204,10 +10047,10 @@ var ts; var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); var questionToken = parseOptionalToken(53); - if (asteriskToken || token() === 17 || token() === 25) { + if (asteriskToken || token === 17 || token === 25) { return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); } - var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 24 || token() === 16 || token() === 56); + var isShorthandPropertyAssignment = tokenIsIdentifier && (token === 24 || token === 16 || token === 56); if (isShorthandPropertyAssignment) { var shorthandDeclaration = createNode(254, fullStart); shorthandDeclaration.name = propertyName; @@ -11270,7 +10113,7 @@ var ts; parseExpected(92); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); - if (node.typeArguments || token() === 17) { + if (node.typeArguments || token === 17) { node.arguments = parseArgumentList(); } return finishNode(node); @@ -11343,8 +10186,8 @@ var ts; parseExpected(86); parseExpected(17); var initializer = undefined; - if (token() !== 23) { - if (token() === 102 || token() === 108 || token() === 74) { + if (token !== 23) { + if (token === 102 || token === 108 || token === 74) { initializer = parseVariableDeclarationList(true); } else { @@ -11370,11 +10213,11 @@ var ts; var forStatement = createNode(206, pos); forStatement.initializer = initializer; parseExpected(23); - if (token() !== 23 && token() !== 18) { + if (token !== 23 && token !== 18) { forStatement.condition = allowInAnd(parseExpression); } parseExpected(23); - if (token() !== 18) { + if (token !== 18) { forStatement.incrementor = allowInAnd(parseExpression); } parseExpected(18); @@ -11426,7 +10269,7 @@ var ts; return finishNode(node); } function parseCaseOrDefaultClause() { - return token() === 71 ? parseCaseClause() : parseDefaultClause(); + return token === 71 ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { var node = createNode(213); @@ -11452,8 +10295,8 @@ var ts; var node = createNode(216); parseExpected(100); node.tryBlock = parseBlock(false); - node.catchClause = token() === 72 ? parseCatchClause() : undefined; - if (!node.catchClause || token() === 85) { + node.catchClause = token === 72 ? parseCatchClause() : undefined; + if (!node.catchClause || token === 85) { parseExpected(85); node.finallyBlock = parseBlock(false); } @@ -11493,19 +10336,19 @@ var ts; } function nextTokenIsIdentifierOrKeywordOnSameLine() { nextToken(); - return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak(); + return ts.tokenIsIdentifierOrKeyword(token) && !scanner.hasPrecedingLineBreak(); } function nextTokenIsFunctionKeywordOnSameLine() { nextToken(); - return token() === 87 && !scanner.hasPrecedingLineBreak(); + return token === 87 && !scanner.hasPrecedingLineBreak(); } function nextTokenIsIdentifierOrKeywordOrNumberOnSameLine() { nextToken(); - return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8) && !scanner.hasPrecedingLineBreak(); + return (ts.tokenIsIdentifierOrKeyword(token) || token === 8) && !scanner.hasPrecedingLineBreak(); } function isDeclaration() { while (true) { - switch (token()) { + switch (token) { case 102: case 108: case 74: @@ -11533,16 +10376,16 @@ var ts; continue; case 137: nextToken(); - return token() === 15 || token() === 69 || token() === 82; + return token === 15 || token === 69 || token === 82; case 89: nextToken(); - return token() === 9 || token() === 37 || - token() === 15 || ts.tokenIsIdentifierOrKeyword(token()); + return token === 9 || token === 37 || + token === 15 || ts.tokenIsIdentifierOrKeyword(token); case 82: nextToken(); - if (token() === 56 || token() === 37 || - token() === 15 || token() === 77 || - token() === 116) { + if (token === 56 || token === 37 || + token === 15 || token === 77 || + token === 116) { return true; } continue; @@ -11558,7 +10401,7 @@ var ts; return lookAhead(isDeclaration); } function isStartOfStatement() { - switch (token()) { + switch (token) { case 55: case 23: case 15: @@ -11606,13 +10449,13 @@ var ts; } function nextTokenIsIdentifierOrStartOfDestructuring() { nextToken(); - return isIdentifier() || token() === 15 || token() === 19; + return isIdentifier() || token === 15 || token === 19; } function isLetDeclaration() { return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); } function parseStatement() { - switch (token()) { + switch (token) { case 23: return parseEmptyStatement(); case 15: @@ -11684,7 +10527,7 @@ var ts; var fullStart = getNodePos(); var decorators = parseDecorators(); var modifiers = parseModifiers(); - switch (token()) { + switch (token) { case 102: case 108: case 74: @@ -11707,7 +10550,7 @@ var ts; return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); case 82: nextToken(); - switch (token()) { + switch (token) { case 77: case 56: return parseExportAssignment(fullStart, decorators, modifiers); @@ -11728,17 +10571,17 @@ var ts; } function nextTokenIsIdentifierOrStringLiteralOnSameLine() { nextToken(); - return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9); + return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token === 9); } function parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage) { - if (token() !== 15 && canParseSemicolon()) { + if (token !== 15 && canParseSemicolon()) { parseSemicolon(); return; } return parseFunctionBlock(isGenerator, isAsync, false, diagnosticMessage); } function parseArrayBindingElement() { - if (token() === 24) { + if (token === 24) { return createNode(193); } var node = createNode(169); @@ -11751,7 +10594,7 @@ var ts; var node = createNode(169); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); - if (tokenIsIdentifier && token() !== 54) { + if (tokenIsIdentifier && token !== 54) { node.name = propertyName; } else { @@ -11777,13 +10620,13 @@ var ts; return finishNode(node); } function isIdentifierOrPattern() { - return token() === 15 || token() === 19 || isIdentifier(); + return token === 15 || token === 19 || isIdentifier(); } function parseIdentifierOrPattern() { - if (token() === 19) { + if (token === 19) { return parseArrayBindingPattern(); } - if (token() === 15) { + if (token === 15) { return parseObjectBindingPattern(); } return parseIdentifier(); @@ -11792,14 +10635,14 @@ var ts; var node = createNode(218); node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); - if (!isInOrOfKeyword(token())) { + if (!isInOrOfKeyword(token)) { node.initializer = parseInitializer(false); } return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { var node = createNode(219); - switch (token()) { + switch (token) { case 102: break; case 108: @@ -11812,7 +10655,7 @@ var ts; ts.Debug.fail(); } nextToken(); - if (token() === 138 && lookAhead(canFollowContextualOfKeyword)) { + if (token === 138 && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { @@ -11886,7 +10729,7 @@ var ts; var asteriskToken = parseOptionalToken(37); var name = parsePropertyName(); var questionToken = parseOptionalToken(53); - if (asteriskToken || token() === 17 || token() === 25) { + if (asteriskToken || token === 17 || token === 25) { return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, ts.Diagnostics.or_expected); } else { @@ -11919,31 +10762,31 @@ var ts; } function isClassMemberStart() { var idToken; - if (token() === 55) { + if (token === 55) { return true; } - while (ts.isModifierKind(token())) { - idToken = token(); + while (ts.isModifierKind(token)) { + idToken = token; if (isClassMemberModifier(idToken)) { return true; } nextToken(); } - if (token() === 37) { + if (token === 37) { return true; } if (isLiteralPropertyName()) { - idToken = token(); + idToken = token; nextToken(); } - if (token() === 19) { + if (token === 19) { return true; } if (idToken !== undefined) { if (!ts.isKeyword(idToken) || idToken === 131 || idToken === 123) { return true; } - switch (token()) { + switch (token) { case 17: case 25: case 54: @@ -11981,8 +10824,8 @@ var ts; var modifiers; while (true) { var modifierStart = scanner.getStartPos(); - var modifierKind = token(); - if (token() === 74 && permitInvalidConstAsModifier) { + var modifierKind = token; + if (token === 74 && permitInvalidConstAsModifier) { if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { break; } @@ -12008,9 +10851,9 @@ var ts; function parseModifiersForArrowFunction() { var flags = 0; var modifiers; - if (token() === 118) { + if (token === 118) { var modifierStart = scanner.getStartPos(); - var modifierKind = token(); + var modifierKind = token; nextToken(); modifiers = []; modifiers.pos = modifierStart; @@ -12022,7 +10865,7 @@ var ts; return modifiers; } function parseClassElement() { - if (token() === 23) { + if (token === 23) { var result = createNode(198); nextToken(); return finishNode(result); @@ -12034,22 +10877,22 @@ var ts; if (accessor) { return accessor; } - if (token() === 121) { + if (token === 121) { return parseConstructorDeclaration(fullStart, decorators, modifiers); } if (isIndexSignature()) { return parseIndexSignatureDeclaration(fullStart, decorators, modifiers); } - if (ts.tokenIsIdentifierOrKeyword(token()) || - token() === 9 || - token() === 8 || - token() === 37 || - token() === 19) { + if (ts.tokenIsIdentifierOrKeyword(token) || + token === 9 || + token === 8 || + token === 37 || + token === 19) { return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); } if (decorators || modifiers) { - var name_10 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name_10, undefined); + var name_8 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(fullStart, decorators, modifiers, name_8, undefined); } ts.Debug.fail("Should not have attempted to parse class member declaration."); } @@ -12082,7 +10925,7 @@ var ts; : undefined; } function isImplementsClause() { - return token() === 106 && lookAhead(nextTokenIsIdentifierOrKeyword); + return token === 106 && lookAhead(nextTokenIsIdentifierOrKeyword); } function parseHeritageClauses(isClassHeritageClause) { if (isHeritageClause()) { @@ -12091,9 +10934,9 @@ var ts; return undefined; } function parseHeritageClause() { - if (token() === 83 || token() === 106) { + if (token === 83 || token === 106) { var node = createNode(251); - node.token = token(); + node.token = token; nextToken(); node.types = parseDelimitedList(7, parseExpressionWithTypeArguments); return finishNode(node); @@ -12103,13 +10946,13 @@ var ts; function parseExpressionWithTypeArguments() { var node = createNode(194); node.expression = parseLeftHandSideExpressionOrHigher(); - if (token() === 25) { + if (token === 25) { node.typeArguments = parseBracketedList(18, parseType, 25, 27); } return finishNode(node); } function isHeritageClause() { - return token() === 83 || token() === 106; + return token === 83 || token === 106; } function parseClassMembers() { return parseList(5, parseClassElement); @@ -12185,14 +11028,14 @@ var ts; var node = createNode(225, fullStart); node.decorators = decorators; setModifiers(node, modifiers); - if (token() === 137) { + if (token === 137) { node.name = parseIdentifier(); node.flags |= 131072; } else { node.name = parseLiteralNode(true); } - if (token() === 15) { + if (token === 15) { node.body = parseModuleBlock(); } else { @@ -12202,7 +11045,7 @@ var ts; } function parseModuleDeclaration(fullStart, decorators, modifiers) { var flags = modifiers ? modifiers.flags : 0; - if (token() === 137) { + if (token === 137) { return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } else if (parseOptional(126)) { @@ -12210,14 +11053,14 @@ var ts; } else { parseExpected(125); - if (token() === 9) { + if (token === 9) { return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } } return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); } function isExternalModuleReference() { - return token() === 129 && + return token === 129 && lookAhead(nextTokenIsOpenParen); } function nextTokenIsOpenParen() { @@ -12242,7 +11085,7 @@ var ts; var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token() !== 24 && token() !== 136) { + if (token !== 24 && token !== 136) { var importEqualsDeclaration = createNode(229, fullStart); importEqualsDeclaration.decorators = decorators; setModifiers(importEqualsDeclaration, modifiers); @@ -12257,8 +11100,8 @@ var ts; importDeclaration.decorators = decorators; setModifiers(importDeclaration, modifiers); if (identifier || - token() === 37 || - token() === 15) { + token === 37 || + token === 15) { importDeclaration.importClause = parseImportClause(identifier, afterImportPos); parseExpected(136); } @@ -12273,7 +11116,7 @@ var ts; } if (!importClause.name || parseOptional(24)) { - importClause.namedBindings = token() === 37 ? parseNamespaceImport() : parseNamedImportsOrExports(233); + importClause.namedBindings = token === 37 ? parseNamespaceImport() : parseNamedImportsOrExports(233); } return finishNode(importClause); } @@ -12291,7 +11134,7 @@ var ts; return finishNode(node); } function parseModuleSpecifier() { - if (token() === 9) { + if (token === 9) { var result = parseLiteralNode(); internIdentifier(result.text); return result; @@ -12320,14 +11163,14 @@ var ts; } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); - var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); + var checkIdentifierIsKeyword = ts.isKeyword(token) && !isIdentifier(); var checkIdentifierStart = scanner.getTokenPos(); var checkIdentifierEnd = scanner.getTextPos(); var identifierName = parseIdentifierName(); - if (token() === 116) { + if (token === 116) { node.propertyName = identifierName; parseExpected(116); - checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); + checkIdentifierIsKeyword = ts.isKeyword(token) && !isIdentifier(); checkIdentifierStart = scanner.getTokenPos(); checkIdentifierEnd = scanner.getTextPos(); node.name = parseIdentifierName(); @@ -12350,7 +11193,7 @@ var ts; } else { node.exportClause = parseNamedImportsOrExports(237); - if (token() === 136 || (token() === 9 && !scanner.hasPrecedingLineBreak())) { + if (token === 136 || (token === 9 && !scanner.hasPrecedingLineBreak())) { parseExpected(136); node.moduleSpecifier = parseModuleSpecifier(); } @@ -12449,7 +11292,7 @@ var ts; var JSDocParser; (function (JSDocParser) { function isJSDocType() { - switch (token()) { + switch (token) { case 37: case 53: case 17: @@ -12462,13 +11305,13 @@ var ts; case 97: return true; } - return ts.tokenIsIdentifierOrKeyword(token()); + return ts.tokenIsIdentifierOrKeyword(token); } JSDocParser.isJSDocType = isJSDocType; function parseJSDocTypeExpressionForTests(content, start, length) { initializeState("file.js", content, 2, undefined, 1); scanner.setText(content, start, length); - currentToken = scanner.scan(); + token = scanner.scan(); var jsDocTypeExpression = parseJSDocTypeExpression(); var diagnostics = parseDiagnostics; clearState(); @@ -12486,12 +11329,12 @@ var ts; JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression; function parseJSDocTopLevelType() { var type = parseJSDocType(); - if (token() === 47) { + if (token === 47) { var unionType = createNode(261, type.pos); unionType.types = parseJSDocTypeList(type); type = finishNode(unionType); } - if (token() === 56) { + if (token === 56) { var optionalType = createNode(268, type.pos); nextToken(); optionalType.type = type; @@ -12502,20 +11345,20 @@ var ts; function parseJSDocType() { var type = parseBasicTypeExpression(); while (true) { - if (token() === 19) { + if (token === 19) { var arrayType = createNode(260, type.pos); arrayType.elementType = type; nextToken(); parseExpected(20); type = finishNode(arrayType); } - else if (token() === 53) { + else if (token === 53) { var nullableType = createNode(263, type.pos); nullableType.type = type; nextToken(); type = finishNode(nullableType); } - else if (token() === 49) { + else if (token === 49) { var nonNullableType = createNode(264, type.pos); nonNullableType.type = type; nextToken(); @@ -12528,7 +11371,7 @@ var ts; return type; } function parseBasicTypeExpression() { - switch (token()) { + switch (token) { case 37: return parseJSDocAllType(); case 53: @@ -12555,15 +11398,7 @@ var ts; case 120: case 133: case 103: - case 93: - case 135: - case 127: return parseTokenNode(); - case 9: - case 8: - case 99: - case 84: - return parseJSDocLiteralType(); } return parseJSDocTypeReference(); } @@ -12594,7 +11429,7 @@ var ts; result.parameters = parseDelimitedList(22, parseJSDocParameter); checkForTrailingComma(result.parameters); parseExpected(18); - if (token() === 54) { + if (token === 54) { nextToken(); result.type = parseJSDocType(); } @@ -12611,12 +11446,12 @@ var ts; function parseJSDocTypeReference() { var result = createNode(267); result.name = parseSimplePropertyName(); - if (token() === 25) { + if (token === 25) { result.typeArguments = parseTypeArguments(); } else { while (parseOptional(21)) { - if (token() === 25) { + if (token === 25) { result.typeArguments = parseTypeArguments(); break; } @@ -12659,7 +11494,7 @@ var ts; function parseJSDocRecordMember() { var result = createNode(266); result.name = parseSimplePropertyName(); - if (token() === 54) { + if (token === 54) { nextToken(); result.type = parseJSDocType(); } @@ -12708,20 +11543,15 @@ var ts; nextToken(); return finishNode(result); } - function parseJSDocLiteralType() { - var result = createNode(282); - result.literal = parseLiteralTypeNode(); - return finishNode(result); - } function parseJSDocUnknownOrNullableType() { var pos = scanner.getStartPos(); nextToken(); - if (token() === 24 || - token() === 16 || - token() === 18 || - token() === 27 || - token() === 56 || - token() === 47) { + if (token === 24 || + token === 16 || + token === 18 || + token === 27 || + token === 56 || + token === 47) { var result = createNode(259, pos); return finishNode(result); } @@ -12741,14 +11571,14 @@ var ts; } JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; function parseJSDocComment(parent, start, length) { - var saveToken = currentToken; + var saveToken = token; var saveParseDiagnosticsLength = parseDiagnostics.length; var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; var comment = parseJSDocCommentWorker(start, length); if (comment) { comment.parent = parent; } - currentToken = saveToken; + token = saveToken; parseDiagnostics.length = saveParseDiagnosticsLength; parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; return comment; @@ -12772,8 +11602,8 @@ var ts; var canParseTag = true; var seenAsterisk = true; nextJSDocToken(); - while (token() !== 1) { - switch (token()) { + while (token !== 1) { + switch (token) { case 55: if (canParseTag) { parseTag(); @@ -12811,12 +11641,12 @@ var ts; return finishNode(result, end); } function skipWhitespace() { - while (token() === 5 || token() === 4) { + while (token === 5 || token === 4) { nextJSDocToken(); } } function parseTag() { - ts.Debug.assert(token() === 55); + ts.Debug.assert(token === 55); var atToken = createNode(55, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); @@ -12862,7 +11692,7 @@ var ts; } } function tryParseTypeExpression() { - if (token() !== 15) { + if (token !== 15) { return undefined; } var typeExpression = parseJSDocTypeExpression(); @@ -12881,7 +11711,7 @@ var ts; } parseExpected(20); } - else if (ts.tokenIsIdentifierOrKeyword(token())) { + else if (ts.tokenIsIdentifierOrKeyword(token)) { name = parseJSDocIdentifierName(); } if (!name) { @@ -12954,8 +11784,8 @@ var ts; if (typeExpression.type.kind === 267) { var jsDocTypeReference = typeExpression.type; if (jsDocTypeReference.name.kind === 69) { - var name_11 = jsDocTypeReference.name; - if (name_11.text === "Object") { + var name_9 = jsDocTypeReference.name; + if (name_9.text === "Object") { typedefTag.jsDocTypeLiteral = scanChildTags(); } } @@ -12974,15 +11804,12 @@ var ts; var canParseTag = true; var seenAsterisk = false; var parentTagTerminated = false; - while (token() !== 1 && !parentTagTerminated) { + while (token !== 1 && !parentTagTerminated) { nextJSDocToken(); - switch (token()) { + switch (token) { case 55: if (canParseTag) { parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral); - if (!parentTagTerminated) { - resumePos = scanner.getStartPos(); - } } seenAsterisk = false; break; @@ -13008,7 +11835,7 @@ var ts; } } function tryParseChildTag(parentTag) { - ts.Debug.assert(token() === 55); + ts.Debug.assert(token === 55); var atToken = createNode(55, scanner.getStartPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); @@ -13041,16 +11868,16 @@ var ts; var typeParameters = []; typeParameters.pos = scanner.getStartPos(); while (true) { - var name_12 = parseJSDocIdentifierName(); - if (!name_12) { + var name_10 = parseJSDocIdentifierName(); + if (!name_10) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(141, name_12.pos); - typeParameter.name = name_12; + var typeParameter = createNode(141, name_10.pos); + typeParameter.name = name_10; finishNode(typeParameter); typeParameters.push(typeParameter); - if (token() === 24) { + if (token === 24) { nextJSDocToken(); } else { @@ -13066,10 +11893,10 @@ var ts; return result; } function nextJSDocToken() { - return currentToken = scanner.scanJSDocToken(); + return token = scanner.scanJSDocToken(); } function parseJSDocIdentifierName() { - return createJSDocIdentifier(ts.tokenIsIdentifierOrKeyword(token())); + return createJSDocIdentifier(ts.tokenIsIdentifierOrKeyword(token)); } function createJSDocIdentifier(isIdentifier) { if (!isIdentifier) { @@ -13149,8 +11976,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { - var node = array_9[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } } @@ -13222,8 +12049,8 @@ var ts; array.intersectsChange = true; array._children = undefined; adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_10 = array; _i < array_10.length; _i++) { - var node = array_10[_i]; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; visitNode(node); } return; @@ -13375,6 +12202,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + ts.bindTime = 0; function getModuleInstanceState(node) { if (node.kind === 222 || node.kind === 223) { return 0; @@ -13412,10 +12240,9 @@ var ts; ts.getModuleInstanceState = getModuleInstanceState; var binder = createBinder(); function bindSourceFile(file, options) { - ts.performance.mark("beforeBind"); + var start = new Date().getTime(); binder(file, options); - ts.performance.mark("afterBind"); - ts.performance.measure("Bind", "beforeBind", "afterBind"); + ts.bindTime += new Date().getTime() - start; } ts.bindSourceFile = bindSourceFile; function createBinder() { @@ -13448,7 +12275,7 @@ var ts; options = opts; languageVersion = ts.getEmitScriptTarget(options); inStrictMode = !!file.externalModuleIndicator; - classifiableNames = ts.createMap(); + classifiableNames = {}; symbolCount = 0; Symbol = ts.objectAllocator.getSymbolConstructor(); if (!file.locals) { @@ -13487,10 +12314,10 @@ var ts; } symbol.declarations.push(node); if (symbolFlags & 1952 && !symbol.exports) { - symbol.exports = ts.createMap(); + symbol.exports = {}; } if (symbolFlags & 6240 && !symbol.members) { - symbol.members = ts.createMap(); + symbol.members = {}; } if (symbolFlags & 107455) { var valueDeclaration = symbol.valueDeclaration; @@ -13574,38 +12401,35 @@ var ts; var isDefaultExport = node.flags & 512; var name = isDefaultExport && parent ? "default" : getDeclarationName(node); var symbol; - if (name === undefined) { - symbol = createSymbol(0, "__missing"); - } - else { - symbol = symbolTable[name] || (symbolTable[name] = createSymbol(0, name)); + if (name !== undefined) { + symbol = ts.hasProperty(symbolTable, name) + ? symbolTable[name] + : (symbolTable[name] = createSymbol(0, name)); if (name && (includes & 788448)) { classifiableNames[name] = name; } if (symbol.flags & excludes) { - if (symbol.isReplaceableByMethod) { - symbol = symbolTable[name] = createSymbol(0, name); + if (node.name) { + node.name.parent = node; } - else { - if (node.name) { - node.name.parent = node; + var message_1 = symbol.flags & 2 + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + : ts.Diagnostics.Duplicate_identifier_0; + ts.forEach(symbol.declarations, function (declaration) { + if (declaration.flags & 512) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; } - var message_1 = symbol.flags & 2 - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - ts.forEach(symbol.declarations, function (declaration) { - if (declaration.flags & 512) { - message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; - } - }); - ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); - }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); - symbol = createSymbol(0, name); - } + }); + ts.forEach(symbol.declarations, function (declaration) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); + }); + file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); + symbol = createSymbol(0, name); } } + else { + symbol = createSymbol(0, "__missing"); + } addDeclarationToSymbol(symbol, node, includes); symbol.parent = parent; return symbol; @@ -13623,8 +12447,8 @@ var ts; else { if (!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 8192)) { var exportKind = (symbolFlags & 107455 ? 1048576 : 0) | - (symbolFlags & 793064 ? 2097152 : 0) | - (symbolFlags & 1920 ? 4194304 : 0); + (symbolFlags & 793056 ? 2097152 : 0) | + (symbolFlags & 1536 ? 4194304 : 0); var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; @@ -13641,7 +12465,7 @@ var ts; if (containerFlags & 1) { container = blockScopeContainer = node; if (containerFlags & 32) { - container.locals = ts.createMap(); + container.locals = {}; } addToContainerChain(container); } @@ -13816,9 +12640,15 @@ var ts; } return false; } + function isNarrowingNullCheckOperands(expr1, expr2) { + return (expr1.kind === 93 || expr1.kind === 69 && expr1.text === "undefined") && isNarrowableOperand(expr2); + } function isNarrowingTypeofOperands(expr1, expr2) { return expr1.kind === 182 && isNarrowableOperand(expr1.expression) && expr2.kind === 9; } + function isNarrowingDiscriminant(expr) { + return expr.kind === 172 && isNarrowableReference(expr.expression); + } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { case 56: @@ -13827,8 +12657,9 @@ var ts; case 31: case 32: case 33: - return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || - isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); + return isNarrowingNullCheckOperands(expr.right, expr.left) || isNarrowingNullCheckOperands(expr.left, expr.right) || + isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right) || + isNarrowingDiscriminant(expr.left) || isNarrowingDiscriminant(expr.right); case 91: return isNarrowableOperand(expr.left); case 24: @@ -13850,6 +12681,10 @@ var ts; } return isNarrowableReference(expr); } + function isNarrowingSwitchStatement(switchStatement) { + var expr = switchStatement.expression; + return expr.kind === 172 && isNarrowableReference(expr.expression); + } function createBranchLabel() { return { flags: 4, @@ -13893,7 +12728,7 @@ var ts; }; } function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { - if (!isNarrowingExpression(switchStatement.expression)) { + if (!isNarrowingSwitchStatement(switchStatement)) { return antecedent; } setFlowNodeReferenced(antecedent); @@ -14481,12 +13316,12 @@ var ts; addDeclarationToSymbol(symbol, node, 131072); var typeLiteralSymbol = createSymbol(2048, "__type"); addDeclarationToSymbol(typeLiteralSymbol, node, 2048); - typeLiteralSymbol.members = ts.createMap(); - typeLiteralSymbol.members[symbol.name] = symbol; + typeLiteralSymbol.members = (_a = {}, _a[symbol.name] = symbol, _a); + var _a; } function bindObjectLiteralExpression(node) { if (inStrictMode) { - var seen = ts.createMap(); + var seen = {}; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; if (prop.name.kind !== 69) { @@ -14525,7 +13360,7 @@ var ts; } default: if (!blockScopeContainer.locals) { - blockScopeContainer.locals = ts.createMap(); + blockScopeContainer.locals = {}; addToContainerChain(blockScopeContainer); } declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); @@ -14738,7 +13573,7 @@ var ts; case 154: return checkTypePredicate(node); case 141: - return declareSymbolAndAddToSymbolTable(node, 262144, 530920); + return declareSymbolAndAddToSymbolTable(node, 262144, 530912); case 142: return bindParameter(node); case 218: @@ -14754,7 +13589,7 @@ var ts; case 254: return bindPropertyOrMethodOrAccessor(node, 4, 0); case 255: - return bindPropertyOrMethodOrAccessor(node, 8, 900095); + return bindPropertyOrMethodOrAccessor(node, 8, 107455); case 247: emitFlags |= 1073741824; return; @@ -14796,10 +13631,10 @@ var ts; inStrictMode = true; return bindClassLikeDeclaration(node); case 222: - return bindBlockScopedDeclaration(node, 64, 792968); + return bindBlockScopedDeclaration(node, 64, 792960); case 279: case 223: - return bindBlockScopedDeclaration(node, 524288, 793064); + return bindBlockScopedDeclaration(node, 524288, 793056); case 224: return bindEnumDeclaration(node); case 225: @@ -14848,14 +13683,15 @@ var ts; bindAnonymousDeclaration(file, 512, "\"" + ts.removeFileExtension(file.fileName) + "\""); } function bindExportAssignment(node) { + var boundExpression = node.kind === 235 ? node.expression : node.right; if (!container.symbol || !container.symbol.exports) { bindAnonymousDeclaration(node, 8388608, getDeclarationName(node)); } + else if (boundExpression.kind === 69 && node.kind === 235) { + declareSymbol(container.symbol.exports, container.symbol, node, 8388608, 0 | 8388608); + } else { - var flags = node.kind === 235 && ts.exportAssignmentIsAlias(node) - ? 8388608 - : 4; - declareSymbol(container.symbol.exports, container.symbol, node, flags, 0 | 8388608); + declareSymbol(container.symbol.exports, container.symbol, node, 4, 0 | 8388608); } } function bindNamespaceExportDeclaration(node) { @@ -14877,7 +13713,7 @@ var ts; return; } } - file.symbol.globalExports = file.symbol.globalExports || ts.createMap(); + file.symbol.globalExports = file.symbol.globalExports || {}; declareSymbol(file.symbol.globalExports, file.symbol, node, 8388608, 8388608); } function bindExportDeclaration(node) { @@ -14908,20 +13744,18 @@ var ts; declareSymbol(file.symbol.exports, file.symbol, node, 4 | 7340032 | 512, 0); } function bindThisPropertyAssignment(node) { - ts.Debug.assert(ts.isInJavaScriptFile(node)); - if (container.kind === 220 || container.kind === 179) { - container.symbol.members = container.symbol.members || ts.createMap(); - declareSymbol(container.symbol.members, container.symbol, node, 4, 0 & ~4); + var assignee; + if (container.kind === 220 || container.kind === 220) { + assignee = container; } else if (container.kind === 148) { - var saveContainer = container; - container = container.parent; - var symbol = bindPropertyOrMethodOrAccessor(node, 4, 0); - if (symbol) { - symbol.isReplaceableByMethod = true; - } - container = saveContainer; + assignee = container.parent; } + else { + return; + } + assignee.symbol.members = assignee.symbol.members || {}; + declareSymbol(assignee.symbol.members, assignee.symbol, node, 4, 0 & ~4); } function bindPrototypePropertyAssignment(node) { var leftSideOfAssignment = node.left; @@ -14935,7 +13769,7 @@ var ts; return; } if (!funcSymbol.members) { - funcSymbol.members = ts.createMap(); + funcSymbol.members = {}; } declareSymbol(funcSymbol.members, funcSymbol, leftSideOfAssignment, 4, 0); } @@ -14965,7 +13799,7 @@ var ts; } var symbol = node.symbol; var prototypeSymbol = createSymbol(4 | 134217728, "prototype"); - if (symbol.exports[prototypeSymbol.name]) { + if (ts.hasProperty(symbol.exports, prototypeSymbol.name)) { if (node.name) { node.name.parent = node; } @@ -15090,7 +13924,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var ambientModuleSymbolRegex = /^".+"$/; var nextSymbolId = 1; var nextNodeId = 1; var nextMergeId = 1; @@ -15103,6 +13936,7 @@ var ts; return node.id; } ts.getNodeId = getNodeId; + ts.checkTime = 0; function getSymbolId(symbol) { if (!symbol.id) { symbol.id = nextSymbolId; @@ -15119,7 +13953,7 @@ var ts; var typeCount = 0; var symbolCount = 0; var emptyArray = []; - var emptySymbols = ts.createMap(); + var emptySymbols = {}; var compilerOptions = host.getCompilerOptions(); var languageVersion = compilerOptions.target || 0; var modulekind = ts.getEmitModuleKind(compilerOptions); @@ -15171,43 +14005,34 @@ var ts; getAliasedSymbol: resolveAlias, getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, - getAmbientModules: getAmbientModules, getJsxElementAttributesType: getJsxElementAttributesType, getJsxIntrinsicTagNames: getJsxIntrinsicTagNames, isOptionalParameter: isOptionalParameter }; - var tupleTypes = []; - var unionTypes = ts.createMap(); - var intersectionTypes = ts.createMap(); - var stringLiteralTypes = ts.createMap(); - var numericLiteralTypes = ts.createMap(); var unknownSymbol = createSymbol(4 | 67108864, "unknown"); var resolvingSymbol = createSymbol(67108864, "__resolving__"); var anyType = createIntrinsicType(1, "any"); - var unknownType = createIntrinsicType(1, "unknown"); - var undefinedType = createIntrinsicType(2048, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 | 33554432, "undefined"); - var nullType = createIntrinsicType(4096, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(4096 | 33554432, "null"); var stringType = createIntrinsicType(2, "string"); var numberType = createIntrinsicType(4, "number"); - var trueType = createIntrinsicType(128, "true"); - var falseType = createIntrinsicType(128, "false"); - var booleanType = createBooleanType([trueType, falseType]); - var esSymbolType = createIntrinsicType(512, "symbol"); - var voidType = createIntrinsicType(1024, "void"); - var neverType = createIntrinsicType(8192, "never"); + var booleanType = createIntrinsicType(8, "boolean"); + var esSymbolType = createIntrinsicType(16777216, "symbol"); + var voidType = createIntrinsicType(16, "void"); + var undefinedType = createIntrinsicType(32, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32 | 2097152, "undefined"); + var nullType = createIntrinsicType(64, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(64 | 2097152, "null"); + var unknownType = createIntrinsicType(1, "unknown"); + var neverType = createIntrinsicType(134217728, "never"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - emptyGenericType.instantiations = ts.createMap(); + emptyGenericType.instantiations = {}; var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - anyFunctionType.flags |= 134217728; + anyFunctionType.flags |= 8388608; var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var anySignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, undefined, 0, false, false); var unknownSignature = createSignature(undefined, undefined, undefined, emptyArray, unknownType, undefined, 0, false, false); - var resolvingSignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, undefined, 0, false, false); var enumNumberIndexInfo = createIndexInfo(stringType, true); - var globals = ts.createMap(); + var globals = {}; var patternAmbientModules; var getGlobalESSymbolConstructorSymbol; var getGlobalPromiseConstructorSymbol; @@ -15243,8 +14068,10 @@ var ts; var flowLoopStart = 0; var flowLoopCount = 0; var visitedFlowCount = 0; - var emptyStringType = getLiteralTypeForText(32, ""); - var zeroType = getLiteralTypeForText(64, "0"); + var tupleTypes = {}; + var unionTypes = {}; + var intersectionTypes = {}; + var stringLiteralTypes = {}; var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; @@ -15260,7 +14087,7 @@ var ts; var potentialThisCollisions = []; var awaitedTypeStack = []; var diagnostics = ts.createDiagnosticCollection(); - var typeofEQFacts = ts.createMap({ + var typeofEQFacts = { "string": 1, "number": 2, "boolean": 4, @@ -15268,8 +14095,8 @@ var ts; "undefined": 16384, "object": 16, "function": 32 - }); - var typeofNEFacts = ts.createMap({ + }; + var typeofNEFacts = { "string": 128, "number": 256, "boolean": 512, @@ -15277,16 +14104,16 @@ var ts; "undefined": 131072, "object": 2048, "function": 4096 - }); - var typeofTypesByName = ts.createMap({ + }; + var typeofTypesByName = { "string": stringType, "number": numberType, "boolean": booleanType, "symbol": esSymbolType, "undefined": undefinedType - }); + }; var jsxElementType; - var jsxTypes = ts.createMap(); + var jsxTypes = {}; var JsxNames = { JSX: "JSX", IntrinsicElements: "IntrinsicElements", @@ -15296,14 +14123,15 @@ var ts; IntrinsicAttributes: "IntrinsicAttributes", IntrinsicClassAttributes: "IntrinsicClassAttributes" }; - var subtypeRelation = ts.createMap(); - var assignableRelation = ts.createMap(); - var comparableRelation = ts.createMap(); - var identityRelation = ts.createMap(); - var enumRelation = ts.createMap(); + var subtypeRelation = {}; + var assignableRelation = {}; + var comparableRelation = {}; + var identityRelation = {}; var _displayBuilder; - var builtinGlobals = ts.createMap(); - builtinGlobals[undefinedSymbol.name] = undefinedSymbol; + var builtinGlobals = (_a = {}, + _a[undefinedSymbol.name] = undefinedSymbol, + _a + ); initializeTypeChecker(); return checker; function getEmitResolver(sourceFile, cancellationToken) { @@ -15329,13 +14157,13 @@ var ts; if (flags & 4) result |= 0; if (flags & 8) - result |= 900095; + result |= 107455; if (flags & 16) result |= 106927; if (flags & 32) result |= 899519; if (flags & 64) - result |= 792968; + result |= 792960; if (flags & 256) result |= 899327; if (flags & 128) @@ -15349,9 +14177,9 @@ var ts; if (flags & 65536) result |= 74687; if (flags & 262144) - result |= 530920; + result |= 530912; if (flags & 524288) - result |= 793064; + result |= 793056; if (flags & 8388608) result |= 8388608; return result; @@ -15372,9 +14200,9 @@ var ts; if (symbol.constEnumOnlyModule) result.constEnumOnlyModule = true; if (symbol.members) - result.members = ts.cloneMap(symbol.members); + result.members = cloneSymbolTable(symbol.members); if (symbol.exports) - result.exports = ts.cloneMap(symbol.exports); + result.exports = cloneSymbolTable(symbol.exports); recordMergedSymbol(result, symbol); return result; } @@ -15394,12 +14222,12 @@ var ts; }); if (source.members) { if (!target.members) - target.members = ts.createMap(); + target.members = {}; mergeSymbolTable(target.members, source.members); } if (source.exports) { if (!target.exports) - target.exports = ts.createMap(); + target.exports = {}; mergeSymbolTable(target.exports, source.exports); } recordMergedSymbol(target, source); @@ -15415,17 +14243,28 @@ var ts; }); } } + function cloneSymbolTable(symbolTable) { + var result = {}; + for (var id in symbolTable) { + if (ts.hasProperty(symbolTable, id)) { + result[id] = symbolTable[id]; + } + } + return result; + } function mergeSymbolTable(target, source) { for (var id in source) { - var targetSymbol = target[id]; - if (!targetSymbol) { - target[id] = source[id]; - } - else { - if (!(targetSymbol.flags & 33554432)) { - target[id] = targetSymbol = cloneSymbol(targetSymbol); + if (ts.hasProperty(source, id)) { + if (!ts.hasProperty(target, id)) { + target[id] = source[id]; + } + else { + var symbol = target[id]; + if (!(symbol.flags & 33554432)) { + target[id] = symbol = cloneSymbol(symbol); + } + mergeSymbol(symbol, source[id]); } - mergeSymbol(targetSymbol, source[id]); } } } @@ -15447,7 +14286,7 @@ var ts; return; } mainModule = resolveExternalModuleSymbol(mainModule); - if (mainModule.flags & 1920) { + if (mainModule.flags & 1536) { mainModule = mainModule.flags & 33554432 ? mainModule : cloneSymbol(mainModule); mergeSymbol(mainModule, moduleAugmentation.symbol); } @@ -15458,11 +14297,13 @@ var ts; } function addToSymbolTable(target, source, message) { for (var id in source) { - if (target[id]) { - ts.forEach(target[id].declarations, addDeclarationDiagnostic(id, message)); - } - else { - target[id] = source[id]; + if (ts.hasProperty(source, id)) { + if (ts.hasProperty(target, id)) { + ts.forEach(target[id].declarations, addDeclarationDiagnostic(id, message)); + } + else { + target[id] = source[id]; + } } } function addDeclarationDiagnostic(id, message) { @@ -15477,25 +14318,23 @@ var ts; } function getNodeLinks(node) { var nodeId = getNodeId(node); - return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); + return nodeLinks[nodeId] || (nodeLinks[nodeId] = {}); } function isGlobalSourceFile(node) { return node.kind === 256 && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { - if (meaning) { + if (meaning && ts.hasProperty(symbols, name)) { var symbol = symbols[name]; - if (symbol) { - ts.Debug.assert((symbol.flags & 16777216) === 0, "Should never get an instantiated symbol here."); - if (symbol.flags & meaning) { + ts.Debug.assert((symbol.flags & 16777216) === 0, "Should never get an instantiated symbol here."); + if (symbol.flags & meaning) { + return symbol; + } + if (symbol.flags & 8388608) { + var target = resolveAlias(symbol); + if (target === unknownSymbol || target.flags & meaning) { return symbol; } - if (symbol.flags & 8388608) { - var target = resolveAlias(symbol); - if (target === unknownSymbol || target.flags & meaning) { - return symbol; - } - } } } } @@ -15579,7 +14418,7 @@ var ts; if (result = getSymbol(location.locals, name, meaning)) { var useResult = true; if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { - if (meaning & result.flags & 793064 && lastLocation.kind !== 273) { + if (meaning & result.flags & 793056 && lastLocation.kind !== 273) { useResult = result.flags & 262144 ? lastLocation === location.type || lastLocation.kind === 142 || @@ -15616,7 +14455,7 @@ var ts; } result = undefined; } - if (moduleExports[name] && + if (ts.hasProperty(moduleExports, name) && moduleExports[name].flags === 8388608 && ts.getDeclarationOfKind(moduleExports[name], 238)) { break; @@ -15645,7 +14484,7 @@ var ts; case 221: case 192: case 222: - if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064)) { + if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056)) { if (lastLocation && lastLocation.flags & 32) { error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); return undefined; @@ -15663,7 +14502,7 @@ var ts; case 140: grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 222) { - if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793064)) { + if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793056)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -15714,9 +14553,8 @@ var ts; } if (!result) { if (nameNotFoundMessage) { - if (!errorLocation || - !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && - !checkAndReportErrorForExtendingInterface(errorLocation)) { + if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForExtendingInterface(errorLocation)) { error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); } } @@ -15734,7 +14572,7 @@ var ts; checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } - if (result && isInExternalModule && (meaning & 107455) === 107455) { + if (result && isInExternalModule) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 228) { error(errorLocation, ts.Diagnostics.Identifier_0_must_be_imported_from_a_module, name); @@ -15744,7 +14582,7 @@ var ts; return result; } function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { - if ((errorLocation.kind === 69 && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { + if (!errorLocation || (errorLocation.kind === 69 && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { return false; } var container = ts.getThisContainer(errorLocation, true); @@ -15773,30 +14611,33 @@ var ts; return false; } function checkAndReportErrorForExtendingInterface(errorLocation) { - var expression = getEntityNameForExtendingInterface(errorLocation); - var isError = !!(expression && resolveEntityName(expression, 64, true)); - if (isError) { + var parentClassExpression = errorLocation; + while (parentClassExpression) { + var kind = parentClassExpression.kind; + if (kind === 69 || kind === 172) { + parentClassExpression = parentClassExpression.parent; + continue; + } + if (kind === 194) { + break; + } + return false; + } + if (!parentClassExpression) { + return false; + } + var expression = parentClassExpression.expression; + if (resolveEntityName(expression, 64, true)) { error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); + return true; } - return isError; - } - function getEntityNameForExtendingInterface(node) { - switch (node.kind) { - case 69: - case 172: - return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; - case 194: - ts.Debug.assert(ts.isEntityNameExpression(node.expression)); - return node.expression; - default: - return undefined; - } + return false; } function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert((result.flags & 2) !== 0); var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) ? d : undefined; }); ts.Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined"); - if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 218), errorLocation)) { + if (!isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 218), errorLocation)) { error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); } } @@ -15834,7 +14675,7 @@ var ts; function getTargetOfImportClause(node) { var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { - var exportDefaultSymbol = ts.isShorthandAmbientModuleSymbol(moduleSymbol) ? + var exportDefaultSymbol = ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration) ? moduleSymbol : moduleSymbol.exports["export="] ? getPropertyOfType(getTypeOfSymbol(moduleSymbol.exports["export="]), "default") : @@ -15853,7 +14694,7 @@ var ts; return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier); } function combineValueAndTypeSymbols(valueSymbol, typeSymbol) { - if (valueSymbol.flags & (793064 | 1920)) { + if (valueSymbol.flags & (793056 | 1536)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.name); @@ -15869,9 +14710,9 @@ var ts; } function getExportOfModule(symbol, name) { if (symbol.flags & 1536) { - var exportedSymbol = getExportsOfSymbol(symbol)[name]; - if (exportedSymbol) { - return resolveSymbol(exportedSymbol); + var exports_1 = getExportsOfSymbol(symbol); + if (ts.hasProperty(exports_1, name)) { + return resolveSymbol(exports_1[name]); } } } @@ -15887,28 +14728,25 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier); if (targetSymbol) { - var name_13 = specifier.propertyName || specifier.name; - if (name_13.text) { - if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + var name_11 = specifier.propertyName || specifier.name; + if (name_11.text) { + if (ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration)) { return moduleSymbol; } var symbolFromVariable = void 0; if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports["export="]) { - symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_13.text); + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_11.text); } else { - symbolFromVariable = getPropertyOfVariable(targetSymbol, name_13.text); + symbolFromVariable = getPropertyOfVariable(targetSymbol, name_11.text); } symbolFromVariable = resolveSymbol(symbolFromVariable); - var symbolFromModule = getExportOfModule(targetSymbol, name_13.text); - if (!symbolFromModule && allowSyntheticDefaultImports && name_13.text === "default") { - symbolFromModule = resolveExternalModuleSymbol(moduleSymbol) || resolveSymbol(moduleSymbol); - } + var symbolFromModule = getExportOfModule(targetSymbol, name_11.text); var symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - error(name_13, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_13)); + error(name_11, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_11)); } return symbol; } @@ -15923,10 +14761,10 @@ var ts; function getTargetOfExportSpecifier(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 107455 | 793064 | 1920); + resolveEntityName(node.propertyName || node.name, 107455 | 793056 | 1536); } function getTargetOfExportAssignment(node) { - return resolveEntityName(node.expression, 107455 | 793064 | 1920); + return resolveEntityName(node.expression, 107455 | 793056 | 1536); } function getTargetOfAliasDeclaration(node) { switch (node.kind) { @@ -15947,7 +14785,7 @@ var ts; } } function resolveSymbol(symbol) { - return symbol && symbol.flags & 8388608 && !(symbol.flags & (107455 | 793064 | 1920)) ? resolveAlias(symbol) : symbol; + return symbol && symbol.flags & 8388608 && !(symbol.flags & (107455 | 793056 | 1536)) ? resolveAlias(symbol) : symbol; } function resolveAlias(symbol) { ts.Debug.assert((symbol.flags & 8388608) !== 0, "Should only get Alias here."); @@ -15955,7 +14793,6 @@ var ts; if (!links.target) { links.target = resolvingSymbol; var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); var target = getTargetOfAliasDeclaration(node); if (links.target === resolvingSymbol) { links.target = target || unknownSymbol; @@ -15985,7 +14822,6 @@ var ts; if (!links.referenced) { links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); if (node.kind === 235) { checkExpressionCached(node.expression); } @@ -16002,11 +14838,11 @@ var ts; entityName = entityName.parent; } if (entityName.kind === 69 || entityName.parent.kind === 139) { - return resolveEntityName(entityName, 1920, false, dontResolveAlias); + return resolveEntityName(entityName, 1536, false, dontResolveAlias); } else { ts.Debug.assert(entityName.parent.kind === 229); - return resolveEntityName(entityName, 107455 | 793064 | 1920, false, dontResolveAlias); + return resolveEntityName(entityName, 107455 | 793056 | 1536, false, dontResolveAlias); } } function getFullyQualifiedName(symbol) { @@ -16018,7 +14854,7 @@ var ts; } var symbol; if (name.kind === 69) { - var message = meaning === 1920 ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; + var message = meaning === 1536 ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; symbol = resolveName(name, name.text, meaning, ignoreErrors ? undefined : message, name); if (!symbol) { return undefined; @@ -16027,7 +14863,7 @@ var ts; else if (name.kind === 139 || name.kind === 172) { var left = name.kind === 139 ? name.left : name.expression; var right = name.kind === 139 ? name.right : name.name; - var namespace = resolveEntityName(left, 1920, ignoreErrors); + var namespace = resolveEntityName(left, 1536, ignoreErrors); if (!namespace || ts.nodeIsMissing(right)) { return undefined; } @@ -16085,14 +14921,7 @@ var ts; } } if (moduleNotFoundError) { - var tsExtension = ts.tryExtractTypeScriptExtension(moduleName); - if (tsExtension) { - var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; - error(moduleReferenceLiteral, diag, tsExtension, ts.removeExtension(moduleName, tsExtension)); - } - else { - error(moduleReferenceLiteral, moduleNotFoundError, moduleName); - } + error(moduleReferenceLiteral, moduleNotFoundError, moduleName); } return undefined; } @@ -16122,7 +14951,7 @@ var ts; } function extendExportSymbols(target, source, lookupTable, exportNode) { for (var id in source) { - if (id !== "default" && !target[id]) { + if (id !== "default" && !ts.hasProperty(target, id)) { target[id] = source[id]; if (lookupTable && exportNode) { lookupTable[id] = { @@ -16130,7 +14959,7 @@ var ts; }; } } - else if (lookupTable && exportNode && id !== "default" && target[id] && resolveSymbol(target[id]) !== resolveSymbol(source[id])) { + else if (lookupTable && exportNode && id !== "default" && ts.hasProperty(target, id) && resolveSymbol(target[id]) !== resolveSymbol(source[id])) { if (!lookupTable[id].exportsWithDuplicate) { lookupTable[id].exportsWithDuplicate = [exportNode]; } @@ -16148,11 +14977,11 @@ var ts; return; } visitedSymbols.push(symbol); - var symbols = ts.cloneMap(symbol.exports); + var symbols = cloneSymbolTable(symbol.exports); var exportStars = symbol.exports["__export"]; if (exportStars) { - var nestedSymbols = ts.createMap(); - var lookupTable = ts.createMap(); + var nestedSymbols = {}; + var lookupTable = {}; for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { var node = _a[_i]; var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); @@ -16161,7 +14990,7 @@ var ts; } for (var id in lookupTable) { var exportsWithDuplicate = lookupTable[id].exportsWithDuplicate; - if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols[id]) { + if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || ts.hasProperty(symbols, id)) { continue; } for (var _b = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _b < exportsWithDuplicate_1.length; _b++) { @@ -16212,8 +15041,8 @@ var ts; } function createType(flags) { var result = new Type(checker, flags); - typeCount++; result.id = typeCount; + typeCount++; return result; } function createIntrinsicType(kind, intrinsicName) { @@ -16221,12 +15050,6 @@ var ts; type.intrinsicName = intrinsicName; return type; } - function createBooleanType(trueFalseTypes) { - var type = getUnionType(trueFalseTypes); - type.flags |= 8; - type.intrinsicName = "boolean"; - return type; - } function createObjectType(kind, symbol) { var type = createType(kind); type.symbol = symbol; @@ -16241,12 +15064,14 @@ var ts; function getNamedMembers(members) { var result; for (var id in members) { - if (!isReservedMemberName(id)) { - if (!result) - result = []; - var symbol = members[id]; - if (symbolIsValue(symbol)) { - result.push(symbol); + if (ts.hasProperty(members, id)) { + if (!isReservedMemberName(id)) { + if (!result) + result = []; + var symbol = members[id]; + if (symbolIsValue(symbol)) { + result.push(symbol); + } } } } @@ -16264,7 +15089,7 @@ var ts; return type; } function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { - return setObjectTypeMembers(createObjectType(2097152, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + return setObjectTypeMembers(createObjectType(65536, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function forEachSymbolTableInScope(enclosingDeclaration, callback) { var result; @@ -16289,7 +15114,7 @@ var ts; return callback(globals); } function getQualifiedLeftMeaning(rightMeaning) { - return rightMeaning === 107455 ? 107455 : 1920; + return rightMeaning === 107455 ? 107455 : 1536; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { function getAccessibleSymbolChainFromSymbolTable(symbols) { @@ -16306,10 +15131,10 @@ var ts; canQualifySymbol(symbolFromSymbolTable, meaning); } } - if (isAccessible(symbols[symbol.name])) { + if (isAccessible(ts.lookUp(symbols, symbol.name))) { return [symbol]; } - return ts.forEachProperty(symbols, function (symbolFromSymbolTable) { + return ts.forEachValue(symbols, function (symbolFromSymbolTable) { if (symbolFromSymbolTable.flags & 8388608 && symbolFromSymbolTable.name !== "export=" && !ts.getDeclarationOfKind(symbolFromSymbolTable, 238)) { @@ -16336,10 +15161,10 @@ var ts; function needsQualification(symbol, enclosingDeclaration, meaning) { var qualify = false; forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { - var symbolFromSymbolTable = symbolTable[symbol.name]; - if (!symbolFromSymbolTable) { + if (!ts.hasProperty(symbolTable, symbol.name)) { return false; } + var symbolFromSymbolTable = symbolTable[symbol.name]; if (symbolFromSymbolTable === symbol) { return true; } @@ -16382,7 +15207,7 @@ var ts; return { accessibility: 1, errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920) : undefined + errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1536) : undefined }; } return hasAccessibleDeclarations; @@ -16453,10 +15278,10 @@ var ts; } else if (entityName.kind === 139 || entityName.kind === 172 || entityName.parent.kind === 229) { - meaning = 1920; + meaning = 1536; } else { - meaning = 793064; + meaning = 793056; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.text, meaning, undefined, undefined); @@ -16507,31 +15332,6 @@ var ts; ts.releaseStringWriter(writer); return result; } - function formatUnionTypes(types) { - var result = []; - var flags = 0; - for (var i = 0; i < types.length; i++) { - var t = types[i]; - flags |= t.flags; - if (!(t.flags & 6144)) { - if (t.flags & (128 | 256)) { - var baseType = t.flags & 128 ? booleanType : t.baseType; - var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { - result.push(baseType); - i += count - 1; - continue; - } - } - result.push(t); - } - } - if (flags & 4096) - result.push(nullType); - if (flags & 2048) - result.push(undefinedType); - return result || types; - } function visibilityToString(flags) { if (flags === 8) { return "private"; @@ -16654,50 +15454,35 @@ var ts; var inObjectTypeLiteral = false; return writeType(type, globalFlags); function writeType(type, flags) { - var nextFlags = flags & ~512; - if (type.flags & 16015) { + if (type.flags & 150995071) { writer.writeKeyword(!(globalFlags & 16) && isTypeAny(type) ? "any" : type.intrinsicName); } - else if (type.flags & 268435456) { + else if (type.flags & 33554432) { if (inObjectTypeLiteral) { writer.reportInaccessibleThisError(); } writer.writeKeyword("this"); } - else if (type.flags & 131072) { - writeTypeReference(type, nextFlags); + else if (type.flags & 4096) { + writeTypeReference(type, flags); + } + else if (type.flags & (1024 | 2048 | 128 | 512)) { + buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793056, 0, flags); + } + else if (type.flags & 8192) { + writeTupleType(type); + } + else if (type.flags & 49152) { + writeUnionOrIntersectionType(type, flags); + } + else if (type.flags & 65536) { + writeAnonymousType(type, flags); } else if (type.flags & 256) { - buildSymbolDisplay(getParentOfSymbol(type.symbol), writer, enclosingDeclaration, 793064, 0, nextFlags); - writePunctuation(writer, 21); - appendSymbolNameOnly(type.symbol, writer); - } - else if (type.flags & (32768 | 65536 | 16 | 16384)) { - buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); - } - else if (!(flags & 512) && type.flags & (2097152 | 1572864) && type.aliasSymbol) { - if (type.flags & 2097152 || !(flags & 1024)) { - var typeArguments = type.aliasTypeArguments; - writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); - } - else { - writeUnionOrIntersectionType(type, nextFlags); - } - } - else if (type.flags & 1572864) { - writeUnionOrIntersectionType(type, nextFlags); - } - else if (type.flags & 2097152) { - writeAnonymousType(type, nextFlags); - } - else if (type.flags & 32) { writer.writeStringLiteral("\"" + ts.escapeString(type.text) + "\""); } - else if (type.flags & 64) { - writer.writeStringLiteral(type.text); - } else { writePunctuation(writer, 15); writeSpace(writer); @@ -16720,7 +15505,7 @@ var ts; } function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { if (symbol.flags & 32 || !isReservedMemberName(symbol.name)) { - buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064, 0, flags); + buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793056, 0, flags); } if (pos < end) { writePunctuation(writer, 25); @@ -16742,11 +15527,6 @@ var ts; writePunctuation(writer, 19); writePunctuation(writer, 20); } - else if (type.target.flags & 262144) { - writePunctuation(writer, 19); - writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 24); - writePunctuation(writer, 20); - } else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; @@ -16768,16 +15548,16 @@ var ts; writeSymbolTypeReference(type.symbol, typeArguments, i, typeParameterCount, flags); } } + function writeTupleType(type) { + writePunctuation(writer, 19); + writeTypeList(type.elementTypes, 24); + writePunctuation(writer, 20); + } function writeUnionOrIntersectionType(type, flags) { if (flags & 64) { writePunctuation(writer, 17); } - if (type.flags & 524288) { - writeTypeList(formatUnionTypes(type.types), 47); - } - else { - writeTypeList(type.types, 46); - } + writeTypeList(type.types, type.flags & 16384 ? 47 : 46); if (flags & 64) { writePunctuation(writer, 18); } @@ -16794,7 +15574,7 @@ var ts; else if (ts.contains(symbolStack, symbol)) { var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { - buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793064, 0, flags); + buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793056, 0, flags); } else { writeKeyword(writer, 117); @@ -17196,13 +15976,13 @@ var ts; function collectLinkedAliases(node) { var exportSymbol; if (node.parent && node.parent.kind === 235) { - exportSymbol = resolveName(node.parent, node.text, 107455 | 793064 | 1920 | 8388608, ts.Diagnostics.Cannot_find_name_0, node); + exportSymbol = resolveName(node.parent, node.text, 107455 | 793056 | 1536 | 8388608, ts.Diagnostics.Cannot_find_name_0, node); } else if (node.parent.kind === 238) { var exportSpecifier = node.parent; exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : - resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, 107455 | 793064 | 1920 | 8388608); + resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, 107455 | 793056 | 1536 | 8388608); } var result = []; if (exportSymbol) { @@ -17219,7 +15999,7 @@ var ts; if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.text, 107455 | 793064 | 1920, undefined, undefined); + var importSymbol = resolveName(declaration, firstIdentifier.text, 107455 | 793056 | 1536, undefined, undefined); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -17260,7 +16040,7 @@ var ts; return getSymbolLinks(target).declaredType; } if (propertyName === 1) { - ts.Debug.assert(!!(target.flags & 32768)); + ts.Debug.assert(!!(target.flags & 1024)); return target.resolvedBaseConstructorType; } if (propertyName === 3) { @@ -17302,7 +16082,7 @@ var ts; return type && (type.flags & 1) !== 0; } function isTypeNever(type) { - return type && (type.flags & 8192) !== 0; + return type && (type.flags & 134217728) !== 0; } function getTypeForBindingElementParent(node) { var symbol = getSymbolOfNode(node); @@ -17339,19 +16119,19 @@ var ts; } var type; if (pattern.kind === 167) { - var name_14 = declaration.propertyName || declaration.name; - if (isComputedNonLiteralName(name_14)) { + var name_12 = declaration.propertyName || declaration.name; + if (isComputedNonLiteralName(name_12)) { return anyType; } if (declaration.initializer) { getContextualType(declaration.initializer); } - var text = getTextOfPropertyName(name_14); + var text = getTextOfPropertyName(name_12); type = getTypeOfPropertyOfType(parentType, text) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || getIndexTypeOfType(parentType, 0); if (!type) { - error(name_14, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_14)); + error(name_12, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_12)); return unknownType; } } @@ -17364,7 +16144,7 @@ var ts; : elementType; if (!type) { if (isTupleType(parentType)) { - error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); + error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), parentType.elementTypes.length, pattern.elements.length); } else { error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), propName); @@ -17376,12 +16156,10 @@ var ts; type = createArrayType(elementType); } } - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 2048)) { + if (strictNullChecks && declaration.initializer && !(getCombinedTypeFlags(checkExpressionCached(declaration.initializer)) & 32)) { type = getTypeWithFacts(type, 131072); } - return declaration.initializer ? - getUnionType([type, checkExpressionCached(declaration.initializer)], true) : - type; + return type; } function getTypeForVariableLikeDeclarationFromJSDocComment(declaration) { var jsDocType = getJSDocTypeForVariableLikeDeclarationFromJSDocComment(declaration); @@ -17411,7 +16189,7 @@ var ts; return undefined; } function addOptionality(type, optional) { - return strictNullChecks && optional ? includeFalsyTypes(type, 2048) : type; + return strictNullChecks && optional ? addTypeKind(type, 32) : type; } function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { if (declaration.flags & 134217728) { @@ -17446,14 +16224,9 @@ var ts; return getReturnTypeOfSignature(getterSignature); } } - var type = void 0; - if (declaration.symbol.name === "this") { - var thisParameter = getContextualThisParameter(func); - type = thisParameter ? getTypeOfSymbol(thisParameter) : undefined; - } - else { - type = getContextuallyTypedParameterType(declaration); - } + var type = declaration.symbol.name === "this" + ? getContextuallyTypedThisType(func) + : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, declaration.questionToken && includeOptionality); } @@ -17465,24 +16238,26 @@ var ts; return checkIdentifier(declaration.name); } if (ts.isBindingPattern(declaration.name)) { - return getTypeFromBindingPattern(declaration.name, false, true); + return getTypeFromBindingPattern(declaration.name, false); } return undefined; } - function getTypeFromBindingElement(element, includePatternInType, reportErrors) { + function getTypeFromBindingElement(element, includePatternInType) { if (element.initializer) { - return checkExpressionCached(element.initializer); + var type = checkExpressionCached(element.initializer); + reportErrorsFromWidening(element, type); + return getWidenedType(type); } if (ts.isBindingPattern(element.name)) { - return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); + return getTypeFromBindingPattern(element.name, includePatternInType); } - if (reportErrors && compilerOptions.noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { + if (compilerOptions.noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { reportImplicitAnyError(element, anyType); } return anyType; } - function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { - var members = ts.createMap(); + function getTypeFromObjectBindingPattern(pattern, includePatternInType) { + var members = {}; var hasComputedProperties = false; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; @@ -17493,7 +16268,7 @@ var ts; var text = getTextOfPropertyName(name); var flags = 4 | 67108864 | (e.initializer ? 536870912 : 0); var symbol = createSymbol(flags, text); - symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); + symbol.type = getTypeFromBindingElement(e, includePatternInType); symbol.bindingElement = e; members[symbol.name] = symbol; }); @@ -17502,27 +16277,27 @@ var ts; result.pattern = pattern; } if (hasComputedProperties) { - result.flags |= 536870912; + result.flags |= 67108864; } return result; } - function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { + function getTypeFromArrayBindingPattern(pattern, includePatternInType) { var elements = pattern.elements; if (elements.length === 0 || elements[elements.length - 1].dotDotDotToken) { return languageVersion >= 2 ? createIterableType(anyType) : anyArrayType; } - var elementTypes = ts.map(elements, function (e) { return e.kind === 193 ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); }); - var result = createTupleType(elementTypes); + var elementTypes = ts.map(elements, function (e) { return e.kind === 193 ? anyType : getTypeFromBindingElement(e, includePatternInType); }); if (includePatternInType) { - result = cloneTypeReference(result); + var result = createNewTupleType(elementTypes); result.pattern = pattern; + return result; } - return result; + return createTupleType(elementTypes); } - function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { + function getTypeFromBindingPattern(pattern, includePatternInType) { return pattern.kind === 167 - ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) - : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); + ? getTypeFromObjectBindingPattern(pattern, includePatternInType) + : getTypeFromArrayBindingPattern(pattern, includePatternInType); } function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { var type = getTypeForVariableLikeDeclaration(declaration, true); @@ -17561,27 +16336,19 @@ var ts; if (declaration.kind === 235) { return links.type = checkExpression(declaration.expression); } - if (declaration.flags & 134217728 && declaration.kind === 280 && declaration.typeExpression) { - return links.type = getTypeFromTypeNode(declaration.typeExpression.type); - } if (!pushTypeResolution(symbol, 0)) { return unknownType; } - var type = void 0; - if (declaration.kind === 187 || - declaration.kind === 172 && declaration.parent.kind === 187) { - if (declaration.flags & 134217728) { - var typeTag = ts.getJSDocTypeTag(declaration.parent); - if (typeTag && typeTag.typeExpression) { - return links.type = getTypeFromTypeNode(typeTag.typeExpression.type); - } - } - var declaredTypes = ts.map(symbol.declarations, function (decl) { return decl.kind === 187 ? - checkExpressionCached(decl.right) : - checkExpressionCached(decl.parent.right); }); - type = getUnionType(declaredTypes, true); + var type = undefined; + if (declaration.kind === 187) { + type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); })); } - else { + else if (declaration.kind === 172) { + if (declaration.parent.kind === 187) { + type = checkExpressionCached(declaration.parent.right); + } + } + if (type === undefined) { type = getWidenedTypeForVariableLikeDeclaration(declaration, true); } if (!popTypeResolution()) { @@ -17649,13 +16416,7 @@ var ts; } else { if (compilerOptions.noImplicitAny) { - if (setter) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } + error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation, symbolToString(symbol)); } type = anyType; } @@ -17675,13 +16436,13 @@ var ts; function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbol.valueDeclaration.kind === 225 && ts.isShorthandAmbientModuleSymbol(symbol)) { + if (symbol.valueDeclaration.kind === 225 && ts.isShorthandAmbientModule(symbol.valueDeclaration)) { links.type = anyType; } else { - var type = createObjectType(2097152, symbol); + var type = createObjectType(65536, symbol); links.type = strictNullChecks && symbol.flags & 536870912 ? - includeFalsyTypes(type, 2048) : type; + addTypeKind(type, 32) : type; } } return links.type; @@ -17732,7 +16493,7 @@ var ts; return unknownType; } function getTargetType(type) { - return type.flags & 131072 ? type.target : type; + return type.flags & 4096 ? type.target : type; } function hasBaseType(type, checkBase) { return check(type); @@ -17792,7 +16553,7 @@ var ts; return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); } function isConstructorType(type) { - return type.flags & 2588672 && getSignaturesOfType(type, 1).length > 0; + return type.flags & 80896 && getSignaturesOfType(type, 1).length > 0; } function getBaseTypeNodeOfClass(type) { return ts.getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); @@ -17819,7 +16580,7 @@ var ts; return unknownType; } var baseConstructorType = checkExpression(baseTypeNode.expression); - if (baseConstructorType.flags & 2588672) { + if (baseConstructorType.flags & 80896) { resolveStructuredTypeMembers(baseConstructorType); } if (!popTypeResolution()) { @@ -17835,28 +16596,25 @@ var ts; return type.resolvedBaseConstructorType; } function getBaseTypes(type) { + var isClass = type.symbol.flags & 32; + var isInterface = type.symbol.flags & 64; if (!type.resolvedBaseTypes) { - if (type.flags & 262144) { - type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters))]; - } - else if (type.symbol.flags & (32 | 64)) { - if (type.symbol.flags & 32) { - resolveBaseTypesOfClass(type); - } - if (type.symbol.flags & 64) { - resolveBaseTypesOfInterface(type); - } - } - else { + if (!isClass && !isInterface) { ts.Debug.fail("type must be class or interface"); } + if (isClass) { + resolveBaseTypesOfClass(type); + } + if (isInterface) { + resolveBaseTypesOfInterface(type); + } } return type.resolvedBaseTypes; } function resolveBaseTypesOfClass(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; var baseConstructorType = getBaseConstructorTypeOfClass(type); - if (!(baseConstructorType.flags & 2588672)) { + if (!(baseConstructorType.flags & 80896)) { return; } var baseTypeNode = getBaseTypeNodeOfClass(type); @@ -17877,7 +16635,7 @@ var ts; if (baseType === unknownType) { return; } - if (!(getTargetType(baseType).flags & (32768 | 65536))) { + if (!(getTargetType(baseType).flags & (1024 | 2048))) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); return; } @@ -17910,7 +16668,7 @@ var ts; var node = _c[_b]; var baseType = getTypeFromTypeNode(node); if (baseType !== unknownType) { - if (getTargetType(baseType).flags & (32768 | 65536)) { + if (getTargetType(baseType).flags & (1024 | 2048)) { if (type !== baseType && !hasBaseType(baseType, type)) { if (type.resolvedBaseTypes === emptyArray) { type.resolvedBaseTypes = [baseType]; @@ -17942,8 +16700,8 @@ var ts; if (baseTypeNodes) { for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { var node = baseTypeNodes_1[_b]; - if (ts.isEntityNameExpression(node.expression)) { - var baseSymbol = resolveEntityName(node.expression, 793064, true); + if (ts.isSupportedExpressionWithTypeArguments(node)) { + var baseSymbol = resolveEntityName(node.expression, 793056, true); if (!baseSymbol || !(baseSymbol.flags & 64) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -17957,20 +16715,20 @@ var ts; function getDeclaredTypeOfClassOrInterface(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var kind = symbol.flags & 32 ? 32768 : 65536; + var kind = symbol.flags & 32 ? 1024 : 2048; var type = links.declaredType = createObjectType(kind, symbol); var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - if (outerTypeParameters || localTypeParameters || kind === 32768 || !isIndependentInterface(symbol)) { - type.flags |= 131072; + if (outerTypeParameters || localTypeParameters || kind === 1024 || !isIndependentInterface(symbol)) { + type.flags |= 4096; type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); type.outerTypeParameters = outerTypeParameters; type.localTypeParameters = localTypeParameters; - type.instantiations = ts.createMap(); + type.instantiations = {}; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 | 268435456); + type.thisType = createType(512 | 33554432); type.thisType.symbol = symbol; type.thisType.constraint = type; } @@ -17983,9 +16741,8 @@ var ts; if (!pushTypeResolution(symbol, 2)) { return unknownType; } - var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - var declaration = ts.getDeclarationOfKind(symbol, 279); var type = void 0; + var declaration = ts.getDeclarationOfKind(symbol, 279); if (declaration) { if (declaration.jsDocTypeLiteral) { type = getTypeFromTypeNode(declaration.jsDocTypeLiteral); @@ -17996,12 +16753,12 @@ var ts; } else { declaration = ts.getDeclarationOfKind(symbol, 223); - type = getTypeFromTypeNode(declaration.type, symbol, typeParameters); + type = getTypeFromTypeNode(declaration.type); } if (popTypeResolution()) { - links.typeParameters = typeParameters; - if (typeParameters) { - links.instantiations = ts.createMap(); + links.typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (links.typeParameters) { + links.instantiations = {}; links.instantiations[getTypeListId(links.typeParameters)] = type; } } @@ -18013,80 +16770,19 @@ var ts; } return links.declaredType; } - function isLiteralEnumMember(symbol, member) { - var expr = member.initializer; - if (!expr) { - return !ts.isInAmbientContext(member); - } - return expr.kind === 8 || - expr.kind === 185 && expr.operator === 36 && - expr.operand.kind === 8 || - expr.kind === 69 && !!symbol.exports[expr.text]; - } - function enumHasLiteralMembers(symbol) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 224) { - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - if (!isLiteralEnumMember(symbol, member)) { - return false; - } - } - } - } - return true; - } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var enumType = links.declaredType = createType(16); - enumType.symbol = symbol; - if (enumHasLiteralMembers(symbol)) { - var memberTypeList = []; - var memberTypes = ts.createMap(); - for (var _i = 0, _a = enumType.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 224) { - computeEnumMemberValues(declaration); - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - var memberSymbol = getSymbolOfNode(member); - var value = getEnumMemberValue(member); - if (!memberTypes[value]) { - var memberType = memberTypes[value] = createType(256); - memberType.symbol = memberSymbol; - memberType.baseType = enumType; - memberType.text = "" + value; - memberTypeList.push(memberType); - } - } - } - } - enumType.memberTypes = memberTypes; - if (memberTypeList.length > 1) { - enumType.flags |= 524288; - enumType.types = memberTypeList; - unionTypes[getTypeListId(memberTypeList)] = enumType; - } - } - } - return links.declaredType; - } - function getDeclaredTypeOfEnumMember(symbol) { - var links = getSymbolLinks(symbol); - if (!links.declaredType) { - var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); - links.declaredType = enumType.flags & 524288 ? - enumType.memberTypes[getEnumMemberValue(symbol.valueDeclaration)] : - enumType; + var type = createType(128); + type.symbol = symbol; + links.declaredType = type; } return links.declaredType; } function getDeclaredTypeOfTypeParameter(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var type = createType(16384); + var type = createType(512); type.symbol = symbol; if (!ts.getDeclarationOfKind(symbol, 141).constraint) { type.constraint = noConstraintType; @@ -18110,14 +16806,11 @@ var ts; if (symbol.flags & 524288) { return getDeclaredTypeOfTypeAlias(symbol); } - if (symbol.flags & 262144) { - return getDeclaredTypeOfTypeParameter(symbol); - } if (symbol.flags & 384) { return getDeclaredTypeOfEnum(symbol); } - if (symbol.flags & 8) { - return getDeclaredTypeOfEnumMember(symbol); + if (symbol.flags & 262144) { + return getDeclaredTypeOfTypeParameter(symbol); } if (symbol.flags & 8388608) { return getDeclaredTypeOfAlias(symbol); @@ -18188,7 +16881,7 @@ var ts; return false; } function createSymbolTable(symbols) { - var result = ts.createMap(); + var result = {}; for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { var symbol = symbols_1[_i]; result[symbol.name] = symbol; @@ -18196,7 +16889,7 @@ var ts; return result; } function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) { - var result = ts.createMap(); + var result = {}; for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { var symbol = symbols_2[_i]; result[symbol.name] = mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper); @@ -18206,7 +16899,7 @@ var ts; function addInheritedMembers(symbols, baseSymbols) { for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) { var s = baseSymbols_1[_i]; - if (!symbols[s.name]) { + if (!ts.hasProperty(symbols, s.name)) { symbols[s.name] = s; } } @@ -18223,27 +16916,19 @@ var ts; return type; } function getTypeWithThisArgument(type, thisArgument) { - if (type.flags & 131072) { + if (type.flags & 4096) { return createTypeReference(type.target, ts.concatenate(type.typeArguments, [thisArgument || type.target.thisType])); } return type; } function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { - var mapper; - var members; - var callSignatures; - var constructSignatures; - var stringIndexInfo; - var numberIndexInfo; - if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { - mapper = identityMapper; - members = source.symbol ? source.symbol.members : createSymbolTable(source.declaredProperties); - callSignatures = source.declaredCallSignatures; - constructSignatures = source.declaredConstructSignatures; - stringIndexInfo = source.declaredStringIndexInfo; - numberIndexInfo = source.declaredNumberIndexInfo; - } - else { + var mapper = identityMapper; + var members = source.symbol.members; + var callSignatures = source.declaredCallSignatures; + var constructSignatures = source.declaredConstructSignatures; + var stringIndexInfo = source.declaredStringIndexInfo; + var numberIndexInfo = source.declaredNumberIndexInfo; + if (!ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { mapper = createTypeMapper(typeParameters, typeArguments); members = createInstantiatedSymbolTable(source.declaredProperties, mapper, typeParameters.length === 1); callSignatures = instantiateList(source.declaredCallSignatures, mapper, instantiateSignature); @@ -18253,7 +16938,7 @@ var ts; } var baseTypes = getBaseTypes(source); if (baseTypes.length) { - if (source.symbol && members === source.symbol.members) { + if (members === source.symbol.members) { members = createSymbolTable(source.declaredProperties); } var thisArgument = ts.lastOrUndefined(typeArguments); @@ -18279,7 +16964,7 @@ var ts; type.typeArguments : ts.concatenate(type.typeArguments, [type]); resolveObjectTypeMembers(type, source, typeParameters, typeArguments); } - function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasStringLiterals) { var sig = new Signature(checker); sig.declaration = declaration; sig.typeParameters = typeParameters; @@ -18289,11 +16974,11 @@ var ts; sig.typePredicate = typePredicate; sig.minArgumentCount = minArgumentCount; sig.hasRestParameter = hasRestParameter; - sig.hasLiteralTypes = hasLiteralTypes; + sig.hasStringLiterals = hasStringLiterals; return sig; } function cloneSignature(sig) { - return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); + return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); } function getDefaultConstructSignatures(classType) { var baseConstructorType = getBaseConstructorTypeOfClass(classType); @@ -18317,6 +17002,22 @@ var ts; } return result; } + function createTupleTypeMemberSymbols(memberTypes) { + var members = {}; + for (var i = 0; i < memberTypes.length; i++) { + var symbol = createSymbol(4 | 67108864, "" + i); + symbol.type = memberTypes[i]; + members[i] = symbol; + } + return members; + } + function resolveTupleTypeMembers(type) { + var arrayElementType = getUnionType(type.elementTypes, true); + var arrayType = resolveStructuredTypeMembers(createTypeFromGenericGlobalType(globalArrayType, [arrayElementType, type])); + var members = createTupleTypeMemberSymbols(type.elementTypes); + addInheritedMembers(members, arrayType.properties); + setObjectTypeMembers(type, members, arrayType.callSignatures, arrayType.constructSignatures, arrayType.stringIndexInfo, arrayType.numberIndexInfo); + } function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) { for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { var s = signatureList_1[_i]; @@ -18362,7 +17063,7 @@ var ts; if (unionSignatures.length > 1) { s = cloneSignature(signature); if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { - var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; }), true); + var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; })); s.thisParameter = createTransientSymbol(signature.thisParameter, thisType); } s.resolvedReturnType = undefined; @@ -18387,7 +17088,7 @@ var ts; indexTypes.push(indexInfo.type); isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; } - return createIndexInfo(getUnionType(indexTypes, true), isAnyReadonly); + return createIndexInfo(getUnionType(indexTypes), isAnyReadonly); } function resolveUnionTypeMembers(type) { var callSignatures = getUnionSignatures(type.types, 0); @@ -18447,7 +17148,7 @@ var ts; constructSignatures = getDefaultConstructSignatures(classType); } var baseConstructorType = getBaseConstructorTypeOfClass(classType); - if (baseConstructorType.flags & 2588672) { + if (baseConstructorType.flags & 80896) { members = createSymbolTable(getNamedMembers(members)); addInheritedMembers(members, getPropertiesOfObjectType(baseConstructorType)); } @@ -18461,36 +17162,41 @@ var ts; } function resolveStructuredTypeMembers(type) { if (!type.members) { - if (type.flags & 131072) { + if (type.flags & 4096) { resolveTypeReferenceMembers(type); } - else if (type.flags & (32768 | 65536)) { + else if (type.flags & (1024 | 2048)) { resolveClassOrInterfaceMembers(type); } - else if (type.flags & 2097152) { + else if (type.flags & 65536) { resolveAnonymousTypeMembers(type); } - else if (type.flags & 524288) { + else if (type.flags & 8192) { + resolveTupleTypeMembers(type); + } + else if (type.flags & 16384) { resolveUnionTypeMembers(type); } - else if (type.flags & 1048576) { + else if (type.flags & 32768) { resolveIntersectionTypeMembers(type); } } return type; } function getPropertiesOfObjectType(type) { - if (type.flags & 2588672) { + if (type.flags & 80896) { return resolveStructuredTypeMembers(type).properties; } return emptyArray; } function getPropertyOfObjectType(type, name) { - if (type.flags & 2588672) { + if (type.flags & 80896) { var resolved = resolveStructuredTypeMembers(type); - var symbol = resolved.members[name]; - if (symbol && symbolIsValue(symbol)) { - return symbol; + if (ts.hasProperty(resolved.members, name)) { + var symbol = resolved.members[name]; + if (symbolIsValue(symbol)) { + return symbol; + } } } } @@ -18501,7 +17207,7 @@ var ts; var prop = _c[_b]; getPropertyOfUnionOrIntersectionType(type, prop.name); } - if (type.flags & 524288) { + if (type.flags & 16384) { break; } } @@ -18509,12 +17215,12 @@ var ts; } function getPropertiesOfType(type) { type = getApparentType(type); - return type.flags & 1572864 ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); + return type.flags & 49152 ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } function getApparentTypeOfTypeParameter(type) { if (!type.resolvedApparentType) { var constraintType = getConstraintOfTypeParameter(type); - while (constraintType && constraintType.flags & 16384) { + while (constraintType && constraintType.flags & 512) { constraintType = getConstraintOfTypeParameter(constraintType); } type.resolvedApparentType = getTypeWithThisArgument(constraintType || emptyObjectType, type); @@ -18522,19 +17228,19 @@ var ts; return type.resolvedApparentType; } function getApparentType(type) { - if (type.flags & 16384) { + if (type.flags & 512) { type = getApparentTypeOfTypeParameter(type); } - if (type.flags & 34) { + if (type.flags & 258) { type = globalStringType; } - else if (type.flags & 340) { + else if (type.flags & 132) { type = globalNumberType; } - else if (type.flags & 136) { + else if (type.flags & 8) { type = globalBooleanType; } - else if (type.flags & 512) { + else if (type.flags & 16777216) { type = getGlobalESSymbolType(); } return type; @@ -18542,7 +17248,7 @@ var ts; function createUnionOrIntersectionProperty(containingType, name) { var types = containingType.types; var props; - var commonFlags = (containingType.flags & 1048576) ? 536870912 : 0; + var commonFlags = (containingType.flags & 32768) ? 536870912 : 0; var isReadonly = false; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var current = types_2[_i]; @@ -18561,7 +17267,7 @@ var ts; isReadonly = true; } } - else if (containingType.flags & 524288) { + else if (containingType.flags & 16384) { return undefined; } } @@ -18574,20 +17280,11 @@ var ts; } var propTypes = []; var declarations = []; - var commonType = undefined; - var hasCommonType = true; for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { var prop = props_1[_a]; if (prop.declarations) { ts.addRange(declarations, prop.declarations); } - var type = getTypeOfSymbol(prop); - if (!commonType) { - commonType = type; - } - else if (type !== commonType) { - hasCommonType = false; - } propTypes.push(getTypeOfSymbol(prop)); } var result = createSymbol(4 | @@ -18595,46 +17292,47 @@ var ts; 268435456 | commonFlags, name); result.containingType = containingType; - result.hasCommonType = hasCommonType; result.declarations = declarations; result.isReadonly = isReadonly; - result.type = containingType.flags & 524288 ? getUnionType(propTypes) : getIntersectionType(propTypes); + result.type = containingType.flags & 16384 ? getUnionType(propTypes) : getIntersectionType(propTypes); return result; } function getPropertyOfUnionOrIntersectionType(type, name) { - var properties = type.resolvedProperties || (type.resolvedProperties = ts.createMap()); - var property = properties[name]; - if (!property) { - property = createUnionOrIntersectionProperty(type, name); - if (property) { - properties[name] = property; - } + var properties = type.resolvedProperties || (type.resolvedProperties = {}); + if (ts.hasProperty(properties, name)) { + return properties[name]; + } + var property = createUnionOrIntersectionProperty(type, name); + if (property) { + properties[name] = property; } return property; } function getPropertyOfType(type, name) { type = getApparentType(type); - if (type.flags & 2588672) { + if (type.flags & 80896) { var resolved = resolveStructuredTypeMembers(type); - var symbol = resolved.members[name]; - if (symbol && symbolIsValue(symbol)) { - return symbol; + if (ts.hasProperty(resolved.members, name)) { + var symbol = resolved.members[name]; + if (symbolIsValue(symbol)) { + return symbol; + } } if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); - if (symbol_1) { - return symbol_1; + var symbol = getPropertyOfObjectType(globalFunctionType, name); + if (symbol) { + return symbol; } } return getPropertyOfObjectType(globalObjectType, name); } - if (type.flags & 1572864) { + if (type.flags & 49152) { return getPropertyOfUnionOrIntersectionType(type, name); } return undefined; } function getSignaturesOfStructuredType(type, kind) { - if (type.flags & 4161536) { + if (type.flags & 130048) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 ? resolved.callSignatures : resolved.constructSignatures; } @@ -18644,7 +17342,7 @@ var ts; return getSignaturesOfStructuredType(getApparentType(type), kind); } function getIndexInfoOfStructuredType(type, kind) { - if (type.flags & 4161536) { + if (type.flags & 130048) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 ? resolved.stringIndexInfo : resolved.numberIndexInfo; } @@ -18669,7 +17367,7 @@ var ts; } } if (propTypes.length) { - return getUnionType(propTypes, true); + return getUnionType(propTypes); } } return undefined; @@ -18752,7 +17450,7 @@ var ts; var links = getNodeLinks(declaration); if (!links.resolvedSignature) { var parameters = []; - var hasLiteralTypes = false; + var hasStringLiterals = false; var minArgumentCount = -1; var thisParameter = undefined; var hasThisParameter = void 0; @@ -18772,7 +17470,7 @@ var ts; parameters.push(paramSymbol); } if (param.type && param.type.kind === 166) { - hasLiteralTypes = true; + hasStringLiterals = true; } if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { if (minArgumentCount < 0) { @@ -18798,9 +17496,6 @@ var ts; if (isJSConstructSignature) { minArgumentCount--; } - if (!thisParameter && ts.isObjectLiteralMethod(declaration)) { - thisParameter = getContextualThisParameter(declaration); - } var classType = declaration.kind === 148 ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; @@ -18811,7 +17506,7 @@ var ts; var typePredicate = declaration.type && declaration.type.kind === 154 ? createTypePredicateFromTypePredicateNode(declaration.type) : undefined; - links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasLiteralTypes); + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasStringLiterals); } return links.resolvedSignature; } @@ -18896,7 +17591,7 @@ var ts; type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); } else if (signature.unionSignatures) { - type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), true); + type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature)); } else { type = getReturnTypeFromBody(signature.declaration); @@ -18920,7 +17615,7 @@ var ts; function getRestTypeOfSignature(signature) { if (signature.hasRestParameter) { var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); - if (type.flags & 131072 && type.target === globalArrayType) { + if (type.flags & 4096 && type.target === globalArrayType) { return type.typeArguments[0]; } } @@ -18940,7 +17635,7 @@ var ts; function getOrCreateTypeFromSignature(signature) { if (!signature.isolatedSignatureType) { var isConstructor = signature.declaration.kind === 148 || signature.declaration.kind === 152; - var type = createObjectType(2097152); + var type = createObjectType(65536 | 262144); type.members = emptySymbols; type.properties = emptyArray; type.callSignatures = !isConstructor ? [signature] : emptyArray; @@ -18984,7 +17679,7 @@ var ts; } function hasConstraintReferenceTo(type, target) { var checked; - while (type && !(type.flags & 268435456) && type.flags & 16384 && !ts.contains(checked, type)) { + while (type && !(type.flags & 33554432) && type.flags & 512 && !ts.contains(checked, type)) { if (type === target) { return true; } @@ -19016,27 +17711,24 @@ var ts; return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 141).parent); } function getTypeListId(types) { - var result = ""; if (types) { - var length_3 = types.length; - var i = 0; - while (i < length_3) { - var startId = types[i].id; - var count = 1; - while (i + count < length_3 && types[i + count].id === startId + count) { - count++; - } - if (result.length) { - result += ","; - } - result += startId; - if (count > 1) { - result += ":" + count; - } - i += count; + switch (types.length) { + case 1: + return "" + types[0].id; + case 2: + return types[0].id + "," + types[1].id; + default: + var result = ""; + for (var i = 0; i < types.length; i++) { + if (i > 0) { + result += ","; + } + result += types[i].id; + } + return result; } } - return result; + return ""; } function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; @@ -19046,29 +17738,20 @@ var ts; result |= type.flags; } } - return result & 234881024; + return result & 14680064; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); var type = target.instantiations[id]; if (!type) { var propagatedFlags = typeArguments ? getPropagatingFlagsOfTypes(typeArguments, 0) : 0; - var flags = 131072 | propagatedFlags; + var flags = 4096 | propagatedFlags; type = target.instantiations[id] = createObjectType(flags, target.symbol); type.target = target; type.typeArguments = typeArguments; } return type; } - function cloneTypeReference(source) { - var type = createObjectType(source.flags, source.symbol); - type.target = source.target; - type.typeArguments = source.typeArguments; - return type; - } - function getTypeReferenceArity(type) { - return type.target.typeParameters ? type.target.typeParameters.length : 0; - } function getTypeFromClassOrInterfaceReference(node, symbol) { var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); var typeParameters = type.localTypeParameters; @@ -19118,9 +17801,8 @@ var ts; case 267: return node.name; case 194: - var expr = node.expression; - if (ts.isEntityNameExpression(expr)) { - return expr; + if (ts.isSupportedExpressionWithTypeArguments(node)) { + return node.expression; } } return undefined; @@ -19129,7 +17811,7 @@ var ts; if (!typeReferenceName) { return unknownSymbol; } - return resolveEntityName(typeReferenceName, 793064) || unknownSymbol; + return resolveEntityName(typeReferenceName, 793056) || unknownSymbol; } function getTypeReferenceType(node, symbol) { if (symbol === unknownSymbol) { @@ -19155,14 +17837,14 @@ var ts; var typeReferenceName = getTypeReferenceName(node); symbol = resolveTypeReferenceName(node, typeReferenceName); type = getTypeReferenceType(node, symbol); + links.resolvedSymbol = symbol; + links.resolvedType = type; } else { - var typeNameOrExpression = node.kind === 155 - ? node.typeName - : ts.isEntityNameExpression(node.expression) - ? node.expression - : undefined; - symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793064) || unknownSymbol; + var typeNameOrExpression = node.kind === 155 ? node.typeName : + ts.isSupportedExpressionWithTypeArguments(node) ? node.expression : + undefined; + symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793056) || unknownSymbol; type = symbol === unknownSymbol ? unknownType : symbol.flags & (32 | 64) ? getTypeFromClassOrInterfaceReference(node, symbol) : symbol.flags & 524288 ? getTypeFromTypeAliasReference(node, symbol) : @@ -19197,7 +17879,7 @@ var ts; return arity ? emptyGenericType : emptyObjectType; } var type = getDeclaredTypeOfSymbol(symbol); - if (!(type.flags & 2588672)) { + if (!(type.flags & 80896)) { error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbol.name); return arity ? emptyGenericType : emptyObjectType; } @@ -19211,7 +17893,7 @@ var ts; return getGlobalSymbol(name, 107455, ts.Diagnostics.Cannot_find_global_value_0); } function getGlobalTypeSymbol(name) { - return getGlobalSymbol(name, 793064, ts.Diagnostics.Cannot_find_global_type_0); + return getGlobalSymbol(name, 793056, ts.Diagnostics.Cannot_find_global_type_0); } function getGlobalSymbol(name, meaning, diagnostic) { return resolveName(undefined, name, meaning, diagnostic, name); @@ -19221,8 +17903,8 @@ var ts; return getTypeOfGlobalSymbol(getGlobalTypeSymbol(name), arity); } function getExportedTypeFromNamespace(namespace, name) { - var namespaceSymbol = getGlobalSymbol(namespace, 1920, undefined); - var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793064); + var namespaceSymbol = getGlobalSymbol(namespace, 1536, undefined); + var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793056); return typeSymbol && getDeclaredTypeOfSymbol(typeSymbol); } function createTypedPropertyDescriptorType(propertyType) { @@ -19250,38 +17932,15 @@ var ts; } return links.resolvedType; } - function createTupleTypeOfArity(arity) { - var typeParameters = []; - var properties = []; - for (var i = 0; i < arity; i++) { - var typeParameter = createType(16384); - typeParameters.push(typeParameter); - var property = createSymbol(4 | 67108864, "" + i); - property.type = typeParameter; - properties.push(property); - } - var type = createObjectType(262144 | 131072); - type.typeParameters = typeParameters; - type.outerTypeParameters = undefined; - type.localTypeParameters = typeParameters; - type.instantiations = ts.createMap(); - type.instantiations[getTypeListId(type.typeParameters)] = type; - type.target = type; - type.typeArguments = type.typeParameters; - type.thisType = createType(16384 | 268435456); - type.thisType.constraint = type; - type.declaredProperties = properties; - type.declaredCallSignatures = emptyArray; - type.declaredConstructSignatures = emptyArray; - type.declaredStringIndexInfo = undefined; - type.declaredNumberIndexInfo = undefined; - return type; - } - function getTupleTypeOfArity(arity) { - return tupleTypes[arity] || (tupleTypes[arity] = createTupleTypeOfArity(arity)); - } function createTupleType(elementTypes) { - return createTypeReference(getTupleTypeOfArity(elementTypes.length), elementTypes); + var id = getTypeListId(elementTypes); + return tupleTypes[id] || (tupleTypes[id] = createNewTupleType(elementTypes)); + } + function createNewTupleType(elementTypes) { + var propagatedFlags = getPropagatingFlagsOfTypes(elementTypes, 0); + var type = createObjectType(8192 | propagatedFlags); + type.elementTypes = elementTypes; + return type; } function getTypeFromTupleTypeNode(node) { var links = getNodeLinks(node); @@ -19290,68 +17949,30 @@ var ts; } return links.resolvedType; } - function binarySearchTypes(types, type) { - var low = 0; - var high = types.length - 1; - var typeId = type.id; - while (low <= high) { - var middle = low + ((high - low) >> 1); - var id = types[middle].id; - if (id === typeId) { - return middle; - } - else if (id > typeId) { - high = middle - 1; - } - else { - low = middle + 1; - } + function addTypeToSet(typeSet, type, typeSetKind) { + if (type.flags & typeSetKind) { + addTypesToSet(typeSet, type.types, typeSetKind); } - return ~low; - } - function containsType(types, type) { - return binarySearchTypes(types, type) >= 0; - } - function addTypeToUnion(typeSet, type) { - if (type.flags & 524288) { - addTypesToUnion(typeSet, type.types); - } - else if (type.flags & 1) { - typeSet.containsAny = true; - } - else if (!strictNullChecks && type.flags & 6144) { - if (type.flags & 2048) + else if (type.flags & (1 | 32 | 64)) { + if (type.flags & 1) + typeSet.containsAny = true; + if (type.flags & 32) typeSet.containsUndefined = true; - if (type.flags & 4096) + if (type.flags & 64) typeSet.containsNull = true; - if (!(type.flags & 33554432)) + if (!(type.flags & 2097152)) typeSet.containsNonWideningType = true; } - else if (!(type.flags & 8192)) { - var len = typeSet.length; - var index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type); - if (index < 0) { - if (!(type.flags & 2097152 && type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); - } - } + else if (type !== neverType && !ts.contains(typeSet, type)) { + typeSet.push(type); } } - function addTypesToUnion(typeSet, types) { + function addTypesToSet(typeSet, types, typeSetKind) { for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { var type = types_4[_i]; - addTypeToUnion(typeSet, type); + addTypeToSet(typeSet, type, typeSetKind); } } - function containsIdenticalType(types, type) { - for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { - var t = types_5[_i]; - if (isTypeIdenticalTo(t, type)) { - return true; - } - } - return false; - } function isSubtypeOfAny(candidate, types) { for (var i = 0, len = types.length; i < len; i++) { if (candidate !== types[i] && isTypeSubtypeOf(candidate, types[i])) { @@ -19369,7 +17990,7 @@ var ts; } } } - function getUnionType(types, subtypeReduction, aliasSymbol, aliasTypeArguments) { + function getUnionType(types, noSubtypeReduction) { if (types.length === 0) { return neverType; } @@ -19377,11 +17998,17 @@ var ts; return types[0]; } var typeSet = []; - addTypesToUnion(typeSet, types); + addTypesToSet(typeSet, types, 16384); if (typeSet.containsAny) { return anyType; } - if (subtypeReduction) { + if (strictNullChecks) { + if (typeSet.containsNull) + typeSet.push(nullType); + if (typeSet.containsUndefined) + typeSet.push(undefinedType); + } + if (!noSubtypeReduction) { removeSubtypes(typeSet); } if (typeSet.length === 0) { @@ -19389,103 +18016,78 @@ var ts; typeSet.containsUndefined ? typeSet.containsNonWideningType ? undefinedType : undefinedWideningType : neverType; } - return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments); - } - function getUnionTypeFromSortedList(types, aliasSymbol, aliasTypeArguments) { - if (types.length === 0) { - return neverType; + else if (typeSet.length === 1) { + return typeSet[0]; } - if (types.length === 1) { - return types[0]; - } - var id = getTypeListId(types); + var id = getTypeListId(typeSet); var type = unionTypes[id]; if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(types, 6144); - type = unionTypes[id] = createObjectType(524288 | propagatedFlags); - type.types = types; - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = aliasTypeArguments; + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, 96); + type = unionTypes[id] = createObjectType(16384 | propagatedFlags); + type.types = typeSet; } return type; } - function getTypeFromUnionTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getTypeFromUnionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), false, aliasSymbol, aliasTypeArguments); + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), true); } return links.resolvedType; } - function addTypeToIntersection(typeSet, type) { - if (type.flags & 1048576) { - addTypesToIntersection(typeSet, type.types); - } - else if (type.flags & 1) { - typeSet.containsAny = true; - } - else if (!(type.flags & 8192) && (strictNullChecks || !(type.flags & 6144)) && !ts.contains(typeSet, type)) { - typeSet.push(type); - } - } - function addTypesToIntersection(typeSet, types) { - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type = types_6[_i]; - addTypeToIntersection(typeSet, type); - } - } - function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { + function getIntersectionType(types) { if (types.length === 0) { return emptyObjectType; } var typeSet = []; - addTypesToIntersection(typeSet, types); + addTypesToSet(typeSet, types, 32768); if (typeSet.containsAny) { return anyType; } + if (strictNullChecks) { + if (typeSet.containsNull) + typeSet.push(nullType); + if (typeSet.containsUndefined) + typeSet.push(undefinedType); + } if (typeSet.length === 1) { return typeSet[0]; } var id = getTypeListId(typeSet); var type = intersectionTypes[id]; if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, 6144); - type = intersectionTypes[id] = createObjectType(1048576 | propagatedFlags); + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, 96); + type = intersectionTypes[id] = createObjectType(32768 | propagatedFlags); type.types = typeSet; - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = aliasTypeArguments; } return type; } - function getTypeFromIntersectionTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getTypeFromIntersectionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, aliasTypeArguments); + links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode)); } return links.resolvedType; } - function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - var type = createObjectType(2097152, node.symbol); - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = aliasTypeArguments; - links.resolvedType = type; + links.resolvedType = createObjectType(65536, node.symbol); } return links.resolvedType; } - function createLiteralType(flags, text) { - var type = createType(flags); + function getStringLiteralTypeForText(text) { + if (ts.hasProperty(stringLiteralTypes, text)) { + return stringLiteralTypes[text]; + } + var type = stringLiteralTypes[text] = createType(256); type.text = text; return type; } - function getLiteralTypeForText(flags, text) { - var map = flags & 32 ? stringLiteralTypes : numericLiteralTypes; - return map[text] || (map[text] = createLiteralType(flags, text)); - } - function getTypeFromLiteralTypeNode(node) { + function getTypeFromStringLiteralTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = checkExpression(node.literal); + links.resolvedType = getStringLiteralTypeForText(ts.unescapeIdentifier(node.text)); } return links.resolvedType; } @@ -19524,7 +18126,7 @@ var ts; } return links.resolvedType; } - function getTypeFromTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getTypeFromTypeNode(node) { switch (node.kind) { case 117: case 258: @@ -19546,19 +18148,11 @@ var ts; return nullType; case 127: return neverType; - case 283: - return nullType; - case 284: - return undefinedType; - case 285: - return neverType; case 165: case 97: return getTypeFromThisTypeNode(node); case 166: - return getTypeFromLiteralTypeNode(node); - case 282: - return getTypeFromLiteralTypeNode(node.literal); + return getTypeFromStringLiteralTypeNode(node); case 155: case 267: return getTypeFromTypeReference(node); @@ -19575,9 +18169,9 @@ var ts; return getTypeFromTupleTypeNode(node); case 162: case 261: - return getTypeFromUnionTypeNode(node, aliasSymbol, aliasTypeArguments); + return getTypeFromUnionTypeNode(node); case 163: - return getTypeFromIntersectionTypeNode(node, aliasSymbol, aliasTypeArguments); + return getTypeFromIntersectionTypeNode(node); case 164: case 263: case 264: @@ -19591,7 +18185,7 @@ var ts; case 281: case 269: case 265: - return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node, aliasSymbol, aliasTypeArguments); + return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); case 69: case 139: var symbol = getSymbolAtLocation(node); @@ -19637,7 +18231,6 @@ var ts; count == 2 ? createBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : createArrayTypeMapper(sources, targets); mapper.mappedTypes = sources; - mapper.targetTypes = targets; return mapper; } function createTypeEraser(sources) { @@ -19670,7 +18263,7 @@ var ts; return mapper; } function cloneTypeParameter(typeParameter) { - var result = createType(16384); + var result = createType(512); result.symbol = typeParameter.symbol; result.target = typeParameter; return result; @@ -19705,7 +18298,7 @@ var ts; if (signature.typePredicate) { freshTypePredicate = cloneTypePredicate(signature.typePredicate, mapper); } - var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); + var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasStringLiterals); result.target = signature; result.mapper = mapper; return result; @@ -19736,11 +18329,9 @@ var ts; else { mapper.instantiations = []; } - var result = createObjectType(2097152 | 4194304, type.symbol); + var result = createObjectType(65536 | 131072, type.symbol); result.target = type; result.mapper = mapper; - result.aliasSymbol = type.aliasSymbol; - result.aliasTypeArguments = mapper.targetTypes; mapper.instantiations[type.id] = result; return result; } @@ -19792,23 +18383,26 @@ var ts; } function instantiateType(type, mapper) { if (type && mapper !== identityMapper) { - if (type.flags & 16384) { + if (type.flags & 512) { return mapper(type); } - if (type.flags & 2097152) { + if (type.flags & 65536) { return type.symbol && type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && - (type.flags & 4194304 || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? + (type.flags & 131072 || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? instantiateAnonymousType(type, mapper) : type; } - if (type.flags & 131072) { + if (type.flags & 4096) { return createTypeReference(type.target, instantiateList(type.typeArguments, mapper, instantiateType)); } - if (type.flags & 524288 && !(type.flags & 8190)) { - return getUnionType(instantiateList(type.types, mapper, instantiateType), false, type.aliasSymbol, mapper.targetTypes); + if (type.flags & 8192) { + return createTupleType(instantiateList(type.elementTypes, mapper, instantiateType)); } - if (type.flags & 1048576) { - return getIntersectionType(instantiateList(type.types, mapper, instantiateType), type.aliasSymbol, mapper.targetTypes); + if (type.flags & 16384) { + return getUnionType(instantiateList(type.types, mapper, instantiateType), true); + } + if (type.flags & 32768) { + return getIntersectionType(instantiateList(type.types, mapper, instantiateType)); } } return type; @@ -19851,10 +18445,10 @@ var ts; return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { - if (type.flags & 2588672) { + if (type.flags & 80896) { var resolved = resolveStructuredTypeMembers(type); if (resolved.constructSignatures.length) { - var result = createObjectType(2097152, type.symbol); + var result = createObjectType(65536, type.symbol); result.members = resolved.members; result.properties = resolved.properties; result.callSignatures = emptyArray; @@ -19865,25 +18459,22 @@ var ts; return type; } function isTypeIdenticalTo(source, target) { - return isTypeRelatedTo(source, target, identityRelation); + return checkTypeRelatedTo(source, target, identityRelation, undefined); } function compareTypesIdentical(source, target) { - return isTypeRelatedTo(source, target, identityRelation) ? -1 : 0; + return checkTypeRelatedTo(source, target, identityRelation, undefined) ? -1 : 0; } function compareTypesAssignable(source, target) { - return isTypeRelatedTo(source, target, assignableRelation) ? -1 : 0; + return checkTypeRelatedTo(source, target, assignableRelation, undefined) ? -1 : 0; } function isTypeSubtypeOf(source, target) { - return isTypeRelatedTo(source, target, subtypeRelation); + return checkTypeSubtypeOf(source, target, undefined); } function isTypeAssignableTo(source, target) { - return isTypeRelatedTo(source, target, assignableRelation); - } - function isTypeInstanceOf(source, target) { - return source === target || isTypeSubtypeOf(source, target) && !isTypeIdenticalTo(source, target); + return checkTypeAssignableTo(source, target, undefined); } function isTypeComparableTo(source, target) { - return isTypeRelatedTo(source, target, comparableRelation); + return checkTypeComparableTo(source, target, undefined); } function areTypesComparable(type1, type2) { return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); @@ -19996,8 +18587,8 @@ var ts; var sourceReturnType = getReturnTypeOfSignature(erasedSource); var targetReturnType = getReturnTypeOfSignature(erasedTarget); if (targetReturnType === voidType - || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation) - || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) { + || checkTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation, undefined) + || checkTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation, undefined)) { return isSignatureAssignableTo(erasedSource, erasedTarget, true); } return false; @@ -20023,88 +18614,6 @@ var ts; sourceNonRestParamCount; } } - function isEnumTypeRelatedTo(source, target, errorReporter) { - if (source === target) { - return true; - } - var id = source.id + "," + target.id; - if (enumRelation[id] !== undefined) { - return enumRelation[id]; - } - if (source.symbol.name !== target.symbol.name || - !(source.symbol.flags & 256) || !(target.symbol.flags & 256) || - (source.flags & 524288) !== (target.flags & 524288)) { - return enumRelation[id] = false; - } - var targetEnumType = getTypeOfSymbol(target.symbol); - for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { - var property = _a[_i]; - if (property.flags & 8) { - var targetProperty = getPropertyOfType(targetEnumType, property.name); - if (!targetProperty || !(targetProperty.flags & 8)) { - if (errorReporter) { - errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, undefined, 128)); - } - return enumRelation[id] = false; - } - } - } - return enumRelation[id] = true; - } - function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { - if (target.flags & 8192) - return false; - if (target.flags & 1 || source.flags & 8192) - return true; - if (source.flags & 34 && target.flags & 2) - return true; - if (source.flags & 340 && target.flags & 4) - return true; - if (source.flags & 136 && target.flags & 8) - return true; - if (source.flags & 256 && target.flags & 16 && source.baseType === target) - return true; - if (source.flags & 16 && target.flags & 16 && isEnumTypeRelatedTo(source, target, errorReporter)) - return true; - if (source.flags & 2048 && (!strictNullChecks || target.flags & (2048 | 1024))) - return true; - if (source.flags & 4096 && (!strictNullChecks || target.flags & 4096)) - return true; - if (relation === assignableRelation || relation === comparableRelation) { - if (source.flags & 1) - return true; - if ((source.flags & 4 | source.flags & 64) && target.flags & 272) - return true; - if (source.flags & 256 && - target.flags & 256 && - source.text === target.text && - isEnumTypeRelatedTo(source.baseType, target.baseType, errorReporter)) { - return true; - } - if (source.flags & 256 && - target.flags & 16 && - isEnumTypeRelatedTo(target, source.baseType, errorReporter)) { - return true; - } - } - return false; - } - function isTypeRelatedTo(source, target, relation) { - if (source === target || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { - return true; - } - if (source.flags & 2588672 && target.flags & 2588672) { - var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; - var related = relation[id]; - if (related !== undefined) { - return related === 1; - } - } - if (source.flags & 4177920 || target.flags & 4177920) { - return checkTypeRelatedTo(source, target, relation, undefined, undefined, undefined); - } - return false; - } function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain) { var errorInfo; var sourceStack; @@ -20143,16 +18652,6 @@ var ts; } reportError(message, sourceType, targetType); } - function tryElaborateErrorsForPrimitivesAndObjects(source, target) { - var sourceType = typeToString(source); - var targetType = typeToString(target); - if ((globalStringType === source && stringType === target) || - (globalNumberType === source && numberType === target) || - (globalBooleanType === source && booleanType === target) || - (getGlobalESSymbolType() === source && esSymbolType === target)) { - reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); - } - } function isRelatedTo(source, target, reportErrors, headMessage) { var result; if (source === target) @@ -20160,50 +18659,78 @@ var ts; if (relation === identityRelation) { return isIdenticalTo(source, target); } - if (isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) - return -1; - if (source.flags & 16777216) { + if (!(target.flags & 134217728)) { + if (target.flags & 1 || source.flags & 134217728) + return -1; + if (source.flags & 32) { + if (!strictNullChecks || target.flags & (32 | 16)) + return -1; + } + if (source.flags & 64) { + if (!strictNullChecks || target.flags & 64) + return -1; + } + if (source.flags & 128 && target === numberType) + return -1; + if (source.flags & 128 && target.flags & 128) { + if (result = enumRelatedTo(source, target, reportErrors)) { + return result; + } + } + if (source.flags & 256 && target === stringType) + return -1; + if (relation === assignableRelation || relation === comparableRelation) { + if (source.flags & 1) + return -1; + if (source === numberType && target.flags & 128) + return -1; + } + if (source.flags & 8 && target.flags & 8) { + return -1; + } + } + if (source.flags & 1048576) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { reportRelationError(headMessage, source, target); } return 0; } - if (target.flags & 1572864) { + if (target.flags & 49152) { source = getRegularTypeOfObjectLiteral(source); } } var saveErrorInfo = errorInfo; - if (source.flags & 524288) { + if (source.flags & 16384) { if (relation === comparableRelation) { - result = someTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190)); + result = someTypeRelatedToType(source, target, reportErrors); } else { - result = eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190)); + result = eachTypeRelatedToType(source, target, reportErrors); } if (result) { return result; } } - else if (target.flags & 1048576) { + else if (target.flags & 32768) { result = typeRelatedToEachType(source, target, reportErrors); if (result) { return result; } } else { - if (source.flags & 1048576) { + if (source.flags & 32768) { if (result = someTypeRelatedToType(source, target, false)) { return result; } } - if (target.flags & 524288) { - if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190) && !(target.flags & 8190))) { + if (target.flags & 16384) { + if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 16777726))) { return result; } } } - if (source.flags & 16384) { + if (source.flags & 512) { var constraint = getConstraintOfTypeParameter(source); if (!constraint || constraint.flags & 1) { constraint = emptyObjectType; @@ -20216,14 +18743,14 @@ var ts; } } else { - if (source.flags & 131072 && target.flags & 131072 && source.target === target.target) { + if (source.flags & 4096 && target.flags & 4096 && source.target === target.target) { if (result = typeArgumentsRelatedTo(source, target, reportErrors)) { return result; } } var apparentSource = getApparentType(source); - if (apparentSource.flags & (2588672 | 1048576) && target.flags & 2588672) { - var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !(source.flags & 8190); + if (apparentSource.flags & (80896 | 32768) && target.flags & 80896) { + var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !(source.flags & 16777726); if (result = objectTypeRelatedTo(apparentSource, source, target, reportStructuralErrors)) { errorInfo = saveErrorInfo; return result; @@ -20231,25 +18758,22 @@ var ts; } } if (reportErrors) { - if (source.flags & 2588672 && target.flags & 8190) { - tryElaborateErrorsForPrimitivesAndObjects(source, target); - } reportRelationError(headMessage, source, target); } return 0; } function isIdenticalTo(source, target) { var result; - if (source.flags & 2588672 && target.flags & 2588672) { - if (source.flags & 131072 && target.flags & 131072 && source.target === target.target) { + if (source.flags & 80896 && target.flags & 80896) { + if (source.flags & 4096 && target.flags & 4096 && source.target === target.target) { if (result = typeArgumentsRelatedTo(source, target, false)) { return result; } } return objectTypeRelatedTo(source, source, target, false); } - if (source.flags & 524288 && target.flags & 524288 || - source.flags & 1048576 && target.flags & 1048576) { + if (source.flags & 16384 && target.flags & 16384 || + source.flags & 32768 && target.flags & 32768) { if (result = eachTypeRelatedToSomeType(source, target, false)) { if (result &= eachTypeRelatedToSomeType(target, source, false)) { return result; @@ -20259,7 +18783,7 @@ var ts; return 0; } function isKnownProperty(type, name) { - if (type.flags & 2588672) { + if (type.flags & 80896) { var resolved = resolveStructuredTypeMembers(type); if ((relation === assignableRelation || relation === comparableRelation) && (type === globalObjectType || isEmptyObjectType(resolved)) || resolved.stringIndexInfo || @@ -20268,7 +18792,7 @@ var ts; return true; } } - else if (type.flags & 1572864) { + else if (type.flags & 49152) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; if (isKnownProperty(t, name)) { @@ -20286,7 +18810,7 @@ var ts; !t.numberIndexInfo; } function hasExcessProperties(source, target, reportErrors) { - if (!(target.flags & 536870912) && maybeTypeOfKind(target, 2588672)) { + if (!(target.flags & 67108864) && maybeTypeOfKind(target, 80896)) { for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; if (!isKnownProperty(target, prop.name)) { @@ -20316,10 +18840,14 @@ var ts; } function typeRelatedToSomeType(source, target, reportErrors) { var targetTypes = target.types; - if (target.flags & 524288 && containsType(targetTypes, source)) { - return -1; - } var len = targetTypes.length; + while (len >= 2 && targetTypes[len - 1].flags & 96) { + var related = isRelatedTo(source, targetTypes[len - 1], false); + if (related) { + return related; + } + len--; + } for (var i = 0; i < len; i++) { var related = isRelatedTo(source, targetTypes[i], reportErrors && i === len - 1); if (related) { @@ -20343,10 +18871,14 @@ var ts; } function someTypeRelatedToType(source, target, reportErrors) { var sourceTypes = source.types; - if (source.flags & 524288 && containsType(sourceTypes, target)) { - return -1; - } var len = sourceTypes.length; + while (len >= 2 && sourceTypes[len - 1].flags & 96) { + var related = isRelatedTo(sourceTypes[len - 1], target, false); + if (related) { + return related; + } + len--; + } for (var i = 0; i < len; i++) { var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); if (related) { @@ -20418,7 +18950,7 @@ var ts; } sourceStack[depth] = source; targetStack[depth] = target; - maybeStack[depth] = ts.createMap(); + maybeStack[depth] = {}; maybeStack[depth][id] = 1; depth++; var saveExpandingFlags = expandingFlags; @@ -20450,7 +18982,7 @@ var ts; if (result) { var maybeCache = maybeStack[depth]; var destinationCache = (result === -1 || depth === 0) ? relation : maybeStack[depth - 1]; - ts.copyProperties(maybeCache, destinationCache); + ts.copyMap(maybeCache, destinationCache); } else { relation[id] = reportErrors ? 3 : 2; @@ -20463,7 +18995,7 @@ var ts; } var result = -1; var properties = getPropertiesOfObjectType(target); - var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 8388608); + var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 524288); for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) { var targetProp = properties_1[_i]; var sourceProp = getPropertyOfType(source, targetProp.name); @@ -20529,7 +19061,7 @@ var ts; return result; } function propertiesIdenticalTo(source, target) { - if (!(source.flags & 2588672 && target.flags & 2588672)) { + if (!(source.flags & 80896 && target.flags & 80896)) { return 0; } var sourceProperties = getPropertiesOfObjectType(source); @@ -20642,7 +19174,7 @@ var ts; return indexTypesIdenticalTo(source, target, kind); } var targetInfo = getIndexInfoOfType(target, kind); - if (!targetInfo || ((targetInfo.type.flags & 1) && !(originalSource.flags & 8190))) { + if (!targetInfo || ((targetInfo.type.flags & 1) && !(originalSource.flags & 16777726))) { return -1; } var sourceInfo = getIndexInfoOfType(source, kind) || @@ -20679,6 +19211,27 @@ var ts; } return 0; } + function enumRelatedTo(source, target, reportErrors) { + if (source.symbol.name !== target.symbol.name || + source.symbol.flags & 128 || + target.symbol.flags & 128) { + return 0; + } + var targetEnumType = getTypeOfSymbol(target.symbol); + for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { + var property = _a[_i]; + if (property.flags & 8) { + var targetProperty = getPropertyOfType(targetEnumType, property.name); + if (!targetProperty || !(targetProperty.flags & 8)) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, undefined, 128)); + } + return 0; + } + } + } + return -1; + } function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) { if (!sourceSignature.declaration || !targetSignature.declaration) { return true; @@ -20701,7 +19254,7 @@ var ts; } } function isAbstractConstructorType(type) { - if (type.flags & 2097152) { + if (type.flags & 65536) { var symbol = type.symbol; if (symbol && symbol.flags & 32) { var declaration = getClassLikeDeclarationOfSymbol(symbol); @@ -20713,12 +19266,12 @@ var ts; return false; } function isDeeplyNestedGeneric(type, stack, depth) { - if (type.flags & (131072 | 4194304) && depth >= 5) { + if (type.flags & (4096 | 131072) && depth >= 5) { var symbol = type.symbol; var count = 0; for (var i = 0; i < depth; i++) { var t = stack[i]; - if (t.flags & (131072 | 4194304) && t.symbol === symbol) { + if (t.flags & (4096 | 131072) && t.symbol === symbol) { count++; if (count >= 5) return true; @@ -20760,10 +19313,8 @@ var ts; source.hasRestParameter === target.hasRestParameter) { return true; } - var sourceRestCount = source.hasRestParameter ? 1 : 0; - var targetRestCount = target.hasRestParameter ? 1 : 0; - if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (sourceRestCount > targetRestCount || - sourceRestCount === targetRestCount && source.parameters.length >= target.parameters.length)) { + if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (source.hasRestParameter && !target.hasRestParameter || + source.hasRestParameter === target.hasRestParameter && source.parameters.length >= target.parameters.length)) { return true; } return false; @@ -20813,23 +19364,31 @@ var ts; return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } function isSupertypeOfEach(candidate, types) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var t = types_5[_i]; if (candidate !== t && !isTypeSubtypeOf(t, candidate)) return false; } return true; } + function getCombinedFlagsOfTypes(types) { + var flags = 0; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var t = types_6[_i]; + flags |= t.flags; + } + return flags; + } function getCommonSupertype(types) { if (!strictNullChecks) { return ts.forEach(types, function (t) { return isSupertypeOfEach(t, types) ? t : undefined; }); } - var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 6144); }); + var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 96); }); if (!primaryTypes.length) { - return getUnionType(types, true); + return getUnionType(types); } var supertype = ts.forEach(primaryTypes, function (t) { return isSupertypeOfEach(t, primaryTypes) ? t : undefined; }); - return supertype && includeFalsyTypes(supertype, getFalsyFlagsOfTypes(types) & 6144); + return supertype && addTypeKind(supertype, getCombinedFlagsOfTypes(types) & 96); } function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { var bestSupertype; @@ -20859,72 +19418,44 @@ var ts; checkTypeSubtypeOf(bestSupertypeDownfallType, bestSupertype, errorLocation, ts.Diagnostics.Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0, errorMessageChainHead); } function isArrayType(type) { - return type.flags & 131072 && type.target === globalArrayType; + return type.flags & 4096 && type.target === globalArrayType; } function isArrayLikeType(type) { - return type.flags & 131072 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || - !(type.flags & 6144) && isTypeAssignableTo(type, anyReadonlyArrayType); + return type.flags & 4096 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || + !(type.flags & 96) && isTypeAssignableTo(type, anyReadonlyArrayType); } function isTupleLikeType(type) { return !!getPropertyOfType(type, "0"); } - function isUnitType(type) { - return (type.flags & (480 | 2048 | 4096)) !== 0; - } - function isUnitUnionType(type) { - return type.flags & 8 ? true : - type.flags & 524288 ? type.flags & 16 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : - isUnitType(type); - } - function getBaseTypeOfUnitType(type) { - return type.flags & 32 ? stringType : - type.flags & 64 ? numberType : - type.flags & 128 ? booleanType : - type.flags & 256 ? type.baseType : - type.flags & 524288 && !(type.flags & 16) ? getUnionType(ts.map(type.types, getBaseTypeOfUnitType)) : - type; + function isStringLiteralUnionType(type) { + return type.flags & 256 ? true : + type.flags & 16384 ? ts.forEach(type.types, isStringLiteralUnionType) : + false; } function isTupleType(type) { - return !!(type.flags & 131072 && type.target.flags & 262144); + return !!(type.flags & 8192); } - function getFalsyFlagsOfTypes(types) { - var result = 0; - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var t = types_8[_i]; - result |= getFalsyFlags(t); - } - return result; + function getCombinedTypeFlags(type) { + return type.flags & 16384 ? getCombinedFlagsOfTypes(type.types) : type.flags; } - function getFalsyFlags(type) { - return type.flags & 524288 ? getFalsyFlagsOfTypes(type.types) : - type.flags & 32 ? type === emptyStringType ? 32 : 0 : - type.flags & 64 ? type === zeroType ? 64 : 0 : - type.flags & 128 ? type === falseType ? 128 : 0 : - type.flags & 7406; - } - function includeFalsyTypes(type, flags) { - if ((getFalsyFlags(type) & flags) === flags) { + function addTypeKind(type, kind) { + if ((getCombinedTypeFlags(type) & kind) === kind) { return type; } var types = [type]; - if (flags & 34) - types.push(emptyStringType); - if (flags & 340) - types.push(zeroType); - if (flags & 136) - types.push(falseType); - if (flags & 1024) + if (kind & 2) + types.push(stringType); + if (kind & 4) + types.push(numberType); + if (kind & 8) + types.push(booleanType); + if (kind & 16) types.push(voidType); - if (flags & 2048) + if (kind & 32) types.push(undefinedType); - if (flags & 4096) + if (kind & 64) types.push(nullType); - return getUnionType(types, true); - } - function removeDefinitelyFalsyTypes(type) { - return getFalsyFlags(type) & 7392 ? - filterType(type, function (t) { return !(getFalsyFlags(t) & 7392); }) : - type; + return getUnionType(types); } function getNonNullableType(type) { return strictNullChecks ? getTypeWithFacts(type, 524288) : type; @@ -20946,7 +19477,7 @@ var ts; return symbol; } function transformTypeOfMembers(type, f) { - var members = ts.createMap(); + var members = {}; for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { var property = _a[_i]; var original = getTypeOfSymbol(property); @@ -20957,7 +19488,7 @@ var ts; return members; } function getRegularTypeOfObjectLiteral(type) { - if (!(type.flags & 16777216)) { + if (!(type.flags & 1048576)) { return type; } var regularType = type.regularType; @@ -20967,7 +19498,7 @@ var ts; var resolved = type; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); - regularNew.flags = resolved.flags & ~16777216; + regularNew.flags = resolved.flags & ~1048576; type.regularType = regularNew; return regularNew; } @@ -20981,28 +19512,31 @@ var ts; return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); } function getWidenedConstituentType(type) { - return type.flags & 6144 ? type : getWidenedType(type); + return type.flags & 96 ? type : getWidenedType(type); } function getWidenedType(type) { - if (type.flags & 100663296) { - if (type.flags & 6144) { + if (type.flags & 6291456) { + if (type.flags & 96) { return anyType; } - if (type.flags & 8388608) { + if (type.flags & 524288) { return getWidenedTypeOfObjectLiteral(type); } - if (type.flags & 524288) { - return getUnionType(ts.map(type.types, getWidenedConstituentType)); + if (type.flags & 16384) { + return getUnionType(ts.map(type.types, getWidenedConstituentType), true); } - if (isArrayType(type) || isTupleType(type)) { - return createTypeReference(type.target, ts.map(type.typeArguments, getWidenedType)); + if (isArrayType(type)) { + return createArrayType(getWidenedType(type.typeArguments[0])); + } + if (isTupleType(type)) { + return createTupleType(ts.map(type.elementTypes, getWidenedType)); } } return type; } function reportWideningErrorsInType(type) { var errorReported = false; - if (type.flags & 524288) { + if (type.flags & 16384) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; if (reportWideningErrorsInType(t)) { @@ -21010,19 +19544,22 @@ var ts; } } } - if (isArrayType(type) || isTupleType(type)) { - for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) { + if (isArrayType(type)) { + return reportWideningErrorsInType(type.typeArguments[0]); + } + if (isTupleType(type)) { + for (var _b = 0, _c = type.elementTypes; _b < _c.length; _b++) { var t = _c[_b]; if (reportWideningErrorsInType(t)) { errorReported = true; } } } - if (type.flags & 8388608) { + if (type.flags & 524288) { for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); - if (t.flags & 33554432) { + if (t.flags & 2097152) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, p.name, typeToString(getWidenedType(t))); } @@ -21067,7 +19604,7 @@ var ts; error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); } function reportErrorsFromWidening(declaration, type) { - if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 33554432) { + if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 2097152) { if (!reportWideningErrorsInType(type)) { reportImplicitAnyError(declaration, type); } @@ -21109,24 +19646,12 @@ var ts; isFixed: false }; } - function couldContainTypeParameters(type) { - return !!(type.flags & 16384 || - type.flags & 131072 && ts.forEach(type.typeArguments, couldContainTypeParameters) || - type.flags & 2097152 && type.symbol && type.symbol.flags & (8192 | 2048 | 32) || - type.flags & 1572864 && couldUnionOrIntersectionContainTypeParameters(type)); - } - function couldUnionOrIntersectionContainTypeParameters(type) { - if (type.couldContainTypeParameters === undefined) { - type.couldContainTypeParameters = ts.forEach(type.types, couldContainTypeParameters); - } - return type.couldContainTypeParameters; - } function inferTypes(context, source, target) { var sourceStack; var targetStack; var depth = 0; var inferiority = 0; - var visited = ts.createMap(); + var visited = {}; inferFromTypes(source, target); function isInProcess(source, target) { for (var i = 0; i < depth; i++) { @@ -21137,21 +19662,11 @@ var ts; return false; } function inferFromTypes(source, target) { - if (!couldContainTypeParameters(target)) { - return; - } - if (source.flags & 524288 && target.flags & 524288 && !(source.flags & 16 && target.flags & 16) || - source.flags & 1048576 && target.flags & 1048576) { - if (source === target) { - for (var _i = 0, _a = source.types; _i < _a.length; _i++) { - var t = _a[_i]; - inferFromTypes(t, t); - } - return; - } + if (source.flags & 16384 && target.flags & 16384 || + source.flags & 32768 && target.flags & 32768) { var matchingTypes = void 0; - for (var _b = 0, _c = target.types; _b < _c.length; _b++) { - var t = _c[_b]; + for (var _i = 0, _a = target.types; _i < _a.length; _i++) { + var t = _a[_i]; if (typeIdenticalToSomeType(t, source.types)) { (matchingTypes || (matchingTypes = [])).push(t); inferFromTypes(t, t); @@ -21162,8 +19677,8 @@ var ts; target = removeTypesFromUnionOrIntersection(target, matchingTypes); } } - if (target.flags & 16384) { - if (source.flags & 134217728) { + if (target.flags & 512) { + if (source.flags & 8388608) { return; } var typeParameters = context.typeParameters; @@ -21182,7 +19697,7 @@ var ts; } } } - else if (source.flags & 131072 && target.flags & 131072 && source.target === target.target) { + else if (source.flags & 4096 && target.flags & 4096 && source.target === target.target) { var sourceTypes = source.typeArguments || emptyArray; var targetTypes = target.typeArguments || emptyArray; var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; @@ -21190,13 +19705,20 @@ var ts; inferFromTypes(sourceTypes[i], targetTypes[i]); } } - else if (target.flags & 1572864) { + else if (source.flags & 8192 && target.flags & 8192 && source.elementTypes.length === target.elementTypes.length) { + var sourceTypes = source.elementTypes; + var targetTypes = target.elementTypes; + for (var i = 0; i < sourceTypes.length; i++) { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } + } + else if (target.flags & 49152) { var targetTypes = target.types; var typeParameterCount = 0; var typeParameter = void 0; - for (var _d = 0, targetTypes_2 = targetTypes; _d < targetTypes_2.length; _d++) { - var t = targetTypes_2[_d]; - if (t.flags & 16384 && ts.contains(context.typeParameters, t)) { + for (var _b = 0, targetTypes_2 = targetTypes; _b < targetTypes_2.length; _b++) { + var t = targetTypes_2[_b]; + if (t.flags & 512 && ts.contains(context.typeParameters, t)) { typeParameter = t; typeParameterCount++; } @@ -21210,16 +19732,18 @@ var ts; inferiority--; } } - else if (source.flags & 1572864) { + else if (source.flags & 49152) { var sourceTypes = source.types; - for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { - var sourceType = sourceTypes_3[_e]; + for (var _c = 0, sourceTypes_3 = sourceTypes; _c < sourceTypes_3.length; _c++) { + var sourceType = sourceTypes_3[_c]; inferFromTypes(sourceType, target); } } else { source = getApparentType(source); - if (source.flags & 2588672) { + if (source.flags & 80896 && (target.flags & 4096 && target.typeArguments || + target.flags & 8192 || + target.flags & 65536 && target.symbol && target.symbol.flags & (8192 | 2048 | 32))) { if (isInProcess(source, target)) { return; } @@ -21227,7 +19751,7 @@ var ts; return; } var key = source.id + "," + target.id; - if (visited[key]) { + if (ts.hasProperty(visited, key)) { return; } visited[key] = true; @@ -21296,8 +19820,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var t = types_7[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -21312,7 +19836,7 @@ var ts; reducedTypes.push(t); } } - return type.flags & 524288 ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); + return type.flags & 16384 ? getUnionType(reducedTypes, true) : getIntersectionType(reducedTypes); } function getInferenceCandidates(context, index) { var inferences = context.inferences[index]; @@ -21324,7 +19848,7 @@ var ts; if (!inferredType) { var inferences = getInferenceCandidates(context, index); if (inferences.length) { - var unionOrSuperType = context.inferUnionTypes ? getUnionType(inferences, true) : getCommonSupertype(inferences); + var unionOrSuperType = context.inferUnionTypes ? getUnionType(inferences) : getCommonSupertype(inferences); inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType; inferenceSucceeded = !!unionOrSuperType; } @@ -21390,6 +19914,10 @@ var ts; } return undefined; } + function isNullOrUndefinedLiteral(node) { + return node.kind === 93 || + node.kind === 69 && getResolvedSymbol(node) === undefinedSymbol; + } function getLeftmostIdentifierOrThis(node) { switch (node.kind) { case 69: @@ -21401,17 +19929,16 @@ var ts; return undefined; } function isMatchingReference(source, target) { - switch (source.kind) { - case 69: - return target.kind === 69 && getResolvedSymbol(source) === getResolvedSymbol(target) || - (target.kind === 218 || target.kind === 169) && - getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); - case 97: - return target.kind === 97; - case 172: - return target.kind === 172 && - source.name.text === target.name.text && - isMatchingReference(source.expression, target.expression); + if (source.kind === target.kind) { + switch (source.kind) { + case 69: + return getResolvedSymbol(source) === getResolvedSymbol(target); + case 97: + return true; + case 172: + return source.name.text === target.name.text && + isMatchingReference(source.expression, target.expression); + } } return false; } @@ -21424,40 +19951,6 @@ var ts; } return false; } - function containsMatchingReferenceDiscriminant(source, target) { - return target.kind === 172 && - containsMatchingReference(source, target.expression) && - isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.text); - } - function getDeclaredTypeOfReference(expr) { - if (expr.kind === 69) { - return getTypeOfSymbol(getResolvedSymbol(expr)); - } - if (expr.kind === 172) { - var type = getDeclaredTypeOfReference(expr.expression); - return type && getTypeOfPropertyOfType(type, expr.name.text); - } - return undefined; - } - function isDiscriminantProperty(type, name) { - if (type && type.flags & 524288) { - var prop = getPropertyOfType(type, name); - if (!prop) { - var filteredType = getTypeWithFacts(type, 4194304); - if (filteredType !== type && filteredType.flags & 524288) { - prop = getPropertyOfType(filteredType, name); - } - } - if (prop && prop.flags & 268435456) { - if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !prop.hasCommonType && - isUnitUnionType(getTypeOfSymbol(prop)); - } - return prop.isDiscriminantProperty; - } - } - return false; - } function isOrContainsMatchingReference(source, target) { return isMatchingReference(source, target) || containsMatchingReference(source, target); } @@ -21484,7 +19977,7 @@ var ts; return flow.id; } function typeMaybeAssignableTo(source, target) { - if (!(source.flags & 524288)) { + if (!(source.flags & 16384)) { return isTypeAssignableTo(source, target); } for (var _i = 0, _a = source.types; _i < _a.length; _i++) { @@ -21496,79 +19989,70 @@ var ts; return false; } function getAssignmentReducedType(declaredType, assignedType) { - if (declaredType !== assignedType) { - var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); - if (reducedType !== neverType) { - return reducedType; + if (declaredType !== assignedType && declaredType.flags & 16384) { + var reducedTypes = ts.filter(declaredType.types, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (reducedTypes.length) { + return reducedTypes.length === 1 ? reducedTypes[0] : getUnionType(reducedTypes); } } return declaredType; } - function getTypeFactsOfTypes(types) { - var result = 0; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; - result |= getTypeFacts(t); - } - return result; - } - function isFunctionObjectType(type) { - var resolved = resolveStructuredTypeMembers(type); - return !!(resolved.callSignatures.length || resolved.constructSignatures.length || - resolved.members["bind"] && isTypeSubtypeOf(type, globalFunctionType)); - } function getTypeFacts(type) { var flags = type.flags; - if (flags & 2) { + if (flags & 258) { return strictNullChecks ? 4079361 : 4194049; } - if (flags & 32) { - return strictNullChecks ? - type === emptyStringType ? 3030785 : 1982209 : - type === emptyStringType ? 3145473 : 4194049; - } - if (flags & (4 | 16)) { + if (flags & 132) { return strictNullChecks ? 4079234 : 4193922; } - if (flags & (64 | 256)) { - var isZero = type === zeroType || type.flags & 256 && type.text === "0"; - return strictNullChecks ? - isZero ? 3030658 : 1982082 : - isZero ? 3145346 : 4193922; - } if (flags & 8) { return strictNullChecks ? 4078980 : 4193668; } - if (flags & 136) { - return strictNullChecks ? - type === falseType ? 3030404 : 1981828 : - type === falseType ? 3145092 : 4193668; + if (flags & 80896) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length || resolved.constructSignatures.length || isTypeSubtypeOf(type, globalFunctionType) ? + strictNullChecks ? 1970144 : 4181984 : + strictNullChecks ? 1972176 : 4184016; } - if (flags & 2588672) { - return isFunctionObjectType(type) ? - strictNullChecks ? 6164448 : 8376288 : - strictNullChecks ? 6166480 : 8378320; - } - if (flags & (1024 | 2048)) { + if (flags & (16 | 32)) { return 2457472; } - if (flags & 4096) { + if (flags & 64) { return 2340752; } - if (flags & 512) { + if (flags & 16777216) { return strictNullChecks ? 1981320 : 4193160; } - if (flags & 16384) { + if (flags & 512) { var constraint = getConstraintOfTypeParameter(type); - return getTypeFacts(constraint || emptyObjectType); + return constraint ? getTypeFacts(constraint) : 4194303; } - if (flags & 1572864) { - return getTypeFactsOfTypes(type.types); + if (flags & 32768) { + return ts.reduceLeft(type.types, function (flags, type) { return flags |= getTypeFacts(type); }, 0); } - return 8388607; + return 4194303; } function getTypeWithFacts(type, include) { - return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); + if (!(type.flags & 16384)) { + return getTypeFacts(type) & include ? type : neverType; + } + var firstType; + var types; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (getTypeFacts(t) & include) { + if (!firstType) { + firstType = t; + } + else { + if (!types) { + types = [firstType]; + } + types.push(t); + } + } + } + return firstType ? types ? getUnionType(types, true) : firstType : neverType; } function getTypeWithDefault(type, defaultExpression) { if (defaultExpression) { @@ -21662,86 +20146,51 @@ var ts; getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } - function getInitialOrAssignedType(node) { - return node.kind === 218 || node.kind === 169 ? - getInitialType(node) : - getAssignedType(node); - } - function getReferenceCandidate(node) { + function getReferenceFromExpression(node) { switch (node.kind) { case 178: - return getReferenceCandidate(node.expression); + return getReferenceFromExpression(node.expression); case 187: switch (node.operatorToken.kind) { case 56: - return getReferenceCandidate(node.left); + return getReferenceFromExpression(node.left); case 24: - return getReferenceCandidate(node.right); + return getReferenceFromExpression(node.right); } } return node; } function getTypeOfSwitchClause(clause) { if (clause.kind === 249) { - var caseType = checkExpression(clause.expression); - return isUnitType(caseType) ? caseType : undefined; + var expr = clause.expression; + return expr.kind === 9 ? getStringLiteralTypeForText(expr.text) : checkExpression(expr); } - return neverType; + return undefined; } function getSwitchClauseTypes(switchStatement) { var links = getNodeLinks(switchStatement); if (!links.switchTypes) { var types = ts.map(switchStatement.caseBlock.clauses, getTypeOfSwitchClause); - links.switchTypes = !ts.contains(types, undefined) ? types : emptyArray; + links.switchTypes = ts.forEach(types, function (t) { return !t || t.flags & 256; }) ? types : emptyArray; } return links.switchTypes; } function eachTypeContainedIn(source, types) { - return source.flags & 524288 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); - } - function isTypeSubsetOf(source, target) { - return source === target || target.flags & 524288 && isTypeSubsetOfUnion(source, target); - } - function isTypeSubsetOfUnion(source, target) { - if (source.flags & 524288) { - for (var _i = 0, _a = source.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (!containsType(target.types, t)) { - return false; - } - } - return true; - } - if (source.flags & 256 && target.flags & 16 && source.baseType === target) { - return true; - } - return containsType(target.types, source); + return source.flags & 16384 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } function filterType(type, f) { - if (type.flags & 524288) { - var types = type.types; - var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered); - } - return f(type) ? type : neverType; + return type.flags & 16384 ? + getUnionType(ts.filter(type.types, f)) : + f(type) ? type : neverType; } - function isIncomplete(flowType) { - return flowType.flags === 0; - } - function getTypeFromFlowType(flowType) { - return flowType.flags === 0 ? flowType.type : flowType; - } - function createFlowType(type, incomplete) { - return incomplete ? { flags: 0, type: type } : type; - } - function getFlowTypeOfReference(reference, declaredType, assumeInitialized, flowContainer) { + function getFlowTypeOfReference(reference, declaredType, assumeInitialized, includeOuterFunctions) { var key; - if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 4178943)) { + if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 16908175)) { return declaredType; } - var initialType = assumeInitialized ? declaredType : includeFalsyTypes(declaredType, 2048); + var initialType = assumeInitialized ? declaredType : addTypeKind(declaredType, 32); var visitedFlowStart = visitedFlowCount; - var result = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); + var result = getTypeAtFlowNode(reference.flowNode); visitedFlowCount = visitedFlowStart; if (reference.parent.kind === 196 && getTypeWithFacts(result, 524288) === neverType) { return declaredType; @@ -21781,7 +20230,7 @@ var ts; } else if (flow.flags & 2) { var container = flow.container; - if (container && container !== flowContainer && reference.kind !== 172) { + if (container && includeOuterFunctions) { flow = container.flowNode; continue; } @@ -21800,9 +20249,16 @@ var ts; } function getTypeAtFlowAssignment(flow) { var node = flow.node; + if ((node.kind === 218 || node.kind === 169) && + reference.kind === 69 && + getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(reference)) === getSymbolOfNode(node)) { + return declaredType.flags & 16384 ? + getAssignmentReducedType(declaredType, getInitialType(node)) : + declaredType; + } if (isMatchingReference(reference, node)) { - return declaredType.flags & 524288 ? - getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : + return declaredType.flags & 16384 ? + getAssignmentReducedType(declaredType, getAssignedType(node)) : declaredType; } if (containsMatchingReference(reference, node)) { @@ -21811,55 +20267,37 @@ var ts; return undefined; } function getTypeAtFlowCondition(flow) { - var flowType = getTypeAtFlowNode(flow.antecedent); - var type = getTypeFromFlowType(flowType); + var type = getTypeAtFlowNode(flow.antecedent); if (type !== neverType) { var assumeTrue = (flow.flags & 32) !== 0; type = narrowType(type, flow.expression, assumeTrue); - if (type === neverType && isIncomplete(flowType)) { + if (type === neverType) { type = narrowType(declaredType, flow.expression, assumeTrue); } } - return createFlowType(type, isIncomplete(flowType)); + return type; } function getTypeAtSwitchClause(flow) { - var flowType = getTypeAtFlowNode(flow.antecedent); - var type = getTypeFromFlowType(flowType); - var expr = flow.switchStatement.expression; - if (isMatchingReference(reference, expr)) { - type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); - } - else if (isMatchingReferenceDiscriminant(expr)) { - type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); - } - return createFlowType(type, isIncomplete(flowType)); + var type = getTypeAtFlowNode(flow.antecedent); + return narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } function getTypeAtFlowBranchLabel(flow) { var antecedentTypes = []; - var subtypeReduction = false; - var seenIncomplete = false; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { var antecedent = _a[_i]; - var flowType = getTypeAtFlowNode(antecedent); - var type = getTypeFromFlowType(flowType); + var type = getTypeAtFlowNode(antecedent); if (type === declaredType && declaredType === initialType) { return type; } if (!ts.contains(antecedentTypes, type)) { antecedentTypes.push(type); } - if (!isTypeSubsetOf(type, declaredType)) { - subtypeReduction = true; - } - if (isIncomplete(flowType)) { - seenIncomplete = true; - } } - return createFlowType(getUnionType(antecedentTypes, subtypeReduction), seenIncomplete); + return getUnionType(antecedentTypes); } function getTypeAtFlowLoopLabel(flow) { var id = getFlowNodeId(flow); - var cache = flowLoopCaches[id] || (flowLoopCaches[id] = ts.createMap()); + var cache = flowLoopCaches[id] || (flowLoopCaches[id] = {}); if (!key) { key = getFlowCacheKey(reference); } @@ -21868,66 +20306,32 @@ var ts; } for (var i = flowLoopStart; i < flowLoopCount; i++) { if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key) { - return createFlowType(getUnionType(flowLoopTypes[i]), true); + return getUnionType(flowLoopTypes[i]); } } var antecedentTypes = []; - var subtypeReduction = false; - var firstAntecedentType; flowLoopNodes[flowLoopCount] = flow; flowLoopKeys[flowLoopCount] = key; flowLoopTypes[flowLoopCount] = antecedentTypes; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { var antecedent = _a[_i]; flowLoopCount++; - var flowType = getTypeAtFlowNode(antecedent); + var type = getTypeAtFlowNode(antecedent); flowLoopCount--; - if (!firstAntecedentType) { - firstAntecedentType = flowType; - } - var type = getTypeFromFlowType(flowType); if (cache[key]) { return cache[key]; } if (!ts.contains(antecedentTypes, type)) { antecedentTypes.push(type); } - if (!isTypeSubsetOf(type, declaredType)) { - subtypeReduction = true; - } if (type === declaredType) { break; } } - var result = getUnionType(antecedentTypes, subtypeReduction); - if (isIncomplete(firstAntecedentType)) { - return createFlowType(result, true); - } - return cache[key] = result; - } - function isMatchingReferenceDiscriminant(expr) { - return expr.kind === 172 && - declaredType.flags & 524288 && - isMatchingReference(reference, expr.expression) && - isDiscriminantProperty(declaredType, expr.name.text); - } - function narrowTypeByDiscriminant(type, propAccess, narrowType) { - var propName = propAccess.name.text; - var propType = getTypeOfPropertyOfType(type, propName); - var narrowedPropType = propType && narrowType(propType); - return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); + return cache[key] = getUnionType(antecedentTypes); } function narrowTypeByTruthiness(type, expr, assumeTrue) { - if (isMatchingReference(reference, expr)) { - return getTypeWithFacts(type, assumeTrue ? 1048576 : 2097152); - } - if (isMatchingReferenceDiscriminant(expr)) { - return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 1048576 : 2097152); }); - } - if (containsMatchingReferenceDiscriminant(reference, expr)) { - return declaredType; - } - return type; + return isMatchingReference(reference, expr) ? getTypeWithFacts(type, assumeTrue ? 1048576 : 2097152) : type; } function narrowTypeByBinaryExpression(type, expr, assumeTrue) { switch (expr.operatorToken.kind) { @@ -21937,29 +20341,26 @@ var ts; case 31: case 32: case 33: - var operator_1 = expr.operatorToken.kind; - var left_1 = getReferenceCandidate(expr.left); - var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 182 && right_1.kind === 9) { - return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); + var left = expr.left; + var operator = expr.operatorToken.kind; + var right = expr.right; + if (isNullOrUndefinedLiteral(right)) { + return narrowTypeByNullCheck(type, left, operator, right, assumeTrue); } - if (right_1.kind === 182 && left_1.kind === 9) { - return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); + if (isNullOrUndefinedLiteral(left)) { + return narrowTypeByNullCheck(type, right, operator, left, assumeTrue); } - if (isMatchingReference(reference, left_1)) { - return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); + if (left.kind === 182 && right.kind === 9) { + return narrowTypeByTypeof(type, left, operator, right, assumeTrue); } - if (isMatchingReference(reference, right_1)) { - return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); + if (right.kind === 182 && left.kind === 9) { + return narrowTypeByTypeof(type, right, operator, left, assumeTrue); } - if (isMatchingReferenceDiscriminant(left_1)) { - return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); + if (left.kind === 172) { + return narrowTypeByDiscriminant(type, left, operator, right, assumeTrue); } - if (isMatchingReferenceDiscriminant(right_1)) { - return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); - } - if (containsMatchingReferenceDiscriminant(reference, left_1) || containsMatchingReferenceDiscriminant(reference, right_1)) { - return declaredType; + if (right.kind === 172) { + return narrowTypeByDiscriminant(type, right, operator, left, assumeTrue); } break; case 91: @@ -21969,37 +20370,23 @@ var ts; } return type; } - function narrowTypeByEquality(type, operator, value, assumeTrue) { - if (type.flags & 1) { - return type; - } + function narrowTypeByNullCheck(type, target, operator, literal, assumeTrue) { if (operator === 31 || operator === 33) { assumeTrue = !assumeTrue; } - var valueType = checkExpression(value); - if (valueType.flags & 6144) { - if (!strictNullChecks) { - return type; - } - var doubleEquals = operator === 30 || operator === 31; - var facts = doubleEquals ? - assumeTrue ? 65536 : 524288 : - value.kind === 93 ? - assumeTrue ? 32768 : 262144 : - assumeTrue ? 16384 : 131072; - return getTypeWithFacts(type, facts); - } - if (type.flags & 2589191) { + if (!strictNullChecks || !isMatchingReference(reference, getReferenceFromExpression(target))) { return type; } - if (assumeTrue) { - var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType !== neverType ? narrowedType : type; - } - return isUnitType(valueType) ? filterType(type, function (t) { return t !== valueType; }) : type; + var doubleEquals = operator === 30 || operator === 31; + var facts = doubleEquals ? + assumeTrue ? 65536 : 524288 : + literal.kind === 93 ? + assumeTrue ? 32768 : 262144 : + assumeTrue ? 16384 : 131072; + return getTypeWithFacts(type, facts); } function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { - var target = getReferenceCandidate(typeOfExpr.expression); + var target = getReferenceFromExpression(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { if (containsMatchingReference(reference, target)) { return declaredType; @@ -22009,40 +20396,76 @@ var ts; if (operator === 31 || operator === 33) { assumeTrue = !assumeTrue; } - if (assumeTrue && !(type.flags & 524288)) { - var targetType = typeofTypesByName[literal.text]; + if (assumeTrue && !(type.flags & 16384)) { + var targetType = ts.getProperty(typeofTypesByName, literal.text); if (targetType && isTypeSubtypeOf(targetType, type)) { return targetType; } } var facts = assumeTrue ? - typeofEQFacts[literal.text] || 64 : - typeofNEFacts[literal.text] || 8192; + ts.getProperty(typeofEQFacts, literal.text) || 64 : + ts.getProperty(typeofNEFacts, literal.text) || 8192; return getTypeWithFacts(type, facts); } + function narrowTypeByDiscriminant(type, propAccess, operator, value, assumeTrue) { + if (!isMatchingReference(reference, propAccess.expression)) { + return type; + } + var propName = propAccess.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return type; + } + var discriminantType = value.kind === 9 ? getStringLiteralTypeForText(value.text) : checkExpression(value); + if (!isStringLiteralUnionType(discriminantType)) { + return type; + } + if (operator === 31 || operator === 33) { + assumeTrue = !assumeTrue; + } + if (assumeTrue) { + return filterType(type, function (t) { return areTypesComparable(getTypeOfPropertyOfType(t, propName), discriminantType); }); + } + if (discriminantType.flags & 256) { + return filterType(type, function (t) { return getTypeOfPropertyOfType(t, propName) !== discriminantType; }); + } + return type; + } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { + if (!isMatchingReference(reference, switchStatement.expression.expression)) { + return type; + } + var propName = switchStatement.expression.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return type; + } var switchTypes = getSwitchClauseTypes(switchStatement); if (!switchTypes.length) { return type; } var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); - var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); - var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType === neverType ? neverType : filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }); + var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, undefined); + var caseTypes = hasDefaultClause ? ts.filter(clauseTypes, function (t) { return !!t; }) : clauseTypes; + var discriminantType = caseTypes.length ? getUnionType(caseTypes) : undefined; + var caseType = discriminantType && filterType(type, function (t) { return isTypeComparableTo(discriminantType, getTypeOfPropertyOfType(t, propName)); }); if (!hasDefaultClause) { return caseType; } - var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, t)); }); - return caseType === neverType ? defaultType : getUnionType([caseType, defaultType]); + var defaultType = filterType(type, function (t) { return !eachTypeContainedIn(getTypeOfPropertyOfType(t, propName), switchTypes); }); + return caseType ? getUnionType([caseType, defaultType]) : defaultType; } function narrowTypeByInstanceof(type, expr, assumeTrue) { - var left = getReferenceCandidate(expr.left); + var left = getReferenceFromExpression(expr.left); if (!isMatchingReference(reference, left)) { if (containsMatchingReference(reference, left)) { return declaredType; } return type; } + if (isTypeAny(type)) { + return type; + } var rightType = checkExpression(expr.right); if (!isTypeSubtypeOf(rightType, globalFunctionType)) { return type; @@ -22055,15 +20478,12 @@ var ts; targetType = prototypePropertyType; } } - if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) { - return type; - } if (!targetType) { var constructSignatures = void 0; - if (rightType.flags & 65536) { + if (rightType.flags & 2048) { constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; } - else if (rightType.flags & 2097152) { + else if (rightType.flags & 65536) { constructSignatures = getSignaturesOfType(rightType, 1); } if (constructSignatures && constructSignatures.length) { @@ -22077,22 +20497,23 @@ var ts; } function getNarrowedType(type, candidate, assumeTrue) { if (!assumeTrue) { - return filterType(type, function (t) { return !isTypeInstanceOf(t, candidate); }); + return type.flags & 16384 ? + getUnionType(ts.filter(type.types, function (t) { return !isTypeSubtypeOf(t, candidate); })) : + type; } - if (type.flags & 524288) { - var assignableType = filterType(type, function (t) { return isTypeInstanceOf(t, candidate); }); - if (assignableType !== neverType) { - return assignableType; + if (type.flags & 16384) { + var assignableConstituents = ts.filter(type.types, function (t) { return isTypeAssignableTo(t, candidate); }); + if (assignableConstituents.length) { + return getUnionType(assignableConstituents); } } - var targetType = type.flags & 16384 ? getApparentType(type) : type; - return isTypeSubtypeOf(candidate, type) ? candidate : + var targetType = type.flags & 512 ? getApparentType(type) : type; + return isTypeAssignableTo(candidate, targetType) ? candidate : isTypeAssignableTo(type, candidate) ? type : - isTypeAssignableTo(candidate, targetType) ? candidate : - getIntersectionType([type, candidate]); + getIntersectionType([type, candidate]); } function narrowTypeByTypePredicate(type, callExpression, assumeTrue) { - if (!hasMatchingArgument(callExpression, reference)) { + if (type.flags & 1 || !hasMatchingArgument(callExpression, reference)) { return type; } var signature = getResolvedSignature(callExpression); @@ -22100,9 +20521,6 @@ var ts; if (!predicate) { return type; } - if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { - return type; - } if (ts.isIdentifierTypePredicate(predicate)) { var predicateArgument = callExpression.arguments[predicate.parameterIndex]; if (predicateArgument) { @@ -22173,48 +20591,20 @@ var ts; function getControlFlowContainer(node) { while (true) { node = node.parent; - if (ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || - node.kind === 226 || - node.kind === 256 || - node.kind === 145) { + if (ts.isFunctionLike(node) || node.kind === 226 || node.kind === 256 || node.kind === 145) { return node; } } } - function isParameterAssigned(symbol) { - var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; - var links = getNodeLinks(func); - if (!(links.flags & 4194304)) { - links.flags |= 4194304; - if (!hasParentWithAssignmentsMarked(func)) { - markParameterAssignments(func); - } - } - return symbol.isAssigned || false; - } - function hasParentWithAssignmentsMarked(node) { - while (true) { - node = node.parent; - if (!node) { - return false; - } - if (ts.isFunctionLike(node) && getNodeLinks(node).flags & 4194304) { - return true; - } - } - } - function markParameterAssignments(node) { - if (node.kind === 69) { - if (ts.isAssignmentTarget(node)) { - var symbol = getResolvedSymbol(node); - if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 142) { - symbol.isAssigned = true; - } - } - } - else { - ts.forEachChild(node, markParameterAssignments); + function isDeclarationIncludedInFlow(reference, declaration, includeOuterFunctions) { + var declarationContainer = getControlFlowContainer(declaration); + var container = getControlFlowContainer(reference); + while (container !== declarationContainer && + (container.kind === 179 || container.kind === 180) && + (includeOuterFunctions || ts.getImmediatelyInvokedFunctionExpression(container))) { + container = getControlFlowContainer(container); } + return container === declarationContainer; } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); @@ -22251,23 +20641,16 @@ var ts; checkCollisionWithCapturedThisVariable(node, node); checkNestedBlockScopedBinding(node, symbol); var type = getTypeOfSymbol(localOrExportSymbol); - var declaration = localOrExportSymbol.valueDeclaration; - if (!(localOrExportSymbol.flags & 3) || ts.isAssignmentTarget(node) || !declaration) { + if (!(localOrExportSymbol.flags & 3) || ts.isAssignmentTarget(node)) { return type; } - var isParameter = ts.getRootDeclaration(declaration).kind === 142; - var declarationContainer = getControlFlowContainer(declaration); - var flowContainer = getControlFlowContainer(node); - var isOuterVariable = flowContainer !== declarationContainer; - while (flowContainer !== declarationContainer && - (flowContainer.kind === 179 || flowContainer.kind === 180) && - (isReadonlySymbol(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { - flowContainer = getControlFlowContainer(flowContainer); - } - var assumeInitialized = !strictNullChecks || (type.flags & 1) !== 0 || isParameter || - isOuterVariable || ts.isInAmbientContext(declaration); - var flowType = getFlowTypeOfReference(node, type, assumeInitialized, flowContainer); - if (!assumeInitialized && !(getFalsyFlags(type) & 2048) && getFalsyFlags(flowType) & 2048) { + var declaration = localOrExportSymbol.valueDeclaration; + var includeOuterFunctions = isReadonlySymbol(localOrExportSymbol); + var assumeInitialized = !strictNullChecks || (type.flags & 1) !== 0 || !declaration || + ts.getRootDeclaration(declaration).kind === 142 || ts.isInAmbientContext(declaration) || + !isDeclarationIncludedInFlow(node, declaration, includeOuterFunctions); + var flowType = getFlowTypeOfReference(node, type, assumeInitialized, includeOuterFunctions); + if (!assumeInitialized && !(getCombinedTypeFlags(type) & 32) && getCombinedTypeFlags(flowType) & 32) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); return type; } @@ -22430,6 +20813,10 @@ var ts; return getInferredClassType(classSymbol); } } + var type = getContextuallyTypedThisType(container); + if (type) { + return type; + } var thisType = getThisTypeOfDeclaration(container); if (thisType) { return thisType; @@ -22438,7 +20825,7 @@ var ts; if (ts.isClassLike(container.parent)) { var symbol = getSymbolOfNode(container.parent); var type = container.flags & 32 ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; - return getFlowTypeOfReference(node, type, true, undefined); + return getFlowTypeOfReference(node, type, true, true); } if (ts.isInJavaScriptFile(node)) { var type = getTypeForThisExpressionFromJSDoc(container); @@ -22571,11 +20958,11 @@ var ts; return false; } } - function getContextualThisParameter(func) { + function getContextuallyTypedThisType(func) { if (isContextSensitiveFunctionOrObjectLiteralMethod(func) && func.kind !== 180) { var contextualSignature = getContextualSignature(func); if (contextualSignature) { - return contextualSignature.thisParameter; + return getThisTypeOfSignature(contextualSignature); } } return undefined; @@ -22632,15 +21019,15 @@ var ts; } } if (ts.isBindingPattern(declaration.name)) { - return getTypeFromBindingPattern(declaration.name, true, false); + return getTypeFromBindingPattern(declaration.name, true); } if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; - var name_15 = declaration.propertyName || declaration.name; + var name_13 = declaration.propertyName || declaration.name; if (ts.isVariableLike(parentDeclaration) && parentDeclaration.type && - !ts.isBindingPattern(name_15)) { - var text = getTextOfPropertyName(name_15); + !ts.isBindingPattern(name_13)) { + var text = getTextOfPropertyName(name_13); if (text) { return getTypeOfPropertyOfType(getTypeFromTypeNode(parentDeclaration.type), text); } @@ -22715,9 +21102,6 @@ var ts; var binaryExpression = node.parent; var operator = binaryExpression.operatorToken.kind; if (operator >= 56 && operator <= 68) { - if (ts.getSpecialPropertyAssignmentKind(binaryExpression) !== 0) { - return undefined; - } if (node === binaryExpression.right) { return checkExpression(binaryExpression.left); } @@ -22737,14 +21121,14 @@ var ts; return undefined; } function applyToContextualType(type, mapper) { - if (!(type.flags & 524288)) { + if (!(type.flags & 16384)) { return mapper(type); } var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var current = types_11[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var current = types_8[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -22762,7 +21146,7 @@ var ts; } function getTypeOfPropertyOfContextualType(type, name) { return applyToContextualType(type, function (t) { - var prop = t.flags & 4161536 ? getPropertyOfType(t, name) : undefined; + var prop = t.flags & 130048 ? getPropertyOfType(t, name) : undefined; return prop ? getTypeOfSymbol(prop) : undefined; }); } @@ -22770,7 +21154,7 @@ var ts; return applyToContextualType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); } function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 524288 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); + return !!(type.flags & 16384 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); } function getContextualTypeForObjectLiteralMethod(node) { ts.Debug.assert(ts.isObjectLiteralMethod(node)); @@ -22876,30 +21260,6 @@ var ts; } return undefined; } - function isLiteralTypeLocation(node) { - var parent = node.parent; - switch (parent.kind) { - case 187: - switch (parent.operatorToken.kind) { - case 32: - case 33: - case 30: - case 31: - return true; - } - break; - case 188: - return (node === parent.whenTrue || - node === parent.whenFalse) && - isLiteralTypeLocation(parent); - case 178: - return isLiteralTypeLocation(parent); - case 249: - case 166: - return true; - } - return false; - } function getNonGenericSignature(type) { var signatures = getSignaturesOfStructuredType(type, 0); if (signatures.length === 1) { @@ -22928,13 +21288,13 @@ var ts; if (!type) { return undefined; } - if (!(type.flags & 524288)) { + if (!(type.flags & 16384)) { return getNonGenericSignature(type); } var signatureList; var types = type.types; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var current = types_12[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var current = types_9[_i]; var signature = getNonGenericSignature(current); if (signature) { if (!signatureList) { @@ -22990,7 +21350,7 @@ var ts; } if (!hasSpreadElement) { if (inDestructuringPattern && elementTypes.length) { - var type = cloneTypeReference(createTupleType(elementTypes)); + var type = createNewTupleType(elementTypes); type.pattern = node; return type; } @@ -23002,7 +21362,7 @@ var ts; for (var i = elementTypes.length; i < patternElements.length; i++) { var patternElement = patternElements[i]; if (hasDefaultValue(patternElement)) { - elementTypes.push(contextualType.typeArguments[i]); + elementTypes.push(contextualType.elementTypes[i]); } else { if (patternElement.kind !== 193) { @@ -23017,15 +21377,13 @@ var ts; } } } - return createArrayType(elementTypes.length ? - getUnionType(elementTypes, true) : - strictNullChecks ? neverType : undefinedWideningType); + return createArrayType(elementTypes.length ? getUnionType(elementTypes) : strictNullChecks ? neverType : undefinedWideningType); } function isNumericName(name) { return name.kind === 140 ? isNumericComputedName(name) : isNumericLiteralName(name.text); } function isNumericComputedName(name) { - return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 340); + return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 132); } function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { return isTypeAny(type) || isTypeOfKind(type, kind); @@ -23037,7 +21395,7 @@ var ts; var links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); - if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 340 | 34 | 512)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 132 | 258 | 16777216)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -23053,13 +21411,13 @@ var ts; propTypes.push(getTypeOfSymbol(properties[i])); } } - var unionType = propTypes.length ? getUnionType(propTypes, true) : undefinedType; + var unionType = propTypes.length ? getUnionType(propTypes) : undefinedType; return createIndexInfo(unionType, false); } function checkObjectLiteral(node, contextualMapper) { var inDestructuringPattern = ts.isAssignmentTarget(node); checkGrammarObjectLiteralExpression(node, inDestructuringPattern); - var propertiesTable = ts.createMap(); + var propertiesTable = {}; var propertiesArray = []; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && @@ -23097,7 +21455,7 @@ var ts; patternWithComputedProperties = true; } } - else if (contextualTypeHasPattern && !(contextualType.flags & 536870912)) { + else if (contextualTypeHasPattern && !(contextualType.flags & 67108864)) { var impliedProp = getPropertyOfType(contextualType, member.name); if (impliedProp) { prop.flags |= impliedProp.flags & 536870912; @@ -23135,7 +21493,7 @@ var ts; if (contextualTypeHasPattern) { for (var _b = 0, _c = getPropertiesOfType(contextualType); _b < _c.length; _b++) { var prop = _c[_b]; - if (!propertiesTable[prop.name]) { + if (!ts.hasProperty(propertiesTable, prop.name)) { if (!(prop.flags & 536870912)) { error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } @@ -23147,8 +21505,8 @@ var ts; var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 0) : undefined; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 1) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16777216; - result.flags |= 8388608 | 67108864 | freshObjectLiteralFlag | (typeFlags & 234881024) | (patternWithComputedProperties ? 536870912 : 0); + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576; + result.flags |= 524288 | 4194304 | freshObjectLiteralFlag | (typeFlags & 14680064) | (patternWithComputedProperties ? 67108864 : 0); if (inDestructuringPattern) { result.pattern = node; } @@ -23202,9 +21560,9 @@ var ts; var correspondingPropSymbol = getPropertyOfType(elementAttributesType, node.name.text); correspondingPropType = correspondingPropSymbol && getTypeOfSymbol(correspondingPropSymbol); if (isUnhyphenatedJsxName(node.name.text)) { - var attributeType = getTypeOfPropertyOfType(elementAttributesType, getTextOfPropertyName(node.name)) || getIndexTypeOfType(elementAttributesType, 0); - if (attributeType) { - correspondingPropType = attributeType; + var indexerType = getIndexTypeOfType(elementAttributesType, 0); + if (indexerType) { + correspondingPropType = indexerType; } else { if (!correspondingPropType) { @@ -23277,7 +21635,7 @@ var ts; return links.resolvedSymbol; } function getJsxElementInstanceType(node, valueType) { - ts.Debug.assert(!(valueType.flags & 524288)); + ts.Debug.assert(!(valueType.flags & 16384)); if (isTypeAny(valueType)) { return anyType; } @@ -23289,11 +21647,11 @@ var ts; return unknownType; } } - return getUnionType(signatures.map(getReturnTypeOfSignature), true); + return getUnionType(signatures.map(getReturnTypeOfSignature)); } function getJsxElementPropertiesName() { - var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920, undefined); - var attribsPropTypeSym = jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.ElementAttributesPropertyNameContainer, 793064); + var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1536, undefined); + var attribsPropTypeSym = jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.ElementAttributesPropertyNameContainer, 793056); var attribPropType = attribsPropTypeSym && getDeclaredTypeOfSymbol(attribsPropTypeSym); var attribProperties = attribPropType && getPropertiesOfType(attribPropType); if (attribProperties) { @@ -23316,16 +21674,16 @@ var ts; if (!elemType) { elemType = checkExpression(node.tagName); } - if (elemType.flags & 524288) { + if (elemType.flags & 16384) { var types = elemType.types; return getUnionType(types.map(function (type) { return getResolvedJsxType(node, type, elemClassType); - }), true); + })); } if (elemType.flags & 2) { return anyType; } - else if (elemType.flags & 32) { + else if (elemType.flags & 256) { var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { var stringLiteralTypeName = elemType.text; @@ -23378,7 +21736,7 @@ var ts; else if (isTypeAny(attributesType) || (attributesType === unknownType)) { return attributesType; } - else if (attributesType.flags & 524288) { + else if (attributesType.flags & 16384) { error(node.tagName, ts.Diagnostics.JSX_element_attributes_type_0_may_not_be_a_union_type, typeToString(attributesType)); return anyType; } @@ -23461,7 +21819,7 @@ var ts; getSymbolLinks(reactSym).referenced = true; } var targetAttributesType = getJsxElementAttributesType(node); - var nameTable = ts.createMap(); + var nameTable = {}; var sawSpreadedAny = false; for (var i = node.attributes.length - 1; i >= 0; i--) { if (node.attributes[i].kind === 246) { @@ -23479,7 +21837,7 @@ var ts; var targetProperties = getPropertiesOfType(targetAttributesType); for (var i = 0; i < targetProperties.length; i++) { if (!(targetProperties[i].flags & 536870912) && - !nameTable[targetProperties[i].name]) { + nameTable[targetProperties[i].name] === undefined) { error(node, ts.Diagnostics.Property_0_is_missing_in_type_1, targetProperties[i].name, typeToString(targetAttributesType)); } } @@ -23540,10 +21898,10 @@ var ts; if (flags & 32) { return true; } - if (type.flags & 268435456) { + if (type.flags & 33554432) { type = getConstraintOfTypeParameter(type); } - if (!(getTargetType(type).flags & (32768 | 65536) && hasBaseType(type, enclosingClass))) { + if (!(getTargetType(type).flags & (1024 | 2048) && hasBaseType(type, enclosingClass))) { error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); return false; } @@ -23552,9 +21910,9 @@ var ts; function checkNonNullExpression(node) { var type = checkExpression(node); if (strictNullChecks) { - var kind = getFalsyFlags(type) & 6144; + var kind = getCombinedTypeFlags(type) & 96; if (kind) { - error(node, kind & 2048 ? kind & 4096 ? + error(node, kind & 32 ? kind & 64 ? ts.Diagnostics.Object_is_possibly_null_or_undefined : ts.Diagnostics.Object_is_possibly_undefined : ts.Diagnostics.Object_is_possibly_null); @@ -23575,13 +21933,13 @@ var ts; return type; } var apparentType = getApparentType(getWidenedType(type)); - if (apparentType === unknownType || (type.flags & 16384 && isTypeAny(apparentType))) { + if (apparentType === unknownType || (type.flags & 512 && isTypeAny(apparentType))) { return apparentType; } var prop = getPropertyOfType(apparentType, right.text); if (!prop) { if (right.text && !checkAndReportErrorForExtendingInterface(node)) { - error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type.flags & 268435456 ? apparentType : type)); + error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type.flags & 33554432 ? apparentType : type)); } return unknownType; } @@ -23600,15 +21958,12 @@ var ts; checkClassPropertyAccess(node, left, apparentType, prop); } var propType = getTypeOfSymbol(prop); - if (prop.flags & 8 && isLiteralContextForType(node, propType)) { - propType = getDeclaredTypeOfSymbol(prop); - } if (node.kind !== 172 || ts.isAssignmentTarget(node) || !(prop.flags & (3 | 4 | 98304)) && - !(prop.flags & 8192 && propType.flags & 524288)) { + !(prop.flags & 8192 && propType.flags & 16384)) { return propType; } - return getFlowTypeOfReference(node, propType, true, undefined); + return getFlowTypeOfReference(node, propType, true, false); } function isValidPropertyAccess(node, propertyName) { var left = node.kind === 172 @@ -23686,22 +22041,21 @@ var ts; return unknownType; } if (node.argumentExpression) { - var name_16 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); - if (name_16 !== undefined) { - var prop = getPropertyOfType(objectType, name_16); + var name_14 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); + if (name_14 !== undefined) { + var prop = getPropertyOfType(objectType, name_14); if (prop) { getNodeLinks(node).resolvedSymbol = prop; return getTypeOfSymbol(prop); } else if (isConstEnum) { - error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_16, symbolToString(objectType.symbol)); + error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_14, symbolToString(objectType.symbol)); return unknownType; } } } - var allowedNullableFlags = strictNullChecks ? 0 : 6144; - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 34 | 340 | 512 | allowedNullableFlags)) { - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 | allowedNullableFlags) || isForInVariableForNumericPropertyNames(node.argumentExpression)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 258 | 132 | 16777216)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 132) || isForInVariableForNumericPropertyNames(node.argumentExpression)) { var numberIndexInfo = getIndexInfoOfType(objectType, 1); if (numberIndexInfo) { getNodeLinks(node).resolvedIndexInfo = numberIndexInfo; @@ -23746,7 +22100,7 @@ var ts; if (!ts.isWellKnownSymbolSyntactically(expression)) { return false; } - if ((expressionType.flags & 512) === 0) { + if ((expressionType.flags & 16777216) === 0) { if (reportError) { error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); } @@ -23810,7 +22164,7 @@ var ts; lastParent = parent_9; } lastSymbol = symbol; - if (signature.hasLiteralTypes) { + if (signature.hasStringLiterals) { specializedIndex++; spliceIndex = specializedIndex; cutoffIndex++; @@ -23884,7 +22238,7 @@ var ts; return callIsIncomplete || hasEnoughArguments; } function getSingleCallSignature(type) { - if (type.flags & 2588672) { + if (type.flags & 80896) { var resolved = resolveStructuredTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -23984,7 +22338,9 @@ var ts; var paramType = getTypeAtPosition(signature, i); var argType = getEffectiveArgumentType(node, i, arg); if (argType === undefined) { - argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + argType = arg.kind === 9 && !reportErrors + ? getStringLiteralTypeForText(arg.text) + : checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); } var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; if (!checkTypeRelatedTo(argType, paramType, relation, errorNode, headMessage)) { @@ -24088,10 +22444,10 @@ var ts; case 69: case 8: case 9: - return getLiteralTypeForText(32, element.name.text); + return getStringLiteralTypeForText(element.name.text); case 140: var nameType = checkComputedPropertyName(element.name); - if (isTypeOfKind(nameType, 512)) { + if (isTypeOfKind(nameType, 16777216)) { return nameType; } else { @@ -24331,7 +22687,9 @@ var ts; } var callSignatures = getSignaturesOfType(apparentType, 0); var constructSignatures = getSignaturesOfType(apparentType, 1); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + if (isTypeAny(funcType) || + (isTypeAny(apparentType) && funcType.flags & 512) || + (!callSignatures.length && !constructSignatures.length && !(funcType.flags & 16384) && isTypeAssignableTo(funcType, globalFunctionType))) { if (funcType !== unknownType && node.typeArguments) { error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); } @@ -24348,21 +22706,6 @@ var ts; } return resolveCall(node, callSignatures, candidatesOutArray); } - function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { - if (isTypeAny(funcType)) { - return true; - } - if (isTypeAny(apparentFuncType) && funcType.flags & 16384) { - return true; - } - if (!numCallSignatures && !numConstructSignatures) { - if (funcType.flags & 524288) { - return false; - } - return isTypeAssignableTo(funcType, globalFunctionType); - } - return false; - } function resolveNewExpression(node, candidatesOutArray) { if (node.arguments && languageVersion < 1) { var spreadIndex = getSpreadArgumentIndex(node.arguments); @@ -24419,18 +22762,6 @@ var ts; var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); if (!isNodeWithinClass(node, declaringClassDeclaration)) { - var containingClass = ts.getContainingClass(node); - if (containingClass) { - var containingType = getTypeOfNode(containingClass); - var baseTypes = getBaseTypes(containingType); - if (baseTypes.length) { - var baseType = baseTypes[0]; - if (flags & 16 && - baseType.symbol === declaration.parent.symbol) { - return true; - } - } - } if (flags & 8) { error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); } @@ -24448,8 +22779,7 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0); - var constructSignatures = getSignaturesOfType(apparentType, 1); - if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { + if (isTypeAny(tagType) || (!callSignatures.length && !(tagType.flags & 16384) && isTypeAssignableTo(tagType, globalFunctionType))) { return resolveUntypedCall(node); } if (!callSignatures.length) { @@ -24480,8 +22810,7 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0); - var constructSignatures = getSignaturesOfType(apparentType, 1); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + if (funcType === anyType || (!callSignatures.length && !(funcType.flags & 16384) && isTypeAssignableTo(funcType, globalFunctionType))) { return resolveUntypedCall(node); } var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); @@ -24510,21 +22839,21 @@ var ts; function getResolvedSignature(node, candidatesOutArray) { var links = getNodeLinks(node); var cached = links.resolvedSignature; - if (cached && cached !== resolvingSignature && !candidatesOutArray) { + if (cached && cached !== anySignature && !candidatesOutArray) { return cached; } - links.resolvedSignature = resolvingSignature; + links.resolvedSignature = anySignature; var result = resolveSignature(node, candidatesOutArray); links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached; return result; } function getResolvedOrAnySignature(node) { - return getNodeLinks(node).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(node); + return getNodeLinks(node).resolvedSignature === anySignature ? anySignature : getResolvedSignature(node); } function getInferredClassType(symbol) { var links = getSymbolLinks(symbol); if (!links.inferredClassType) { - links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, undefined, undefined); + links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, undefined, undefined); } return links.inferredClassType; } @@ -24581,7 +22910,7 @@ var ts; if (strictNullChecks) { var declaration = symbol.valueDeclaration; if (declaration && declaration.initializer) { - return includeFalsyTypes(type, 2048); + return addTypeKind(type, 32); } } return type; @@ -24593,12 +22922,6 @@ var ts; } function assignContextualParameterTypes(signature, context, mapper) { var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); - if (context.thisParameter) { - if (!signature.thisParameter) { - signature.thisParameter = createTransientSymbol(context.thisParameter, undefined); - } - assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter), mapper); - } for (var i = 0; i < len; i++) { var parameter = signature.parameters[i]; var contextualParameterType = getTypeAtPosition(context, i); @@ -24696,7 +23019,7 @@ var ts; return isAsync ? createPromiseReturnType(func, voidType) : voidType; } } - type = contextualSignature ? getUnionType(types, true) : getCommonSupertype(types); + type = contextualSignature ? getUnionType(types) : getCommonSupertype(types); if (!type) { if (funcIsGenerator) { error(func, ts.Diagnostics.No_best_common_type_exists_among_yield_expressions); @@ -24704,7 +23027,7 @@ var ts; } else { error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); - return isAsync ? createPromiseReturnType(func, getUnionType(types, true)) : getUnionType(types, true); + return isAsync ? createPromiseReturnType(func, getUnionType(types)) : getUnionType(types); } } if (funcIsGenerator) { @@ -24734,18 +23057,24 @@ var ts; return aggregatedTypes; } function isExhaustiveSwitchStatement(node) { - if (!node.possiblyExhaustive) { + var expr = node.expression; + if (!node.possiblyExhaustive || expr.kind !== 172) { return false; } - var type = checkExpression(node.expression); - if (!isUnitUnionType(type)) { + var type = checkExpression(expr.expression); + if (!(type.flags & 16384)) { + return false; + } + var propName = expr.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { return false; } var switchTypes = getSwitchClauseTypes(node); if (!switchTypes.length) { return false; } - return eachTypeContainedIn(type, switchTypes); + return eachTypeContainedIn(propType, switchTypes); } function functionHasImplicitReturn(func) { if (!(func.flags & 32768)) { @@ -24795,7 +23124,7 @@ var ts; if (!produceDiagnostics) { return; } - if (returnType && maybeTypeOfKind(returnType, 1 | 1024)) { + if (returnType && maybeTypeOfKind(returnType, 1 | 16)) { return; } if (ts.nodeIsMissing(func.body) || func.body.kind !== 199 || !functionHasImplicitReturn(func)) { @@ -24897,7 +23226,7 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 340)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 132)) { error(operand, diagnostic); return false; } @@ -24991,22 +23320,16 @@ var ts; } function checkPrefixUnaryExpression(node) { var operandType = checkExpression(node.operand); - if (node.operator === 36 && node.operand.kind === 8 && isLiteralContextForType(node, numberType)) { - return getLiteralTypeForText(64, "" + -node.operand.text); - } switch (node.operator) { case 35: case 36: case 50: - if (maybeTypeOfKind(operandType, 512)) { + if (maybeTypeOfKind(operandType, 16777216)) { error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } return numberType; case 49: - var facts = getTypeFacts(operandType) & (1048576 | 2097152); - return facts === 1048576 ? falseType : - facts === 2097152 ? trueType : - booleanType; + return booleanType; case 41: case 42: var ok = checkArithmeticOperandType(node.operand, getNonNullableType(operandType), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); @@ -25029,10 +23352,10 @@ var ts; if (type.flags & kind) { return true; } - if (type.flags & 1572864) { + if (type.flags & 49152) { var types = type.types; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -25044,20 +23367,20 @@ var ts; if (type.flags & kind) { return true; } - if (type.flags & 524288) { + if (type.flags & 16384) { var types = type.types; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; if (!isTypeOfKind(t, kind)) { return false; } } return true; } - if (type.flags & 1048576) { + if (type.flags & 32768) { var types = type.types; - for (var _a = 0, types_15 = types; _a < types_15.length; _a++) { - var t = types_15[_a]; + for (var _a = 0, types_12 = types; _a < types_12.length; _a++) { + var t = types_12[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -25066,13 +23389,13 @@ var ts; return false; } function isConstEnumObjectType(type) { - return type.flags & (2588672 | 2097152) && type.symbol && isConstEnumSymbol(type.symbol); + return type.flags & (80896 | 65536) && type.symbol && isConstEnumSymbol(type.symbol); } function isConstEnumSymbol(symbol) { return (symbol.flags & 128) !== 0; } function checkInstanceOfExpression(left, right, leftType, rightType) { - if (isTypeOfKind(leftType, 8190)) { + if (isTypeOfKind(leftType, 16777726)) { error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } if (!(isTypeAny(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) { @@ -25081,10 +23404,10 @@ var ts; return booleanType; } function checkInExpression(left, right, leftType, rightType) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 34 | 340 | 512)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258 | 132 | 16777216)) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 2588672 | 16384)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 80896 | 512)) { error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; @@ -25099,14 +23422,14 @@ var ts; } function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, contextualMapper) { if (property.kind === 253 || property.kind === 254) { - var name_17 = property.name; - if (name_17.kind === 140) { - checkComputedPropertyName(name_17); + var name_15 = property.name; + if (name_15.kind === 140) { + checkComputedPropertyName(name_15); } - if (isComputedNonLiteralName(name_17)) { + if (isComputedNonLiteralName(name_15)) { return undefined; } - var text = getTextOfPropertyName(name_17); + var text = getTextOfPropertyName(name_15); var type = isTypeAny(objectLiteralType) ? objectLiteralType : getTypeOfPropertyOfType(objectLiteralType, text) || @@ -25121,7 +23444,7 @@ var ts; } } else { - error(name_17, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_17)); + error(name_15, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_15)); } } else { @@ -25151,9 +23474,8 @@ var ts; return checkDestructuringAssignment(element, type, contextualMapper); } else { - checkExpression(element); if (isTupleType(sourceType)) { - error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); + error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), sourceType.elementTypes.length, elements.length); } else { error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); @@ -25183,7 +23505,7 @@ var ts; var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { if (strictNullChecks && - !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 2048)) { + !(getCombinedTypeFlags(checkExpression(prop.objectAssignmentInitializer)) & 32)) { sourceType = getTypeWithFacts(sourceType, 131072); } checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, contextualMapper); @@ -25213,14 +23535,7 @@ var ts; return sourceType; } function isTypeEqualityComparableTo(source, target) { - return (target.flags & 6144) !== 0 || isTypeComparableTo(source, target); - } - function getBestChoiceType(type1, type2) { - var firstAssignableToSecond = isTypeAssignableTo(type1, type2); - var secondAssignableToFirst = isTypeAssignableTo(type2, type1); - return secondAssignableToFirst && !firstAssignableToSecond ? type1 : - firstAssignableToSecond && !secondAssignableToFirst ? type2 : - getUnionType([type1, type2], true); + return (target.flags & 96) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, contextualMapper) { return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, contextualMapper, node); @@ -25255,15 +23570,15 @@ var ts; case 68: case 46: case 66: - if (leftType.flags & 6144) + if (leftType.flags & 96) leftType = rightType; - if (rightType.flags & 6144) + if (rightType.flags & 96) rightType = leftType; leftType = getNonNullableType(leftType); rightType = getNonNullableType(rightType); var suggestedOperator = void 0; - if ((leftType.flags & 136) && - (rightType.flags & 136) && + if ((leftType.flags & 8) && + (rightType.flags & 8) && (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator)); } @@ -25277,18 +23592,18 @@ var ts; return numberType; case 35: case 57: - if (leftType.flags & 6144) + if (leftType.flags & 96) leftType = rightType; - if (rightType.flags & 6144) + if (rightType.flags & 96) rightType = leftType; leftType = getNonNullableType(leftType); rightType = getNonNullableType(rightType); var resultType = void 0; - if (isTypeOfKind(leftType, 340) && isTypeOfKind(rightType, 340)) { + if (isTypeOfKind(leftType, 132) && isTypeOfKind(rightType, 132)) { resultType = numberType; } else { - if (isTypeOfKind(leftType, 34) || isTypeOfKind(rightType, 34)) { + if (isTypeOfKind(leftType, 258) || isTypeOfKind(rightType, 258)) { resultType = stringType; } else if (isTypeAny(leftType) || isTypeAny(rightType)) { @@ -25320,12 +23635,6 @@ var ts; case 31: case 32: case 33: - var leftIsUnit = isUnitUnionType(leftType); - var rightIsUnit = isUnitUnionType(rightType); - if (!leftIsUnit || !rightIsUnit) { - leftType = leftIsUnit ? getBaseTypeOfUnitType(leftType) : leftType; - rightType = rightIsUnit ? getBaseTypeOfUnitType(rightType) : rightType; - } if (!isTypeEqualityComparableTo(leftType, rightType) && !isTypeEqualityComparableTo(rightType, leftType)) { reportOperatorError(); } @@ -25335,13 +23644,9 @@ var ts; case 90: return checkInExpression(left, right, leftType, rightType); case 51: - return getTypeFacts(leftType) & 1048576 ? - includeFalsyTypes(rightType, getFalsyFlags(strictNullChecks ? leftType : getBaseTypeOfUnitType(rightType))) : - leftType; + return strictNullChecks ? addTypeKind(rightType, getCombinedTypeFlags(leftType) & 112) : rightType; case 52: - return getTypeFacts(leftType) & 2097152 ? - getBestChoiceType(removeDefinitelyFalsyTypes(leftType), rightType) : - leftType; + return getUnionType([getNonNullableType(leftType), rightType]); case 56: checkAssignmentOperator(rightType); return getRegularTypeOfObjectLiteral(rightType); @@ -25349,8 +23654,8 @@ var ts; return rightType; } function checkForDisallowedESSymbolOperand(operator) { - var offendingSymbolOperand = maybeTypeOfKind(leftType, 512) ? left : - maybeTypeOfKind(rightType, 512) ? right : + var offendingSymbolOperand = maybeTypeOfKind(leftType, 16777216) ? left : + maybeTypeOfKind(rightType, 16777216) ? right : undefined; if (offendingSymbolOperand) { error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); @@ -25435,63 +23740,14 @@ var ts; checkExpression(node.condition); var type1 = checkExpression(node.whenTrue, contextualMapper); var type2 = checkExpression(node.whenFalse, contextualMapper); - return getBestChoiceType(type1, type2); + return getUnionType([type1, type2]); } - function typeContainsLiteralFromEnum(type, enumType) { - if (type.flags & 524288) { - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (t.flags & 256 && t.baseType === enumType) { - return true; - } - } - } - if (type.flags & 256) { - return type.baseType === enumType; - } - return false; - } - function isLiteralContextForType(node, type) { - if (isLiteralTypeLocation(node)) { - return true; - } + function checkStringLiteralExpression(node) { var contextualType = getContextualType(node); - if (contextualType) { - if (contextualType.flags & 16384) { - var apparentType = getApparentTypeOfTypeParameter(contextualType); - if (type === apparentType) { - return true; - } - contextualType = apparentType; - } - if (type.flags & 2) { - return maybeTypeOfKind(contextualType, 32); - } - if (type.flags & 4) { - return maybeTypeOfKind(contextualType, (64 | 256)); - } - if (type.flags & 8) { - return maybeTypeOfKind(contextualType, 128); - } - if (type.flags & 16) { - return typeContainsLiteralFromEnum(contextualType, type); - } - } - return false; - } - function checkLiteralExpression(node) { - if (node.kind === 8) { - checkGrammarNumericLiteral(node); - } - switch (node.kind) { - case 9: - return isLiteralContextForType(node, stringType) ? getLiteralTypeForText(32, node.text) : stringType; - case 8: - return isLiteralContextForType(node, numberType) ? getLiteralTypeForText(64, node.text) : numberType; - case 99: - case 84: - return isLiteralContextForType(node, booleanType) ? node.kind === 99 ? trueType : falseType : booleanType; + if (contextualType && isStringLiteralUnionType(contextualType)) { + return getStringLiteralTypeForText(node.text); } + return stringType; } function checkTemplateExpression(node) { ts.forEach(node.templateSpans, function (templateSpan) { @@ -25564,6 +23820,10 @@ var ts; } return type; } + function checkNumericLiteral(node) { + checkGrammarNumericLiteral(node); + return numberType; + } function checkExpressionWorker(node, contextualMapper) { switch (node.kind) { case 69: @@ -25574,13 +23834,15 @@ var ts; return checkSuperExpression(node); case 93: return nullWideningType; - case 9: - case 8: case 99: case 84: - return checkLiteralExpression(node); + return booleanType; + case 8: + return checkNumericLiteral(node); case 189: return checkTemplateExpression(node); + case 9: + return checkStringLiteralExpression(node); case 11: return stringType; case 10: @@ -25725,9 +23987,9 @@ var ts; else if (parameterName) { var hasReportedError = false; for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { - var name_18 = _a[_i].name; - if (ts.isBindingPattern(name_18) && - checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_18, parameterName, typePredicate.parameterName)) { + var name_16 = _a[_i].name; + if (ts.isBindingPattern(name_16) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_16, parameterName, typePredicate.parameterName)) { hasReportedError = true; break; } @@ -25755,15 +24017,15 @@ var ts; } function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) { for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { - var name_19 = _a[_i].name; - if (name_19.kind === 69 && - name_19.text === predicateVariableName) { + var name_17 = _a[_i].name; + if (name_17.kind === 69 && + name_17.text === predicateVariableName) { error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name_19.kind === 168 || - name_19.kind === 167) { - if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_19, predicateVariableNode, predicateVariableName)) { + else if (name_17.kind === 168 || + name_17.kind === 167) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_17, predicateVariableNode, predicateVariableName)) { return true; } } @@ -25811,21 +24073,22 @@ var ts; checkAsyncFunctionReturnType(node); } } - if (noUnusedIdentifiers && !node.body) { + if (!node.body) { checkUnusedTypeParameters(node); } } } function checkClassForDuplicateDeclarations(node) { - var instanceNames = ts.createMap(); - var staticNames = ts.createMap(); + var getter = 1, setter = 2, property = getter | setter; + var instanceNames = {}; + var staticNames = {}; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; if (member.kind === 148) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var param = _c[_b]; if (ts.isParameterPropertyDeclaration(param)) { - addName(instanceNames, param.name, param.name.text, 3); + addName(instanceNames, param.name, param.name.text, property); } } } @@ -25836,21 +24099,21 @@ var ts; if (memberName) { switch (member.kind) { case 149: - addName(names, member.name, memberName, 1); + addName(names, member.name, memberName, getter); break; case 150: - addName(names, member.name, memberName, 2); + addName(names, member.name, memberName, setter); break; case 145: - addName(names, member.name, memberName, 3); + addName(names, member.name, memberName, property); break; } } } } function addName(names, location, name, meaning) { - var prev = names[name]; - if (prev) { + if (ts.hasProperty(names, name)) { + var prev = names[name]; if (prev & meaning) { error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); } @@ -25864,7 +24127,7 @@ var ts; } } function checkObjectTypeForDuplicateDeclarations(node) { - var names = ts.createMap(); + var names = {}; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; if (member.kind == 144) { @@ -25878,7 +24141,7 @@ var ts; default: continue; } - if (names[memberName]) { + if (ts.hasProperty(names, memberName)) { error(member.symbol.valueDeclaration.name, ts.Diagnostics.Duplicate_identifier_0, memberName); error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); } @@ -26020,7 +24283,12 @@ var ts; checkSignatureDeclaration(node); if (node.kind === 149) { if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 32768)) { - if (!(node.flags & 65536)) { + if (node.flags & 65536) { + if (compilerOptions.noImplicitReturns) { + error(node.name, ts.Diagnostics.Not_all_code_paths_return_a_value); + } + } + else { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); } } @@ -26042,10 +24310,7 @@ var ts; checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type); } } - var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 149) { - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); - } + getTypeOfAccessors(getSymbolOfNode(node)); } if (node.parent.kind !== 171) { checkSourceElement(node.body); @@ -26098,9 +24363,6 @@ var ts; checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } - if (type.flags & 16 && !type.memberTypes && getNodeLinks(node).resolvedSymbol.flags & 8) { - error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); - } } } function checkTypeQuery(node) { @@ -26370,10 +24632,10 @@ var ts; case 224: return 2097152 | 1048576; case 229: - var result_2 = 0; + var result_1 = 0; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_2 |= getDeclarationSpaces(d); }); - return result_2; + ts.forEach(target.declarations, function (d) { result_1 |= getDeclarationSpaces(d); }); + return result_1; default: return 1048576; } @@ -26396,7 +24658,7 @@ var ts; if (isTypeAny(promise)) { return undefined; } - if (promise.flags & 131072) { + if (promise.flags & 4096) { if (promise.target === tryGetGlobalPromiseType() || promise.target === getGlobalPromiseLikeType()) { return promise.typeArguments[0]; @@ -26422,7 +24684,7 @@ var ts; if (onfulfilledParameterSignatures.length === 0) { return undefined; } - return getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), true); + return getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); } function getTypeOfFirstParameterOfSignature(signature) { return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType; @@ -26433,13 +24695,13 @@ var ts; function checkAwaitedType(type, location, message) { return checkAwaitedTypeWorker(type); function checkAwaitedTypeWorker(type) { - if (type.flags & 524288) { + if (type.flags & 16384) { var types = []; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var constituentType = _a[_i]; types.push(checkAwaitedTypeWorker(constituentType)); } - return getUnionType(types, true); + return getUnionType(types); } else { var promisedType = getPromisedType(type); @@ -26544,7 +24806,7 @@ var ts; function checkTypeNodeAsExpression(node) { if (node && node.kind === 155) { var root = getFirstIdentifier(node.typeName); - var meaning = root.parent.kind === 155 ? 793064 : 1920; + var meaning = root.parent.kind === 155 ? 793056 : 1536; var rootSymbol = resolveName(root, root.text, meaning | 8388608, undefined, undefined); if (rootSymbol && rootSymbol.flags & 8388608) { var aliasTarget = resolveAlias(rootSymbol); @@ -26700,19 +24962,20 @@ var ts; function checkUnusedLocalsAndParameters(node) { if (node.parent.kind !== 222 && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { var _loop_1 = function(key) { - var local = node.locals[key]; - if (!local.isReferenced) { - if (local.valueDeclaration && local.valueDeclaration.kind === 142) { - var parameter = local.valueDeclaration; - if (compilerOptions.noUnusedParameters && - !ts.isParameterPropertyDeclaration(parameter) && - !parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(parameter)) { - error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); + if (ts.hasProperty(node.locals, key)) { + var local_1 = node.locals[key]; + if (!local_1.isReferenced) { + if (local_1.valueDeclaration && local_1.valueDeclaration.kind === 142) { + var parameter = local_1.valueDeclaration; + if (compilerOptions.noUnusedParameters && + !ts.isParameterPropertyDeclaration(parameter) && + !parameterNameStartsWithUnderscore(parameter)) { + error(local_1.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local_1.name); + } + } + else if (compilerOptions.noUnusedLocals) { + ts.forEach(local_1.declarations, function (d) { return error(d.name || d, ts.Diagnostics._0_is_declared_but_never_used, local_1.name); }); } - } - else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return error(d.name || d, ts.Diagnostics._0_is_declared_but_never_used, local.name); }); } } }; @@ -26721,9 +24984,6 @@ var ts; } } } - function parameterIsThisKeyword(parameter) { - return parameter.name && parameter.name.originalKeywordKind === 97; - } function parameterNameStartsWithUnderscore(parameter) { return parameter.name && parameter.name.kind === 69 && parameter.name.text.charCodeAt(0) === 95; } @@ -26741,7 +25001,7 @@ var ts; for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; if (!parameter.symbol.isReferenced && parameter.flags & 8) { - error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_never_used, parameter.symbol.name); + error(parameter.name, ts.Diagnostics._0_is_declared_but_never_used, parameter.symbol.name); } } } @@ -26752,14 +25012,9 @@ var ts; function checkUnusedTypeParameters(node) { if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { if (node.typeParameters) { - var symbol = getSymbolOfNode(node); - var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations); - if (lastDeclaration !== node) { - return; - } for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { var typeParameter = _a[_i]; - if (!getMergedSymbol(typeParameter.symbol).isReferenced) { + if (!typeParameter.symbol.isReferenced) { error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name); } } @@ -26769,12 +25024,14 @@ var ts; function checkUnusedModuleMembers(node) { if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { for (var key in node.locals) { - var local = node.locals[key]; - if (!local.isReferenced && !local.exportSymbol) { - for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (!ts.isAmbientModule(declaration)) { - error(declaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); + if (ts.hasProperty(node.locals, key)) { + var local = node.locals[key]; + if (!local.isReferenced && !local.exportSymbol) { + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (!ts.isAmbientModule(declaration)) { + error(declaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); + } } } } @@ -26908,8 +25165,8 @@ var ts; container.kind === 225 || container.kind === 256); if (!namesShareScope) { - var name_20 = symbolToString(localDeclarationSymbol); - error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_20, name_20); + var name_18 = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_18, name_18); } } } @@ -26979,8 +25236,8 @@ var ts; } var parent_11 = node.parent.parent; var parentType = getTypeForBindingElementParent(parent_11); - var name_21 = node.propertyName || node.name; - var property = getPropertyOfType(parentType, getTextOfPropertyName(name_21)); + var name_19 = node.propertyName || node.name; + var property = getPropertyOfType(parentType, getTextOfPropertyName(name_19)); if (parent_11.initializer && property && getParentOfSymbol(property)) { checkClassPropertyAccess(parent_11, parent_11.initializer, parentType, property); } @@ -27156,7 +25413,7 @@ var ts; if (varExpr.kind === 170 || varExpr.kind === 171) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } - else if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 34)) { + else if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258)) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); } else { @@ -27164,7 +25421,7 @@ var ts; } } var rightType = checkNonNullExpression(node.expression); - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 2588672 | 16384)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 80896 | 512)) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); } checkSourceElement(node.statement); @@ -27217,7 +25474,7 @@ var ts; } var typeAsIterable = type; if (!typeAsIterable.iterableElementType) { - if ((type.flags & 131072) && type.target === getGlobalIterableType()) { + if ((type.flags & 4096) && type.target === getGlobalIterableType()) { typeAsIterable.iterableElementType = type.typeArguments[0]; } else { @@ -27232,7 +25489,7 @@ var ts; } return undefined; } - typeAsIterable.iterableElementType = getElementTypeOfIterator(getUnionType(ts.map(iteratorFunctionSignatures, getReturnTypeOfSignature), true), errorNode); + typeAsIterable.iterableElementType = getElementTypeOfIterator(getUnionType(ts.map(iteratorFunctionSignatures, getReturnTypeOfSignature)), errorNode); } } return typeAsIterable.iterableElementType; @@ -27243,7 +25500,7 @@ var ts; } var typeAsIterator = type; if (!typeAsIterator.iteratorElementType) { - if ((type.flags & 131072) && type.target === getGlobalIteratorType()) { + if ((type.flags & 4096) && type.target === getGlobalIteratorType()) { typeAsIterator.iteratorElementType = type.typeArguments[0]; } else { @@ -27258,7 +25515,7 @@ var ts; } return undefined; } - var iteratorNextResult = getUnionType(ts.map(iteratorNextFunctionSignatures, getReturnTypeOfSignature), true); + var iteratorNextResult = getUnionType(ts.map(iteratorNextFunctionSignatures, getReturnTypeOfSignature)); if (isTypeAny(iteratorNextResult)) { return undefined; } @@ -27278,7 +25535,7 @@ var ts; if (isTypeAny(type)) { return undefined; } - if ((type.flags & 131072) && type.target === getGlobalIterableIteratorType()) { + if ((type.flags & 4096) && type.target === getGlobalIterableIteratorType()) { return type.typeArguments[0]; } return getElementTypeOfIterable(type, undefined) || @@ -27287,10 +25544,10 @@ var ts; function checkElementTypeOfArrayOrString(arrayOrStringType, errorNode) { ts.Debug.assert(languageVersion < 2); var arrayType = arrayOrStringType; - if (arrayOrStringType.flags & 524288) { - arrayType = getUnionType(ts.filter(arrayOrStringType.types, function (t) { return !(t.flags & 34); }), true); + if (arrayOrStringType.flags & 16384) { + arrayType = getUnionType(ts.filter(arrayOrStringType.types, function (t) { return !(t.flags & 258); })); } - else if (arrayOrStringType.flags & 34) { + else if (arrayOrStringType.flags & 258) { arrayType = neverType; } var hasStringConstituent = arrayOrStringType !== arrayType; @@ -27315,10 +25572,10 @@ var ts; } var arrayElementType = getIndexTypeOfType(arrayType, 1) || unknownType; if (hasStringConstituent) { - if (arrayElementType.flags & 34) { + if (arrayElementType.flags & 258) { return stringType; } - return getUnionType([arrayElementType, stringType], true); + return getUnionType([arrayElementType, stringType]); } return arrayElementType; } @@ -27330,7 +25587,7 @@ var ts; } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { var unwrappedReturnType = ts.isAsyncFunctionLike(func) ? getPromisedType(returnType) : returnType; - return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 1024 | 1); + return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16 | 1); } function checkReturnStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { @@ -27461,7 +25718,7 @@ var ts; else { var identifierName = catchClause.variableDeclaration.name.text; var locals = catchClause.block.locals; - if (locals) { + if (locals && ts.hasProperty(locals, identifierName)) { var localSymbol = locals[identifierName]; if (localSymbol && (localSymbol.flags & 2) !== 0) { grammarErrorOnNode(localSymbol.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, identifierName); @@ -27486,7 +25743,7 @@ var ts; checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1); }); - if (type.flags & 32768 && ts.isClassLike(type.symbol.valueDeclaration)) { + if (type.flags & 1024 && ts.isClassLike(type.symbol.valueDeclaration)) { var classDeclaration = type.symbol.valueDeclaration; for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; @@ -27501,7 +25758,7 @@ var ts; var errorNode; if (stringIndexType && numberIndexType) { errorNode = declaredNumberIndexer || declaredStringIndexer; - if (!errorNode && (type.flags & 65536)) { + if (!errorNode && (type.flags & 2048)) { var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0) && getIndexTypeOfType(base, 1); }); errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; } @@ -27523,7 +25780,7 @@ var ts; else if (indexDeclaration) { errorNode = indexDeclaration; } - else if (containingType.flags & 65536) { + else if (containingType.flags & 2048) { var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.name) && getIndexTypeOfType(base, indexKind); }); errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; } @@ -27631,11 +25888,6 @@ var ts; } checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); - if (baseType_1.symbol.valueDeclaration && !ts.isInAmbientContext(baseType_1.symbol.valueDeclaration)) { - if (!isBlockScopedNameDeclaredBeforeUse(baseType_1.symbol.valueDeclaration, node)) { - error(baseTypeNode, ts.Diagnostics.A_class_must_be_declared_after_its_base_class); - } - } if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32)) { var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments); if (ts.forEach(constructors, function (sig) { return getReturnTypeOfSignature(sig) !== baseType_1; })) { @@ -27649,15 +25901,15 @@ var ts; if (implementedTypeNodes) { for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { var typeRefNode = implementedTypeNodes_1[_b]; - if (!ts.isEntityNameExpression(typeRefNode.expression)) { + if (!ts.isSupportedExpressionWithTypeArguments(typeRefNode)) { error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); } checkTypeReferenceNode(typeRefNode); if (produceDiagnostics) { var t = getTypeFromTypeNode(typeRefNode); if (t !== unknownType) { - var declaredType = (t.flags & 131072) ? t.target : t; - if (declaredType.flags & (32768 | 65536)) { + var declaredType = (t.flags & 4096) ? t.target : t; + if (declaredType.flags & (1024 | 2048)) { checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_implements_interface_1); } else { @@ -27781,7 +26033,7 @@ var ts; if (baseTypes.length < 2) { return true; } - var seen = ts.createMap(); + var seen = {}; ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen[p.name] = { prop: p, containingType: type }; }); var ok = true; for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { @@ -27789,11 +26041,11 @@ var ts; var properties = getPropertiesOfObjectType(getTypeWithThisArgument(base, type.thisType)); for (var _a = 0, properties_4 = properties; _a < properties_4.length; _a++) { var prop = properties_4[_a]; - var existing = seen[prop.name]; - if (!existing) { + if (!ts.hasProperty(seen, prop.name)) { seen[prop.name] = { prop: prop, containingType: base }; } else { + var existing = seen[prop.name]; var isInheritedProperty = existing.containingType !== type; if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) { ok = false; @@ -27831,7 +26083,7 @@ var ts; checkObjectTypeForDuplicateDeclarations(node); } ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) { - if (!ts.isEntityNameExpression(heritageElement.expression)) { + if (!ts.isSupportedExpressionWithTypeArguments(heritageElement)) { error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); } checkTypeReferenceNode(heritageElement); @@ -27839,7 +26091,7 @@ var ts; ts.forEach(node.members, checkSourceElement); if (produceDiagnostics) { checkTypeForDuplicateIndexSignatures(node); - registerForUnusedIdentifiersCheck(node); + checkUnusedTypeParameters(node); } } function checkTypeAliasDeclaration(node) { @@ -28154,6 +26406,9 @@ var ts; } } } + if (compilerOptions.noImplicitAny && !node.body) { + reportImplicitAnyError(node, anyType); + } if (node.body) { checkSourceElement(node.body); if (!ts.isGlobalScopeAugmentation(node)) { @@ -28179,9 +26434,9 @@ var ts; break; case 169: case 218: - var name_22 = node.name; - if (ts.isBindingPattern(name_22)) { - for (var _b = 0, _c = name_22.elements; _b < _c.length; _b++) { + var name_20 = node.name; + if (ts.isBindingPattern(name_20)) { + for (var _b = 0, _c = name_20.elements; _b < _c.length; _b++) { var el = _c[_b]; checkModuleAugmentationElement(el, isGlobalAugmentation); } @@ -28207,20 +26462,19 @@ var ts; } } function getFirstIdentifier(node) { - switch (node.kind) { - case 69: - return node; - case 139: - do { - node = node.left; - } while (node.kind !== 69); - return node; - case 172: - do { - node = node.expression; - } while (node.kind !== 69); - return node; + while (true) { + if (node.kind === 139) { + node = node.left; + } + else if (node.kind === 172) { + node = node.expression; + } + else { + break; + } } + ts.Debug.assert(node.kind === 69); + return node; } function checkExternalImportOrExportDeclaration(node) { var moduleName = ts.getExternalModuleName(node); @@ -28248,8 +26502,8 @@ var ts; var target = resolveAlias(symbol); if (target !== unknownSymbol) { var excludedMeanings = (symbol.flags & (107455 | 1048576) ? 107455 : 0) | - (symbol.flags & 793064 ? 793064 : 0) | - (symbol.flags & 1920 ? 1920 : 0); + (symbol.flags & 793056 ? 793056 : 0) | + (symbol.flags & 1536 ? 1536 : 0); if (target.flags & excludedMeanings) { var message = node.kind === 238 ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : @@ -28303,11 +26557,11 @@ var ts; if (target !== unknownSymbol) { if (target.flags & 107455) { var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 107455 | 1920).flags & 1920)) { + if (!(resolveEntityName(moduleName, 107455 | 1536).flags & 1536)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 793064) { + if (target.flags & 793056) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -28351,7 +26605,7 @@ var ts; checkAliasSymbol(node); if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; - var symbol = resolveName(exportedName, exportedName.text, 107455 | 793064 | 1920 | 8388608, undefined, undefined); + var symbol = resolveName(exportedName, exportedName.text, 107455 | 793056 | 1536 | 8388608, undefined, undefined); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, exportedName.text); } @@ -28407,13 +26661,13 @@ var ts; error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } - var exports_1 = getExportsOfModule(moduleSymbol); - for (var id in exports_1) { + var exports_2 = getExportsOfModule(moduleSymbol); + for (var id in exports_2) { if (id === "__export") { continue; } - var _a = exports_1[id], declarations = _a.declarations, flags = _a.flags; - if (flags & (1920 | 64 | 384)) { + var _a = exports_2[id], declarations = _a.declarations, flags = _a.flags; + if (flags & (1536 | 64 | 384)) { continue; } var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverload); @@ -28583,10 +26837,9 @@ var ts; } } function checkSourceFile(node) { - ts.performance.mark("beforeCheck"); + var start = new Date().getTime(); checkSourceFileWorker(node); - ts.performance.mark("afterCheck"); - ts.performance.measure("Check", "beforeCheck", "afterCheck"); + ts.checkTime += new Date().getTime() - start; } function checkSourceFileWorker(node) { var links = getNodeLinks(node); @@ -28657,7 +26910,7 @@ var ts; return false; } function getSymbolsInScope(location, meaning) { - var symbols = ts.createMap(); + var symbols = {}; var memberFlags = 0; if (isInsideWithStatementBody(location)) { return []; @@ -28688,7 +26941,7 @@ var ts; case 221: case 222: if (!(memberFlags & 32)) { - copySymbols(getSymbolOfNode(location).members, meaning & 793064); + copySymbols(getSymbolOfNode(location).members, meaning & 793056); } break; case 179: @@ -28709,7 +26962,7 @@ var ts; function copySymbol(symbol, meaning) { if (symbol.flags & meaning) { var id = symbol.name; - if (!symbols[id]) { + if (!ts.hasProperty(symbols, id)) { symbols[id] = symbol; } } @@ -28797,13 +27050,15 @@ var ts; default: } } - if (entityName.parent.kind === 235 && ts.isEntityNameExpression(entityName)) { - return resolveEntityName(entityName, 107455 | 793064 | 1920 | 8388608); + if (entityName.parent.kind === 235) { + return resolveEntityName(entityName, 107455 | 793056 | 1536 | 8388608); } - if (entityName.kind !== 172 && isInRightSideOfImportOrExportAssignment(entityName)) { - var importEqualsDeclaration = ts.getAncestor(entityName, 229); - ts.Debug.assert(importEqualsDeclaration !== undefined); - return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importEqualsDeclaration, true); + if (entityName.kind !== 172) { + if (isInRightSideOfImportOrExportAssignment(entityName)) { + var importEqualsDeclaration = ts.getAncestor(entityName, 229); + ts.Debug.assert(importEqualsDeclaration !== undefined); + return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importEqualsDeclaration, true); + } } if (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; @@ -28811,13 +27066,13 @@ var ts; if (isHeritageClauseElementIdentifier(entityName)) { var meaning = 0; if (entityName.parent.kind === 194) { - meaning = 793064; + meaning = 793056; if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { meaning |= 107455; } } else { - meaning = 1920; + meaning = 1536; } meaning |= 8388608; return resolveEntityName(entityName, meaning); @@ -28848,7 +27103,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = (entityName.parent.kind === 155 || entityName.parent.kind === 267) ? 793064 : 1920; + var meaning = (entityName.parent.kind === 155 || entityName.parent.kind === 267) ? 793056 : 1536; return resolveEntityName(entityName, meaning, false, true); } else if (entityName.parent.kind === 246) { @@ -28940,7 +27195,7 @@ var ts; function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 107455 | 793064 | 1920 | 8388608); + resolveEntityName(node.propertyName || node.name, 107455 | 793056 | 1536 | 8388608); } function getTypeOfNode(node) { if (isInsideWithStatementBody(node)) { @@ -29021,7 +27276,7 @@ var ts; var propsByName = createSymbolTable(getPropertiesOfType(type)); if (getSignaturesOfType(type, 0).length || getSignaturesOfType(type, 1).length) { ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { - if (!propsByName[p.name]) { + if (!ts.hasProperty(propsByName, p.name)) { propsByName[p.name] = p; } }); @@ -29031,9 +27286,9 @@ var ts; function getRootSymbols(symbol) { if (symbol.flags & 268435456) { var symbols_3 = []; - var name_23 = symbol.name; + var name_21 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_23); + var symbol = getPropertyOfType(t, name_21); if (symbol) { symbols_3.push(symbol); } @@ -29057,7 +27312,7 @@ var ts; } function moduleExportsSomeValue(moduleReferenceExpression) { var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); - if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + if (!moduleSymbol) { return true; } var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol); @@ -29066,7 +27321,7 @@ var ts; if (symbolLinks.exportsSomeValue === undefined) { symbolLinks.exportsSomeValue = hasExportAssignment ? !!(moduleSymbol.flags & 107455) - : ts.forEachProperty(getExportsOfModule(moduleSymbol), isValue); + : ts.forEachValue(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { @@ -29210,7 +27465,7 @@ var ts; return undefined; } function isFunctionType(type) { - return type.flags & 2588672 && getSignaturesOfType(type, 0).length > 0; + return type.flags & 80896 && getSignaturesOfType(type, 0).length > 0; } function getTypeReferenceSerializationKind(typeName) { var valueSymbol = resolveEntityName(typeName, 107455, true); @@ -29218,7 +27473,7 @@ var ts; if (constructorType && isConstructorType(constructorType)) { return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue; } - var typeSymbol = resolveEntityName(typeName, 793064, true); + var typeSymbol = resolveEntityName(typeName, 793056, true); if (!typeSymbol) { return ts.TypeReferenceSerializationKind.ObjectType; } @@ -29229,22 +27484,22 @@ var ts; else if (type.flags & 1) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (isTypeOfKind(type, 1024)) { + else if (isTypeOfKind(type, 16)) { return ts.TypeReferenceSerializationKind.VoidType; } - else if (isTypeOfKind(type, 136)) { + else if (isTypeOfKind(type, 8)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeOfKind(type, 340)) { + else if (isTypeOfKind(type, 132)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (isTypeOfKind(type, 34)) { + else if (isTypeOfKind(type, 258)) { return ts.TypeReferenceSerializationKind.StringLikeType; } - else if (isTupleType(type)) { + else if (isTypeOfKind(type, 8192)) { return ts.TypeReferenceSerializationKind.ArrayLikeType; } - else if (isTypeOfKind(type, 512)) { + else if (isTypeOfKind(type, 16777216)) { return ts.TypeReferenceSerializationKind.ESSymbolType; } else if (isFunctionType(type)) { @@ -29279,7 +27534,7 @@ var ts; getSymbolDisplayBuilder().buildTypeDisplay(baseType, writer, enclosingDeclaration, flags); } function hasGlobalName(name) { - return !!globals[name]; + return ts.hasProperty(globals, name); } function getReferencedValueSymbol(reference) { return getNodeLinks(reference).resolvedSymbol || @@ -29296,14 +27551,14 @@ var ts; if (resolvedTypeReferenceDirectives) { fileToDirective = ts.createFileMap(); for (var key in resolvedTypeReferenceDirectives) { + if (!ts.hasProperty(resolvedTypeReferenceDirectives, key)) { + continue; + } var resolvedDirective = resolvedTypeReferenceDirectives[key]; if (!resolvedDirective) { continue; } var file = host.getSourceFile(resolvedDirective.resolvedFileName); - if (!file) { - continue; - } fileToDirective.set(file.path, key); } } @@ -29342,7 +27597,7 @@ var ts; } var meaning = (node.kind === 172) || (node.kind === 69 && isInTypeQuery(node)) ? 107455 | 1048576 - : 793064 | 1920; + : 793056 | 1536; var symbol = resolveEntityName(node, meaning, true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; } @@ -29417,12 +27672,7 @@ var ts; (augmentations || (augmentations = [])).push(file.moduleAugmentations); } if (file.symbol && file.symbol.globalExports) { - var source = file.symbol.globalExports; - for (var id in source) { - if (!(id in globals)) { - globals[id] = source[id]; - } - } + mergeSymbolTable(globals, file.symbol.globalExports); } }); if (augmentations) { @@ -29453,7 +27703,7 @@ var ts; getGlobalTypedPropertyDescriptorType = ts.memoize(function () { return getGlobalType("TypedPropertyDescriptor", 1); }); getGlobalESSymbolConstructorSymbol = ts.memoize(function () { return getGlobalValueSymbol("Symbol"); }); getGlobalPromiseType = ts.memoize(function () { return getGlobalType("Promise", 1); }); - tryGetGlobalPromiseType = ts.memoize(function () { return getGlobalSymbol("Promise", 793064, undefined) && getGlobalPromiseType(); }); + tryGetGlobalPromiseType = ts.memoize(function () { return getGlobalSymbol("Promise", 793056, undefined) && getGlobalPromiseType(); }); getGlobalPromiseLikeType = ts.memoize(function () { return getGlobalType("PromiseLike", 1); }); getInstantiatedGlobalPromiseLikeType = ts.memoize(createInstantiatedPromiseLikeType); getGlobalPromiseConstructorSymbol = ts.memoize(function () { return getGlobalValueSymbol("Promise"); }); @@ -29473,7 +27723,7 @@ var ts; getGlobalIterableIteratorType = ts.memoize(function () { return emptyGenericType; }); } anyArrayType = createArrayType(anyType); - var symbol = getGlobalSymbol("ReadonlyArray", 793064, undefined); + var symbol = getGlobalSymbol("ReadonlyArray", 793056, undefined); globalReadonlyArrayType = symbol && getTypeOfGlobalSymbol(symbol, 1); anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; } @@ -29487,7 +27737,7 @@ var ts; function createThenableType() { var thenPropertySymbol = createSymbol(67108864 | 4, "then"); getSymbolLinks(thenPropertySymbol).type = globalFunctionType; - var thenableType = createObjectType(2097152); + var thenableType = createObjectType(65536); thenableType.properties = [thenPropertySymbol]; thenableType.members = createSymbolTable(thenableType.properties); thenableType.callSignatures = []; @@ -29515,9 +27765,49 @@ var ts; return false; } function checkGrammarModifiers(node) { - var quickResult = reportObviousModifierErrors(node); - if (quickResult !== undefined) { - return quickResult; + switch (node.kind) { + case 149: + case 150: + case 148: + case 145: + case 144: + case 147: + case 146: + case 153: + case 225: + case 230: + case 229: + case 236: + case 235: + case 179: + case 180: + case 142: + break; + case 220: + if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 118) && + node.parent.kind !== 226 && node.parent.kind !== 256) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + break; + case 221: + case 222: + case 200: + case 223: + if (node.modifiers && node.parent.kind !== 226 && node.parent.kind !== 256) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + break; + case 224: + if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 74) && + node.parent.kind !== 226 && node.parent.kind !== 256) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + break; + default: + return false; + } + if (!node.modifiers) { + return; } var lastStatic, lastPrivate, lastProtected, lastDeclare, lastAsync, lastReadonly; var flags = 0; @@ -29710,56 +28000,6 @@ var ts; return checkGrammarAsyncModifier(node, lastAsync); } } - function reportObviousModifierErrors(node) { - return !node.modifiers - ? false - : shouldReportBadModifier(node) - ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here) - : undefined; - } - function shouldReportBadModifier(node) { - switch (node.kind) { - case 149: - case 150: - case 148: - case 145: - case 144: - case 147: - case 146: - case 153: - case 225: - case 230: - case 229: - case 236: - case 235: - case 179: - case 180: - case 142: - return false; - default: - if (node.parent.kind === 226 || node.parent.kind === 256) { - return false; - } - switch (node.kind) { - case 220: - return nodeHasAnyModifiersExcept(node, 118); - case 221: - return nodeHasAnyModifiersExcept(node, 115); - case 222: - case 200: - case 223: - return true; - case 224: - return nodeHasAnyModifiersExcept(node, 74); - default: - ts.Debug.fail(); - return false; - } - } - } - function nodeHasAnyModifiersExcept(node, allowedModifier) { - return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier; - } function checkGrammarAsyncModifier(node, asyncModifier) { if (languageVersion < 2) { return grammarErrorOnNode(asyncModifier, ts.Diagnostics.Async_functions_are_only_available_when_targeting_ECMAScript_2015_or_higher); @@ -29992,16 +28232,16 @@ var ts; } } function checkGrammarObjectLiteralExpression(node, inDestructuring) { - var seen = ts.createMap(); + var seen = {}; var Property = 1; var GetAccessor = 2; var SetAccessor = 4; var GetOrSetAccessor = GetAccessor | SetAccessor; var _loop_2 = function(prop) { - var name_24 = prop.name; + var name_22 = prop.name; if (prop.kind === 193 || - name_24.kind === 140) { - checkGrammarComputedPropertyName(name_24); + name_22.kind === 140) { + checkGrammarComputedPropertyName(name_22); } if (prop.kind === 254 && !inDestructuring && prop.objectAssignmentInitializer) { return { value: grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment) }; @@ -30014,8 +28254,8 @@ var ts; var currentKind = void 0; if (prop.kind === 253 || prop.kind === 254) { checkGrammarForInvalidQuestionMark(prop, prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name_24.kind === 8) { - checkGrammarNumericLiteral(name_24); + if (name_22.kind === 8) { + checkGrammarNumericLiteral(name_22); } currentKind = Property; } @@ -30031,28 +28271,28 @@ var ts; else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - var effectiveName = ts.getPropertyNameForPropertyNameNode(name_24); + var effectiveName = ts.getPropertyNameForPropertyNameNode(name_22); if (effectiveName === undefined) { return "continue"; } - if (!seen[effectiveName]) { + if (!ts.hasProperty(seen, effectiveName)) { seen[effectiveName] = currentKind; } else { var existingKind = seen[effectiveName]; if (currentKind === Property && existingKind === Property) { - grammarErrorOnNode(name_24, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_24)); + grammarErrorOnNode(name_22, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_22)); } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { seen[effectiveName] = currentKind | existingKind; } else { - return { value: grammarErrorOnNode(name_24, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name) }; + return { value: grammarErrorOnNode(name_22, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name) }; } } else { - return { value: grammarErrorOnNode(name_24, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name) }; + return { value: grammarErrorOnNode(name_22, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name) }; } } }; @@ -30063,19 +28303,19 @@ var ts; } } function checkGrammarJsxElement(node) { - var seen = ts.createMap(); + var seen = {}; for (var _i = 0, _a = node.attributes; _i < _a.length; _i++) { var attr = _a[_i]; if (attr.kind === 247) { continue; } var jsxAttr = attr; - var name_25 = jsxAttr.name; - if (!seen[name_25.text]) { - seen[name_25.text] = true; + var name_23 = jsxAttr.name; + if (!ts.hasProperty(seen, name_23.text)) { + seen[name_23.text] = true; } else { - return grammarErrorOnNode(name_25, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + return grammarErrorOnNode(name_23, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; if (initializer && initializer.kind === 248 && !initializer.expression) { @@ -30399,7 +28639,6 @@ var ts; node.kind === 229 || node.kind === 236 || node.kind === 235 || - node.kind === 228 || (node.flags & 2) || (node.flags & (1 | 512))) { return false; @@ -30451,15 +28690,7 @@ var ts; return true; } } - function getAmbientModules() { - var result = []; - for (var sym in globals) { - if (ambientModuleSymbolRegex.test(sym)) { - result.push(globals[sym]); - } - } - return result; - } + var _a; } ts.createTypeChecker = createTypeChecker; })(ts || (ts = {})); @@ -30493,7 +28724,6 @@ var ts; ts.getNullSourceMapWriter = getNullSourceMapWriter; function createSourceMapWriter(host, writer) { var compilerOptions = host.getCompilerOptions(); - var extendedDiagnostics = compilerOptions.extendedDiagnostics; var currentSourceFile; var sourceMapDir; var stopOverridingSpan = false; @@ -30622,9 +28852,6 @@ var ts; if (pos === -1) { return; } - if (extendedDiagnostics) { - ts.performance.mark("beforeSourcemap"); - } var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos); sourceLinePos.line++; sourceLinePos.character++; @@ -30652,10 +28879,6 @@ var ts; lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; } updateLastEncodedAndRecordedSpans(); - if (extendedDiagnostics) { - ts.performance.mark("afterSourcemap"); - ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); - } } function getStartPos(range) { var rangeHasDecorators = !!range.decorators; @@ -30743,11 +28966,11 @@ var ts; return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined); function getDeclarationDiagnosticsFromFile(_a, sources, isBundledEmit) { var declarationFilePath = _a.declarationFilePath; - emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit, false); + emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit); } } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles) { + function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit) { var newLine = host.getNewLine(); var compilerOptions = host.getCompilerOptions(); var write; @@ -30783,7 +29006,7 @@ var ts; ts.forEach(sourceFile.referencedFiles, function (fileReference) { var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); if (referencedFile && !ts.contains(emittedReferencedFiles, referencedFile)) { - if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference, emitOnlyDtsFiles)) { + if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference)) { addedGlobalFileReference = true; } emittedReferencedFiles.push(referencedFile); @@ -30833,7 +29056,9 @@ var ts; }); if (usedTypeDirectiveReferences) { for (var directive in usedTypeDirectiveReferences) { - referencesOutput += "/// " + newLine; + if (ts.hasProperty(usedTypeDirectiveReferences, directive)) { + referencesOutput += "/// " + newLine; + } } } return { @@ -30922,11 +29147,11 @@ var ts; return; } if (!usedTypeDirectiveReferences) { - usedTypeDirectiveReferences = ts.createMap(); + usedTypeDirectiveReferences = {}; } for (var _i = 0, typeReferenceDirectives_1 = typeReferenceDirectives; _i < typeReferenceDirectives_1.length; _i++) { var directive = typeReferenceDirectives_1[_i]; - if (!(directive in usedTypeDirectiveReferences)) { + if (!ts.hasProperty(usedTypeDirectiveReferences, directive)) { usedTypeDirectiveReferences[directive] = directive; } } @@ -30968,7 +29193,7 @@ var ts; } else { errorNameNode = declaration.name; - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 | 1024, writer); + resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2, writer); errorNameNode = undefined; } } @@ -30980,7 +29205,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 | 1024, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2, writer); errorNameNode = undefined; } } @@ -31078,7 +29303,7 @@ var ts; writeEntityName(entityName); } function emitExpressionWithTypeArguments(node) { - if (ts.isEntityNameExpression(node.expression)) { + if (ts.isSupportedExpressionWithTypeArguments(node)) { ts.Debug.assert(node.expression.kind === 69 || node.expression.kind === 172); emitEntityName(node.expression); if (node.typeArguments) { @@ -31147,15 +29372,15 @@ var ts; } function getExportDefaultTempVariableName() { var baseName = "_default"; - if (!(baseName in currentIdentifiers)) { + if (!ts.hasProperty(currentIdentifiers, baseName)) { return baseName; } var count = 0; while (true) { count++; - var name_26 = baseName + "_" + count; - if (!(name_26 in currentIdentifiers)) { - return name_26; + var name_24 = baseName + "_" + count; + if (!ts.hasProperty(currentIdentifiers, name_24)) { + return name_24; } } } @@ -31173,7 +29398,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 | 1024, writer); + resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2, writer); write(";"); writeLine(); write(node.isExportEquals ? "export = " : "export default "); @@ -31570,7 +29795,7 @@ var ts; emitCommaList(typeReferences, emitTypeOfTypeReference); } function emitTypeOfTypeReference(node) { - if (ts.isEntityNameExpression(node.expression)) { + if (ts.isSupportedExpressionWithTypeArguments(node)) { emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError); } else if (!isImplementsList && node.expression.kind === 93) { @@ -31578,7 +29803,7 @@ var ts; } else { writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 | 1024, writer); + resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2, writer); } function getHeritageClauseVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; @@ -31668,8 +29893,7 @@ var ts; } else { writeTextOfNode(currentText, node.name); - if ((node.kind === 145 || node.kind === 144 || - (node.kind === 142 && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { + if ((node.kind === 145 || node.kind === 144 || node.kind === 142) && ts.hasQuestionToken(node)) { write("?"); } if ((node.kind === 145 || node.kind === 144) && node.parent.kind === 159) { @@ -32142,14 +30366,14 @@ var ts; return emitSourceFile(node); } } - function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { + function writeReferencePath(referencedFile, addBundledFileReference) { var declFileName; var addedBundledEmitReference = false; if (ts.isDeclarationFile(referencedFile)) { declFileName = referencedFile.fileName; } else { - ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile, emitOnlyDtsFiles); + ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile); } if (declFileName) { declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, false); @@ -32166,8 +30390,8 @@ var ts; } } } - function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) { - var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles); + function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) { + var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit); var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; if (!emitSkipped) { var declarationOutput = emitDeclarationResult.referencesOutput @@ -32205,7 +30429,7 @@ var ts; return getResolvedExternalModuleName(host, file); } ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; - var entities = ts.createMap({ + var entities = { "quot": 0x0022, "amp": 0x0026, "apos": 0x0027, @@ -32459,8 +30683,8 @@ var ts; "clubs": 0x2663, "hearts": 0x2665, "diams": 0x2666 - }); - function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles) { + }; + function emitFiles(resolver, host, targetSourceFile) { var extendsHelper = "\nvar __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n};"; var assignHelper = "\nvar __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n};"; var decorateHelper = "\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};"; @@ -32476,7 +30700,7 @@ var ts; var emitSkipped = false; var newLine = host.getNewLine(); var emitJavaScript = createFileEmitter(); - ts.forEachExpectedEmitFile(host, emitFile, targetSourceFile, emitOnlyDtsFiles); + ts.forEachExpectedEmitFile(host, emitFile, targetSourceFile); return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -32485,7 +30709,7 @@ var ts; }; function isUniqueLocalName(name, container) { for (var node = container; ts.isNodeDescendentOf(node, container); node = node.nextContainer) { - if (node.locals && name in node.locals) { + if (node.locals && ts.hasProperty(node.locals, name)) { if (node.locals[name].flags & (107455 | 1048576 | 8388608)) { return false; } @@ -32496,13 +30720,13 @@ var ts; function setLabeledJump(state, isBreak, labelText, labelMarker) { if (isBreak) { if (!state.labeledNonLocalBreaks) { - state.labeledNonLocalBreaks = ts.createMap(); + state.labeledNonLocalBreaks = {}; } state.labeledNonLocalBreaks[labelText] = labelMarker; } else { if (!state.labeledNonLocalContinues) { - state.labeledNonLocalContinues = ts.createMap(); + state.labeledNonLocalContinues = {}; } state.labeledNonLocalContinues[labelText] = labelMarker; } @@ -32560,26 +30784,26 @@ var ts; var isOwnFileEmit; var emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos) { } : emitLeadingCommentsOfPositionWorker; var setSourceMapWriterEmit = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? changeSourceMapEmit : function (writer) { }; - var moduleEmitDelegates = ts.createMap((_a = {}, + var moduleEmitDelegates = (_a = {}, _a[ts.ModuleKind.ES6] = emitES6Module, _a[ts.ModuleKind.AMD] = emitAMDModule, _a[ts.ModuleKind.System] = emitSystemModule, _a[ts.ModuleKind.UMD] = emitUMDModule, _a[ts.ModuleKind.CommonJS] = emitCommonJSModule, _a - )); - var bundleEmitDelegates = ts.createMap((_b = {}, + ); + var bundleEmitDelegates = (_b = {}, _b[ts.ModuleKind.ES6] = function () { }, _b[ts.ModuleKind.AMD] = emitAMDModule, _b[ts.ModuleKind.System] = emitSystemModule, _b[ts.ModuleKind.UMD] = function () { }, _b[ts.ModuleKind.CommonJS] = function () { }, _b - )); + ); return doEmit; function doEmit(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit) { sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); - generatedNameSet = ts.createMap(); + generatedNameSet = {}; nodeToGeneratedName = []; decoratedClassAliases = []; isOwnFileEmit = !isBundledEmit; @@ -32590,7 +30814,7 @@ var ts; writeLine(); var sourceMappingURL = sourceMap.getSourceMappingURL(); if (sourceMappingURL) { - write("//# " + "sourceMappingURL" + "=" + sourceMappingURL); + write("//# sourceMappingURL=" + sourceMappingURL); } writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, compilerOptions.emitBOM, sourceFiles); sourceMap.reset(); @@ -32638,24 +30862,24 @@ var ts; } function isUniqueName(name) { return !resolver.hasGlobalName(name) && - !(name in currentFileIdentifiers) && - !(name in generatedNameSet); + !ts.hasProperty(currentFileIdentifiers, name) && + !ts.hasProperty(generatedNameSet, name); } function makeTempVariableName(flags) { if (flags && !(tempFlags & flags)) { - var name_27 = flags === 268435456 ? "_i" : "_n"; - if (isUniqueName(name_27)) { + var name_25 = flags === 268435456 ? "_i" : "_n"; + if (isUniqueName(name_25)) { tempFlags |= flags; - return name_27; + return name_25; } } while (true) { var count = tempFlags & 268435455; tempFlags++; if (count !== 8 && count !== 13) { - var name_28 = count < 26 ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); - if (isUniqueName(name_28)) { - return name_28; + var name_26 = count < 26 ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); + if (isUniqueName(name_26)) { + return name_26; } } } @@ -33353,8 +31577,8 @@ var ts; } else if (declaration.kind === 234) { write(getGeneratedNameForNode(declaration.parent.parent.parent)); - var name_29 = declaration.propertyName || declaration.name; - var identifier = ts.getTextOfNodeFromSourceText(currentText, name_29); + var name_27 = declaration.propertyName || declaration.name; + var identifier = ts.getTextOfNodeFromSourceText(currentText, name_27); if (languageVersion === 0 && identifier === "default") { write('["default"]'); } @@ -33421,8 +31645,8 @@ var ts; function emitIdentifier(node) { if (convertedLoopState) { if (node.text == "arguments" && resolver.isArgumentsLocalBinding(node)) { - var name_30 = convertedLoopState.argumentsName || (convertedLoopState.argumentsName = makeUniqueName("arguments")); - write(name_30); + var name_28 = convertedLoopState.argumentsName || (convertedLoopState.argumentsName = makeUniqueName("arguments")); + write(name_28); return; } } @@ -33536,10 +31760,6 @@ var ts; else if (node.parent.kind === 188 && node.parent.condition === node) { return true; } - else if (node.parent.kind === 185 || node.parent.kind === 181 || - node.parent.kind === 182 || node.parent.kind === 183) { - return true; - } return false; } function needsParenthesisForPropertyAccessOrInvocation(node) { @@ -33878,9 +32098,9 @@ var ts; if (languageVersion === 2 && node.expression.kind === 95 && isInAsyncMethodWithSuperInES6(node)) { - var name_31 = ts.createSynthesizedNode(9); - name_31.text = node.name.text; - emitSuperAccessInAsyncMethod(node.expression, name_31); + var name_29 = ts.createSynthesizedNode(9); + name_29.text = node.name.text; + emitSuperAccessInAsyncMethod(node.expression, name_29); return; } emit(node.expression); @@ -34126,7 +32346,6 @@ var ts; operand.kind !== 181 && operand.kind !== 186 && operand.kind !== 175 && - !(operand.kind === 187 && node.expression.kind === 195) && !(operand.kind === 174 && node.parent.kind === 175) && !(operand.kind === 179 && node.parent.kind === 174) && !(operand.kind === 8 && node.parent.kind === 172)) { @@ -34168,7 +32387,7 @@ var ts; if (modulekind === ts.ModuleKind.System || node.kind !== 69 || ts.nodeIsSynthesized(node)) { return false; } - return !exportEquals && exportSpecifiers && node.text in exportSpecifiers; + return !exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, node.text); } function emitPrefixUnaryExpression(node) { var isPlusPlusOrMinusMinus = (node.operator === 41 @@ -34629,12 +32848,12 @@ var ts; for (var _c = 0, _d = convertedLoopState.hoistedLocalVariables; _c < _d.length; _c++) { var id = _d[_c]; if (!seen) { - seen = ts.createMap(); + seen = {}; } else { write(", "); } - if (!(id.text in seen)) { + if (!ts.hasProperty(seen, id.text)) { emit(id); seen[id.text] = id.text; } @@ -35087,7 +33306,7 @@ var ts; } if (convertedLoopState) { if (!convertedLoopState.labels) { - convertedLoopState.labels = ts.createMap(); + convertedLoopState.labels = {}; } convertedLoopState.labels[node.label.text] = node.label.text; } @@ -35185,7 +33404,7 @@ var ts; if (modulekind === ts.ModuleKind.System) { return; } - if (!exportEquals && exportSpecifiers && name.text in exportSpecifiers) { + if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { for (var _a = 0, _b = exportSpecifiers[name.text]; _a < _b.length; _a++) { var specifier = _b[_a]; writeLine(); @@ -35554,12 +33773,12 @@ var ts; function emitParameter(node) { if (languageVersion < 2) { if (ts.isBindingPattern(node.name)) { - var name_32 = createTempVariable(0); + var name_30 = createTempVariable(0); if (!tempParameters) { tempParameters = []; } - tempParameters.push(name_32); - emit(name_32); + tempParameters.push(name_30); + emit(name_30); } else { emit(node.name); @@ -35618,12 +33837,11 @@ var ts; } function emitRestParameter(node) { if (languageVersion < 2 && ts.hasDeclaredRestParameter(node)) { - var restParam = node.parameters[node.parameters.length - 1]; + var restIndex = node.parameters.length - 1; + var restParam = node.parameters[restIndex]; if (ts.isBindingPattern(restParam.name)) { return; } - var skipThisCount = node.parameters.length && node.parameters[0].name.originalKeywordKind === 97 ? 1 : 0; - var restIndex = node.parameters.length - 1 - skipThisCount; var tempName = createTempVariable(268435456).text; writeLine(); emitLeadingComments(restParam); @@ -35736,7 +33954,7 @@ var ts; write("("); if (node) { var parameters = node.parameters; - var skipCount = node.parameters.length && node.parameters[0].name.originalKeywordKind === 97 ? 1 : 0; + var skipCount = node.parameters.length && node.parameters[0].name.text === "this" ? 1 : 0; var omitCount = languageVersion < 2 && ts.hasDeclaredRestParameter(node) ? 1 : 0; emitList(parameters, skipCount, parameters.length - omitCount - skipCount, false, false); } @@ -36153,7 +34371,12 @@ var ts; emitSignatureParameters(ctor); } else { - write("()"); + if (baseTypeElement) { + write("(...args)"); + } + else { + write("()"); + } } } var startIndex = 0; @@ -36185,7 +34408,7 @@ var ts; write("_super.apply(this, arguments);"); } else { - write("super(...arguments);"); + write("super(...args);"); } emitEnd(baseTypeElement); } @@ -36241,13 +34464,13 @@ var ts; if (isES6ExportedDeclaration(node) && !(node.flags & 512) && decoratedClassAlias === undefined) { write("export "); } + if (!isHoistedDeclarationInSystemModule) { + write("let "); + } if (decoratedClassAlias !== undefined) { - write("let " + decoratedClassAlias); + write("" + decoratedClassAlias); } else { - if (!isHoistedDeclarationInSystemModule) { - write("let "); - } emitDeclarationName(node); } write(" = "); @@ -36263,7 +34486,7 @@ var ts; var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 192; var generatedName; if (isClassExpressionWithStaticProperties) { - generatedName = node.name ? getGeneratedNameForNode(node.name) : makeUniqueName("classExpression"); + generatedName = getGeneratedNameForNode(node.name); var synthesizedNode = ts.createSynthesizedNode(69); synthesizedNode.text = generatedName; recordTempDeclaration(synthesizedNode); @@ -36713,11 +34936,10 @@ var ts; } if (valueDeclaration) { var parameters = valueDeclaration.parameters; - var skipThisCount = parameters.length && parameters[0].name.originalKeywordKind === 97 ? 1 : 0; var parameterCount = parameters.length; - if (parameterCount > skipThisCount) { - for (var i = skipThisCount; i < parameterCount; i++) { - if (i > skipThisCount) { + if (parameterCount > 0) { + for (var i = 0; i < parameterCount; i++) { + if (i > 0) { write(", "); } if (parameters[i].dotDotDotToken) { @@ -36972,7 +35194,7 @@ var ts; } } function tryRenameExternalModule(moduleName) { - if (renamedDependencies && moduleName.text in renamedDependencies) { + if (renamedDependencies && ts.hasProperty(renamedDependencies, moduleName.text)) { return "\"" + renamedDependencies[moduleName.text] + "\""; } return undefined; @@ -37073,7 +35295,7 @@ var ts; write(" = "); } else { - var isNakedImport = node.kind === 230 && !node.importClause; + var isNakedImport = 230 && !node.importClause; if (!isNakedImport) { write(varOrConst); write(getGeneratedNameForNode(node)); @@ -37272,7 +35494,7 @@ var ts; } function collectExternalModuleInfo(sourceFile) { externalImports = []; - exportSpecifiers = ts.createMap(); + exportSpecifiers = {}; exportEquals = undefined; hasExportStarsToExportValues = false; for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) { @@ -37304,8 +35526,8 @@ var ts; else { for (var _c = 0, _d = node.exportClause.elements; _c < _d.length; _c++) { var specifier = _d[_c]; - var name_33 = (specifier.propertyName || specifier.name).text; - (exportSpecifiers[name_33] || (exportSpecifiers[name_33] = [])).push(specifier); + var name_31 = (specifier.propertyName || specifier.name).text; + (exportSpecifiers[name_31] || (exportSpecifiers[name_31] = [])).push(specifier); } } break; @@ -37343,9 +35565,9 @@ var ts; } function getExternalModuleNameText(importNode, emitRelativePathAsModuleName) { if (emitRelativePathAsModuleName) { - var name_34 = getExternalModuleNameFromDeclaration(host, resolver, importNode); - if (name_34) { - return "\"" + name_34 + "\""; + var name_32 = getExternalModuleNameFromDeclaration(host, resolver, importNode); + if (name_32) { + return "\"" + name_32 + "\""; } } var moduleName = ts.getExternalModuleName(importNode); @@ -37384,7 +35606,7 @@ var ts; if (!hasExportStarsToExportValues) { return undefined; } - if (!exportedDeclarations && !ts.someProperties(exportSpecifiers)) { + if (!exportedDeclarations && ts.isEmpty(exportSpecifiers)) { var hasExportDeclarationWithExportClause = false; for (var _a = 0, externalImports_2 = externalImports; _a < externalImports_2.length; _a++) { var externalImport = externalImports_2[_a]; @@ -37488,15 +35710,15 @@ var ts; if (hoistedVars) { writeLine(); write("var "); - var seen = ts.createMap(); + var seen = {}; for (var i = 0; i < hoistedVars.length; i++) { var local = hoistedVars[i]; - var name_35 = local.kind === 69 + var name_33 = local.kind === 69 ? local : local.name; - if (name_35) { - var text = ts.unescapeIdentifier(name_35.text); - if (text in seen) { + if (name_33) { + var text = ts.unescapeIdentifier(name_33.text); + if (ts.hasProperty(seen, text)) { continue; } else { @@ -37574,15 +35796,15 @@ var ts; } if (node.kind === 218 || node.kind === 169) { if (shouldHoistVariable(node, false)) { - var name_36 = node.name; - if (name_36.kind === 69) { + var name_34 = node.name; + if (name_34.kind === 69) { if (!hoistedVars) { hoistedVars = []; } - hoistedVars.push(name_36); + hoistedVars.push(name_34); } else { - ts.forEachChild(name_36, visit); + ts.forEachChild(name_34, visit); } } return; @@ -37739,7 +35961,7 @@ var ts; write("System.register("); writeModuleName(node, emitRelativePathAsModuleName); write("["); - var groupIndices = ts.createMap(); + var groupIndices = {}; var dependencyGroups = []; for (var i = 0; i < externalImports.length; i++) { var text = getExternalModuleNameText(externalImports[i], emitRelativePathAsModuleName); @@ -37747,7 +35969,7 @@ var ts; continue; } var key = text.substr(1, text.length - 2); - if (key in groupIndices) { + if (ts.hasProperty(groupIndices, key)) { var groupIndex = groupIndices[key]; dependencyGroups[groupIndex].push(externalImports[i]); continue; @@ -38462,25 +36684,21 @@ var ts; } var _a, _b; } - function emitFile(_a, sourceFiles, isBundledEmit, emitOnlyDtsFiles) { + function emitFile(_a, sourceFiles, isBundledEmit) { var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath; - if (!emitOnlyDtsFiles) { - if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { - emitJavaScript(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); - } - else { - emitSkipped = true; - } + if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { + emitJavaScript(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + } + else { + emitSkipped = true; } if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; + emitSkipped = ts.writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; } if (!emitSkipped && emittedFilesList) { - if (!emitOnlyDtsFiles) { - emittedFilesList.push(jsFilePath); - if (sourceMapFilePath) { - emittedFilesList.push(sourceMapFilePath); - } + emittedFilesList.push(jsFilePath); + if (sourceMapFilePath) { + emittedFilesList.push(sourceMapFilePath); } if (declarationFilePath) { emittedFilesList.push(declarationFilePath); @@ -38492,12 +36710,16 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.version = "2.0.5"; + ts.programTime = 0; + ts.emitTime = 0; + ts.ioReadTime = 0; + ts.ioWriteTime = 0; + ts.version = "2.0.0"; var emptyArray = []; - function findConfigFile(searchPath, fileExists, configName) { - if (configName === void 0) { configName = "tsconfig.json"; } + var defaultTypeRoots = ["node_modules/@types"]; + function findConfigFile(searchPath, fileExists) { while (true) { - var fileName = ts.combinePaths(searchPath, configName); + var fileName = ts.combinePaths(searchPath, "tsconfig.json"); if (fileExists(fileName)) { return fileName; } @@ -38547,6 +36769,87 @@ var ts; return ts.getNormalizedPathFromPathComponents(commonPathComponents); } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; + function trace(host, message) { + host.trace(ts.formatMessage.apply(undefined, arguments)); + } + function isTraceEnabled(compilerOptions, host) { + return compilerOptions.traceResolution && host.trace !== undefined; + } + function hasZeroOrOneAsteriskCharacter(str) { + var seenAsterisk = false; + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) === 42) { + if (!seenAsterisk) { + seenAsterisk = true; + } + else { + return false; + } + } + } + return true; + } + ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; + function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { + return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; + } + function moduleHasNonRelativeName(moduleName) { + if (ts.isRootedDiskPath(moduleName)) { + return false; + } + var i = moduleName.lastIndexOf("./", 1); + var startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === 46); + return !startsWithDotSlashOrDotDotSlash; + } + function tryReadTypesSection(packageJsonPath, baseDirectory, state) { + var jsonContent; + try { + var jsonText = state.host.readFile(packageJsonPath); + jsonContent = jsonText ? JSON.parse(jsonText) : {}; + } + catch (e) { + jsonContent = {}; + } + var typesFile; + var fieldName; + if (jsonContent.typings) { + if (typeof jsonContent.typings === "string") { + fieldName = "typings"; + typesFile = jsonContent.typings; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, "typings", typeof jsonContent.typings); + } + } + } + if (!typesFile && jsonContent.types) { + if (typeof jsonContent.types === "string") { + fieldName = "types"; + typesFile = jsonContent.types; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, "types", typeof jsonContent.types); + } + } + } + if (typesFile) { + var typesFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath); + } + return typesFilePath; + } + if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); + } + var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); + return mainFilePath; + } + return undefined; + } var typeReferenceExtensions = [".d.ts"]; function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { @@ -38559,30 +36862,13 @@ var ts; else if (host.getCurrentDirectory) { currentDirectory = host.getCurrentDirectory(); } - return currentDirectory && getDefaultTypeRoots(currentDirectory, host); - } - ts.getEffectiveTypeRoots = getEffectiveTypeRoots; - function getDefaultTypeRoots(currentDirectory, host) { - if (!host.directoryExists) { - return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + if (!currentDirectory) { + return undefined; } - var typeRoots; - while (true) { - var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes); - if (host.directoryExists(atTypes)) { - (typeRoots || (typeRoots = [])).push(atTypes); - } - var parent_15 = ts.getDirectoryPath(currentDirectory); - if (parent_15 === currentDirectory) { - break; - } - currentDirectory = parent_15; - } - return typeRoots; + return ts.map(defaultTypeRoots, function (d) { return ts.combinePaths(currentDirectory, d); }); } - var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { - var traceEnabled = ts.isTraceEnabled(options, host); + var traceEnabled = isTraceEnabled(options, host); var moduleResolutionState = { compilerOptions: options, host: host, @@ -38593,35 +36879,35 @@ var ts; if (traceEnabled) { if (containingFile === undefined) { if (typeRoots === undefined) { - ts.trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); } else { - ts.trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); } } else { if (typeRoots === undefined) { - ts.trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); } else { - ts.trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); } } } var failedLookupLocations = []; if (typeRoots && typeRoots.length) { if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); } var primarySearchPaths = typeRoots; for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) { var typeRoot = primarySearchPaths_1[_i]; var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); - var resolvedFile_1 = ts.loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !ts.directoryProbablyExists(candidateDirectory, host), moduleResolutionState); + var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState); if (resolvedFile_1) { if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true); + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true); } return { resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 }, @@ -38632,7 +36918,7 @@ var ts; } else { if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); + trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); } } var resolvedFile; @@ -38642,21 +36928,21 @@ var ts; } if (initialLocationForSecondaryLookup !== undefined) { if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); + trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - resolvedFile = ts.loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, false); + resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState); if (traceEnabled) { if (resolvedFile) { - ts.trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); } else { - ts.trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); } } } else { if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); + trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); } } return { @@ -38667,8 +36953,398 @@ var ts; }; } ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; + function resolveModuleName(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + } + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + if (traceEnabled) { + trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + var result; + switch (moduleResolution) { + case ts.ModuleResolutionKind.NodeJs: + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); + break; + case ts.ModuleResolutionKind.Classic: + result = classicNameResolver(moduleName, containingFile, compilerOptions, host); + break; + } + if (traceEnabled) { + if (result.resolvedModule) { + trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); + } + else { + trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); + } + } + return result; + } + ts.resolveModuleName = resolveModuleName; + function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (moduleHasNonRelativeName(moduleName)) { + return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); + } + else { + return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); + } + } + function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.rootDirs) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var matchedRootDir; + var matchedNormalizedPrefix; + for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { + var rootDir = _a[_i]; + var normalizedRoot = ts.normalizePath(rootDir); + if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { + normalizedRoot += ts.directorySeparator; + } + var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && + (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); + } + if (isLongestMatchingPrefix) { + matchedNormalizedPrefix = normalizedRoot; + matchedRootDir = rootDir; + } + } + if (matchedNormalizedPrefix) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); + } + var suffix = candidate.substr(matchedNormalizedPrefix.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); + } + for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { + var rootDir = _c[_b]; + if (rootDir === matchedRootDir) { + continue; + } + var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); + } + var baseDirectory = ts.getDirectoryPath(candidate_1); + var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + if (resolvedFileName_1) { + return resolvedFileName_1; + } + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); + } + } + return undefined; + } + function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.baseUrl) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + } + var matchedPattern = undefined; + if (state.compilerOptions.paths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + matchedPattern = matchPatternOrExact(ts.getKeys(state.compilerOptions.paths), moduleName); + } + if (matchedPattern) { + var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName); + var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) { + var subst = _a[_i]; + var path = matchedStar ? subst.replace("*", matchedStar) : subst; + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + } + return undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); + } + return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + } + } + function matchPatternOrExact(patternStrings, candidate) { + var patterns = []; + for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { + var patternString = patternStrings_1[_i]; + var pattern = tryParsePattern(patternString); + if (pattern) { + patterns.push(pattern); + } + else if (patternString === candidate) { + return patternString; + } + } + return findBestPatternMatch(patterns, function (_) { return _; }, candidate); + } + function patternText(_a) { + var prefix = _a.prefix, suffix = _a.suffix; + return prefix + "*" + suffix; + } + function matchedText(pattern, candidate) { + ts.Debug.assert(isPatternMatch(pattern, candidate)); + return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); + } + function findBestPatternMatch(values, getPattern, candidate) { + var matchedValue = undefined; + var longestMatchPrefixLength = -1; + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var v = values_1[_i]; + var pattern = getPattern(v); + if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { + longestMatchPrefixLength = pattern.prefix.length; + matchedValue = v; + } + } + return matchedValue; + } + ts.findBestPatternMatch = findBestPatternMatch; + function isPatternMatch(_a, candidate) { + var prefix = _a.prefix, suffix = _a.suffix; + return candidate.length >= prefix.length + suffix.length && + ts.startsWith(candidate, prefix) && + ts.endsWith(candidate, suffix); + } + function tryParsePattern(pattern) { + ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); + var indexOfStar = pattern.indexOf("*"); + return indexOfStar === -1 ? undefined : { + prefix: pattern.substr(0, indexOfStar), + suffix: pattern.substr(indexOfStar + 1) + }; + } + ts.tryParsePattern = tryParsePattern; + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { + var containingDirectory = ts.getDirectoryPath(containingFile); + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var traceEnabled = isTraceEnabled(compilerOptions, host); + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); + var isExternalLibraryImport = false; + if (!resolvedFileName) { + if (moduleHasNonRelativeName(moduleName)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); + } + resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state); + isExternalLibraryImport = resolvedFileName !== undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, false, state); + } + } + if (resolvedFileName && host.realpath) { + var originalFileName = resolvedFileName; + resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName)); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); + } + } + return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; + function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); + } + var resolvedFileName = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); + return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); + } + function directoryProbablyExists(directoryName, host) { + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + var resolvedByAddingOrKeepingExtension = loadModuleFromFileWorker(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); + if (resolvedByAddingOrKeepingExtension) { + return resolvedByAddingOrKeepingExtension; + } + if (ts.hasJavaScriptFileExtension(candidate)) { + var extensionless = ts.removeFileExtension(candidate); + if (state.traceEnabled) { + var extension = candidate.substring(extensionless.length); + trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); + } + return loadModuleFromFileWorker(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); + } + } + function loadModuleFromFileWorker(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + var directory = ts.getDirectoryPath(candidate); + if (directory) { + onlyRecordFailures = !directoryProbablyExists(directory, state.host); + } + } + return ts.forEach(extensions, tryLoad); + function tryLoad(ext) { + if (state.skipTsx && ts.isJsxOrTsxExtension(ext)) { + return undefined; + } + var fileName = ts.fileExtensionIs(candidate, ext) ? candidate : candidate + ext; + if (!onlyRecordFailures && state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); + } + return fileName; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); + } + failedLookupLocation.push(fileName); + return undefined; + } + } + } + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { + var packageJsonPath = ts.combinePaths(candidate, "package.json"); + var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); + if (directoryExists && state.host.fileExists(packageJsonPath)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); + if (typesFile) { + var result = loadModuleFromFile(typesFile, extensions, failedLookupLocation, !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host), state); + if (result) { + return result; + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field); + } + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); + } + failedLookupLocation.push(packageJsonPath); + } + return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); + } + function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { + var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); + var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions); + var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); + if (result) { + return result; + } + result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); + if (result) { + return result; + } + } + function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state) { + directory = ts.normalizeSlashes(directory); + while (true) { + var baseName = ts.getBaseFileName(directory); + if (baseName !== "node_modules") { + var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); + if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { + return packageResult; + } + else { + var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); + if (typesResult || packageResult) { + return typesResult || packageResult; + } + } + } + var parentPath = ts.getDirectoryPath(directory); + if (parentPath === directory) { + break; + } + directory = parentPath; + } + return undefined; + } + function classicNameResolver(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; + var failedLookupLocations = []; + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var containingDirectory = ts.getDirectoryPath(containingFile); + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); + if (resolvedFileName) { + return createResolvedModule(resolvedFileName, false, failedLookupLocations); + } + var referencedSourceFile; + if (moduleHasNonRelativeName(moduleName)) { + while (true) { + var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state); + if (referencedSourceFile) { + break; + } + var parentPath = ts.getDirectoryPath(containingDirectory); + if (parentPath === containingDirectory) { + break; + } + containingDirectory = parentPath; + } + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, false, state); + } + return referencedSourceFile + ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } + : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; + } + ts.classicNameResolver = classicNameResolver; + ts.defaultInitCompilerOptions = { + module: ts.ModuleKind.CommonJS, + target: 1, + noImplicitAny: false, + sourceMap: false + }; function createCompilerHost(options, setParentNodes) { - var existingDirectories = ts.createMap(); + var existingDirectories = {}; function getCanonicalFileName(fileName) { return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } @@ -38676,10 +37352,9 @@ var ts; function getSourceFile(fileName, languageVersion, onError) { var text; try { - ts.performance.mark("beforeIORead"); + var start = new Date().getTime(); text = ts.sys.readFile(fileName, options.charset); - ts.performance.mark("afterIORead"); - ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); + ts.ioReadTime += new Date().getTime() - start; } catch (e) { if (onError) { @@ -38692,7 +37367,7 @@ var ts; return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined; } function directoryExists(directoryPath) { - if (directoryPath in existingDirectories) { + if (ts.hasProperty(existingDirectories, directoryPath)) { return true; } if (ts.sys.directoryExists(directoryPath)) { @@ -38711,11 +37386,11 @@ var ts; var outputFingerprints; function writeFileIfUpdated(fileName, data, writeByteOrderMark) { if (!outputFingerprints) { - outputFingerprints = ts.createMap(); + outputFingerprints = {}; } var hash = ts.sys.createHash(data); var mtimeBefore = ts.sys.getModifiedTime(fileName); - if (mtimeBefore && fileName in outputFingerprints) { + if (mtimeBefore && ts.hasProperty(outputFingerprints, fileName)) { var fingerprint = outputFingerprints[fileName]; if (fingerprint.byteOrderMark === writeByteOrderMark && fingerprint.hash === hash && @@ -38733,7 +37408,7 @@ var ts; } function writeFile(fileName, data, writeByteOrderMark, onError) { try { - ts.performance.mark("beforeIOWrite"); + var start = new Date().getTime(); ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { writeFileIfUpdated(fileName, data, writeByteOrderMark); @@ -38741,8 +37416,7 @@ var ts; else { ts.sys.writeFile(fileName, data, writeByteOrderMark); } - ts.performance.mark("afterIOWrite"); - ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + ts.ioWriteTime += new Date().getTime() - start; } catch (e) { if (onError) { @@ -38781,22 +37455,6 @@ var ts; return ts.sortAndDeduplicateDiagnostics(diagnostics); } ts.getPreEmitDiagnostics = getPreEmitDiagnostics; - function formatDiagnostics(diagnostics, host) { - var output = ""; - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; - if (diagnostic.file) { - var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; - var fileName = diagnostic.file.fileName; - var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }); - output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): "; - } - var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); - output += category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine(); - } - return output; - } - ts.formatDiagnostics = formatDiagnostics; function flattenDiagnosticMessageText(messageText, newLine) { if (typeof messageText === "string") { return messageText; @@ -38825,17 +37483,25 @@ var ts; return []; } var resolutions = []; - var cache = ts.createMap(); + var cache = {}; for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { - var name_37 = names_1[_i]; - var result = name_37 in cache - ? cache[name_37] - : cache[name_37] = loader(name_37, containingFile); + var name_35 = names_1[_i]; + var result = void 0; + if (ts.hasProperty(cache, name_35)) { + result = cache[name_35]; + } + else { + result = loader(name_35, containingFile); + cache[name_35] = result; + } resolutions.push(result); } return resolutions; } - function getAutomaticTypeDirectiveNames(options, host) { + function getInferredTypesRoot(options, rootFiles, host) { + return computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + function getAutomaticTypeDirectiveNames(options, rootFiles, host) { if (options.types) { return options.types; } @@ -38846,15 +37512,7 @@ var ts; for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { var root = typeRoots_1[_i]; if (host.directoryExists(root)) { - for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { - var typeDirectivePath = _b[_a]; - var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = ts.pathToPackageJson(ts.combinePaths(root, normalized)); - var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null; - if (!isNotNeededPackage) { - result.push(ts.getBaseFileName(normalized)); - } - } + result = result.concat(host.getDirectories(root)); } } } @@ -38869,13 +37527,13 @@ var ts; var diagnosticsProducingTypeChecker; var noDiagnosticsTypeChecker; var classifiableNames; - var resolvedTypeReferenceDirectives = ts.createMap(); + var resolvedTypeReferenceDirectives = {}; var fileProcessingDiagnostics = ts.createDiagnosticCollection(); - var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; - var currentNodeModulesDepth = 0; - var modulesWithElidedImports = ts.createMap(); - var sourceFilesFoundSearchingNodeModules = ts.createMap(); - ts.performance.mark("beforeProgram"); + var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 2; + var currentNodeModulesJsDepth = 0; + var modulesWithElidedImports = {}; + var sourceFilesFoundSearchingNodeModules = {}; + var start = new Date().getTime(); host = host || createCompilerHost(options); var skipDefaultLib = options.noLib; var programDiagnostics = ts.createDiagnosticCollection(); @@ -38887,7 +37545,7 @@ var ts; resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }; } else { - var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; + var loader_1 = function (moduleName, containingFile) { return resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(moduleNames, containingFile, loader_1); }; } var resolveTypeReferenceDirectiveNamesWorker; @@ -38902,9 +37560,10 @@ var ts; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; if (!tryReuseStructureFromOldProgram()) { ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); - var typeReferences = getAutomaticTypeDirectiveNames(options, host); + var typeReferences = getAutomaticTypeDirectiveNames(options, rootNames, host); if (typeReferences) { - var containingFilename = ts.combinePaths(host.getCurrentDirectory(), "__inferred type names__.ts"); + var inferredRoot = getInferredTypesRoot(options, rootNames, host); + var containingFilename = ts.combinePaths(inferredRoot, "__inferred type names__.ts"); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i]); @@ -38945,12 +37604,10 @@ var ts; getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, - getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, - dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker + getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; } }; verifyCompilerOptions(); - ts.performance.mark("afterProgram"); - ts.performance.measure("Program", "beforeProgram", "afterProgram"); + ts.programTime += new Date().getTime() - start; return program; function getCommonSourceDirectory() { if (typeof commonSourceDirectory === "undefined") { @@ -38969,10 +37626,10 @@ var ts; function getClassifiableNames() { if (!classifiableNames) { getTypeChecker(); - classifiableNames = ts.createMap(); + classifiableNames = {}; for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { var sourceFile = files_2[_i]; - ts.copyProperties(sourceFile.classifiableNames, classifiableNames); + ts.copyMap(sourceFile.classifiableNames, classifiableNames); } } return classifiableNames; @@ -38995,7 +37652,7 @@ var ts; (oldOptions.maxNodeModuleJsDepth !== options.maxNodeModuleJsDepth) || !ts.arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) || !ts.arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) || - !ts.equalOwnProperties(oldOptions.paths, options.paths)) { + !ts.mapIsEqualTo(oldOptions.paths, options.paths)) { return false; } ts.Debug.assert(!oldProgram.structureIsReused); @@ -39085,7 +37742,7 @@ var ts; getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, - isSourceFileFromExternalLibrary: function (file) { return !!sourceFilesFoundSearchingNodeModules[file.path]; }, + isSourceFileFromExternalLibrary: function (file) { return !!ts.lookUp(sourceFilesFoundSearchingNodeModules, file.path); }, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked }; @@ -39093,19 +37750,17 @@ var ts; function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, true)); } - function dropDiagnosticsProducingTypeChecker() { - diagnosticsProducingTypeChecker = undefined; - } function getTypeChecker() { return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, false)); } - function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { - return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles); }); + function emit(sourceFile, writeFileCallback, cancellationToken) { + var _this = this; + return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); }); } function isEmitBlocked(emitFileName) { return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); } - function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { + function emitWorker(program, sourceFile, writeFileCallback, cancellationToken) { var declarationDiagnostics = []; if (options.noEmit) { return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; @@ -39125,10 +37780,9 @@ var ts; } } var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); - ts.performance.mark("beforeEmit"); - var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles); - ts.performance.mark("afterEmit"); - ts.performance.measure("Emit", "beforeEmit", "afterEmit"); + var start = new Date().getTime(); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile); + ts.emitTime += new Date().getTime() - start; return emitResult; } function getSourceFile(fileName) { @@ -39267,16 +37921,16 @@ var ts; case 175: var expression = node; if (expression.typeArguments && expression.typeArguments.length > 0) { - var start = expression.typeArguments.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, expression.typeArguments.end - start, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); + var start_2 = expression.typeArguments.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start_2, expression.typeArguments.end - start_2, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); return true; } break; case 142: var parameter = node; if (parameter.modifiers) { - var start = parameter.modifiers.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, parameter.modifiers.end - start, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); + var start_3 = parameter.modifiers.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start_3, parameter.modifiers.end - start_3, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); return true; } if (parameter.questionToken) { @@ -39320,8 +37974,8 @@ var ts; } function checkTypeParameters(typeParameters) { if (typeParameters) { - var start = typeParameters.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, typeParameters.end - start, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); + var start_4 = typeParameters.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start_4, typeParameters.end - start_4, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); return true; } return false; @@ -39508,17 +38162,8 @@ var ts; if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); } - if (file_1 && sourceFilesFoundSearchingNodeModules[file_1.path] && currentNodeModulesDepth == 0) { - sourceFilesFoundSearchingNodeModules[file_1.path] = false; - if (!options.noResolve) { - processReferencedFiles(file_1, ts.getDirectoryPath(fileName), isDefaultLib); - processTypeReferenceDirectives(file_1); - } - modulesWithElidedImports[file_1.path] = false; - processImportedModules(file_1, ts.getDirectoryPath(fileName)); - } - else if (file_1 && modulesWithElidedImports[file_1.path]) { - if (currentNodeModulesDepth < maxNodeModulesJsDepth) { + if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) { + if (currentNodeModulesJsDepth < maxNodeModulesJsDepth) { modulesWithElidedImports[file_1.path] = false; processImportedModules(file_1, ts.getDirectoryPath(fileName)); } @@ -39535,7 +38180,6 @@ var ts; }); filesByName.set(path, file); if (file) { - sourceFilesFoundSearchingNodeModules[path] = (currentNodeModulesDepth > 0); file.path = path; if (host.useCaseSensitiveFileNames()) { var existingFile = filesByNameIgnoreCase.get(path); @@ -39569,14 +38213,13 @@ var ts; }); } function processTypeReferenceDirectives(file) { - var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); + var typeDirectives = ts.map(file.typeReferenceDirectives, function (l) { return l.fileName; }); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; var resolvedTypeReferenceDirective = resolutions[i]; - var fileName = ref.fileName.toLocaleLowerCase(); - ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective); - processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end); + ts.setResolvedTypeReferenceDirective(file, ref.fileName, resolvedTypeReferenceDirective); + processTypeReferenceDirective(ref.fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end); } } function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, refFile, refPos, refEnd) { @@ -39593,7 +38236,7 @@ var ts; if (previousResolution) { var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) { - fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_to_resolve_this_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); } saveResolution = false; } @@ -39627,7 +38270,7 @@ var ts; function processImportedModules(file, basePath) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { - file.resolvedModules = ts.createMap(); + file.resolvedModules = {}; var moduleNames = ts.map(ts.concatenate(file.imports, file.moduleAugmentations), getTextOfLiteral); var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory)); for (var i = 0; i < moduleNames.length; i++) { @@ -39637,9 +38280,12 @@ var ts; var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport; var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName); if (isFromNodeModulesSearch) { - currentNodeModulesDepth++; + sourceFilesFoundSearchingNodeModules[resolvedPath] = true; } - var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth; + if (isJsFileFromNodeModules) { + currentNodeModulesJsDepth++; + } + var elideImport = isJsFileFromNodeModules && currentNodeModulesJsDepth > maxNodeModulesJsDepth; var shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport; if (elideImport) { modulesWithElidedImports[file.path] = true; @@ -39647,8 +38293,8 @@ var ts; else if (shouldAddFile) { findSourceFile(resolution.resolvedFileName, resolvedPath, false, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); } - if (isFromNodeModulesSearch) { - currentNodeModulesDepth--; + if (isJsFileFromNodeModules) { + currentNodeModulesJsDepth--; } } } @@ -39715,18 +38361,15 @@ var ts; if (!ts.hasProperty(options.paths, key)) { continue; } - if (!ts.hasZeroOrOneAsteriskCharacter(key)) { + if (!hasZeroOrOneAsteriskCharacter(key)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); } if (ts.isArray(options.paths[key])) { - if (options.paths[key].length === 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key)); - } for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { var subst = _a[_i]; var typeOfSubst = typeof subst; if (typeOfSubst === "string") { - if (!ts.hasZeroOrOneAsteriskCharacter(subst)) { + if (!hasZeroOrOneAsteriskCharacter(subst)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key)); } } @@ -39767,7 +38410,7 @@ var ts; } var languageVersion = options.target || 0; var outFile = options.outFile || options.out; - var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); + var firstExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) ? f : undefined; }); if (options.isolatedModules) { if (options.module === ts.ModuleKind.None && languageVersion < 2) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); @@ -39778,17 +38421,17 @@ var ts; programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); } } - else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 && options.module === ts.ModuleKind.None) { - var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); + else if (firstExternalModuleSourceFile && languageVersion < 2 && options.module === ts.ModuleKind.None) { + var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } if (outFile) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); } - else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) { - var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); + else if (options.module === undefined && firstExternalModuleSourceFile) { + var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); } } if (options.outDir || @@ -40406,24 +39049,24 @@ var ts; switch (n.kind) { case 199: if (!ts.isFunctionBlock(n)) { - var parent_16 = n.parent; + var parent_15 = n.parent; var openBrace = ts.findChildOfKind(n, 15, sourceFile); var closeBrace = ts.findChildOfKind(n, 16, sourceFile); - if (parent_16.kind === 204 || - parent_16.kind === 207 || - parent_16.kind === 208 || - parent_16.kind === 206 || - parent_16.kind === 203 || - parent_16.kind === 205 || - parent_16.kind === 212 || - parent_16.kind === 252) { - addOutliningSpan(parent_16, openBrace, closeBrace, autoCollapse(n)); + if (parent_15.kind === 204 || + parent_15.kind === 207 || + parent_15.kind === 208 || + parent_15.kind === 206 || + parent_15.kind === 203 || + parent_15.kind === 205 || + parent_15.kind === 212 || + parent_15.kind === 252) { + addOutliningSpan(parent_15, openBrace, closeBrace, autoCollapse(n)); break; } - if (parent_16.kind === 216) { - var tryStatement = parent_16; + if (parent_15.kind === 216) { + var tryStatement = parent_15; if (tryStatement.tryBlock === n) { - addOutliningSpan(parent_16, openBrace, closeBrace, autoCollapse(n)); + addOutliningSpan(parent_15, openBrace, closeBrace, autoCollapse(n)); break; } else if (tryStatement.finallyBlock === n) { @@ -40479,17 +39122,17 @@ var ts; (function (ts) { var NavigateTo; (function (NavigateTo) { - function getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount, excludeDts) { + function getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; var baseSensitivity = { sensitivity: "base" }; ts.forEach(program.getSourceFiles(), function (sourceFile) { cancellationToken.throwIfCancellationRequested(); var nameToDeclarations = sourceFile.getNamedDeclarations(); - for (var name_38 in nameToDeclarations) { - var declarations = nameToDeclarations[name_38]; + for (var name_36 in nameToDeclarations) { + var declarations = ts.getProperty(nameToDeclarations, name_36); if (declarations) { - var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_38); + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_36); if (!matches) { continue; } @@ -40500,17 +39143,14 @@ var ts; if (!containers) { return undefined; } - matches = patternMatcher.getMatches(containers, name_38); + matches = patternMatcher.getMatches(containers, name_36); if (!matches) { continue; } } var fileName = sourceFile.fileName; var matchKind = bestMatchKind(matches); - if (excludeDts && ts.fileExtensionIs(declaration.getSourceFile().fileName, ".d.ts")) { - continue; - } - rawItems.push({ name: name_38, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); + rawItems.push({ name: name_36, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); } } } @@ -40756,9 +39396,9 @@ var ts; case 169: case 218: var decl = node; - var name_39 = decl.name; - if (ts.isBindingPattern(name_39)) { - addChildrenRecursively(name_39); + var name_37 = decl.name; + if (ts.isBindingPattern(name_37)) { + addChildrenRecursively(name_37); } else if (decl.initializer && isFunctionOrClassExpression(decl.initializer)) { addChildrenRecursively(decl.initializer); @@ -40819,14 +39459,14 @@ var ts; } } function mergeChildren(children) { - var nameToItems = ts.createMap(); + var nameToItems = {}; ts.filterMutate(children, function (child) { var decl = child.node; var name = decl.name && nodeText(decl.name); if (!name) { return true; } - var itemsWithSameName = nameToItems[name]; + var itemsWithSameName = ts.getProperty(nameToItems, name); if (!itemsWithSameName) { nameToItems[name] = child; return true; @@ -41054,7 +39694,7 @@ var ts; function convertToTopLevelItem(n) { return { text: getItemName(n.node), - kind: ts.getNodeKind(n.node), + kind: nodeKind(n.node), kindModifiers: ts.getNodeModifiers(n.node), spans: getSpans(n), childItems: ts.map(n.children, convertToChildItem) || emptyChildItemArray, @@ -41065,7 +39705,7 @@ var ts; function convertToChildItem(n) { return { text: getItemName(n.node), - kind: ts.getNodeKind(n.node), + kind: nodeKind(n.node), kindModifiers: ts.getNodeModifiers(n.node), spans: getSpans(n), childItems: emptyChildItemArray, @@ -41085,6 +39725,46 @@ var ts; return spans; } } + function nodeKind(node) { + switch (node.kind) { + case 256: + return ts.ScriptElementKind.moduleElement; + case 255: + return ts.ScriptElementKind.memberVariableElement; + case 218: + case 169: + var variableDeclarationNode = void 0; + var name_38; + if (node.kind === 169) { + name_38 = node.name; + variableDeclarationNode = node; + while (variableDeclarationNode && variableDeclarationNode.kind !== 218) { + variableDeclarationNode = variableDeclarationNode.parent; + } + ts.Debug.assert(!!variableDeclarationNode); + } + else { + ts.Debug.assert(!ts.isBindingPattern(node.name)); + variableDeclarationNode = node; + name_38 = node.name; + } + if (ts.isConst(variableDeclarationNode)) { + return ts.ScriptElementKind.constElement; + } + else if (ts.isLet(variableDeclarationNode)) { + return ts.ScriptElementKind.letElement; + } + else { + return ts.ScriptElementKind.variableElement; + } + case 180: + return ts.ScriptElementKind.functionElement; + case 279: + return ts.ScriptElementKind.typeElement; + default: + return ts.getNodeKind(node); + } + } function getModuleName(moduleDeclaration) { if (ts.isAmbientModule(moduleDeclaration)) { return ts.getTextOfNode(moduleDeclaration.name); @@ -41152,7 +39832,7 @@ var ts; }; } function createPatternMatcher(pattern) { - var stringToWordSpans = ts.createMap(); + var stringToWordSpans = {}; pattern = pattern.trim(); var dotSeparatedSegments = pattern.split(".").map(function (p) { return createSegment(p.trim()); }); var invalidPattern = dotSeparatedSegments.length === 0 || ts.forEach(dotSeparatedSegments, segmentIsInvalid); @@ -41195,7 +39875,7 @@ var ts; return totalMatch; } function getWordSpans(word) { - if (!(word in stringToWordSpans)) { + if (!ts.hasProperty(stringToWordSpans, word)) { stringToWordSpans[word] = breakIntoWordSpans(word); } return stringToWordSpans[word]; @@ -41207,7 +39887,7 @@ var ts; return createPatternMatch(PatternMatchKind.exact, punctuationStripped, candidate === chunk.text); } else { - return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, ts.startsWith(candidate, chunk.text)); + return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, startsWith(candidate, chunk.text)); } } var isLowercase = chunk.isLowerCase; @@ -41379,6 +40059,14 @@ var ts; var str = String.fromCharCode(ch); return str === str.toLowerCase(); } + function startsWith(string, search) { + for (var i = 0, n = search.length; i < n; i++) { + if (string.charCodeAt(i) !== search.charCodeAt(i)) { + return false; + } + } + return true; + } function indexOfIgnoringCase(string, value) { for (var i = 0, n = string.length - value.length; i <= n; i++) { if (startsWithIgnoringCase(string, value, i)) { @@ -41589,7 +40277,7 @@ var ts; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; var nameToDeclarations = sourceFile.getNamedDeclarations(); - var declarations = nameToDeclarations[name.text]; + var declarations = ts.getProperty(nameToDeclarations, name.text); if (declarations) { for (var _b = 0, declarations_8 = declarations; _b < declarations_8.length; _b++) { var declaration = declarations_8[_b]; @@ -41853,7 +40541,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var tripleSlashDirectivePrefixRegex = /^\/\/\/\s*= node.end) { + if (c.kind === 282 && c.pos <= node.pos && c.end >= node.end) { return c; } }); @@ -42186,7 +40873,8 @@ var ts; ts.findPrecedingToken = findPrecedingToken; function isInString(sourceFile, position) { var previousToken = findPrecedingToken(position, sourceFile); - if (previousToken && previousToken.kind === 9) { + if (previousToken && + (previousToken.kind === 9 || previousToken.kind === 166)) { var start = previousToken.getStart(); var end = previousToken.getEnd(); if (start < position && position < end) { @@ -42335,6 +41023,7 @@ var ts; ts.isComment = isComment; function isStringOrRegularExpressionOrTemplateLiteral(kind) { if (kind === 9 + || kind === 166 || kind === 10 || ts.isTemplateLiteralKind(kind)) { return true; @@ -42396,27 +41085,6 @@ var ts; return false; } ts.isArrayLiteralOrObjectLiteralDestructuringPattern = isArrayLiteralOrObjectLiteralDestructuringPattern; - function hasTrailingDirectorySeparator(path) { - var lastCharacter = path.charAt(path.length - 1); - return lastCharacter === "/" || lastCharacter === "\\"; - } - ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; - function isInReferenceComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, isReferenceComment); - function isReferenceComment(c) { - var commentText = sourceFile.text.substring(c.pos, c.end); - return tripleSlashDirectivePrefixRegex.test(commentText); - } - } - ts.isInReferenceComment = isInReferenceComment; - function isInNonReferenceComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, isNonReferenceComment); - function isNonReferenceComment(c) { - var commentText = sourceFile.text.substring(c.pos, c.end); - return !tripleSlashDirectivePrefixRegex.test(commentText); - } - } - ts.isInNonReferenceComment = isInNonReferenceComment; })(ts || (ts = {})); var ts; (function (ts) { @@ -42635,34 +41303,158 @@ var ts; if (host && host.getScriptKind) { scriptKind = host.getScriptKind(fileName); } - if (!scriptKind) { + if (!scriptKind || scriptKind === 0) { scriptKind = ts.getScriptKindFromFileName(fileName); } return ts.ensureScriptKind(fileName, scriptKind); } ts.getScriptKind = getScriptKind; - function sanitizeConfigFile(configFileName, content) { - var options = { - fileName: "config.js", - compilerOptions: { - target: 2, - removeComments: true - }, - reportDiagnostics: true - }; - var _a = ts.transpileModule("(" + content + ")", options), outputText = _a.outputText, diagnostics = _a.diagnostics; - var trimmedOutput = outputText.trim(); - for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { - var diagnostic = diagnostics_3[_i]; - diagnostic.start = diagnostic.start - 1; +})(ts || (ts = {})); +var ts; +(function (ts) { + var JsTyping; + (function (JsTyping) { + ; + ; + var safeList; + function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typingOptions, compilerOptions) { + var inferredTypings = {}; + if (!typingOptions || !typingOptions.enableAutoDiscovery) { + return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; + } + fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { return ts.scriptKindIs(f, undefined, 1, 2); }); + if (!safeList) { + var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); + if (result.config) { + safeList = result.config; + } + else { + safeList = {}; + } + ; + } + var filesToWatch = []; + var searchDirs = []; + var exclude = []; + mergeTypings(typingOptions.include); + exclude = typingOptions.exclude || []; + var possibleSearchDirs = ts.map(fileNames, ts.getDirectoryPath); + if (projectRootPath !== undefined) { + possibleSearchDirs.push(projectRootPath); + } + searchDirs = ts.deduplicate(possibleSearchDirs); + for (var _i = 0, searchDirs_1 = searchDirs; _i < searchDirs_1.length; _i++) { + var searchDir = searchDirs_1[_i]; + var packageJsonPath = ts.combinePaths(searchDir, "package.json"); + getTypingNamesFromJson(packageJsonPath, filesToWatch); + var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); + getTypingNamesFromJson(bowerJsonPath, filesToWatch); + var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); + getTypingNamesFromNodeModuleFolder(nodeModulesPath); + } + getTypingNamesFromSourceFileNames(fileNames); + for (var name_39 in packageNameToTypingLocation) { + if (ts.hasProperty(inferredTypings, name_39) && !inferredTypings[name_39]) { + inferredTypings[name_39] = packageNameToTypingLocation[name_39]; + } + } + for (var _a = 0, exclude_1 = exclude; _a < exclude_1.length; _a++) { + var excludeTypingName = exclude_1[_a]; + delete inferredTypings[excludeTypingName]; + } + var newTypingNames = []; + var cachedTypingPaths = []; + for (var typing in inferredTypings) { + if (inferredTypings[typing] !== undefined) { + cachedTypingPaths.push(inferredTypings[typing]); + } + else { + newTypingNames.push(typing); + } + } + return { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; + function mergeTypings(typingNames) { + if (!typingNames) { + return; + } + for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) { + var typing = typingNames_1[_i]; + if (!ts.hasProperty(inferredTypings, typing)) { + inferredTypings[typing] = undefined; + } + } + } + function getTypingNamesFromJson(jsonPath, filesToWatch) { + var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }); + if (result.config) { + var jsonConfig = result.config; + filesToWatch.push(jsonPath); + if (jsonConfig.dependencies) { + mergeTypings(ts.getKeys(jsonConfig.dependencies)); + } + if (jsonConfig.devDependencies) { + mergeTypings(ts.getKeys(jsonConfig.devDependencies)); + } + if (jsonConfig.optionalDependencies) { + mergeTypings(ts.getKeys(jsonConfig.optionalDependencies)); + } + if (jsonConfig.peerDependencies) { + mergeTypings(ts.getKeys(jsonConfig.peerDependencies)); + } + } + } + function getTypingNamesFromSourceFileNames(fileNames) { + var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension); + var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); }); + var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); }); + if (safeList === undefined) { + mergeTypings(cleanedTypingNames); + } + else { + mergeTypings(ts.filter(cleanedTypingNames, function (f) { return ts.hasProperty(safeList, f); })); + } + var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.scriptKindIs(f, undefined, 2); }); + if (hasJsxFile) { + mergeTypings(["react"]); + } + } + function getTypingNamesFromNodeModuleFolder(nodeModulesPath) { + if (!host.directoryExists(nodeModulesPath)) { + return; + } + var typingNames = []; + var fileNames = host.readDirectory(nodeModulesPath, ["*.json"], undefined, undefined, 2); + for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { + var fileName = fileNames_2[_i]; + var normalizedFileName = ts.normalizePath(fileName); + if (ts.getBaseFileName(normalizedFileName) !== "package.json") { + continue; + } + var result = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + if (!result.config) { + continue; + } + var packageJson = result.config; + if (packageJson._requiredBy && + ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { + continue; + } + if (!packageJson.name) { + continue; + } + if (packageJson.typings) { + var absolutePath = ts.getNormalizedAbsolutePath(packageJson.typings, ts.getDirectoryPath(normalizedFileName)); + inferredTypings[packageJson.name] = absolutePath; + } + else { + typingNames.push(packageJson.name); + } + } + mergeTypings(typingNames); + } } - var _b = ts.parseConfigFileTextToJson(configFileName, trimmedOutput.substring(1, trimmedOutput.length - 2), false), config = _b.config, error = _b.error; - return { - configJsonObject: config || {}, - diagnostics: error ? ts.concatenate(diagnostics, [error]) : diagnostics - }; - } - ts.sanitizeConfigFile = sanitizeConfigFile; + JsTyping.discoverTypings = discoverTypings; + })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); var ts; (function (ts) { @@ -42759,9 +41551,6 @@ var ts; } return false; } - function shouldRescanJsxText(node) { - return node && node.kind === 244; - } function shouldRescanSlashToken(container) { return container.kind === 10; } @@ -42789,9 +41578,7 @@ var ts; ? 3 : shouldRescanJsxIdentifier(n) ? 4 - : shouldRescanJsxText(n) - ? 5 - : 0; + : 0; if (lastTokenInfo && expectedScanAction === lastScanAction) { return fixTokenKind(lastTokenInfo, n); } @@ -42819,10 +41606,6 @@ var ts; currentToken = scanner.scanJsxIdentifier(); lastScanAction = 4; } - else if (expectedScanAction === 5) { - currentToken = scanner.reScanJsxToken(); - lastScanAction = 5; - } else { lastScanAction = 0; } @@ -43124,7 +41907,7 @@ var ts; this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 8)); this.SpaceAfterVoidOperator = new formatting.Rule(formatting.RuleDescriptor.create3(103, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsVoidOpContext), 2)); this.NoSpaceBetweenReturnAndSemicolon = new formatting.Rule(formatting.RuleDescriptor.create1(94, 23), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([18, 79, 80, 71]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNotForContext), 2)); + this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([18, 79, 80, 71]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isNonJsxElementContext, Rules.IsNotForContext), 2)); this.SpaceAfterTryFinally = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([100, 85]), 15), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([123, 131]), 69), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); this.SpaceBeforeBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryKeywordOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); @@ -43155,11 +41938,6 @@ var ts; this.SpaceBetweenAsyncAndOpenParen = new formatting.Rule(formatting.RuleDescriptor.create1(118, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsArrowFunctionContext, Rules.IsNonJsxSameLineTokenContext), 2)); this.SpaceBetweenAsyncAndFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(118, 87), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); this.NoSpaceBetweenTagAndTemplateString = new formatting.Rule(formatting.RuleDescriptor.create3(69, formatting.Shared.TokenRange.FromTokens([11, 12])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceBeforeJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 69), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNextTokenParentJsxAttribute, Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBeforeSlashInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 39), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBeforeGreaterThanTokenInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create1(39, 27), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 56), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create3(56, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8)); this.HighPriorityCommonRules = [ this.IgnoreBeforeComment, this.IgnoreAfterLineComment, this.NoSpaceBeforeColon, this.SpaceAfterColon, this.NoSpaceBeforeQuestionMark, this.SpaceAfterQuestionMarkInConditionalOperator, @@ -43186,8 +41964,6 @@ var ts; this.SpaceAfterVoidOperator, this.SpaceBetweenAsyncAndOpenParen, this.SpaceBetweenAsyncAndFunctionKeyword, this.NoSpaceBetweenTagAndTemplateString, - this.SpaceBeforeJsxAttribute, this.SpaceBeforeSlashInJsxOpeningElement, this.NoSpaceBeforeGreaterThanTokenInJsxOpeningElement, - this.NoSpaceBeforeEqualInJsxAttribute, this.NoSpaceAfterEqualInJsxAttribute, this.NoSpaceAfterConstructor, this.NoSpaceAfterModuleImport, this.SpaceAfterCertainTypeScriptKeywords, this.SpaceBeforeCertainTypeScriptKeywords, this.SpaceAfterModuleName, @@ -43215,8 +41991,8 @@ var ts; this.NoSpaceBeforeOpenParenInFuncDecl, this.SpaceBetweenStatements, this.SpaceAfterTryFinally ]; - this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2)); - this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext), 8)); + this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2)); + this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isNonJsxElementContext), 8)); this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); this.SpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); this.NoSpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); @@ -43242,10 +42018,10 @@ var ts; this.SpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([12, 13]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([13, 14])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.SpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([13, 14])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); - this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); - this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); - this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); + this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isJsxExpressionContext), 8)); + this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isJsxExpressionContext), 2)); + this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isJsxExpressionContext), 8)); + this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isJsxExpressionContext), 2)); this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(87, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(87, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 8)); } @@ -43420,21 +42196,12 @@ var ts; Rules.IsNonJsxSameLineTokenContext = function (context) { return context.TokensAreOnSameLine() && context.contextNode.kind !== 244; }; - Rules.IsNonJsxElementContext = function (context) { + Rules.isNonJsxElementContext = function (context) { return context.contextNode.kind !== 241; }; - Rules.IsJsxExpressionContext = function (context) { + Rules.isJsxExpressionContext = function (context) { return context.contextNode.kind === 248; }; - Rules.IsNextTokenParentJsxAttribute = function (context) { - return context.nextTokenParent.kind === 246; - }; - Rules.IsJsxAttributeContext = function (context) { - return context.contextNode.kind === 246; - }; - Rules.IsJsxSelfClosingElementContext = function (context) { - return context.contextNode.kind === 242; - }; Rules.IsNotBeforeBlockInFunctionDeclarationContext = function (context) { return !Rules.IsFunctionDeclContext(context) && !Rules.IsBeforeBlockContext(context); }; @@ -43784,25 +42551,25 @@ var ts; }; RulesProvider.prototype.createActiveRules = function (options) { var rules = this.globalRules.HighPriorityCommonRules.slice(0); - if (options.insertSpaceAfterCommaDelimiter) { + if (options.InsertSpaceAfterCommaDelimiter) { rules.push(this.globalRules.SpaceAfterComma); } else { rules.push(this.globalRules.NoSpaceAfterComma); } - if (options.insertSpaceAfterFunctionKeywordForAnonymousFunctions) { + if (options.InsertSpaceAfterFunctionKeywordForAnonymousFunctions) { rules.push(this.globalRules.SpaceAfterAnonymousFunctionKeyword); } else { rules.push(this.globalRules.NoSpaceAfterAnonymousFunctionKeyword); } - if (options.insertSpaceAfterKeywordsInControlFlowStatements) { + if (options.InsertSpaceAfterKeywordsInControlFlowStatements) { rules.push(this.globalRules.SpaceAfterKeywordInControl); } else { rules.push(this.globalRules.NoSpaceAfterKeywordInControl); } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { + if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { rules.push(this.globalRules.SpaceAfterOpenParen); rules.push(this.globalRules.SpaceBeforeCloseParen); rules.push(this.globalRules.NoSpaceBetweenParens); @@ -43812,7 +42579,7 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseParen); rules.push(this.globalRules.NoSpaceBetweenParens); } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { + if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { rules.push(this.globalRules.SpaceAfterOpenBracket); rules.push(this.globalRules.SpaceBeforeCloseBracket); rules.push(this.globalRules.NoSpaceBetweenBrackets); @@ -43822,7 +42589,7 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseBracket); rules.push(this.globalRules.NoSpaceBetweenBrackets); } - if (options.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { + if (options.InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle); rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail); } @@ -43830,7 +42597,7 @@ var ts; rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle); rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail); } - if (options.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) { + if (options.InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) { rules.push(this.globalRules.SpaceAfterOpenBraceInJsxExpression); rules.push(this.globalRules.SpaceBeforeCloseBraceInJsxExpression); } @@ -43838,13 +42605,13 @@ var ts; rules.push(this.globalRules.NoSpaceAfterOpenBraceInJsxExpression); rules.push(this.globalRules.NoSpaceBeforeCloseBraceInJsxExpression); } - if (options.insertSpaceAfterSemicolonInForStatements) { + if (options.InsertSpaceAfterSemicolonInForStatements) { rules.push(this.globalRules.SpaceAfterSemicolonInFor); } else { rules.push(this.globalRules.NoSpaceAfterSemicolonInFor); } - if (options.insertSpaceBeforeAndAfterBinaryOperators) { + if (options.InsertSpaceBeforeAndAfterBinaryOperators) { rules.push(this.globalRules.SpaceBeforeBinaryOperator); rules.push(this.globalRules.SpaceAfterBinaryOperator); } @@ -43852,10 +42619,10 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeBinaryOperator); rules.push(this.globalRules.NoSpaceAfterBinaryOperator); } - if (options.placeOpenBraceOnNewLineForControlBlocks) { + if (options.PlaceOpenBraceOnNewLineForControlBlocks) { rules.push(this.globalRules.NewLineBeforeOpenBraceInControl); } - if (options.placeOpenBraceOnNewLineForFunctions) { + if (options.PlaceOpenBraceOnNewLineForFunctions) { rules.push(this.globalRules.NewLineBeforeOpenBraceInFunction); rules.push(this.globalRules.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock); } @@ -44024,7 +42791,7 @@ var ts; break; } if (formatting.SmartIndenter.shouldIndentChildNode(n, child)) { - return options.indentSize; + return options.IndentSize; } previousLine = line; child = n; @@ -44084,12 +42851,12 @@ var ts; } function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) { var indentation = inheritedIndentation; - var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0; + var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.IndentSize : 0; if (effectiveParentStartLine === startLine) { indentation = startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(); - delta = Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta); + delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta(node) + delta); } else if (indentation === -1) { if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { @@ -44161,13 +42928,13 @@ var ts; recomputeIndentation: function (lineAdded) { if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent, node)) { if (lineAdded) { - indentation += options.indentSize; + indentation += options.IndentSize; } else { - indentation -= options.indentSize; + indentation -= options.IndentSize; } if (formatting.SmartIndenter.shouldIndentChildNode(node)) { - delta = options.indentSize; + delta = options.IndentSize; } else { delta = 0; @@ -44527,7 +43294,7 @@ var ts; } var lineDelta = currentStartLine - previousStartLine; if (lineDelta !== 1) { - recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.newLineCharacter); + recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.NewLineCharacter); } break; case 2: @@ -44586,14 +43353,14 @@ var ts; var internedTabsIndentation; var internedSpacesIndentation; function getIndentationString(indentation, options) { - var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.tabSize || internedSizes.indentSize !== options.indentSize); + var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.TabSize || internedSizes.indentSize !== options.IndentSize); if (resetInternedStrings) { - internedSizes = { tabSize: options.tabSize, indentSize: options.indentSize }; + internedSizes = { tabSize: options.TabSize, indentSize: options.IndentSize }; internedTabsIndentation = internedSpacesIndentation = undefined; } - if (!options.convertTabsToSpaces) { - var tabs = Math.floor(indentation / options.tabSize); - var spaces = indentation - tabs * options.tabSize; + if (!options.ConvertTabsToSpaces) { + var tabs = Math.floor(indentation / options.TabSize); + var spaces = indentation - tabs * options.TabSize; var tabString = void 0; if (!internedTabsIndentation) { internedTabsIndentation = []; @@ -44608,13 +43375,13 @@ var ts; } else { var spacesString = void 0; - var quotient = Math.floor(indentation / options.indentSize); - var remainder = indentation % options.indentSize; + var quotient = Math.floor(indentation / options.IndentSize); + var remainder = indentation % options.IndentSize; if (!internedSpacesIndentation) { internedSpacesIndentation = []; } if (internedSpacesIndentation[quotient] === undefined) { - spacesString = repeat(" ", options.indentSize * quotient); + spacesString = repeat(" ", options.IndentSize * quotient); internedSpacesIndentation[quotient] = spacesString; } else { @@ -44643,7 +43410,7 @@ var ts; if (position > sourceFile.text.length) { return getBaseIndentation(options); } - if (options.indentStyle === ts.IndentStyle.None) { + if (options.IndentStyle === ts.IndentStyle.None) { return 0; } var precedingToken = ts.findPrecedingToken(position, sourceFile); @@ -44655,7 +43422,7 @@ var ts; return 0; } var lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line; - if (options.indentStyle === ts.IndentStyle.Block) { + if (options.IndentStyle === ts.IndentStyle.Block) { var current_1 = position; while (current_1 > 0) { var char = sourceFile.text.charCodeAt(current_1); @@ -44684,7 +43451,7 @@ var ts; indentationDelta = 0; } else { - indentationDelta = lineAtPosition !== currentStart.line ? options.indentSize : 0; + indentationDelta = lineAtPosition !== currentStart.line ? options.IndentSize : 0; } break; } @@ -44694,7 +43461,7 @@ var ts; } actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); if (actualIndentation !== -1) { - return actualIndentation + options.indentSize; + return actualIndentation + options.IndentSize; } previous = current; current = current.parent; @@ -44705,15 +43472,15 @@ var ts; return getIndentationForNodeWorker(current, currentStart, undefined, indentationDelta, sourceFile, options); } SmartIndenter.getIndentation = getIndentation; + function getBaseIndentation(options) { + return options.BaseIndentSize || 0; + } + SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) { var start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, 0, sourceFile, options); } SmartIndenter.getIndentationForNode = getIndentationForNode; - function getBaseIndentation(options) { - return options.baseIndentSize || 0; - } - SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, options) { var parent = current.parent; var parentStart; @@ -44743,7 +43510,7 @@ var ts; } } if (shouldIndentChildNode(parent, current) && !parentAndChildShareLine) { - indentationDelta += options.indentSize; + indentationDelta += options.IndentSize; } current = parent; currentStart = parentStart; @@ -44921,7 +43688,7 @@ var ts; break; } if (ch === 9) { - column += options.tabSize + (column % options.tabSize); + column += options.TabSize + (column % options.TabSize); } else { column++; @@ -45043,20 +43810,6 @@ var ts; } ScriptSnapshot.fromString = fromString; })(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {})); - function realizeDiagnostics(diagnostics, newLine) { - return diagnostics.map(function (d) { return realizeDiagnostic(d, newLine); }); - } - ts.realizeDiagnostics = realizeDiagnostics; - function realizeDiagnostic(diagnostic, newLine) { - return { - message: ts.flattenDiagnosticMessageText(diagnostic.messageText, newLine), - start: diagnostic.start, - length: diagnostic.length, - category: ts.DiagnosticCategory[diagnostic.category].toLowerCase(), - code: diagnostic.code - }; - } - ts.realizeDiagnostic = realizeDiagnostic; var scanner = ts.createScanner(2, true); var emptyArray = []; var jsDocTagNames = [ @@ -45101,20 +43854,19 @@ var ts; "version" ]; var jsDocCompletionEntries; - function createNode(kind, pos, end, parent) { - var node = kind >= 139 ? new NodeObject(kind, pos, end) : - kind === 69 ? new IdentifierObject(kind, pos, end) : - new TokenObject(kind, pos, end); + function createNode(kind, pos, end, flags, parent) { + var node = new NodeObject(kind, pos, end); + node.flags = flags; node.parent = parent; return node; } var NodeObject = (function () { function NodeObject(kind, pos, end) { + this.kind = kind; this.pos = pos; this.end = end; this.flags = 0; this.parent = undefined; - this.kind = kind; } NodeObject.prototype.getSourceFile = function () { return ts.getSourceFileOfNode(this); @@ -45149,14 +43901,14 @@ var ts; var token = useJSDocScanner ? scanner.scanJSDocToken() : scanner.scan(); var textPos = scanner.getTextPos(); if (textPos <= end) { - nodes.push(createNode(token, pos, textPos, this)); + nodes.push(createNode(token, pos, textPos, 0, this)); } pos = textPos; } return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(286, nodes.pos, nodes.end, this); + var list = createNode(282, nodes.pos, nodes.end, 0, this); list._children = []; var pos = nodes.pos; for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { @@ -45179,16 +43931,13 @@ var ts; scanner.setText((sourceFile || this.getSourceFile()).text); children = []; var pos_3 = this.pos; - var useJSDocScanner_1 = this.kind >= 273 && this.kind <= 285; + var useJSDocScanner_1 = this.kind >= 273 && this.kind <= 281; var processNode = function (node) { - var isJSDocTagNode = ts.isJSDocTag(node); - if (!isJSDocTagNode && pos_3 < node.pos) { + if (pos_3 < node.pos) { pos_3 = _this.addSyntheticNodes(children, pos_3, node.pos, useJSDocScanner_1); } children.push(node); - if (!isJSDocTagNode) { - pos_3 = node.end; - } + pos_3 = node.end; }; var processNodes = function (nodes) { if (pos_3 < nodes.pos) { @@ -45244,73 +43993,6 @@ var ts; }; return NodeObject; }()); - var TokenOrIdentifierObject = (function () { - function TokenOrIdentifierObject(pos, end) { - this.pos = pos; - this.end = end; - this.flags = 0; - this.parent = undefined; - } - TokenOrIdentifierObject.prototype.getSourceFile = function () { - return ts.getSourceFileOfNode(this); - }; - TokenOrIdentifierObject.prototype.getStart = function (sourceFile, includeJsDocComment) { - return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment); - }; - TokenOrIdentifierObject.prototype.getFullStart = function () { - return this.pos; - }; - TokenOrIdentifierObject.prototype.getEnd = function () { - return this.end; - }; - TokenOrIdentifierObject.prototype.getWidth = function (sourceFile) { - return this.getEnd() - this.getStart(sourceFile); - }; - TokenOrIdentifierObject.prototype.getFullWidth = function () { - return this.end - this.pos; - }; - TokenOrIdentifierObject.prototype.getLeadingTriviaWidth = function (sourceFile) { - return this.getStart(sourceFile) - this.pos; - }; - TokenOrIdentifierObject.prototype.getFullText = function (sourceFile) { - return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end); - }; - TokenOrIdentifierObject.prototype.getText = function (sourceFile) { - return (sourceFile || this.getSourceFile()).text.substring(this.getStart(), this.getEnd()); - }; - TokenOrIdentifierObject.prototype.getChildCount = function (sourceFile) { - return 0; - }; - TokenOrIdentifierObject.prototype.getChildAt = function (index, sourceFile) { - return undefined; - }; - TokenOrIdentifierObject.prototype.getChildren = function (sourceFile) { - return emptyArray; - }; - TokenOrIdentifierObject.prototype.getFirstToken = function (sourceFile) { - return undefined; - }; - TokenOrIdentifierObject.prototype.getLastToken = function (sourceFile) { - return undefined; - }; - return TokenOrIdentifierObject; - }()); - var TokenObject = (function (_super) { - __extends(TokenObject, _super); - function TokenObject(kind, pos, end) { - _super.call(this, pos, end); - this.kind = kind; - } - return TokenObject; - }(TokenOrIdentifierObject)); - var IdentifierObject = (function (_super) { - __extends(IdentifierObject, _super); - function IdentifierObject(kind, pos, end) { - _super.call(this, pos, end); - } - return IdentifierObject; - }(TokenOrIdentifierObject)); - IdentifierObject.prototype.kind = 69; var SymbolObject = (function () { function SymbolObject(flags, name) { this.flags = flags; @@ -45613,7 +44295,7 @@ var ts; return this.checker.getIndexTypeOfType(this, 1); }; TypeObject.prototype.getBaseTypes = function () { - return this.flags & (32768 | 65536) + return this.flags & (1024 | 2048) ? this.checker.getBaseTypes(this) : undefined; }; @@ -45670,7 +44352,7 @@ var ts; return this.namedDeclarations; }; SourceFileObject.prototype.computeNamedDeclarations = function () { - var result = ts.createMap(); + var result = {}; ts.forEachChild(this, visit); return result; function addDeclaration(declaration) { @@ -45681,13 +44363,13 @@ var ts; } } function getDeclarations(name) { - return result[name] || (result[name] = []); + return ts.getProperty(result, name) || (result[name] = []); } function getDeclarationName(declaration) { if (declaration.name) { - var result_3 = getTextOfIdentifierOrLiteral(declaration.name); - if (result_3 !== undefined) { - return result_3; + var result_2 = getTextOfIdentifierOrLiteral(declaration.name); + if (result_2 !== undefined) { + return result_2; } if (declaration.name.kind === 140) { var expr = declaration.name.expression; @@ -45815,30 +44497,6 @@ var ts; IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; })(ts.IndentStyle || (ts.IndentStyle = {})); var IndentStyle = ts.IndentStyle; - function toEditorSettings(optionsAsMap) { - var allPropertiesAreCamelCased = true; - for (var key in optionsAsMap) { - if (ts.hasProperty(optionsAsMap, key) && !isCamelCase(key)) { - allPropertiesAreCamelCased = false; - break; - } - } - if (allPropertiesAreCamelCased) { - return optionsAsMap; - } - var settings = {}; - for (var key in optionsAsMap) { - if (ts.hasProperty(optionsAsMap, key)) { - var newKey = isCamelCase(key) ? key : key.charAt(0).toLowerCase() + key.substr(1); - settings[newKey] = optionsAsMap[key]; - } - } - return settings; - } - ts.toEditorSettings = toEditorSettings; - function isCamelCase(s) { - return !s.length || s.charAt(0) === s.charAt(0).toLowerCase(); - } (function (SymbolDisplayPartKind) { SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; SymbolDisplayPartKind[SymbolDisplayPartKind["className"] = 1] = "className"; @@ -45888,7 +44546,6 @@ var ts; ScriptElementKind.interfaceElement = "interface"; ScriptElementKind.typeElement = "type"; ScriptElementKind.enumElement = "enum"; - ScriptElementKind.enumMemberElement = "const"; ScriptElementKind.variableElement = "var"; ScriptElementKind.localVariableElement = "local var"; ScriptElementKind.functionElement = "function"; @@ -45908,8 +44565,6 @@ var ts; ScriptElementKind.alias = "alias"; ScriptElementKind.constElement = "const"; ScriptElementKind.letElement = "let"; - ScriptElementKind.directory = "directory"; - ScriptElementKind.externalModuleName = "external module name"; })(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {})); var ScriptElementKindModifier; (function (ScriptElementKindModifier) { @@ -45969,8 +44624,8 @@ var ts; if (declaration.kind !== 218 && declaration.kind !== 220) { return false; } - for (var parent_17 = declaration.parent; !ts.isFunctionBlock(parent_17); parent_17 = parent_17.parent) { - if (parent_17.kind === 256 || parent_17.kind === 226) { + for (var parent_16 = declaration.parent; !ts.isFunctionBlock(parent_16); parent_16 = parent_16.parent) { + if (parent_16.kind === 256 || parent_16.kind === 226) { return false; } } @@ -46048,16 +44703,43 @@ var ts; }; return HostCache; }()); + var SyntaxTreeCache = (function () { + function SyntaxTreeCache(host) { + this.host = host; + } + SyntaxTreeCache.prototype.getCurrentSourceFile = function (fileName) { + var scriptSnapshot = this.host.getScriptSnapshot(fileName); + if (!scriptSnapshot) { + throw new Error("Could not find file: '" + fileName + "'."); + } + var scriptKind = ts.getScriptKind(fileName, this.host); + var version = this.host.getScriptVersion(fileName); + var sourceFile; + if (this.currentFileName !== fileName) { + sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 2, version, true, scriptKind); + } + else if (this.currentFileVersion !== version) { + var editRange = scriptSnapshot.getChangeRange(this.currentFileScriptSnapshot); + sourceFile = updateLanguageServiceSourceFile(this.currentSourceFile, scriptSnapshot, version, editRange); + } + if (sourceFile) { + this.currentFileVersion = version; + this.currentFileName = fileName; + this.currentFileScriptSnapshot = scriptSnapshot; + this.currentSourceFile = sourceFile; + } + return this.currentSourceFile; + }; + return SyntaxTreeCache; + }()); function setSourceFileFields(sourceFile, scriptSnapshot, version) { sourceFile.version = version; sourceFile.scriptSnapshot = scriptSnapshot; } - var tripleSlashDirectiveFragmentRegex = /^(\/\/\/\s*= commentRange.pos && position <= commentRange.end && commentRange; }); - if (!range) { - return undefined; - } - var text = sourceFile.text.substr(range.pos, position - range.pos); - var match = tripleSlashDirectiveFragmentRegex.exec(text); - if (match) { - var prefix = match[1]; - var kind = match[2]; - var toComplete = match[3]; - var scriptPath = ts.getDirectoryPath(sourceFile.path); - var entries_3; - if (kind === "path") { - var span = getDirectoryFragmentTextSpan(toComplete, range.pos + prefix.length); - entries_3 = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(program.getCompilerOptions()), true, span, sourceFile.path); - } - else { - var span = { start: range.pos + prefix.length, length: match[0].length - prefix.length }; - entries_3 = getCompletionEntriesFromTypings(host, program.getCompilerOptions(), scriptPath, span); - } - return { - isMemberCompletion: false, - isNewIdentifierLocation: true, - entries: entries_3 - }; - } - return undefined; - } - function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { - if (result === void 0) { result = []; } - if (options.types) { - for (var _i = 0, _a = options.types; _i < _a.length; _i++) { - var moduleName = _a[_i]; - result.push(createCompletionEntryForModule(moduleName, ScriptElementKind.externalModuleName, span)); - } - } - else if (host.getDirectories) { - var typeRoots = ts.getEffectiveTypeRoots(options, host); - for (var _b = 0, typeRoots_2 = typeRoots; _b < typeRoots_2.length; _b++) { - var root = typeRoots_2[_b]; - getCompletionEntriesFromDirectories(host, options, root, span, result); - } - } - if (host.getDirectories) { - for (var _c = 0, _d = findPackageJsons(scriptPath); _c < _d.length; _c++) { - var package = _d[_c]; - var typesDir = ts.combinePaths(ts.getDirectoryPath(package), "node_modules/@types"); - getCompletionEntriesFromDirectories(host, options, typesDir, span, result); - } - } - return result; - } - function getCompletionEntriesFromDirectories(host, options, directory, span, result) { - if (host.getDirectories && tryDirectoryExists(host, directory)) { - var directories = tryGetDirectories(host, directory); - if (directories) { - for (var _i = 0, directories_3 = directories; _i < directories_3.length; _i++) { - var typeDirectory = directories_3[_i]; - typeDirectory = ts.normalizePath(typeDirectory); - result.push(createCompletionEntryForModule(ts.getBaseFileName(typeDirectory), ScriptElementKind.externalModuleName, span)); - } - } - } - } - function findPackageJsons(currentDir) { - var paths = []; - var currentConfigPath; - while (true) { - currentConfigPath = ts.findConfigFile(currentDir, function (f) { return tryFileExists(host, f); }, "package.json"); - if (currentConfigPath) { - paths.push(currentConfigPath); - currentDir = ts.getDirectoryPath(currentConfigPath); - var parent_21 = ts.getDirectoryPath(currentDir); - if (currentDir === parent_21) { - break; - } - currentDir = parent_21; - } - else { - break; - } - } - return paths; - } - function enumerateNodeModulesVisibleToScript(host, scriptPath) { - var result = []; - if (host.readFile && host.fileExists) { - for (var _i = 0, _a = findPackageJsons(scriptPath); _i < _a.length; _i++) { - var packageJson = _a[_i]; - var package = tryReadingPackageJson(packageJson); - if (!package) { - return; - } - var nodeModulesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules"); - var foundModuleNames = []; - for (var _b = 0, nodeModulesDependencyKeys_1 = nodeModulesDependencyKeys; _b < nodeModulesDependencyKeys_1.length; _b++) { - var key = nodeModulesDependencyKeys_1[_b]; - addPotentialPackageNames(package[key], foundModuleNames); - } - for (var _c = 0, foundModuleNames_1 = foundModuleNames; _c < foundModuleNames_1.length; _c++) { - var moduleName = foundModuleNames_1[_c]; - var moduleDir = ts.combinePaths(nodeModulesDir, moduleName); - result.push({ - moduleName: moduleName, - moduleDir: moduleDir - }); - } - } - } - return result; - function tryReadingPackageJson(filePath) { - try { - var fileText = tryReadFile(host, filePath); - return fileText ? JSON.parse(fileText) : undefined; - } - catch (e) { - return undefined; - } - } - function addPotentialPackageNames(dependencies, result) { - if (dependencies) { - for (var dep in dependencies) { - if (dependencies.hasOwnProperty(dep) && !ts.startsWith(dep, "@types/")) { - result.push(dep); - } - } - } - } - } - function createCompletionEntryForModule(name, kind, replacementSpan) { - return { name: name, kind: kind, kindModifiers: ScriptElementKindModifier.none, sortText: name, replacementSpan: replacementSpan }; - } - function getDirectoryFragmentTextSpan(text, textStart) { - var index = text.lastIndexOf(ts.directorySeparator); - var offset = index !== -1 ? index + 1 : 0; - return { start: textStart + offset, length: text.length - offset }; - } - function isPathRelativeToScript(path) { - if (path && path.length >= 2 && path.charCodeAt(0) === 46) { - var slashIndex = path.length >= 3 && path.charCodeAt(1) === 46 ? 2 : 1; - var slashCharCode = path.charCodeAt(slashIndex); - return slashCharCode === 47 || slashCharCode === 92; - } - return false; - } - function normalizeAndPreserveTrailingSlash(path) { - return ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(ts.normalizePath(path)) : ts.normalizePath(path); - } - function tryGetDirectories(host, directoryName) { - return tryIOAndConsumeErrors(host, host.getDirectories, directoryName); - } - function tryReadDirectory(host, path, extensions, exclude, include) { - return tryIOAndConsumeErrors(host, host.readDirectory, path, extensions, exclude, include); - } - function tryReadFile(host, path) { - return tryIOAndConsumeErrors(host, host.readFile, path); - } - function tryFileExists(host, path) { - return tryIOAndConsumeErrors(host, host.fileExists, path); - } - function tryDirectoryExists(host, path) { - try { - return ts.directoryProbablyExists(path, host); - } - catch (e) { } - return undefined; - } - function tryIOAndConsumeErrors(host, toApply) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - try { - return toApply && toApply.apply(host, args); - } - catch (e) { } - return undefined; - } } function getCompletionEntryDetails(fileName, position, entryName) { synchronizeHostData(); @@ -48434,7 +46629,7 @@ var ts; displayParts.push(ts.keywordPart(92)); displayParts.push(ts.spacePart()); } - if (!(type.flags & 2097152) && type.symbol) { + if (!(type.flags & 65536) && type.symbol) { ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, undefined, 1)); } addSignatureDisplayParts(signature, allSignatures, 8); @@ -48495,7 +46690,7 @@ var ts; displayParts.push(ts.spacePart()); displayParts.push(ts.operatorPart(56)); displayParts.push(ts.spacePart()); - ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 512)); + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration)); } if (symbolFlags & 384) { addNewLineIfDisplayPartsExist(); @@ -48569,14 +46764,7 @@ var ts; } if (symbolFlags & 8388608) { addNewLineIfDisplayPartsExist(); - if (symbol.declarations[0].kind === 228) { - displayParts.push(ts.keywordPart(82)); - displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(126)); - } - else { - displayParts.push(ts.keywordPart(89)); - } + displayParts.push(ts.keywordPart(89)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); ts.forEach(symbol.declarations, function (declaration) { @@ -48647,24 +46835,6 @@ var ts; } if (!documentation) { documentation = symbol.getDocumentationComment(); - if (documentation.length === 0 && symbol.flags & 4) { - if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 256; })) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (!declaration.parent || declaration.parent.kind !== 187) { - continue; - } - var rhsSymbol = program.getTypeChecker().getSymbolAtLocation(declaration.parent.right); - if (!rhsSymbol) { - continue; - } - documentation = rhsSymbol.getDocumentationComment(); - if (documentation.length > 0) { - break; - } - } - } - } } return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind }; function addNewLineIfDisplayPartsExist() { @@ -48861,7 +47031,7 @@ var ts; } var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); if (typeReferenceDirective) { - var referenceFile = program.getResolvedTypeReferenceDirectives()[typeReferenceDirective.fileName]; + var referenceFile = ts.lookUp(program.getResolvedTypeReferenceDirectives(), typeReferenceDirective.fileName); if (referenceFile && referenceFile.resolvedFileName) { return [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)]; } @@ -48918,14 +47088,14 @@ var ts; if (!type) { return undefined; } - if (type.flags & 524288 && !(type.flags & 16)) { - var result_4 = []; + if (type.flags & 16384) { + var result_3 = []; ts.forEach(type.types, function (t) { if (t.symbol) { - ts.addRange(result_4, getDefinitionFromSymbol(t.symbol, node)); + ts.addRange(result_3, getDefinitionFromSymbol(t.symbol, node)); } }); - return result_4; + return result_3; } if (!type.symbol) { return undefined; @@ -48973,14 +47143,14 @@ var ts; if (!referencedSymbols) { return undefined; } - var fileNameToDocumentHighlights = ts.createMap(); + var fileNameToDocumentHighlights = {}; var result = []; for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) { var referencedSymbol = referencedSymbols_1[_i]; for (var _a = 0, _b = referencedSymbol.references; _a < _b.length; _a++) { var referenceEntry = _b[_a]; var fileName_1 = referenceEntry.fileName; - var documentHighlights = fileNameToDocumentHighlights[fileName_1]; + var documentHighlights = ts.getProperty(fileNameToDocumentHighlights, fileName_1); if (!documentHighlights) { documentHighlights = { fileName: fileName_1, highlightSpans: [] }; fileNameToDocumentHighlights[fileName_1] = documentHighlights; @@ -49116,17 +47286,17 @@ var ts; function getThrowStatementOwner(throwStatement) { var child = throwStatement; while (child.parent) { - var parent_22 = child.parent; - if (ts.isFunctionBlock(parent_22) || parent_22.kind === 256) { - return parent_22; + var parent_20 = child.parent; + if (ts.isFunctionBlock(parent_20) || parent_20.kind === 256) { + return parent_20; } - if (parent_22.kind === 216) { - var tryStatement = parent_22; + if (parent_20.kind === 216) { + var tryStatement = parent_20; if (tryStatement.tryBlock === child && tryStatement.catchClause) { return child; } } - child = parent_22; + child = parent_20; } return undefined; } @@ -49549,7 +47719,7 @@ var ts; var sourceFile = sourceFiles_4[_i]; cancellationToken.throwIfCancellationRequested(); var nameTable = getNameTable(sourceFile); - if (nameTable[internedName] !== undefined) { + if (ts.lookUp(nameTable, internedName) !== undefined) { result = result || []; getReferencesInNode(sourceFile, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex); } @@ -49569,8 +47739,7 @@ var ts; name: name, kind: info.symbolKind, fileName: declarations[0].getSourceFile().fileName, - textSpan: ts.createTextSpan(declarations[0].getStart(), 0), - displayParts: info.displayParts + textSpan: ts.createTextSpan(declarations[0].getStart(), 0) }; } function getAliasSymbolForPropertyNameSymbol(symbol, location) { @@ -49701,8 +47870,7 @@ var ts; fileName: targetLabel.getSourceFile().fileName, kind: ScriptElementKind.label, name: labelName, - textSpan: ts.createTextSpanFromBounds(targetLabel.getStart(), targetLabel.getEnd()), - displayParts: [ts.displayPart(labelName, SymbolDisplayPartKind.text)] + textSpan: ts.createTextSpanFromBounds(targetLabel.getStart(), targetLabel.getEnd()) }; return [{ definition: definition, references: references }]; } @@ -49728,6 +47896,7 @@ var ts; } function getReferencesInNode(container, searchSymbol, searchText, searchLocation, searchMeaning, findInStrings, findInComments, result, symbolToIndex) { var sourceFile = container.getSourceFile(); + var tripleSlashDirectivePrefixRegex = /^\/\/\/\s*= 0 ? s : undefined; }); + var result_4 = []; + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result_4, {}); + return ts.forEach(result_4, function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); } return undefined; }); @@ -50075,20 +48247,20 @@ var ts; var contextualType = typeChecker.getContextualType(objectLiteral); var name = getNameFromObjectLiteralElement(node); if (name && contextualType) { - var result_6 = []; - var symbol_2 = contextualType.getProperty(name); - if (symbol_2) { - result_6.push(symbol_2); + var result_5 = []; + var symbol_1 = contextualType.getProperty(name); + if (symbol_1) { + result_5.push(symbol_1); } - if (contextualType.flags & 524288) { + if (contextualType.flags & 16384) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_6.push(symbol); + result_5.push(symbol); } }); } - return result_6; + return result_5; } return undefined; } @@ -50139,12 +48311,12 @@ var ts; } return false; } - function getNavigateToItems(searchValue, maxResultCount, excludeDts) { + function getNavigateToItems(searchValue, maxResultCount) { synchronizeHostData(); var checker = getProgram().getTypeChecker(); - return ts.NavigateTo.getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount, excludeDts); + return ts.NavigateTo.getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount); } - function getEmitOutput(fileName, emitDeclarationsOnly) { + function getEmitOutput(fileName) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var outputFiles = []; @@ -50155,7 +48327,7 @@ var ts; text: data }); } - var emitOutput = program.emit(sourceFile, writeFile, cancellationToken, emitDeclarationsOnly); + var emitOutput = program.emit(sourceFile, writeFile, cancellationToken); return { outputFiles: outputFiles, emitSkipped: emitOutput.emitSkipped @@ -50303,6 +48475,7 @@ var ts; case 172: case 139: case 9: + case 166: case 84: case 99: case 93: @@ -50603,9 +48776,6 @@ var ts; } } function tryClassifyNode(node) { - if (ts.isJSDocTag(node)) { - return true; - } if (ts.nodeIsMissing(node)) { return true; } @@ -50680,7 +48850,7 @@ var ts; else if (tokenKind === 8) { return 4; } - else if (tokenKind === 9) { + else if (tokenKind === 9 || tokenKind === 166) { return token.parent.kind === 246 ? 24 : 6; } else if (tokenKind === 10) { @@ -50791,37 +48961,33 @@ var ts; return undefined; } } - function getIndentationAtPosition(fileName, position, optionsOrSettings) { - var start = ts.timestamp(); - var settings = toEditorSettings(optionsOrSettings); + function getIndentationAtPosition(fileName, position, editorOptions) { + var start = new Date().getTime(); var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - log("getIndentationAtPosition: getCurrentSourceFile: " + (ts.timestamp() - start)); - start = ts.timestamp(); - var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, settings); - log("getIndentationAtPosition: computeIndentation : " + (ts.timestamp() - start)); + log("getIndentationAtPosition: getCurrentSourceFile: " + (new Date().getTime() - start)); + start = new Date().getTime(); + var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, editorOptions); + log("getIndentationAtPosition: computeIndentation : " + (new Date().getTime() - start)); return result; } - function getFormattingEditsForRange(fileName, start, end, optionsOrSettings) { - var settings = toEditorSettings(optionsOrSettings); + function getFormattingEditsForRange(fileName, start, end, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(settings), settings); + return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(options), options); } - function getFormattingEditsForDocument(fileName, optionsOrSettings) { - var settings = toEditorSettings(optionsOrSettings); + function getFormattingEditsForDocument(fileName, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.formatting.formatDocument(sourceFile, getRuleProvider(settings), settings); + return ts.formatting.formatDocument(sourceFile, getRuleProvider(options), options); } - function getFormattingEditsAfterKeystroke(fileName, position, key, optionsOrSettings) { - var settings = toEditorSettings(optionsOrSettings); + function getFormattingEditsAfterKeystroke(fileName, position, key, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); if (key === "}") { - return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(settings), settings); + return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(options), options); } else if (key === ";") { - return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(settings), settings); + return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(options), options); } else if (key === "\n") { - return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(settings), settings); + return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(options), options); } return []; } @@ -50987,7 +49153,7 @@ var ts; function getStringLiteralTypeForNode(node, typeChecker) { var searchNode = node.parent.kind === 166 ? node.parent : node; var type = typeChecker.getTypeAtLocation(searchNode); - if (type && type.flags & 32) { + if (type && type.flags & 256) { return type; } return undefined; @@ -51129,7 +49295,7 @@ var ts; } ts.getNameTable = getNameTable; function initializeNameTable(sourceFile) { - var nameTable = ts.createMap(); + var nameTable = {}; walk(sourceFile); sourceFile.nameTable = nameTable; function walk(node) { @@ -51197,7 +49363,7 @@ var ts; var lastEnd = 0; for (var i = 0, n = dense.length; i < n; i += 3) { var start = dense[i]; - var length_5 = dense[i + 1]; + var length_3 = dense[i + 1]; var type = dense[i + 2]; if (lastEnd >= 0) { var whitespaceLength_1 = start - lastEnd; @@ -51205,8 +49371,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: TokenClass.Whitespace }); } } - entries.push({ length: length_5, classification: convertClassification(type) }); - lastEnd = start + length_5; + entries.push({ length: length_3, classification: convertClassification(type) }); + lastEnd = start + length_3; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -51342,7 +49508,7 @@ var ts; var end = scanner.getTextPos(); addResult(start, end, classFromKind(token)); if (end >= text.length) { - if (token === 9) { + if (token === 9 || token === 166) { var tokenText = scanner.getTokenText(); if (scanner.isUnterminated()) { var lastCharIndex = tokenText.length - 1; @@ -51472,6 +49638,7 @@ var ts; case 8: return 4; case 9: + case 166: return 6; case 10: return 7; @@ -51506,8 +49673,6 @@ var ts; function initializeServices() { ts.objectAllocator = { getNodeConstructor: function () { return NodeObject; }, - getTokenConstructor: function () { return TokenObject; }, - getIdentifierConstructor: function () { return IdentifierObject; }, getSourceFileConstructor: function () { return SourceFileObject; }, getSymbolConstructor: function () { return SymbolObject; }, getTypeConstructor: function () { return TypeObject; }, @@ -51520,2279 +49685,43 @@ var ts; (function (ts) { var server; (function (server) { - var ScriptInfo = (function () { - function ScriptInfo(host, fileName, content, scriptKind, isOpen, hasMixedContent) { - if (isOpen === void 0) { isOpen = false; } - if (hasMixedContent === void 0) { hasMixedContent = false; } - this.host = host; - this.fileName = fileName; - this.scriptKind = scriptKind; - this.isOpen = isOpen; - this.hasMixedContent = hasMixedContent; - this.containingProjects = []; - this.path = ts.toPath(fileName, host.getCurrentDirectory(), ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames)); - this.svc = server.ScriptVersionCache.fromString(host, content); - this.scriptKind = scriptKind - ? scriptKind - : ts.getScriptKindFromFileName(fileName); - } - ScriptInfo.prototype.getFormatCodeSettings = function () { - return this.formatCodeSettings; - }; - ScriptInfo.prototype.attachToProject = function (project) { - var isNew = !this.isAttached(project); - if (isNew) { - this.containingProjects.push(project); - } - return isNew; - }; - ScriptInfo.prototype.isAttached = function (project) { - switch (this.containingProjects.length) { - case 0: return false; - case 1: return this.containingProjects[0] === project; - case 2: return this.containingProjects[0] === project || this.containingProjects[1] === project; - default: return ts.contains(this.containingProjects, project); - } - }; - ScriptInfo.prototype.detachFromProject = function (project) { - switch (this.containingProjects.length) { - case 0: - return; - case 1: - if (this.containingProjects[0] === project) { - this.containingProjects.pop(); - } - break; - case 2: - if (this.containingProjects[0] === project) { - this.containingProjects[0] = this.containingProjects.pop(); - } - else if (this.containingProjects[1] === project) { - this.containingProjects.pop(); - } - break; - default: - server.removeItemFromSet(this.containingProjects, project); - break; - } - }; - ScriptInfo.prototype.detachAllProjects = function () { - for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { - var p = _a[_i]; - p.removeFile(this, false); - } - this.containingProjects.length = 0; - }; - ScriptInfo.prototype.getDefaultProject = function () { - if (this.containingProjects.length === 0) { - return server.Errors.ThrowNoProject(); - } - ts.Debug.assert(this.containingProjects.length !== 0); - return this.containingProjects[0]; - }; - ScriptInfo.prototype.setFormatOptions = function (formatSettings) { - if (formatSettings) { - if (!this.formatCodeSettings) { - this.formatCodeSettings = server.getDefaultFormatCodeSettings(this.host); - } - server.mergeMaps(this.formatCodeSettings, formatSettings); - } - }; - ScriptInfo.prototype.setWatcher = function (watcher) { - this.stopWatcher(); - this.fileWatcher = watcher; - }; - ScriptInfo.prototype.stopWatcher = function () { - if (this.fileWatcher) { - this.fileWatcher.close(); - this.fileWatcher = undefined; - } - }; - ScriptInfo.prototype.getLatestVersion = function () { - return this.svc.latestVersion().toString(); - }; - ScriptInfo.prototype.reload = function (script) { - this.svc.reload(script); - this.markContainingProjectsAsDirty(); - }; - ScriptInfo.prototype.saveTo = function (fileName) { - var snap = this.snap(); - this.host.writeFile(fileName, snap.getText(0, snap.getLength())); - }; - ScriptInfo.prototype.reloadFromFile = function () { - if (this.hasMixedContent) { - this.reload(""); - } - else { - this.svc.reloadFromFile(this.fileName); - this.markContainingProjectsAsDirty(); - } - }; - ScriptInfo.prototype.snap = function () { - return this.svc.getSnapshot(); - }; - ScriptInfo.prototype.getLineInfo = function (line) { - var snap = this.snap(); - return snap.index.lineNumberToInfo(line); - }; - ScriptInfo.prototype.editContent = function (start, end, newText) { - this.svc.edit(start, end - start, newText); - this.markContainingProjectsAsDirty(); - }; - ScriptInfo.prototype.markContainingProjectsAsDirty = function () { - for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { - var p = _a[_i]; - p.markAsDirty(); - } - }; - ScriptInfo.prototype.lineToTextSpan = function (line) { - var index = this.snap().index; - var lineInfo = index.lineNumberToInfo(line + 1); - var len; - if (lineInfo.leaf) { - len = lineInfo.leaf.text.length; - } - else { - var nextLineInfo = index.lineNumberToInfo(line + 2); - len = nextLineInfo.offset - lineInfo.offset; - } - return ts.createTextSpan(lineInfo.offset, len); - }; - ScriptInfo.prototype.lineOffsetToPosition = function (line, offset) { - var index = this.snap().index; - var lineInfo = index.lineNumberToInfo(line); - return (lineInfo.offset + offset - 1); - }; - ScriptInfo.prototype.positionToLineOffset = function (position) { - var index = this.snap().index; - var lineOffset = index.charOffsetToLineNumberAndPos(position); - return { line: lineOffset.line, offset: lineOffset.offset + 1 }; - }; - return ScriptInfo; - }()); - server.ScriptInfo = ScriptInfo; - })(server = ts.server || (ts.server = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - var server; - (function (server) { - var LSHost = (function () { - function LSHost(host, project, cancellationToken) { - var _this = this; - this.host = host; - this.project = project; - this.cancellationToken = cancellationToken; - this.getCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); - this.resolvedModuleNames = ts.createFileMap(); - this.resolvedTypeReferenceDirectives = ts.createFileMap(); - if (host.trace) { - this.trace = function (s) { return host.trace(s); }; - } - this.resolveModuleName = function (moduleName, containingFile, compilerOptions, host) { - var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host); - if (primaryResult.resolvedModule) { - if (ts.fileExtensionIsAny(primaryResult.resolvedModule.resolvedFileName, ts.supportedTypeScriptExtensions)) { - return primaryResult; - } - } - var secondaryLookupFailedLookupLocations = []; - var globalCache = _this.project.projectService.typingsInstaller.globalTypingsCacheLocation; - if (_this.project.getTypingOptions().enableAutoDiscovery && globalCache) { - var traceEnabled = ts.isTraceEnabled(compilerOptions, host); - if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, _this.project.getProjectName(), moduleName, globalCache); - } - var state = { compilerOptions: compilerOptions, host: host, skipTsx: false, traceEnabled: traceEnabled }; - var resolvedName = ts.loadModuleFromNodeModules(moduleName, globalCache, secondaryLookupFailedLookupLocations, state, true); - if (resolvedName) { - return ts.createResolvedModule(resolvedName, true, primaryResult.failedLookupLocations.concat(secondaryLookupFailedLookupLocations)); - } - } - if (!primaryResult.resolvedModule && secondaryLookupFailedLookupLocations.length) { - primaryResult.failedLookupLocations = primaryResult.failedLookupLocations.concat(secondaryLookupFailedLookupLocations); - } - return primaryResult; - }; - } - LSHost.prototype.resolveNamesWithLocalCache = function (names, containingFile, cache, loader, getResult) { - var path = ts.toPath(containingFile, this.host.getCurrentDirectory(), this.getCanonicalFileName); - var currentResolutionsInFile = cache.get(path); - var newResolutions = ts.createMap(); - var resolvedModules = []; - var compilerOptions = this.getCompilationSettings(); - for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { - var name_43 = names_2[_i]; - var resolution = newResolutions[name_43]; - if (!resolution) { - var existingResolution = currentResolutionsInFile && currentResolutionsInFile[name_43]; - if (moduleResolutionIsValid(existingResolution)) { - resolution = existingResolution; - } - else { - newResolutions[name_43] = resolution = loader(name_43, containingFile, compilerOptions, this); - } - } - ts.Debug.assert(resolution !== undefined); - resolvedModules.push(getResult(resolution)); - } - cache.set(path, newResolutions); - return resolvedModules; - function moduleResolutionIsValid(resolution) { - if (!resolution) { - return false; - } - if (getResult(resolution)) { - return true; - } - return resolution.failedLookupLocations.length === 0; - } - }; - LSHost.prototype.getProjectVersion = function () { - return this.project.getProjectVersion(); - }; - LSHost.prototype.getCompilationSettings = function () { - return this.compilationSettings; - }; - LSHost.prototype.useCaseSensitiveFileNames = function () { - return this.host.useCaseSensitiveFileNames; - }; - LSHost.prototype.getCancellationToken = function () { - return this.cancellationToken; - }; - LSHost.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { - return this.resolveNamesWithLocalCache(typeDirectiveNames, containingFile, this.resolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, function (m) { return m.resolvedTypeReferenceDirective; }); - }; - LSHost.prototype.resolveModuleNames = function (moduleNames, containingFile) { - return this.resolveNamesWithLocalCache(moduleNames, containingFile, this.resolvedModuleNames, this.resolveModuleName, function (m) { return m.resolvedModule; }); - }; - LSHost.prototype.getDefaultLibFileName = function () { - var nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.host.getExecutingFilePath())); - return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilationSettings)); - }; - LSHost.prototype.getScriptSnapshot = function (filename) { - var scriptInfo = this.project.getScriptInfoLSHost(filename); - if (scriptInfo) { - return scriptInfo.snap(); - } - }; - LSHost.prototype.getScriptFileNames = function () { - return this.project.getRootFilesLSHost(); - }; - LSHost.prototype.getTypeRootsVersion = function () { - return this.project.typesVersion; - }; - LSHost.prototype.getScriptKind = function (fileName) { - var info = this.project.getScriptInfoLSHost(fileName); - return info && info.scriptKind; - }; - LSHost.prototype.getScriptVersion = function (filename) { - var info = this.project.getScriptInfoLSHost(filename); - return info && info.getLatestVersion(); - }; - LSHost.prototype.getCurrentDirectory = function () { - return this.host.getCurrentDirectory(); - }; - LSHost.prototype.resolvePath = function (path) { - return this.host.resolvePath(path); - }; - LSHost.prototype.fileExists = function (path) { - return this.host.fileExists(path); - }; - LSHost.prototype.directoryExists = function (path) { - return this.host.directoryExists(path); - }; - LSHost.prototype.readFile = function (fileName) { - return this.host.readFile(fileName); - }; - LSHost.prototype.getDirectories = function (path) { - return this.host.getDirectories(path); - }; - LSHost.prototype.notifyFileRemoved = function (info) { - this.resolvedModuleNames.remove(info.path); - this.resolvedTypeReferenceDirectives.remove(info.path); - }; - LSHost.prototype.setCompilationSettings = function (opt) { - this.compilationSettings = opt; - this.resolvedModuleNames.clear(); - this.resolvedTypeReferenceDirectives.clear(); - }; - return LSHost; - }()); - server.LSHost = LSHost; - })(server = ts.server || (ts.server = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - var server; - (function (server) { - server.nullTypingsInstaller = { - enqueueInstallTypingsRequest: function () { }, - attach: function (projectService) { }, - onProjectClosed: function (p) { }, - globalTypingsCacheLocation: undefined - }; - var TypingsCacheEntry = (function () { - function TypingsCacheEntry() { - } - return TypingsCacheEntry; - }()); - function setIsEqualTo(arr1, arr2) { - if (arr1 === arr2) { - return true; - } - if ((arr1 || server.emptyArray).length === 0 && (arr2 || server.emptyArray).length === 0) { - return true; - } - var set = ts.createMap(); - var unique = 0; - for (var _i = 0, arr1_1 = arr1; _i < arr1_1.length; _i++) { - var v = arr1_1[_i]; - if (set[v] !== true) { - set[v] = true; - unique++; - } - } - for (var _a = 0, arr2_1 = arr2; _a < arr2_1.length; _a++) { - var v = arr2_1[_a]; - if (!ts.hasProperty(set, v)) { - return false; - } - if (set[v] === true) { - set[v] = false; - unique--; - } - } - return unique === 0; - } - function typingOptionsChanged(opt1, opt2) { - return opt1.enableAutoDiscovery !== opt2.enableAutoDiscovery || - !setIsEqualTo(opt1.include, opt2.include) || - !setIsEqualTo(opt1.exclude, opt2.exclude); - } - function compilerOptionsChanged(opt1, opt2) { - return opt1.allowJs != opt2.allowJs; - } - function toTypingsArray(arr) { - arr.sort(); - return arr; - } - var TypingsCache = (function () { - function TypingsCache(installer) { - this.installer = installer; - this.perProjectCache = ts.createMap(); - } - TypingsCache.prototype.getTypingsForProject = function (project, forceRefresh) { - var typingOptions = project.getTypingOptions(); - if (!typingOptions || !typingOptions.enableAutoDiscovery) { - return server.emptyArray; - } - var entry = this.perProjectCache[project.getProjectName()]; - var result = entry ? entry.typings : server.emptyArray; - if (forceRefresh || !entry || typingOptionsChanged(typingOptions, entry.typingOptions) || compilerOptionsChanged(project.getCompilerOptions(), entry.compilerOptions)) { - this.perProjectCache[project.getProjectName()] = { - compilerOptions: project.getCompilerOptions(), - typingOptions: typingOptions, - typings: result, - poisoned: true - }; - this.installer.enqueueInstallTypingsRequest(project, typingOptions); - } - return result; - }; - TypingsCache.prototype.invalidateCachedTypingsForProject = function (project) { - var typingOptions = project.getTypingOptions(); - if (!typingOptions.enableAutoDiscovery) { - return; - } - this.installer.enqueueInstallTypingsRequest(project, typingOptions); - }; - TypingsCache.prototype.updateTypingsForProject = function (projectName, compilerOptions, typingOptions, newTypings) { - this.perProjectCache[projectName] = { - compilerOptions: compilerOptions, - typingOptions: typingOptions, - typings: toTypingsArray(newTypings), - poisoned: false - }; - }; - TypingsCache.prototype.onProjectClosed = function (project) { - delete this.perProjectCache[project.getProjectName()]; - this.installer.onProjectClosed(project); - }; - return TypingsCache; - }()); - server.TypingsCache = TypingsCache; - })(server = ts.server || (ts.server = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - var server; - (function (server) { - var crypto = require("crypto"); - function shouldEmitFile(scriptInfo) { - return !scriptInfo.hasMixedContent; - } - server.shouldEmitFile = shouldEmitFile; - var BuilderFileInfo = (function () { - function BuilderFileInfo(scriptInfo, project) { - this.scriptInfo = scriptInfo; - this.project = project; - } - BuilderFileInfo.prototype.isExternalModuleOrHasOnlyAmbientExternalModules = function () { - var sourceFile = this.getSourceFile(); - return ts.isExternalModule(sourceFile) || this.containsOnlyAmbientModules(sourceFile); - }; - BuilderFileInfo.prototype.containsOnlyAmbientModules = function (sourceFile) { - for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - if (statement.kind !== 225 || statement.name.kind !== 9) { - return false; - } - } - return true; - }; - BuilderFileInfo.prototype.computeHash = function (text) { - return crypto.createHash("md5") - .update(text) - .digest("base64"); - }; - BuilderFileInfo.prototype.getSourceFile = function () { - return this.project.getSourceFile(this.scriptInfo.path); - }; - BuilderFileInfo.prototype.updateShapeSignature = function () { - var sourceFile = this.getSourceFile(); - if (!sourceFile) { - return true; - } - var lastSignature = this.lastCheckedShapeSignature; - if (sourceFile.isDeclarationFile) { - this.lastCheckedShapeSignature = this.computeHash(sourceFile.text); - } - else { - var emitOutput = this.project.getFileEmitOutput(this.scriptInfo, true); - if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { - this.lastCheckedShapeSignature = this.computeHash(emitOutput.outputFiles[0].text); - } - } - return !lastSignature || this.lastCheckedShapeSignature !== lastSignature; - }; - return BuilderFileInfo; - }()); - server.BuilderFileInfo = BuilderFileInfo; - var AbstractBuilder = (function () { - function AbstractBuilder(project, ctor) { - this.project = project; - this.ctor = ctor; - this.fileInfos = ts.createFileMap(); - } - AbstractBuilder.prototype.getFileInfo = function (path) { - return this.fileInfos.get(path); - }; - AbstractBuilder.prototype.getOrCreateFileInfo = function (path) { - var fileInfo = this.getFileInfo(path); - if (!fileInfo) { - var scriptInfo = this.project.getScriptInfo(path); - fileInfo = new this.ctor(scriptInfo, this.project); - this.setFileInfo(path, fileInfo); - } - return fileInfo; - }; - AbstractBuilder.prototype.getFileInfoPaths = function () { - return this.fileInfos.getKeys(); - }; - AbstractBuilder.prototype.setFileInfo = function (path, info) { - this.fileInfos.set(path, info); - }; - AbstractBuilder.prototype.removeFileInfo = function (path) { - this.fileInfos.remove(path); - }; - AbstractBuilder.prototype.forEachFileInfo = function (action) { - this.fileInfos.forEachValue(function (path, value) { return action(value); }); - }; - AbstractBuilder.prototype.emitFile = function (scriptInfo, writeFile) { - var fileInfo = this.getFileInfo(scriptInfo.path); - if (!fileInfo) { - return false; - } - var _a = this.project.getFileEmitOutput(fileInfo.scriptInfo, false), emitSkipped = _a.emitSkipped, outputFiles = _a.outputFiles; - if (!emitSkipped) { - var projectRootPath = this.project.getProjectRootPath(); - for (var _i = 0, outputFiles_1 = outputFiles; _i < outputFiles_1.length; _i++) { - var outputFile = outputFiles_1[_i]; - var outputFileAbsoluteFileName = ts.getNormalizedAbsolutePath(outputFile.name, projectRootPath ? projectRootPath : ts.getDirectoryPath(scriptInfo.fileName)); - writeFile(outputFileAbsoluteFileName, outputFile.text, outputFile.writeByteOrderMark); - } - } - return !emitSkipped; - }; - return AbstractBuilder; - }()); - var NonModuleBuilder = (function (_super) { - __extends(NonModuleBuilder, _super); - function NonModuleBuilder(project) { - _super.call(this, project, BuilderFileInfo); - this.project = project; - } - NonModuleBuilder.prototype.onProjectUpdateGraph = function () { - }; - NonModuleBuilder.prototype.getFilesAffectedBy = function (scriptInfo) { - var info = this.getOrCreateFileInfo(scriptInfo.path); - var singleFileResult = scriptInfo.hasMixedContent ? [] : [scriptInfo.fileName]; - if (info.updateShapeSignature()) { - var options = this.project.getCompilerOptions(); - if (options && (options.out || options.outFile)) { - return singleFileResult; - } - return this.project.getAllEmittableFiles(); - } - return singleFileResult; - }; - return NonModuleBuilder; - }(AbstractBuilder)); - var ModuleBuilderFileInfo = (function (_super) { - __extends(ModuleBuilderFileInfo, _super); - function ModuleBuilderFileInfo() { - _super.apply(this, arguments); - this.references = []; - this.referencedBy = []; - } - ModuleBuilderFileInfo.compareFileInfos = function (lf, rf) { - var l = lf.scriptInfo.fileName; - var r = rf.scriptInfo.fileName; - return (l < r ? -1 : (l > r ? 1 : 0)); - }; - ; - ModuleBuilderFileInfo.addToReferenceList = function (array, fileInfo) { - if (array.length === 0) { - array.push(fileInfo); - return; - } - var insertIndex = ts.binarySearch(array, fileInfo, ModuleBuilderFileInfo.compareFileInfos); - if (insertIndex < 0) { - array.splice(~insertIndex, 0, fileInfo); - } - }; - ModuleBuilderFileInfo.removeFromReferenceList = function (array, fileInfo) { - if (!array || array.length === 0) { - return; - } - if (array[0] === fileInfo) { - array.splice(0, 1); - return; - } - var removeIndex = ts.binarySearch(array, fileInfo, ModuleBuilderFileInfo.compareFileInfos); - if (removeIndex >= 0) { - array.splice(removeIndex, 1); - } - }; - ModuleBuilderFileInfo.prototype.addReferencedBy = function (fileInfo) { - ModuleBuilderFileInfo.addToReferenceList(this.referencedBy, fileInfo); - }; - ModuleBuilderFileInfo.prototype.removeReferencedBy = function (fileInfo) { - ModuleBuilderFileInfo.removeFromReferenceList(this.referencedBy, fileInfo); - }; - ModuleBuilderFileInfo.prototype.removeFileReferences = function () { - for (var _i = 0, _a = this.references; _i < _a.length; _i++) { - var reference = _a[_i]; - reference.removeReferencedBy(this); - } - this.references = []; - }; - return ModuleBuilderFileInfo; - }(BuilderFileInfo)); - var ModuleBuilder = (function (_super) { - __extends(ModuleBuilder, _super); - function ModuleBuilder(project) { - _super.call(this, project, ModuleBuilderFileInfo); - this.project = project; - } - ModuleBuilder.prototype.getReferencedFileInfos = function (fileInfo) { - var _this = this; - if (!fileInfo.isExternalModuleOrHasOnlyAmbientExternalModules()) { - return []; - } - var referencedFilePaths = this.project.getReferencedFiles(fileInfo.scriptInfo.path); - if (referencedFilePaths.length > 0) { - return ts.map(referencedFilePaths, function (f) { return _this.getOrCreateFileInfo(f); }).sort(ModuleBuilderFileInfo.compareFileInfos); - } - return []; - }; - ModuleBuilder.prototype.onProjectUpdateGraph = function () { - this.ensureProjectDependencyGraphUpToDate(); - }; - ModuleBuilder.prototype.ensureProjectDependencyGraphUpToDate = function () { - var _this = this; - if (!this.projectVersionForDependencyGraph || this.project.getProjectVersion() !== this.projectVersionForDependencyGraph) { - var currentScriptInfos = this.project.getScriptInfos(); - for (var _i = 0, currentScriptInfos_1 = currentScriptInfos; _i < currentScriptInfos_1.length; _i++) { - var scriptInfo = currentScriptInfos_1[_i]; - var fileInfo = this.getOrCreateFileInfo(scriptInfo.path); - this.updateFileReferences(fileInfo); - } - this.forEachFileInfo(function (fileInfo) { - if (!_this.project.containsScriptInfo(fileInfo.scriptInfo)) { - fileInfo.removeFileReferences(); - _this.removeFileInfo(fileInfo.scriptInfo.path); - } - }); - this.projectVersionForDependencyGraph = this.project.getProjectVersion(); - } - }; - ModuleBuilder.prototype.updateFileReferences = function (fileInfo) { - if (fileInfo.scriptVersionForReferences === fileInfo.scriptInfo.getLatestVersion()) { - return; - } - var newReferences = this.getReferencedFileInfos(fileInfo); - var oldReferences = fileInfo.references; - var oldIndex = 0; - var newIndex = 0; - while (oldIndex < oldReferences.length && newIndex < newReferences.length) { - var oldReference = oldReferences[oldIndex]; - var newReference = newReferences[newIndex]; - var compare = ModuleBuilderFileInfo.compareFileInfos(oldReference, newReference); - if (compare < 0) { - oldReference.removeReferencedBy(fileInfo); - oldIndex++; - } - else if (compare > 0) { - newReference.addReferencedBy(fileInfo); - newIndex++; - } - else { - oldIndex++; - newIndex++; - } - } - for (var i = oldIndex; i < oldReferences.length; i++) { - oldReferences[i].removeReferencedBy(fileInfo); - } - for (var i = newIndex; i < newReferences.length; i++) { - newReferences[i].addReferencedBy(fileInfo); - } - fileInfo.references = newReferences; - fileInfo.scriptVersionForReferences = fileInfo.scriptInfo.getLatestVersion(); - }; - ModuleBuilder.prototype.getFilesAffectedBy = function (scriptInfo) { - this.ensureProjectDependencyGraphUpToDate(); - var singleFileResult = scriptInfo.hasMixedContent ? [] : [scriptInfo.fileName]; - var fileInfo = this.getFileInfo(scriptInfo.path); - if (!fileInfo || !fileInfo.updateShapeSignature()) { - return singleFileResult; - } - if (!fileInfo.isExternalModuleOrHasOnlyAmbientExternalModules()) { - return this.project.getAllEmittableFiles(); - } - var options = this.project.getCompilerOptions(); - if (options && (options.isolatedModules || options.out || options.outFile)) { - return singleFileResult; - } - var queue = fileInfo.referencedBy.slice(0); - var fileNameSet = ts.createMap(); - fileNameSet[scriptInfo.fileName] = scriptInfo; - while (queue.length > 0) { - var processingFileInfo = queue.pop(); - if (processingFileInfo.updateShapeSignature() && processingFileInfo.referencedBy.length > 0) { - for (var _i = 0, _a = processingFileInfo.referencedBy; _i < _a.length; _i++) { - var potentialFileInfo = _a[_i]; - if (!fileNameSet[potentialFileInfo.scriptInfo.fileName]) { - queue.push(potentialFileInfo); - } - } - } - fileNameSet[processingFileInfo.scriptInfo.fileName] = processingFileInfo.scriptInfo; - } - var result = []; - for (var fileName in fileNameSet) { - if (shouldEmitFile(fileNameSet[fileName])) { - result.push(fileName); - } - } - return result; - }; - return ModuleBuilder; - }(AbstractBuilder)); - function createBuilder(project) { - var moduleKind = project.getCompilerOptions().module; - switch (moduleKind) { - case ts.ModuleKind.None: - return new NonModuleBuilder(project); - default: - return new ModuleBuilder(project); - } - } - server.createBuilder = createBuilder; - })(server = ts.server || (ts.server = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - var server; - (function (server) { - (function (ProjectKind) { - ProjectKind[ProjectKind["Inferred"] = 0] = "Inferred"; - ProjectKind[ProjectKind["Configured"] = 1] = "Configured"; - ProjectKind[ProjectKind["External"] = 2] = "External"; - })(server.ProjectKind || (server.ProjectKind = {})); - var ProjectKind = server.ProjectKind; - function remove(items, item) { - var index = items.indexOf(item); - if (index >= 0) { - items.splice(index, 1); - } - } - function isJsOrDtsFile(info) { - return info.scriptKind === 1 || info.scriptKind == 2 || ts.fileExtensionIs(info.fileName, ".d.ts"); - } - function allRootFilesAreJsOrDts(project) { - return project.getRootScriptInfos().every(isJsOrDtsFile); - } - server.allRootFilesAreJsOrDts = allRootFilesAreJsOrDts; - function allFilesAreJsOrDts(project) { - return project.getScriptInfos().every(isJsOrDtsFile); - } - server.allFilesAreJsOrDts = allFilesAreJsOrDts; - var Project = (function () { - function Project(projectKind, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) { - this.projectKind = projectKind; - this.projectService = projectService; - this.documentRegistry = documentRegistry; - this.languageServiceEnabled = languageServiceEnabled; - this.compilerOptions = compilerOptions; - this.compileOnSaveEnabled = compileOnSaveEnabled; - this.rootFiles = []; - this.rootFilesMap = ts.createFileMap(); - this.lastReportedVersion = 0; - this.projectStructureVersion = 0; - this.projectStateVersion = 0; - this.typesVersion = 0; - if (!this.compilerOptions) { - this.compilerOptions = ts.getDefaultCompilerOptions(); - this.compilerOptions.allowNonTsExtensions = true; - this.compilerOptions.allowJs = true; - } - else if (hasExplicitListOfFiles) { - this.compilerOptions.allowNonTsExtensions = true; - } - if (languageServiceEnabled) { - this.enableLanguageService(); - } - else { - this.disableLanguageService(); - } - this.builder = server.createBuilder(this); - this.markAsDirty(); - } - Project.prototype.isJsOnlyProject = function () { - this.updateGraph(); - return allFilesAreJsOrDts(this); - }; - Project.prototype.getProjectErrors = function () { - return this.projectErrors; - }; - Project.prototype.getLanguageService = function (ensureSynchronized) { - if (ensureSynchronized === void 0) { ensureSynchronized = true; } - if (ensureSynchronized) { - this.updateGraph(); - } - return this.languageService; - }; - Project.prototype.getCompileOnSaveAffectedFileList = function (scriptInfo) { - if (!this.languageServiceEnabled) { - return []; - } - this.updateGraph(); - return this.builder.getFilesAffectedBy(scriptInfo); - }; - Project.prototype.getProjectVersion = function () { - return this.projectStateVersion.toString(); - }; - Project.prototype.enableLanguageService = function () { - var lsHost = new server.LSHost(this.projectService.host, this, this.projectService.cancellationToken); - lsHost.setCompilationSettings(this.compilerOptions); - this.languageService = ts.createLanguageService(lsHost, this.documentRegistry); - this.lsHost = lsHost; - this.languageServiceEnabled = true; - }; - Project.prototype.disableLanguageService = function () { - this.languageService = server.nullLanguageService; - this.lsHost = server.nullLanguageServiceHost; - this.languageServiceEnabled = false; - }; - Project.prototype.getSourceFile = function (path) { - if (!this.program) { - return undefined; - } - return this.program.getSourceFileByPath(path); - }; - Project.prototype.updateTypes = function () { - this.typesVersion++; - this.markAsDirty(); - this.updateGraph(); - }; - Project.prototype.close = function () { - if (this.program) { - for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) { - var f = _a[_i]; - var info = this.projectService.getScriptInfo(f.fileName); - info.detachFromProject(this); - } - } - else { - for (var _b = 0, _c = this.rootFiles; _b < _c.length; _b++) { - var root = _c[_b]; - root.detachFromProject(this); - } - } - this.rootFiles = undefined; - this.rootFilesMap = undefined; - this.program = undefined; - this.languageService.dispose(); - }; - Project.prototype.getCompilerOptions = function () { - return this.compilerOptions; - }; - Project.prototype.hasRoots = function () { - return this.rootFiles && this.rootFiles.length > 0; - }; - Project.prototype.getRootFiles = function () { - return this.rootFiles && this.rootFiles.map(function (info) { return info.fileName; }); - }; - Project.prototype.getRootFilesLSHost = function () { - var result = []; - if (this.rootFiles) { - for (var _i = 0, _a = this.rootFiles; _i < _a.length; _i++) { - var f = _a[_i]; - result.push(f.fileName); - } - if (this.typingFiles) { - for (var _b = 0, _c = this.typingFiles; _b < _c.length; _b++) { - var f = _c[_b]; - result.push(f); - } - } - } - return result; - }; - Project.prototype.getRootScriptInfos = function () { - return this.rootFiles; - }; - Project.prototype.getScriptInfos = function () { - var _this = this; - return ts.map(this.program.getSourceFiles(), function (sourceFile) { return _this.getScriptInfoLSHost(sourceFile.path); }); - }; - Project.prototype.getFileEmitOutput = function (info, emitOnlyDtsFiles) { - if (!this.languageServiceEnabled) { - return undefined; - } - return this.getLanguageService().getEmitOutput(info.fileName, emitOnlyDtsFiles); - }; - Project.prototype.getFileNames = function () { - if (!this.program) { - return []; - } - if (!this.languageServiceEnabled) { - var rootFiles = this.getRootFiles(); - if (this.compilerOptions) { - var defaultLibrary = ts.getDefaultLibFilePath(this.compilerOptions); - if (defaultLibrary) { - (rootFiles || (rootFiles = [])).push(server.asNormalizedPath(defaultLibrary)); - } - } - return rootFiles; - } - var sourceFiles = this.program.getSourceFiles(); - return sourceFiles.map(function (sourceFile) { return server.asNormalizedPath(sourceFile.fileName); }); - }; - Project.prototype.getAllEmittableFiles = function () { - if (!this.languageServiceEnabled) { - return []; - } - var defaultLibraryFileName = ts.getDefaultLibFileName(this.compilerOptions); - var infos = this.getScriptInfos(); - var result = []; - for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { - var info = infos_1[_i]; - if (ts.getBaseFileName(info.fileName) !== defaultLibraryFileName && server.shouldEmitFile(info)) { - result.push(info.fileName); - } - } - return result; - }; - Project.prototype.containsScriptInfo = function (info) { - return this.isRoot(info) || (this.program && this.program.getSourceFileByPath(info.path) !== undefined); - }; - Project.prototype.containsFile = function (filename, requireOpen) { - var info = this.projectService.getScriptInfoForNormalizedPath(filename); - if (info && (info.isOpen || !requireOpen)) { - return this.containsScriptInfo(info); - } - }; - Project.prototype.isRoot = function (info) { - return this.rootFilesMap && this.rootFilesMap.contains(info.path); - }; - Project.prototype.addRoot = function (info) { - if (!this.isRoot(info)) { - this.rootFiles.push(info); - this.rootFilesMap.set(info.path, info); - info.attachToProject(this); - this.markAsDirty(); - } - }; - Project.prototype.removeFile = function (info, detachFromProject) { - if (detachFromProject === void 0) { detachFromProject = true; } - this.removeRootFileIfNecessary(info); - this.lsHost.notifyFileRemoved(info); - if (detachFromProject) { - info.detachFromProject(this); - } - this.markAsDirty(); - }; - Project.prototype.markAsDirty = function () { - this.projectStateVersion++; - }; - Project.prototype.updateGraph = function () { - if (!this.languageServiceEnabled) { - return true; - } - var hasChanges = this.updateGraphWorker(); - var cachedTypings = this.projectService.typingsCache.getTypingsForProject(this, hasChanges); - if (this.setTypings(cachedTypings)) { - hasChanges = this.updateGraphWorker() || hasChanges; - } - if (hasChanges) { - this.projectStructureVersion++; - } - return !hasChanges; - }; - Project.prototype.setTypings = function (typings) { - if (ts.arrayIsEqualTo(this.typingFiles, typings)) { - return false; - } - this.typingFiles = typings; - this.markAsDirty(); - return true; - }; - Project.prototype.updateGraphWorker = function () { - var oldProgram = this.program; - this.program = this.languageService.getProgram(); - var hasChanges = false; - if (!oldProgram || (this.program !== oldProgram && !oldProgram.structureIsReused)) { - hasChanges = true; - if (oldProgram) { - for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { - var f = _a[_i]; - if (this.program.getSourceFileByPath(f.path)) { - continue; - } - var scriptInfoToDetach = this.projectService.getScriptInfo(f.fileName); - if (scriptInfoToDetach) { - scriptInfoToDetach.detachFromProject(this); - } - } - } - } - this.builder.onProjectUpdateGraph(); - return hasChanges; - }; - Project.prototype.getScriptInfoLSHost = function (fileName) { - var scriptInfo = this.projectService.getOrCreateScriptInfo(fileName, false); - if (scriptInfo) { - scriptInfo.attachToProject(this); - } - return scriptInfo; - }; - Project.prototype.getScriptInfoForNormalizedPath = function (fileName) { - var scriptInfo = this.projectService.getOrCreateScriptInfoForNormalizedPath(fileName, false); - if (scriptInfo && !scriptInfo.isAttached(this)) { - return server.Errors.ThrowProjectDoesNotContainDocument(fileName, this); - } - return scriptInfo; - }; - Project.prototype.getScriptInfo = function (uncheckedFileName) { - return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); - }; - Project.prototype.filesToString = function () { - if (!this.program) { - return ""; - } + var spaceCache = []; + function generateSpaces(n) { + if (!spaceCache[n]) { var strBuilder = ""; - for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) { - var file = _a[_i]; - strBuilder += file.fileName + "\n"; + for (var i = 0; i < n; i++) { + strBuilder += " "; } - return strBuilder; - }; - Project.prototype.setCompilerOptions = function (compilerOptions) { - if (compilerOptions) { - if (this.projectKind === ProjectKind.Inferred) { - compilerOptions.allowJs = true; - } - compilerOptions.allowNonTsExtensions = true; - this.compilerOptions = compilerOptions; - this.lsHost.setCompilationSettings(compilerOptions); - this.markAsDirty(); - } - }; - Project.prototype.reloadScript = function (filename) { - var script = this.projectService.getScriptInfoForNormalizedPath(filename); - if (script) { - ts.Debug.assert(script.isAttached(this)); - script.reloadFromFile(); - return true; - } - return false; - }; - Project.prototype.getChangesSinceVersion = function (lastKnownVersion) { - this.updateGraph(); - var info = { - projectName: this.getProjectName(), - version: this.projectStructureVersion, - isInferred: this.projectKind === ProjectKind.Inferred, - options: this.getCompilerOptions() - }; - if (this.lastReportedFileNames && lastKnownVersion === this.lastReportedVersion) { - if (this.projectStructureVersion == this.lastReportedVersion) { - return { info: info, projectErrors: this.projectErrors }; - } - var lastReportedFileNames = this.lastReportedFileNames; - var currentFiles = ts.arrayToMap(this.getFileNames(), function (x) { return x; }); - var added = []; - var removed = []; - for (var id in currentFiles) { - if (!ts.hasProperty(lastReportedFileNames, id)) { - added.push(id); - } - } - for (var id in lastReportedFileNames) { - if (!ts.hasProperty(currentFiles, id)) { - removed.push(id); - } - } - this.lastReportedFileNames = currentFiles; - this.lastReportedVersion = this.projectStructureVersion; - return { info: info, changes: { added: added, removed: removed }, projectErrors: this.projectErrors }; - } - else { - var projectFileNames = this.getFileNames(); - this.lastReportedFileNames = ts.arrayToMap(projectFileNames, function (x) { return x; }); - this.lastReportedVersion = this.projectStructureVersion; - return { info: info, files: projectFileNames, projectErrors: this.projectErrors }; - } - }; - Project.prototype.getReferencedFiles = function (path) { - var _this = this; - if (!this.languageServiceEnabled) { - return []; - } - var sourceFile = this.getSourceFile(path); - if (!sourceFile) { - return []; - } - var referencedFiles = ts.createMap(); - if (sourceFile.imports && sourceFile.imports.length > 0) { - var checker = this.program.getTypeChecker(); - for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var importName = _a[_i]; - var symbol = checker.getSymbolAtLocation(importName); - if (symbol && symbol.declarations && symbol.declarations[0]) { - var declarationSourceFile = symbol.declarations[0].getSourceFile(); - if (declarationSourceFile) { - referencedFiles[declarationSourceFile.path] = true; - } - } - } - } - var currentDirectory = ts.getDirectoryPath(path); - var getCanonicalFileName = ts.createGetCanonicalFileName(this.projectService.host.useCaseSensitiveFileNames); - if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { - for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { - var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, currentDirectory, getCanonicalFileName); - referencedFiles[referencedPath] = true; - } - } - if (sourceFile.resolvedTypeReferenceDirectiveNames) { - for (var typeName in sourceFile.resolvedTypeReferenceDirectiveNames) { - var resolvedTypeReferenceDirective = sourceFile.resolvedTypeReferenceDirectiveNames[typeName]; - if (!resolvedTypeReferenceDirective) { - continue; - } - var fileName = resolvedTypeReferenceDirective.resolvedFileName; - var typeFilePath = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - referencedFiles[typeFilePath] = true; - } - } - var allFileNames = ts.map(Object.keys(referencedFiles), function (key) { return key; }); - return ts.filter(allFileNames, function (file) { return _this.projectService.host.fileExists(file); }); - }; - Project.prototype.removeRootFileIfNecessary = function (info) { - if (this.isRoot(info)) { - remove(this.rootFiles, info); - this.rootFilesMap.remove(info.path); - } - }; - return Project; - }()); - server.Project = Project; - var InferredProject = (function (_super) { - __extends(InferredProject, _super); - function InferredProject(projectService, documentRegistry, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) { - _super.call(this, ProjectKind.Inferred, projectService, documentRegistry, undefined, languageServiceEnabled, compilerOptions, compileOnSaveEnabled); - this.compileOnSaveEnabled = compileOnSaveEnabled; - this.directoriesWatchedForTsconfig = []; - this.inferredProjectName = server.makeInferredProjectName(InferredProject.NextId); - InferredProject.NextId++; + spaceCache[n] = strBuilder; } - InferredProject.prototype.getProjectName = function () { - return this.inferredProjectName; - }; - InferredProject.prototype.getProjectRootPath = function () { - if (this.projectService.useSingleInferredProject) { - return undefined; - } - var rootFiles = this.getRootFiles(); - return ts.getDirectoryPath(rootFiles[0]); - }; - InferredProject.prototype.close = function () { - _super.prototype.close.call(this); - for (var _i = 0, _a = this.directoriesWatchedForTsconfig; _i < _a.length; _i++) { - var directory = _a[_i]; - this.projectService.stopWatchingDirectory(directory); - } - }; - InferredProject.prototype.getTypingOptions = function () { - return { - enableAutoDiscovery: allRootFilesAreJsOrDts(this), - include: [], - exclude: [] - }; - }; - InferredProject.NextId = 1; - return InferredProject; - }(Project)); - server.InferredProject = InferredProject; - var ConfiguredProject = (function (_super) { - __extends(ConfiguredProject, _super); - function ConfiguredProject(configFileName, projectService, documentRegistry, hasExplicitListOfFiles, compilerOptions, wildcardDirectories, languageServiceEnabled, compileOnSaveEnabled) { - _super.call(this, ProjectKind.Configured, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled); - this.configFileName = configFileName; - this.wildcardDirectories = wildcardDirectories; - this.compileOnSaveEnabled = compileOnSaveEnabled; - this.openRefCount = 0; - } - ConfiguredProject.prototype.getProjectRootPath = function () { - return ts.getDirectoryPath(this.configFileName); - }; - ConfiguredProject.prototype.setProjectErrors = function (projectErrors) { - this.projectErrors = projectErrors; - }; - ConfiguredProject.prototype.setTypingOptions = function (newTypingOptions) { - this.typingOptions = newTypingOptions; - }; - ConfiguredProject.prototype.getTypingOptions = function () { - return this.typingOptions; - }; - ConfiguredProject.prototype.getProjectName = function () { - return this.configFileName; - }; - ConfiguredProject.prototype.watchConfigFile = function (callback) { - var _this = this; - this.projectFileWatcher = this.projectService.host.watchFile(this.configFileName, function (_) { return callback(_this); }); - }; - ConfiguredProject.prototype.watchTypeRoots = function (callback) { - var _this = this; - var roots = this.getEffectiveTypeRoots(); - var watchers = []; - for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { - var root = roots_1[_i]; - this.projectService.logger.info("Add type root watcher for: " + root); - watchers.push(this.projectService.host.watchDirectory(root, function (path) { return callback(_this, path); }, false)); - } - this.typeRootsWatchers = watchers; - }; - ConfiguredProject.prototype.watchConfigDirectory = function (callback) { - var _this = this; - if (this.directoryWatcher) { - return; - } - var directoryToWatch = ts.getDirectoryPath(this.configFileName); - this.projectService.logger.info("Add recursive watcher for: " + directoryToWatch); - this.directoryWatcher = this.projectService.host.watchDirectory(directoryToWatch, function (path) { return callback(_this, path); }, true); - }; - ConfiguredProject.prototype.watchWildcards = function (callback) { - var _this = this; - if (!this.wildcardDirectories) { - return; - } - var configDirectoryPath = ts.getDirectoryPath(this.configFileName); - this.directoriesWatchedForWildcards = ts.reduceProperties(this.wildcardDirectories, function (watchers, flag, directory) { - if (ts.comparePaths(configDirectoryPath, directory, ".", !_this.projectService.host.useCaseSensitiveFileNames) !== 0) { - var recursive = (flag & 1) !== 0; - _this.projectService.logger.info("Add " + (recursive ? "recursive " : "") + "watcher for: " + directory); - watchers[directory] = _this.projectService.host.watchDirectory(directory, function (path) { return callback(_this, path); }, recursive); - } - return watchers; - }, {}); - }; - ConfiguredProject.prototype.stopWatchingDirectory = function () { - if (this.directoryWatcher) { - this.directoryWatcher.close(); - this.directoryWatcher = undefined; - } - }; - ConfiguredProject.prototype.close = function () { - _super.prototype.close.call(this); - if (this.projectFileWatcher) { - this.projectFileWatcher.close(); - } - if (this.typeRootsWatchers) { - for (var _i = 0, _a = this.typeRootsWatchers; _i < _a.length; _i++) { - var watcher = _a[_i]; - watcher.close(); - } - this.typeRootsWatchers = undefined; - } - for (var id in this.directoriesWatchedForWildcards) { - this.directoriesWatchedForWildcards[id].close(); - } - this.directoriesWatchedForWildcards = undefined; - this.stopWatchingDirectory(); - }; - ConfiguredProject.prototype.addOpenRef = function () { - this.openRefCount++; - }; - ConfiguredProject.prototype.deleteOpenRef = function () { - this.openRefCount--; - return this.openRefCount; - }; - ConfiguredProject.prototype.getEffectiveTypeRoots = function () { - return ts.getEffectiveTypeRoots(this.getCompilerOptions(), this.projectService.host) || []; - }; - return ConfiguredProject; - }(Project)); - server.ConfiguredProject = ConfiguredProject; - var ExternalProject = (function (_super) { - __extends(ExternalProject, _super); - function ExternalProject(externalProjectName, projectService, documentRegistry, compilerOptions, languageServiceEnabled, compileOnSaveEnabled, projectFilePath) { - _super.call(this, ProjectKind.External, projectService, documentRegistry, true, languageServiceEnabled, compilerOptions, compileOnSaveEnabled); - this.externalProjectName = externalProjectName; - this.compileOnSaveEnabled = compileOnSaveEnabled; - this.projectFilePath = projectFilePath; - } - ExternalProject.prototype.getProjectRootPath = function () { - if (this.projectFilePath) { - return ts.getDirectoryPath(this.projectFilePath); - } - return ts.getDirectoryPath(ts.normalizeSlashes(this.externalProjectName)); - }; - ExternalProject.prototype.getTypingOptions = function () { - return this.typingOptions; - }; - ExternalProject.prototype.setProjectErrors = function (projectErrors) { - this.projectErrors = projectErrors; - }; - ExternalProject.prototype.setTypingOptions = function (newTypingOptions) { - if (!newTypingOptions) { - newTypingOptions = { - enableAutoDiscovery: allRootFilesAreJsOrDts(this), - include: [], - exclude: [] - }; - } - else { - if (newTypingOptions.enableAutoDiscovery === undefined) { - newTypingOptions.enableAutoDiscovery = allRootFilesAreJsOrDts(this); - } - if (!newTypingOptions.include) { - newTypingOptions.include = []; - } - if (!newTypingOptions.exclude) { - newTypingOptions.exclude = []; - } - } - this.typingOptions = newTypingOptions; - }; - ExternalProject.prototype.getProjectName = function () { - return this.externalProjectName; - }; - return ExternalProject; - }(Project)); - server.ExternalProject = ExternalProject; - })(server = ts.server || (ts.server = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - var server; - (function (server) { - server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; - function combineProjectOutput(projects, action, comparer, areEqual) { - var result = projects.reduce(function (previous, current) { return ts.concatenate(previous, action(current)); }, []).sort(comparer); - return projects.length > 1 ? ts.deduplicate(result, areEqual) : result; + return spaceCache[n]; } - server.combineProjectOutput = combineProjectOutput; - var fileNamePropertyReader = { - getFileName: function (x) { return x; }, - getScriptKind: function (_) { return undefined; }, - hasMixedContent: function (_) { return false; } - }; - var externalFilePropertyReader = { - getFileName: function (x) { return x.fileName; }, - getScriptKind: function (x) { return x.scriptKind; }, - hasMixedContent: function (x) { return x.hasMixedContent; } - }; - function findProjectByName(projectName, projects) { - for (var _i = 0, projects_1 = projects; _i < projects_1.length; _i++) { - var proj = projects_1[_i]; - if (proj.getProjectName() === projectName) { - return proj; + server.generateSpaces = generateSpaces; + function generateIndentString(n, editorOptions) { + if (editorOptions.ConvertTabsToSpaces) { + return generateSpaces(n); + } + else { + var result = ""; + for (var i = 0; i < Math.floor(n / editorOptions.TabSize); i++) { + result += "\t"; } + for (var i = 0; i < n % editorOptions.TabSize; i++) { + result += " "; + } + return result; } } - function createFileNotFoundDiagnostic(fileName) { - return ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, fileName); - } - function isRootFileInInferredProject(info) { - if (info.containingProjects.length === 0) { - return false; - } - return info.containingProjects[0].projectKind === server.ProjectKind.Inferred && info.containingProjects[0].isRoot(info); - } - var DirectoryWatchers = (function () { - function DirectoryWatchers(projectService) { - this.projectService = projectService; - this.directoryWatchersForTsconfig = ts.createMap(); - this.directoryWatchersRefCount = ts.createMap(); - } - DirectoryWatchers.prototype.stopWatchingDirectory = function (directory) { - this.directoryWatchersRefCount[directory]--; - if (this.directoryWatchersRefCount[directory] === 0) { - this.projectService.logger.info("Close directory watcher for: " + directory); - this.directoryWatchersForTsconfig[directory].close(); - delete this.directoryWatchersForTsconfig[directory]; - } - }; - DirectoryWatchers.prototype.startWatchingContainingDirectoriesForFile = function (fileName, project, callback) { - var currentPath = ts.getDirectoryPath(fileName); - var parentPath = ts.getDirectoryPath(currentPath); - while (currentPath != parentPath) { - if (!this.directoryWatchersForTsconfig[currentPath]) { - this.projectService.logger.info("Add watcher for: " + currentPath); - this.directoryWatchersForTsconfig[currentPath] = this.projectService.host.watchDirectory(currentPath, callback); - this.directoryWatchersRefCount[currentPath] = 1; - } - else { - this.directoryWatchersRefCount[currentPath] += 1; - } - project.directoriesWatchedForTsconfig.push(currentPath); - currentPath = parentPath; - parentPath = ts.getDirectoryPath(parentPath); - } - }; - return DirectoryWatchers; - }()); - var ProjectService = (function () { - function ProjectService(host, logger, cancellationToken, useSingleInferredProject, typingsInstaller, eventHandler) { - if (typingsInstaller === void 0) { typingsInstaller = server.nullTypingsInstaller; } - this.host = host; - this.logger = logger; - this.cancellationToken = cancellationToken; - this.useSingleInferredProject = useSingleInferredProject; - this.typingsInstaller = typingsInstaller; - this.eventHandler = eventHandler; - this.filenameToScriptInfo = ts.createFileMap(); - this.externalProjectToConfiguredProjectMap = ts.createMap(); - this.externalProjects = []; - this.inferredProjects = []; - this.configuredProjects = []; - this.openFiles = []; - this.toCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - this.directoryWatchers = new DirectoryWatchers(this); - this.throttledOperations = new server.ThrottledOperations(host); - this.typingsInstaller.attach(this); - this.typingsCache = new server.TypingsCache(this.typingsInstaller); - this.hostConfiguration = { - formatCodeOptions: server.getDefaultFormatCodeSettings(this.host), - hostInfo: "Unknown host" - }; - this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames, host.getCurrentDirectory()); - } - ProjectService.prototype.getChangedFiles_TestOnly = function () { - return this.changedFiles; - }; - ProjectService.prototype.ensureInferredProjectsUpToDate_TestOnly = function () { - this.ensureInferredProjectsUpToDate(); - }; - ProjectService.prototype.updateTypingsForProject = function (response) { - var project = this.findProject(response.projectName); - if (!project) { - return; - } - switch (response.kind) { - case "set": - this.typingsCache.updateTypingsForProject(response.projectName, response.compilerOptions, response.typingOptions, response.typings); - project.updateGraph(); - break; - case "invalidate": - this.typingsCache.invalidateCachedTypingsForProject(project); - break; - } - }; - ProjectService.prototype.setCompilerOptionsForInferredProjects = function (projectCompilerOptions) { - this.compilerOptionsForInferredProjects = projectCompilerOptions; - this.compileOnSaveForInferredProjects = projectCompilerOptions.compileOnSave; - for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { - var proj = _a[_i]; - proj.setCompilerOptions(projectCompilerOptions); - proj.compileOnSaveEnabled = projectCompilerOptions.compileOnSave; - } - this.updateProjectGraphs(this.inferredProjects); - }; - ProjectService.prototype.stopWatchingDirectory = function (directory) { - this.directoryWatchers.stopWatchingDirectory(directory); - }; - ProjectService.prototype.findProject = function (projectName) { - if (projectName === undefined) { - return undefined; - } - if (server.isInferredProjectName(projectName)) { - this.ensureInferredProjectsUpToDate(); - return findProjectByName(projectName, this.inferredProjects); - } - return this.findExternalProjectByProjectName(projectName) || this.findConfiguredProjectByProjectName(server.toNormalizedPath(projectName)); - }; - ProjectService.prototype.getDefaultProjectForFile = function (fileName, refreshInferredProjects) { - if (refreshInferredProjects) { - this.ensureInferredProjectsUpToDate(); - } - var scriptInfo = this.getScriptInfoForNormalizedPath(fileName); - return scriptInfo && scriptInfo.getDefaultProject(); - }; - ProjectService.prototype.ensureInferredProjectsUpToDate = function () { - if (this.changedFiles) { - var projectsToUpdate = void 0; - if (this.changedFiles.length === 1) { - projectsToUpdate = this.changedFiles[0].containingProjects; - } - else { - projectsToUpdate = []; - for (var _i = 0, _a = this.changedFiles; _i < _a.length; _i++) { - var f = _a[_i]; - projectsToUpdate = projectsToUpdate.concat(f.containingProjects); - } - } - this.updateProjectGraphs(projectsToUpdate); - this.changedFiles = undefined; - } - }; - ProjectService.prototype.findContainingExternalProject = function (fileName) { - for (var _i = 0, _a = this.externalProjects; _i < _a.length; _i++) { - var proj = _a[_i]; - if (proj.containsFile(fileName)) { - return proj; - } - } - return undefined; - }; - ProjectService.prototype.getFormatCodeOptions = function (file) { - var formatCodeSettings; - if (file) { - var info = this.getScriptInfoForNormalizedPath(file); - if (info) { - formatCodeSettings = info.getFormatCodeSettings(); - } - } - return formatCodeSettings || this.hostConfiguration.formatCodeOptions; - }; - ProjectService.prototype.updateProjectGraphs = function (projects) { - var shouldRefreshInferredProjects = false; - for (var _i = 0, projects_2 = projects; _i < projects_2.length; _i++) { - var p = projects_2[_i]; - if (!p.updateGraph()) { - shouldRefreshInferredProjects = true; - } - } - if (shouldRefreshInferredProjects) { - this.refreshInferredProjects(); - } - }; - ProjectService.prototype.onSourceFileChanged = function (fileName) { - var info = this.getScriptInfoForNormalizedPath(fileName); - if (!info) { - this.logger.info("Error: got watch notification for unknown file: " + fileName); - return; - } - if (!this.host.fileExists(fileName)) { - this.handleDeletedFile(info); - } - else { - if (info && (!info.isOpen)) { - info.reloadFromFile(); - this.updateProjectGraphs(info.containingProjects); - } - } - }; - ProjectService.prototype.handleDeletedFile = function (info) { - this.logger.info(info.fileName + " deleted"); - info.stopWatcher(); - if (!info.isOpen) { - this.filenameToScriptInfo.remove(info.path); - var containingProjects = info.containingProjects.slice(); - info.detachAllProjects(); - this.updateProjectGraphs(containingProjects); - if (!this.eventHandler) { - return; - } - for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { - var openFile = _a[_i]; - this.eventHandler({ eventName: "context", data: { project: openFile.getDefaultProject(), fileName: openFile.fileName } }); - } - } - this.printProjects(); - }; - ProjectService.prototype.onTypeRootFileChanged = function (project, fileName) { - var _this = this; - this.logger.info("Type root file " + fileName + " changed"); - this.throttledOperations.schedule(project.configFileName + " * type root", 250, function () { - project.updateTypes(); - _this.updateConfiguredProject(project); - _this.refreshInferredProjects(); - }); - }; - ProjectService.prototype.onSourceFileInDirectoryChangedForConfiguredProject = function (project, fileName) { - var _this = this; - if (fileName && !ts.isSupportedSourceFileName(fileName, project.getCompilerOptions())) { - return; - } - this.logger.info("Detected source file changes: " + fileName); - this.throttledOperations.schedule(project.configFileName, 250, function () { return _this.handleChangeInSourceFileForConfiguredProject(project); }); - }; - ProjectService.prototype.handleChangeInSourceFileForConfiguredProject = function (project) { - var _this = this; - var _a = this.convertConfigFileContentToProjectOptions(project.configFileName), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors; - this.reportConfigFileDiagnostics(project.getProjectName(), configFileErrors); - var newRootFiles = projectOptions.files.map((function (f) { return _this.getCanonicalFileName(f); })); - var currentRootFiles = project.getRootFiles().map((function (f) { return _this.getCanonicalFileName(f); })); - if (!ts.arrayIsEqualTo(currentRootFiles.sort(), newRootFiles.sort())) { - this.logger.info("Updating configured project"); - this.updateConfiguredProject(project); - this.refreshInferredProjects(); - } - }; - ProjectService.prototype.onConfigChangedForConfiguredProject = function (project) { - this.logger.info("Config file changed: " + project.configFileName); - this.updateConfiguredProject(project); - this.refreshInferredProjects(); - }; - ProjectService.prototype.onConfigFileAddedForInferredProject = function (fileName) { - if (ts.getBaseFileName(fileName) != "tsconfig.json") { - this.logger.info(fileName + " is not tsconfig.json"); - return; - } - var configFileErrors = this.convertConfigFileContentToProjectOptions(fileName).configFileErrors; - this.reportConfigFileDiagnostics(fileName, configFileErrors); - this.logger.info("Detected newly added tsconfig file: " + fileName); - this.reloadProjects(); - }; - ProjectService.prototype.getCanonicalFileName = function (fileName) { - var name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); - return ts.normalizePath(name); - }; - ProjectService.prototype.removeProject = function (project) { - this.logger.info("remove project: " + project.getRootFiles().toString()); - project.close(); - switch (project.projectKind) { - case server.ProjectKind.External: - server.removeItemFromSet(this.externalProjects, project); - break; - case server.ProjectKind.Configured: - server.removeItemFromSet(this.configuredProjects, project); - break; - case server.ProjectKind.Inferred: - server.removeItemFromSet(this.inferredProjects, project); - break; - } - }; - ProjectService.prototype.assignScriptInfoToInferredProjectIfNecessary = function (info, addToListOfOpenFiles) { - var externalProject = this.findContainingExternalProject(info.fileName); - if (externalProject) { - if (addToListOfOpenFiles) { - this.openFiles.push(info); - } - return; - } - var foundConfiguredProject = false; - for (var _i = 0, _a = info.containingProjects; _i < _a.length; _i++) { - var p = _a[_i]; - if (p.projectKind === server.ProjectKind.Configured) { - foundConfiguredProject = true; - if (addToListOfOpenFiles) { - (p).addOpenRef(); - } - } - } - if (foundConfiguredProject) { - if (addToListOfOpenFiles) { - this.openFiles.push(info); - } - return; - } - if (info.containingProjects.length === 0) { - var inferredProject = this.createInferredProjectWithRootFileIfNecessary(info); - if (!this.useSingleInferredProject) { - for (var _b = 0, _c = this.openFiles; _b < _c.length; _b++) { - var f = _c[_b]; - if (f.containingProjects.length === 0) { - continue; - } - var defaultProject = f.getDefaultProject(); - if (isRootFileInInferredProject(info) && defaultProject !== inferredProject && inferredProject.containsScriptInfo(f)) { - this.removeProject(defaultProject); - f.attachToProject(inferredProject); - } - } - } - } - if (addToListOfOpenFiles) { - this.openFiles.push(info); - } - }; - ProjectService.prototype.closeOpenFile = function (info) { - info.reloadFromFile(); - server.removeItemFromSet(this.openFiles, info); - info.isOpen = false; - var projectsToRemove; - for (var _i = 0, _a = info.containingProjects; _i < _a.length; _i++) { - var p = _a[_i]; - if (p.projectKind === server.ProjectKind.Configured) { - if (p.deleteOpenRef() === 0) { - (projectsToRemove || (projectsToRemove = [])).push(p); - } - } - else if (p.projectKind === server.ProjectKind.Inferred && p.isRoot(info)) { - (projectsToRemove || (projectsToRemove = [])).push(p); - } - } - if (projectsToRemove) { - for (var _b = 0, projectsToRemove_1 = projectsToRemove; _b < projectsToRemove_1.length; _b++) { - var project = projectsToRemove_1[_b]; - this.removeProject(project); - } - var orphanFiles = void 0; - for (var _c = 0, _d = this.openFiles; _c < _d.length; _c++) { - var f = _d[_c]; - if (f.containingProjects.length === 0) { - (orphanFiles || (orphanFiles = [])).push(f); - } - } - if (orphanFiles) { - for (var _e = 0, orphanFiles_1 = orphanFiles; _e < orphanFiles_1.length; _e++) { - var f = orphanFiles_1[_e]; - this.assignScriptInfoToInferredProjectIfNecessary(f, false); - } - } - } - if (info.containingProjects.length === 0) { - this.filenameToScriptInfo.remove(info.path); - } - }; - ProjectService.prototype.openOrUpdateConfiguredProjectForFile = function (fileName) { - var searchPath = ts.getDirectoryPath(fileName); - this.logger.info("Search path: " + searchPath); - var configFileName = this.findConfigFile(server.asNormalizedPath(searchPath)); - if (!configFileName) { - this.logger.info("No config files found."); - return {}; - } - this.logger.info("Config file name: " + configFileName); - var project = this.findConfiguredProjectByProjectName(configFileName); - if (!project) { - var _a = this.openConfigFile(configFileName, fileName), success = _a.success, errors = _a.errors; - if (!success) { - return { configFileName: configFileName, configFileErrors: errors }; - } - this.logger.info("Opened configuration file " + configFileName); - if (errors && errors.length > 0) { - return { configFileName: configFileName, configFileErrors: errors }; - } - } - else { - this.updateConfiguredProject(project); - } - return { configFileName: configFileName }; - }; - ProjectService.prototype.findConfigFile = function (searchPath) { - while (true) { - var tsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "tsconfig.json")); - if (this.host.fileExists(tsconfigFileName)) { - return tsconfigFileName; - } - var jsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "jsconfig.json")); - if (this.host.fileExists(jsconfigFileName)) { - return jsconfigFileName; - } - var parentPath = server.asNormalizedPath(ts.getDirectoryPath(searchPath)); - if (parentPath === searchPath) { - break; - } - searchPath = parentPath; - } - return undefined; - }; - ProjectService.prototype.printProjects = function () { - if (!this.logger.hasLevel(server.LogLevel.verbose)) { - return; - } - this.logger.startGroup(); - var counter = 0; - counter = printProjects(this.logger, this.externalProjects, counter); - counter = printProjects(this.logger, this.configuredProjects, counter); - counter = printProjects(this.logger, this.inferredProjects, counter); - this.logger.info("Open files: "); - for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { - var rootFile = _a[_i]; - this.logger.info(rootFile.fileName); - } - this.logger.endGroup(); - function printProjects(logger, projects, counter) { - for (var _i = 0, projects_3 = projects; _i < projects_3.length; _i++) { - var project = projects_3[_i]; - project.updateGraph(); - logger.info("Project '" + project.getProjectName() + "' (" + server.ProjectKind[project.projectKind] + ") " + counter); - logger.info(project.filesToString()); - logger.info("-----------------------------------------------"); - counter++; - } - return counter; - } - }; - ProjectService.prototype.findConfiguredProjectByProjectName = function (configFileName) { - return findProjectByName(configFileName, this.configuredProjects); - }; - ProjectService.prototype.findExternalProjectByProjectName = function (projectFileName) { - return findProjectByName(projectFileName, this.externalProjects); - }; - ProjectService.prototype.convertConfigFileContentToProjectOptions = function (configFilename) { - configFilename = ts.normalizePath(configFilename); - var configFileContent = this.host.readFile(configFilename); - var errors; - var result = ts.parseConfigFileTextToJson(configFilename, configFileContent); - var config = result.config; - if (result.error) { - var _a = ts.sanitizeConfigFile(configFilename, configFileContent), sanitizedConfig = _a.configJsonObject, diagnostics = _a.diagnostics; - config = sanitizedConfig; - errors = diagnostics.length ? diagnostics : [result.error]; - } - var parsedCommandLine = ts.parseJsonConfigFileContent(config, this.host, ts.getDirectoryPath(configFilename), {}, configFilename); - if (parsedCommandLine.errors.length) { - errors = ts.concatenate(errors, parsedCommandLine.errors); - } - ts.Debug.assert(!!parsedCommandLine.fileNames); - if (parsedCommandLine.fileNames.length === 0) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename)); - return { success: false, configFileErrors: errors }; - } - var projectOptions = { - files: parsedCommandLine.fileNames, - compilerOptions: parsedCommandLine.options, - configHasFilesProperty: config["files"] !== undefined, - wildcardDirectories: ts.createMap(parsedCommandLine.wildcardDirectories), - typingOptions: parsedCommandLine.typingOptions, - compileOnSave: parsedCommandLine.compileOnSave - }; - return { success: true, projectOptions: projectOptions, configFileErrors: errors }; - }; - ProjectService.prototype.exceededTotalSizeLimitForNonTsFiles = function (options, fileNames, propertyReader) { - if (options && options.disableSizeLimit || !this.host.getFileSize) { - return false; - } - var totalNonTsFileSize = 0; - for (var _i = 0, fileNames_3 = fileNames; _i < fileNames_3.length; _i++) { - var f = fileNames_3[_i]; - var fileName = propertyReader.getFileName(f); - if (ts.hasTypeScriptFileExtension(fileName)) { - continue; - } - totalNonTsFileSize += this.host.getFileSize(fileName); - if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles) { - return true; - } - } - return false; - }; - ProjectService.prototype.createAndAddExternalProject = function (projectFileName, files, options, typingOptions) { - var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, options, !this.exceededTotalSizeLimitForNonTsFiles(options, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave); - this.addFilesToProjectAndUpdateGraph(project, files, externalFilePropertyReader, undefined, typingOptions, undefined); - this.externalProjects.push(project); - return project; - }; - ProjectService.prototype.reportConfigFileDiagnostics = function (configFileName, diagnostics, triggerFile) { - if (diagnostics && diagnostics.length > 0) { - this.eventHandler({ - eventName: "configFileDiag", - data: { configFileName: configFileName, diagnostics: diagnostics, triggerFile: triggerFile } - }); - } - }; - ProjectService.prototype.createAndAddConfiguredProject = function (configFileName, projectOptions, configFileErrors, clientFileName) { - var _this = this; - var sizeLimitExceeded = this.exceededTotalSizeLimitForNonTsFiles(projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); - var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, projectOptions.wildcardDirectories, !sizeLimitExceeded, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave); - this.addFilesToProjectAndUpdateGraph(project, projectOptions.files, fileNamePropertyReader, clientFileName, projectOptions.typingOptions, configFileErrors); - project.watchConfigFile(function (project) { return _this.onConfigChangedForConfiguredProject(project); }); - if (!sizeLimitExceeded) { - this.watchConfigDirectoryForProject(project, projectOptions); - } - project.watchWildcards(function (project, path) { return _this.onSourceFileInDirectoryChangedForConfiguredProject(project, path); }); - project.watchTypeRoots(function (project, path) { return _this.onTypeRootFileChanged(project, path); }); - this.configuredProjects.push(project); - return project; - }; - ProjectService.prototype.watchConfigDirectoryForProject = function (project, options) { - var _this = this; - if (!options.configHasFilesProperty) { - project.watchConfigDirectory(function (project, path) { return _this.onSourceFileInDirectoryChangedForConfiguredProject(project, path); }); - } - }; - ProjectService.prototype.addFilesToProjectAndUpdateGraph = function (project, files, propertyReader, clientFileName, typingOptions, configFileErrors) { - var errors; - for (var _i = 0, files_4 = files; _i < files_4.length; _i++) { - var f = files_4[_i]; - var rootFilename = propertyReader.getFileName(f); - var scriptKind = propertyReader.getScriptKind(f); - var hasMixedContent = propertyReader.hasMixedContent(f); - if (this.host.fileExists(rootFilename)) { - var info = this.getOrCreateScriptInfoForNormalizedPath(server.toNormalizedPath(rootFilename), clientFileName == rootFilename, undefined, scriptKind, hasMixedContent); - project.addRoot(info); - } - else { - (errors || (errors = [])).push(createFileNotFoundDiagnostic(rootFilename)); - } - } - project.setProjectErrors(ts.concatenate(configFileErrors, errors)); - project.setTypingOptions(typingOptions); - project.updateGraph(); - }; - ProjectService.prototype.openConfigFile = function (configFileName, clientFileName) { - var conversionResult = this.convertConfigFileContentToProjectOptions(configFileName); - var projectOptions = conversionResult.success - ? conversionResult.projectOptions - : { files: [], compilerOptions: {} }; - var project = this.createAndAddConfiguredProject(configFileName, projectOptions, conversionResult.configFileErrors, clientFileName); - return { - success: conversionResult.success, - project: project, - errors: project.getProjectErrors() - }; - }; - ProjectService.prototype.updateNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypingOptions, compileOnSave, configFileErrors) { - var oldRootScriptInfos = project.getRootScriptInfos(); - var newRootScriptInfos = []; - var newRootScriptInfoMap = server.createNormalizedPathMap(); - var projectErrors; - var rootFilesChanged = false; - for (var _i = 0, newUncheckedFiles_1 = newUncheckedFiles; _i < newUncheckedFiles_1.length; _i++) { - var f = newUncheckedFiles_1[_i]; - var newRootFile = propertyReader.getFileName(f); - if (!this.host.fileExists(newRootFile)) { - (projectErrors || (projectErrors = [])).push(createFileNotFoundDiagnostic(newRootFile)); - continue; - } - var normalizedPath = server.toNormalizedPath(newRootFile); - var scriptInfo = this.getScriptInfoForNormalizedPath(normalizedPath); - if (!scriptInfo || !project.isRoot(scriptInfo)) { - rootFilesChanged = true; - if (!scriptInfo) { - var scriptKind = propertyReader.getScriptKind(f); - var hasMixedContent = propertyReader.hasMixedContent(f); - scriptInfo = this.getOrCreateScriptInfoForNormalizedPath(normalizedPath, false, undefined, scriptKind, hasMixedContent); - } - } - newRootScriptInfos.push(scriptInfo); - newRootScriptInfoMap.set(scriptInfo.fileName, scriptInfo); - } - if (rootFilesChanged || newRootScriptInfos.length !== oldRootScriptInfos.length) { - var toAdd = void 0; - var toRemove = void 0; - for (var _a = 0, oldRootScriptInfos_1 = oldRootScriptInfos; _a < oldRootScriptInfos_1.length; _a++) { - var oldFile = oldRootScriptInfos_1[_a]; - if (!newRootScriptInfoMap.contains(oldFile.fileName)) { - (toRemove || (toRemove = [])).push(oldFile); - } - } - for (var _b = 0, newRootScriptInfos_1 = newRootScriptInfos; _b < newRootScriptInfos_1.length; _b++) { - var newFile = newRootScriptInfos_1[_b]; - if (!project.isRoot(newFile)) { - (toAdd || (toAdd = [])).push(newFile); - } - } - if (toRemove) { - for (var _c = 0, toRemove_1 = toRemove; _c < toRemove_1.length; _c++) { - var f = toRemove_1[_c]; - project.removeFile(f); - } - } - if (toAdd) { - for (var _d = 0, toAdd_1 = toAdd; _d < toAdd_1.length; _d++) { - var f = toAdd_1[_d]; - if (f.isOpen && isRootFileInInferredProject(f)) { - var inferredProject = f.containingProjects[0]; - inferredProject.removeFile(f); - if (!inferredProject.hasRoots()) { - this.removeProject(inferredProject); - } - } - project.addRoot(f); - } - } - } - project.setCompilerOptions(newOptions); - project.setTypingOptions(newTypingOptions); - if (compileOnSave !== undefined) { - project.compileOnSaveEnabled = compileOnSave; - } - project.setProjectErrors(ts.concatenate(configFileErrors, projectErrors)); - project.updateGraph(); - }; - ProjectService.prototype.updateConfiguredProject = function (project) { - if (!this.host.fileExists(project.configFileName)) { - this.logger.info("Config file deleted"); - this.removeProject(project); - return; - } - var _a = this.convertConfigFileContentToProjectOptions(project.configFileName), success = _a.success, projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors; - if (!success) { - this.updateNonInferredProject(project, [], fileNamePropertyReader, {}, {}, false, configFileErrors); - return configFileErrors; - } - if (this.exceededTotalSizeLimitForNonTsFiles(projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader)) { - project.setCompilerOptions(projectOptions.compilerOptions); - if (!project.languageServiceEnabled) { - return; - } - project.disableLanguageService(); - project.stopWatchingDirectory(); - } - else { - if (!project.languageServiceEnabled) { - project.enableLanguageService(); - } - this.watchConfigDirectoryForProject(project, projectOptions); - this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typingOptions, projectOptions.compileOnSave, configFileErrors); - } - }; - ProjectService.prototype.createInferredProjectWithRootFileIfNecessary = function (root) { - var _this = this; - var useExistingProject = this.useSingleInferredProject && this.inferredProjects.length; - var project = useExistingProject - ? this.inferredProjects[0] - : new server.InferredProject(this, this.documentRegistry, true, this.compilerOptionsForInferredProjects, this.compileOnSaveForInferredProjects); - project.addRoot(root); - this.directoryWatchers.startWatchingContainingDirectoriesForFile(root.fileName, project, function (fileName) { return _this.onConfigFileAddedForInferredProject(fileName); }); - project.updateGraph(); - if (!useExistingProject) { - this.inferredProjects.push(project); - } - return project; - }; - ProjectService.prototype.getOrCreateScriptInfo = function (uncheckedFileName, openedByClient, fileContent, scriptKind) { - return this.getOrCreateScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName), openedByClient, fileContent, scriptKind); - }; - ProjectService.prototype.getScriptInfo = function (uncheckedFileName) { - return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); - }; - ProjectService.prototype.getOrCreateScriptInfoForNormalizedPath = function (fileName, openedByClient, fileContent, scriptKind, hasMixedContent) { - var _this = this; - var info = this.getScriptInfoForNormalizedPath(fileName); - if (!info) { - var content = void 0; - if (this.host.fileExists(fileName)) { - content = fileContent || (hasMixedContent ? "" : this.host.readFile(fileName)); - } - if (!content) { - if (openedByClient) { - content = ""; - } - } - if (content !== undefined) { - info = new server.ScriptInfo(this.host, fileName, content, scriptKind, openedByClient, hasMixedContent); - this.filenameToScriptInfo.set(info.path, info); - if (!info.isOpen && !hasMixedContent) { - info.setWatcher(this.host.watchFile(fileName, function (_) { return _this.onSourceFileChanged(fileName); })); - } - } - } - if (info) { - if (fileContent) { - info.reload(fileContent); - } - if (openedByClient) { - info.isOpen = true; - } - } - return info; - }; - ProjectService.prototype.getScriptInfoForNormalizedPath = function (fileName) { - return this.filenameToScriptInfo.get(server.normalizedPathToPath(fileName, this.host.getCurrentDirectory(), this.toCanonicalFileName)); - }; - ProjectService.prototype.setHostConfiguration = function (args) { - if (args.file) { - var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(args.file)); - if (info) { - info.setFormatOptions(args.formatOptions); - this.logger.info("Host configuration update for file " + args.file); - } - } - else { - if (args.hostInfo !== undefined) { - this.hostConfiguration.hostInfo = args.hostInfo; - this.logger.info("Host information " + args.hostInfo); - } - if (args.formatOptions) { - server.mergeMaps(this.hostConfiguration.formatCodeOptions, args.formatOptions); - this.logger.info("Format host information updated"); - } - } - }; - ProjectService.prototype.closeLog = function () { - this.logger.close(); - }; - ProjectService.prototype.reloadProjects = function () { - this.logger.info("reload projects."); - for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { - var info = _a[_i]; - this.openOrUpdateConfiguredProjectForFile(info.fileName); - } - this.refreshInferredProjects(); - }; - ProjectService.prototype.refreshInferredProjects = function () { - this.logger.info("updating project structure from ..."); - this.printProjects(); - var orphantedFiles = []; - for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { - var info = _a[_i]; - if (info.containingProjects.length === 0) { - orphantedFiles.push(info); - } - else { - if (isRootFileInInferredProject(info) && info.containingProjects.length > 1) { - var inferredProject = info.containingProjects[0]; - ts.Debug.assert(inferredProject.projectKind === server.ProjectKind.Inferred); - inferredProject.removeFile(info); - if (!inferredProject.hasRoots()) { - this.removeProject(inferredProject); - } - } - } - } - for (var _b = 0, orphantedFiles_1 = orphantedFiles; _b < orphantedFiles_1.length; _b++) { - var f = orphantedFiles_1[_b]; - this.assignScriptInfoToInferredProjectIfNecessary(f, false); - } - for (var _c = 0, _d = this.inferredProjects; _c < _d.length; _c++) { - var p = _d[_c]; - p.updateGraph(); - } - this.printProjects(); - }; - ProjectService.prototype.openClientFile = function (fileName, fileContent, scriptKind) { - return this.openClientFileWithNormalizedPath(server.toNormalizedPath(fileName), fileContent, scriptKind); - }; - ProjectService.prototype.openClientFileWithNormalizedPath = function (fileName, fileContent, scriptKind, hasMixedContent) { - var _a = this.findContainingExternalProject(fileName) - ? {} - : this.openOrUpdateConfiguredProjectForFile(fileName), _b = _a.configFileName, configFileName = _b === void 0 ? undefined : _b, _c = _a.configFileErrors, configFileErrors = _c === void 0 ? undefined : _c; - var info = this.getOrCreateScriptInfoForNormalizedPath(fileName, true, fileContent, scriptKind, hasMixedContent); - this.assignScriptInfoToInferredProjectIfNecessary(info, true); - this.printProjects(); - return { configFileName: configFileName, configFileErrors: configFileErrors }; - }; - ProjectService.prototype.closeClientFile = function (uncheckedFileName) { - var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); - if (info) { - this.closeOpenFile(info); - info.isOpen = false; - } - this.printProjects(); - }; - ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) { - var _loop_4 = function(proj) { - var knownProject = ts.forEach(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName() && p; }); - result.push(proj.getChangesSinceVersion(knownProject && knownProject.version)); - }; - for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) { - var proj = currentProjects_1[_i]; - _loop_4(proj); - } - }; - ProjectService.prototype.synchronizeProjectList = function (knownProjects) { - var files = []; - this.collectChanges(knownProjects, this.externalProjects, files); - this.collectChanges(knownProjects, this.configuredProjects, files); - this.collectChanges(knownProjects, this.inferredProjects, files); - return files; - }; - ProjectService.prototype.applyChangesInOpenFiles = function (openFiles, changedFiles, closedFiles) { - var recordChangedFiles = changedFiles && !openFiles && !closedFiles; - if (openFiles) { - for (var _i = 0, openFiles_1 = openFiles; _i < openFiles_1.length; _i++) { - var file = openFiles_1[_i]; - var scriptInfo = this.getScriptInfo(file.fileName); - ts.Debug.assert(!scriptInfo || !scriptInfo.isOpen); - var normalizedPath = scriptInfo ? scriptInfo.fileName : server.toNormalizedPath(file.fileName); - this.openClientFileWithNormalizedPath(normalizedPath, file.content, file.scriptKind, file.hasMixedContent); - } - } - if (changedFiles) { - for (var _a = 0, changedFiles_1 = changedFiles; _a < changedFiles_1.length; _a++) { - var file = changedFiles_1[_a]; - var scriptInfo = this.getScriptInfo(file.fileName); - ts.Debug.assert(!!scriptInfo); - for (var i = file.changes.length - 1; i >= 0; i--) { - var change = file.changes[i]; - scriptInfo.editContent(change.span.start, change.span.start + change.span.length, change.newText); - } - if (recordChangedFiles) { - if (!this.changedFiles) { - this.changedFiles = [scriptInfo]; - } - else if (this.changedFiles.indexOf(scriptInfo) < 0) { - this.changedFiles.push(scriptInfo); - } - } - } - } - if (closedFiles) { - for (var _b = 0, closedFiles_1 = closedFiles; _b < closedFiles_1.length; _b++) { - var file = closedFiles_1[_b]; - this.closeClientFile(file); - } - } - if (openFiles || closedFiles) { - this.refreshInferredProjects(); - } - }; - ProjectService.prototype.closeConfiguredProject = function (configFile) { - var configuredProject = this.findConfiguredProjectByProjectName(configFile); - if (configuredProject && configuredProject.deleteOpenRef() === 0) { - this.removeProject(configuredProject); - } - }; - ProjectService.prototype.closeExternalProject = function (uncheckedFileName, suppressRefresh) { - if (suppressRefresh === void 0) { suppressRefresh = false; } - var fileName = server.toNormalizedPath(uncheckedFileName); - var configFiles = this.externalProjectToConfiguredProjectMap[fileName]; - if (configFiles) { - var shouldRefreshInferredProjects = false; - for (var _i = 0, configFiles_1 = configFiles; _i < configFiles_1.length; _i++) { - var configFile = configFiles_1[_i]; - if (this.closeConfiguredProject(configFile)) { - shouldRefreshInferredProjects = true; - } - } - delete this.externalProjectToConfiguredProjectMap[fileName]; - if (shouldRefreshInferredProjects && !suppressRefresh) { - this.refreshInferredProjects(); - } - } - else { - var externalProject = this.findExternalProjectByProjectName(uncheckedFileName); - if (externalProject) { - this.removeProject(externalProject); - if (!suppressRefresh) { - this.refreshInferredProjects(); - } - } - } - }; - ProjectService.prototype.openExternalProject = function (proj) { - var tsConfigFiles; - var rootFiles = []; - for (var _i = 0, _a = proj.rootFiles; _i < _a.length; _i++) { - var file = _a[_i]; - var normalized = server.toNormalizedPath(file.fileName); - if (ts.getBaseFileName(normalized) === "tsconfig.json") { - (tsConfigFiles || (tsConfigFiles = [])).push(normalized); - } - else { - rootFiles.push(file); - } - } - if (tsConfigFiles) { - tsConfigFiles.sort(); - } - var externalProject = this.findExternalProjectByProjectName(proj.projectFileName); - var exisingConfigFiles; - if (externalProject) { - if (!tsConfigFiles) { - this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, proj.options, proj.typingOptions, proj.options.compileOnSave, undefined); - return; - } - this.closeExternalProject(proj.projectFileName, true); - } - else if (this.externalProjectToConfiguredProjectMap[proj.projectFileName]) { - if (!tsConfigFiles) { - this.closeExternalProject(proj.projectFileName, true); - } - else { - var oldConfigFiles = this.externalProjectToConfiguredProjectMap[proj.projectFileName]; - var iNew = 0; - var iOld = 0; - while (iNew < tsConfigFiles.length && iOld < oldConfigFiles.length) { - var newConfig = tsConfigFiles[iNew]; - var oldConfig = oldConfigFiles[iOld]; - if (oldConfig < newConfig) { - this.closeConfiguredProject(oldConfig); - iOld++; - } - else if (oldConfig > newConfig) { - iNew++; - } - else { - (exisingConfigFiles || (exisingConfigFiles = [])).push(oldConfig); - iOld++; - iNew++; - } - } - for (var i = iOld; i < oldConfigFiles.length; i++) { - this.closeConfiguredProject(oldConfigFiles[i]); - } - } - } - if (tsConfigFiles) { - this.externalProjectToConfiguredProjectMap[proj.projectFileName] = tsConfigFiles; - for (var _b = 0, tsConfigFiles_1 = tsConfigFiles; _b < tsConfigFiles_1.length; _b++) { - var tsconfigFile = tsConfigFiles_1[_b]; - var project = this.findConfiguredProjectByProjectName(tsconfigFile); - if (!project) { - var result = this.openConfigFile(tsconfigFile); - project = result.success && result.project; - } - if (project && !ts.contains(exisingConfigFiles, tsconfigFile)) { - project.addOpenRef(); - } - } - } - else { - delete this.externalProjectToConfiguredProjectMap[proj.projectFileName]; - this.createAndAddExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typingOptions); - } - this.refreshInferredProjects(); - }; - return ProjectService; - }()); - server.ProjectService = ProjectService; - })(server = ts.server || (ts.server = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - var server; - (function (server) { - function hrTimeToMilliseconds(time) { - var seconds = time[0]; - var nanoseconds = time[1]; - return ((1e9 * seconds) + nanoseconds) / 1000000.0; - } + server.generateIndentString = generateIndentString; function compareNumber(a, b) { - return a - b; + if (a < b) { + return -1; + } + else if (a === b) { + return 0; + } + else + return 1; } function compareFileStart(a, b) { if (a.file < b.file) { @@ -53811,10 +49740,9 @@ var ts; } } function formatDiag(fileName, project, diag) { - var scriptInfo = project.getScriptInfoForNormalizedPath(fileName); return { - start: scriptInfo.positionToLineOffset(diag.start), - end: scriptInfo.positionToLineOffset(diag.start + diag.length), + start: project.compilerService.host.positionToLineOffset(fileName, diag.start), + end: project.compilerService.host.positionToLineOffset(fileName, diag.start + diag.length), text: ts.flattenDiagnosticMessageText(diag.messageText, "\n") }; } @@ -53826,9 +49754,8 @@ var ts; }; } function allEditsBeforePos(edits, pos) { - for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) { - var edit = edits_1[_i]; - if (ts.textSpanEnd(edit.span) >= pos) { + for (var i = 0, len = edits.length; i < len; i++) { + if (ts.textSpanEnd(edits[i].span) >= pos) { return false; } } @@ -53837,153 +49764,68 @@ var ts; var CommandNames; (function (CommandNames) { CommandNames.Brace = "brace"; - CommandNames.BraceFull = "brace-full"; - CommandNames.BraceCompletion = "braceCompletion"; CommandNames.Change = "change"; CommandNames.Close = "close"; CommandNames.Completions = "completions"; - CommandNames.CompletionsFull = "completions-full"; CommandNames.CompletionDetails = "completionEntryDetails"; - CommandNames.CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList"; - CommandNames.CompileOnSaveEmitFile = "compileOnSaveEmitFile"; CommandNames.Configure = "configure"; CommandNames.Definition = "definition"; - CommandNames.DefinitionFull = "definition-full"; CommandNames.Exit = "exit"; CommandNames.Format = "format"; CommandNames.Formatonkey = "formatonkey"; - CommandNames.FormatFull = "format-full"; - CommandNames.FormatonkeyFull = "formatonkey-full"; - CommandNames.FormatRangeFull = "formatRange-full"; CommandNames.Geterr = "geterr"; CommandNames.GeterrForProject = "geterrForProject"; CommandNames.SemanticDiagnosticsSync = "semanticDiagnosticsSync"; CommandNames.SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; CommandNames.NavBar = "navbar"; - CommandNames.NavBarFull = "navbar-full"; CommandNames.Navto = "navto"; - CommandNames.NavtoFull = "navto-full"; CommandNames.Occurrences = "occurrences"; CommandNames.DocumentHighlights = "documentHighlights"; - CommandNames.DocumentHighlightsFull = "documentHighlights-full"; CommandNames.Open = "open"; CommandNames.Quickinfo = "quickinfo"; - CommandNames.QuickinfoFull = "quickinfo-full"; CommandNames.References = "references"; - CommandNames.ReferencesFull = "references-full"; CommandNames.Reload = "reload"; CommandNames.Rename = "rename"; - CommandNames.RenameInfoFull = "rename-full"; - CommandNames.RenameLocationsFull = "renameLocations-full"; CommandNames.Saveto = "saveto"; CommandNames.SignatureHelp = "signatureHelp"; - CommandNames.SignatureHelpFull = "signatureHelp-full"; CommandNames.TypeDefinition = "typeDefinition"; CommandNames.ProjectInfo = "projectInfo"; CommandNames.ReloadProjects = "reloadProjects"; CommandNames.Unknown = "unknown"; - CommandNames.OpenExternalProject = "openExternalProject"; - CommandNames.OpenExternalProjects = "openExternalProjects"; - CommandNames.CloseExternalProject = "closeExternalProject"; - CommandNames.SynchronizeProjectList = "synchronizeProjectList"; - CommandNames.ApplyChangedToOpenFiles = "applyChangedToOpenFiles"; - CommandNames.EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full"; - CommandNames.Cleanup = "cleanup"; - CommandNames.OutliningSpans = "outliningSpans"; - CommandNames.TodoComments = "todoComments"; - CommandNames.Indentation = "indentation"; - CommandNames.DocCommentTemplate = "docCommentTemplate"; - CommandNames.CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full"; - CommandNames.NameOrDottedNameSpan = "nameOrDottedNameSpan"; - CommandNames.BreakpointStatement = "breakpointStatement"; - CommandNames.CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects"; })(CommandNames = server.CommandNames || (server.CommandNames = {})); - function formatMessage(msg, logger, byteLength, newLine) { - var verboseLogging = logger.hasLevel(server.LogLevel.verbose); - var json = JSON.stringify(msg); - if (verboseLogging) { - logger.info(msg.type + ": " + json); - } - var len = byteLength(json, "utf8"); - return "Content-Length: " + (1 + len) + "\r\n\r\n" + json + newLine; - } - server.formatMessage = formatMessage; + var Errors; + (function (Errors) { + Errors.NoProject = new Error("No Project."); + Errors.ProjectLanguageServiceDisabled = new Error("The project's language service is disabled."); + })(Errors || (Errors = {})); var Session = (function () { - function Session(host, cancellationToken, useSingleInferredProject, typingsInstaller, byteLength, hrtime, logger, canUseEvents) { + function Session(host, byteLength, hrtime, logger) { var _this = this; this.host = host; - this.typingsInstaller = typingsInstaller; this.byteLength = byteLength; this.hrtime = hrtime; this.logger = logger; - this.canUseEvents = canUseEvents; this.changeSeq = 0; - this.handlers = ts.createMap((_a = {}, - _a[CommandNames.OpenExternalProject] = function (request) { - _this.projectService.openExternalProject(request.arguments); - return _this.requiredResponse(true); - }, - _a[CommandNames.OpenExternalProjects] = function (request) { - for (var _i = 0, _a = request.arguments.projects; _i < _a.length; _i++) { - var proj = _a[_i]; - _this.projectService.openExternalProject(proj); - } - return _this.requiredResponse(true); - }, - _a[CommandNames.CloseExternalProject] = function (request) { - _this.projectService.closeExternalProject(request.arguments.projectFileName); - return _this.requiredResponse(true); - }, - _a[CommandNames.SynchronizeProjectList] = function (request) { - var result = _this.projectService.synchronizeProjectList(request.arguments.knownProjects); - if (!result.some(function (p) { return p.projectErrors && p.projectErrors.length !== 0; })) { - return _this.requiredResponse(result); - } - var converted = ts.map(result, function (p) { - if (!p.projectErrors || p.projectErrors.length === 0) { - return p; - } - return { - info: p.info, - changes: p.changes, - files: p.files, - projectErrors: _this.convertToDiagnosticsWithLinePosition(p.projectErrors, undefined) - }; - }); - return _this.requiredResponse(converted); - }, - _a[CommandNames.ApplyChangedToOpenFiles] = function (request) { - _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles, request.arguments.changedFiles, request.arguments.closedFiles); - _this.changeSeq++; - return _this.requiredResponse(true); - }, + this.handlers = (_a = {}, _a[CommandNames.Exit] = function () { _this.exit(); - return _this.notRequired(); + return { responseRequired: false }; }, _a[CommandNames.Definition] = function (request) { - return _this.requiredResponse(_this.getDefinition(request.arguments, true)); - }, - _a[CommandNames.DefinitionFull] = function (request) { - return _this.requiredResponse(_this.getDefinition(request.arguments, false)); + var defArgs = request.arguments; + return { response: _this.getDefinition(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true }; }, _a[CommandNames.TypeDefinition] = function (request) { - return _this.requiredResponse(_this.getTypeDefinition(request.arguments)); + var defArgs = request.arguments; + return { response: _this.getTypeDefinition(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true }; }, _a[CommandNames.References] = function (request) { - return _this.requiredResponse(_this.getReferences(request.arguments, true)); - }, - _a[CommandNames.ReferencesFull] = function (request) { - return _this.requiredResponse(_this.getReferences(request.arguments, false)); + var defArgs = request.arguments; + return { response: _this.getReferences(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true }; }, _a[CommandNames.Rename] = function (request) { - return _this.requiredResponse(_this.getRenameLocations(request.arguments, true)); - }, - _a[CommandNames.RenameLocationsFull] = function (request) { - return _this.requiredResponse(_this.getRenameLocations(request.arguments, false)); - }, - _a[CommandNames.RenameInfoFull] = function (request) { - return _this.requiredResponse(_this.getRenameInfo(request.arguments)); + var renameArgs = request.arguments; + return { response: _this.getRenameLocations(renameArgs.line, renameArgs.offset, renameArgs.file, renameArgs.findInComments, renameArgs.findInStrings), responseRequired: true }; }, _a[CommandNames.Open] = function (request) { var openArgs = request.arguments; @@ -54002,81 +49844,34 @@ var ts; scriptKind = 2; break; } - _this.openClientFile(server.toNormalizedPath(openArgs.file), openArgs.fileContent, scriptKind); - return _this.notRequired(); + _this.openClientFile(openArgs.file, openArgs.fileContent, scriptKind); + return { responseRequired: false }; }, _a[CommandNames.Quickinfo] = function (request) { - return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, true)); - }, - _a[CommandNames.QuickinfoFull] = function (request) { - return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, false)); - }, - _a[CommandNames.OutliningSpans] = function (request) { - return _this.requiredResponse(_this.getOutliningSpans(request.arguments)); - }, - _a[CommandNames.TodoComments] = function (request) { - return _this.requiredResponse(_this.getTodoComments(request.arguments)); - }, - _a[CommandNames.Indentation] = function (request) { - return _this.requiredResponse(_this.getIndentation(request.arguments)); - }, - _a[CommandNames.NameOrDottedNameSpan] = function (request) { - return _this.requiredResponse(_this.getNameOrDottedNameSpan(request.arguments)); - }, - _a[CommandNames.BreakpointStatement] = function (request) { - return _this.requiredResponse(_this.getBreakpointStatement(request.arguments)); - }, - _a[CommandNames.BraceCompletion] = function (request) { - return _this.requiredResponse(_this.isValidBraceCompletion(request.arguments)); - }, - _a[CommandNames.DocCommentTemplate] = function (request) { - return _this.requiredResponse(_this.getDocCommentTemplate(request.arguments)); + var quickinfoArgs = request.arguments; + return { response: _this.getQuickInfo(quickinfoArgs.line, quickinfoArgs.offset, quickinfoArgs.file), responseRequired: true }; }, _a[CommandNames.Format] = function (request) { - return _this.requiredResponse(_this.getFormattingEditsForRange(request.arguments)); + var formatArgs = request.arguments; + return { response: _this.getFormattingEditsForRange(formatArgs.line, formatArgs.offset, formatArgs.endLine, formatArgs.endOffset, formatArgs.file), responseRequired: true }; }, _a[CommandNames.Formatonkey] = function (request) { - return _this.requiredResponse(_this.getFormattingEditsAfterKeystroke(request.arguments)); - }, - _a[CommandNames.FormatFull] = function (request) { - return _this.requiredResponse(_this.getFormattingEditsForDocumentFull(request.arguments)); - }, - _a[CommandNames.FormatonkeyFull] = function (request) { - return _this.requiredResponse(_this.getFormattingEditsAfterKeystrokeFull(request.arguments)); - }, - _a[CommandNames.FormatRangeFull] = function (request) { - return _this.requiredResponse(_this.getFormattingEditsForRangeFull(request.arguments)); + var formatOnKeyArgs = request.arguments; + return { response: _this.getFormattingEditsAfterKeystroke(formatOnKeyArgs.line, formatOnKeyArgs.offset, formatOnKeyArgs.key, formatOnKeyArgs.file), responseRequired: true }; }, _a[CommandNames.Completions] = function (request) { - return _this.requiredResponse(_this.getCompletions(request.arguments, true)); - }, - _a[CommandNames.CompletionsFull] = function (request) { - return _this.requiredResponse(_this.getCompletions(request.arguments, false)); + var completionsArgs = request.arguments; + return { response: _this.getCompletions(completionsArgs.line, completionsArgs.offset, completionsArgs.prefix, completionsArgs.file), responseRequired: true }; }, _a[CommandNames.CompletionDetails] = function (request) { - return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments)); - }, - _a[CommandNames.CompileOnSaveAffectedFileList] = function (request) { - return _this.requiredResponse(_this.getCompileOnSaveAffectedFileList(request.arguments)); - }, - _a[CommandNames.CompileOnSaveEmitFile] = function (request) { - return _this.requiredResponse(_this.emitFile(request.arguments)); + var completionDetailsArgs = request.arguments; + return { + response: _this.getCompletionEntryDetails(completionDetailsArgs.line, completionDetailsArgs.offset, completionDetailsArgs.entryNames, completionDetailsArgs.file), responseRequired: true + }; }, _a[CommandNames.SignatureHelp] = function (request) { - return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, true)); - }, - _a[CommandNames.SignatureHelpFull] = function (request) { - return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, false)); - }, - _a[CommandNames.CompilerOptionsDiagnosticsFull] = function (request) { - return _this.requiredResponse(_this.getCompilerOptionsDiagnostics(request.arguments)); - }, - _a[CommandNames.EncodedSemanticClassificationsFull] = function (request) { - return _this.requiredResponse(_this.getEncodedSemanticClassifications(request.arguments)); - }, - _a[CommandNames.Cleanup] = function (request) { - _this.cleanup(); - return _this.requiredResponse(true); + var signatureHelpArgs = request.arguments; + return { response: _this.getSignatureHelpItems(signatureHelpArgs.line, signatureHelpArgs.offset, signatureHelpArgs.file), responseRequired: true }; }, _a[CommandNames.SemanticDiagnosticsSync] = function (request) { return _this.requiredResponse(_this.getSemanticDiagnosticsSync(request.arguments)); @@ -54093,105 +49888,95 @@ var ts; return { response: _this.getDiagnosticsForProject(delay, file), responseRequired: false }; }, _a[CommandNames.Change] = function (request) { - _this.change(request.arguments); - return _this.notRequired(); + var changeArgs = request.arguments; + _this.change(changeArgs.line, changeArgs.offset, changeArgs.endLine, changeArgs.endOffset, changeArgs.insertString, changeArgs.file); + return { responseRequired: false }; }, _a[CommandNames.Configure] = function (request) { - _this.projectService.setHostConfiguration(request.arguments); + var configureArgs = request.arguments; + _this.projectService.setHostConfiguration(configureArgs); _this.output(undefined, CommandNames.Configure, request.seq); - return _this.notRequired(); + return { responseRequired: false }; }, _a[CommandNames.Reload] = function (request) { - _this.reload(request.arguments, request.seq); - return _this.requiredResponse({ reloadFinished: true }); + var reloadArgs = request.arguments; + _this.reload(reloadArgs.file, reloadArgs.tmpfile, request.seq); + return { response: { reloadFinished: true }, responseRequired: true }; }, _a[CommandNames.Saveto] = function (request) { var savetoArgs = request.arguments; _this.saveToTmp(savetoArgs.file, savetoArgs.tmpfile); - return _this.notRequired(); + return { responseRequired: false }; }, _a[CommandNames.Close] = function (request) { var closeArgs = request.arguments; _this.closeClientFile(closeArgs.file); - return _this.notRequired(); + return { responseRequired: false }; }, _a[CommandNames.Navto] = function (request) { - return _this.requiredResponse(_this.getNavigateToItems(request.arguments, true)); - }, - _a[CommandNames.NavtoFull] = function (request) { - return _this.requiredResponse(_this.getNavigateToItems(request.arguments, false)); + var navtoArgs = request.arguments; + return { response: _this.getNavigateToItems(navtoArgs.searchValue, navtoArgs.file, navtoArgs.maxResultCount), responseRequired: true }; }, _a[CommandNames.Brace] = function (request) { - return _this.requiredResponse(_this.getBraceMatching(request.arguments, true)); - }, - _a[CommandNames.BraceFull] = function (request) { - return _this.requiredResponse(_this.getBraceMatching(request.arguments, false)); + var braceArguments = request.arguments; + return { response: _this.getBraceMatching(braceArguments.line, braceArguments.offset, braceArguments.file), responseRequired: true }; }, _a[CommandNames.NavBar] = function (request) { - return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, true)); - }, - _a[CommandNames.NavBarFull] = function (request) { - return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, false)); + var navBarArgs = request.arguments; + return { response: _this.getNavigationBarItems(navBarArgs.file), responseRequired: true }; }, _a[CommandNames.Occurrences] = function (request) { - return _this.requiredResponse(_this.getOccurrences(request.arguments)); + var _a = request.arguments, line = _a.line, offset = _a.offset, fileName = _a.file; + return { response: _this.getOccurrences(line, offset, fileName), responseRequired: true }; }, _a[CommandNames.DocumentHighlights] = function (request) { - return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, true)); - }, - _a[CommandNames.DocumentHighlightsFull] = function (request) { - return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, false)); - }, - _a[CommandNames.CompilerOptionsForInferredProjects] = function (request) { - return _this.requiredResponse(_this.setCompilerOptionsForInferredProjects(request.arguments)); + var _a = request.arguments, line = _a.line, offset = _a.offset, fileName = _a.file, filesToSearch = _a.filesToSearch; + return { response: _this.getDocumentHighlights(line, offset, fileName, filesToSearch), responseRequired: true }; }, _a[CommandNames.ProjectInfo] = function (request) { - return _this.requiredResponse(_this.getProjectInfo(request.arguments)); + var _a = request.arguments, file = _a.file, needFileNameList = _a.needFileNameList; + return { response: _this.getProjectInfo(file, needFileNameList), responseRequired: true }; }, _a[CommandNames.ReloadProjects] = function (request) { - _this.projectService.reloadProjects(); - return _this.notRequired(); + _this.reloadProjects(); + return { responseRequired: false }; }, _a - )); - var eventHandler = canUseEvents - ? function (event) { return _this.handleEvent(event); } - : undefined; - this.projectService = new server.ProjectService(host, logger, cancellationToken, useSingleInferredProject, typingsInstaller, eventHandler); - this.gcTimer = new server.GcTimer(host, 7000, logger); + ); + this.projectService = + new server.ProjectService(host, logger, function (eventName, project, fileName) { + _this.handleEvent(eventName, project, fileName); + }); var _a; } - Session.prototype.handleEvent = function (event) { + Session.prototype.handleEvent = function (eventName, project, fileName) { var _this = this; - switch (event.eventName) { - case "context": - var _a = event.data, project = _a.project, fileName = _a.fileName; - this.projectService.logger.info("got context event, updating diagnostics for " + fileName); - this.updateErrorCheck([{ fileName: fileName, project: project }], this.changeSeq, function (n) { return n === _this.changeSeq; }, 100); - break; - case "configFileDiag": - var _b = event.data, triggerFile = _b.triggerFile, configFileName = _b.configFileName, diagnostics = _b.diagnostics; - this.configFileDiagnosticEvent(triggerFile, configFileName, diagnostics); + if (eventName == "context") { + this.projectService.log("got context event, updating diagnostics for" + fileName, "Info"); + this.updateErrorCheck([{ fileName: fileName, project: project }], this.changeSeq, function (n) { return n === _this.changeSeq; }, 100); } }; Session.prototype.logError = function (err, cmd) { + var typedErr = err; var msg = "Exception on executing command " + cmd; - if (err.message) { - msg += ":\n" + err.message; - if (err.stack) { - msg += "\n" + err.stack; + if (typedErr.message) { + msg += ":\n" + typedErr.message; + if (typedErr.stack) { + msg += "\n" + typedErr.stack; } } - this.logger.msg(msg, server.Msg.Err); + this.projectService.log(msg); + }; + Session.prototype.sendLineToClient = function (line) { + this.host.write(line + this.host.newLine); }; Session.prototype.send = function (msg) { - if (msg.type === "event" && !this.canUseEvents) { - if (this.logger.hasLevel(server.LogLevel.verbose)) { - this.logger.info("Session does not support events: ignored event: " + JSON.stringify(msg)); - } - return; + var json = JSON.stringify(msg); + if (this.logger.isVerbose()) { + this.logger.info(msg.type + ": " + json); } - this.host.write(formatMessage(msg, this.logger, this.byteLength, this.host.newLine)); + this.sendLineToClient("Content-Length: " + (1 + this.byteLength(json, "utf8")) + + "\r\n\r\n" + json); }; Session.prototype.configFileDiagnosticEvent = function (triggerFile, configFile, diagnostics) { var bakedDiags = ts.map(diagnostics, formatConfigFileDiag); @@ -54216,7 +50001,7 @@ var ts; }; this.send(ev); }; - Session.prototype.output = function (info, cmdName, reqSeq, errorMsg) { + Session.prototype.response = function (info, cmdName, reqSeq, errorMsg) { if (reqSeq === void 0) { reqSeq = 0; } var res = { seq: 0, @@ -54233,9 +50018,13 @@ var ts; } this.send(res); }; + Session.prototype.output = function (body, commandName, requestSequence, errorMessage) { + if (requestSequence === void 0) { requestSequence = 0; } + this.response(body, commandName, requestSequence, errorMessage); + }; Session.prototype.semanticCheck = function (file, project) { try { - var diags = project.getLanguageService().getSemanticDiagnostics(file); + var diags = project.compilerService.languageService.getSemanticDiagnostics(file); if (diags) { var bakedDiags = diags.map(function (diag) { return formatDiag(file, project, diag); }); this.event({ file: file, diagnostics: bakedDiags }, "semanticDiag"); @@ -54247,7 +50036,7 @@ var ts; }; Session.prototype.syntacticCheck = function (file, project) { try { - var diags = project.getLanguageService().getSyntacticDiagnostics(file); + var diags = project.compilerService.languageService.getSyntacticDiagnostics(file); if (diags) { var bakedDiags = diags.map(function (diag) { return formatDiag(file, project, diag); }); this.event({ file: file, diagnostics: bakedDiags }, "syntaxDiag"); @@ -54257,12 +50046,15 @@ var ts; this.logError(err, "syntactic check"); } }; + Session.prototype.reloadProjects = function () { + this.projectService.reloadProjects(); + }; Session.prototype.updateProjectStructure = function (seq, matchSeq, ms) { var _this = this; if (ms === void 0) { ms = 1500; } - this.host.setTimeout(function () { + setTimeout(function () { if (matchSeq(seq)) { - _this.projectService.refreshInferredProjects(); + _this.projectService.updateProjectStructure(); } }, ms); }; @@ -54275,10 +50067,10 @@ var ts; followMs = ms; } if (this.errorTimer) { - this.host.clearTimeout(this.errorTimer); + clearTimeout(this.errorTimer); } if (this.immediateId) { - this.host.clearImmediate(this.immediateId); + clearImmediate(this.immediateId); this.immediateId = undefined; } var index = 0; @@ -54286,13 +50078,13 @@ var ts; if (matchSeq(seq)) { var checkSpec_1 = checkList[index]; index++; - if (checkSpec_1.project.containsFile(checkSpec_1.fileName, requireOpen)) { + if (checkSpec_1.project.getSourceFileFromName(checkSpec_1.fileName, requireOpen)) { _this.syntacticCheck(checkSpec_1.fileName, checkSpec_1.project); - _this.immediateId = _this.host.setImmediate(function () { + _this.immediateId = setImmediate(function () { _this.semanticCheck(checkSpec_1.fileName, checkSpec_1.project); _this.immediateId = undefined; if (checkList.length > index) { - _this.errorTimer = _this.host.setTimeout(checkOne, followMs); + _this.errorTimer = setTimeout(checkOne, followMs); } else { _this.errorTimer = undefined; @@ -54302,111 +50094,61 @@ var ts; } }; if ((checkList.length > index) && (matchSeq(seq))) { - this.errorTimer = this.host.setTimeout(checkOne, ms); + this.errorTimer = setTimeout(checkOne, ms); } }; - Session.prototype.cleanProjects = function (caption, projects) { - if (!projects) { - return; + Session.prototype.getDefinition = function (line, offset, fileName) { + var file = ts.normalizePath(fileName); + var project = this.projectService.getProjectForFile(file); + if (!project || project.languageServiceDiabled) { + throw Errors.NoProject; } - this.logger.info("cleaning " + caption); - for (var _i = 0, projects_4 = projects; _i < projects_4.length; _i++) { - var p = projects_4[_i]; - p.getLanguageService(false).cleanupSemanticCache(); - } - }; - Session.prototype.cleanup = function () { - this.cleanProjects("inferred projects", this.projectService.inferredProjects); - this.cleanProjects("configured projects", this.projectService.configuredProjects); - this.cleanProjects("external projects", this.projectService.externalProjects); - if (this.host.gc) { - this.logger.info("host.gc()"); - this.host.gc(); - } - }; - Session.prototype.getEncodedSemanticClassifications = function (args) { - var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - return project.getLanguageService().getEncodedSemanticClassifications(file, args); - }; - Session.prototype.getProject = function (projectFileName) { - return projectFileName && this.projectService.findProject(projectFileName); - }; - Session.prototype.getCompilerOptionsDiagnostics = function (args) { - var project = this.getProject(args.projectFileName); - return this.convertToDiagnosticsWithLinePosition(project.getLanguageService().getCompilerOptionsDiagnostics(), undefined); - }; - Session.prototype.convertToDiagnosticsWithLinePosition = function (diagnostics, scriptInfo) { - var _this = this; - return diagnostics.map(function (d) { return { - message: ts.flattenDiagnosticMessageText(d.messageText, _this.host.newLine), - start: d.start, - length: d.length, - category: ts.DiagnosticCategory[d.category].toLowerCase(), - code: d.code, - startLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start), - endLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start + d.length) - }; }); - }; - Session.prototype.getDiagnosticsWorker = function (args, selector, includeLinePosition) { - var _a = this.getFileAndProject(args), project = _a.project, file = _a.file; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var diagnostics = selector(project, file); - return includeLinePosition - ? this.convertToDiagnosticsWithLinePosition(diagnostics, scriptInfo) - : diagnostics.map(function (d) { return formatDiag(file, project, d); }); - }; - Session.prototype.getDefinition = function (args, simplifiedResult) { - var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, scriptInfo); - var definitions = project.getLanguageService().getDefinitionAtPosition(file, position); + var compilerService = project.compilerService; + var position = compilerService.host.lineOffsetToPosition(file, line, offset); + var definitions = compilerService.languageService.getDefinitionAtPosition(file, position); if (!definitions) { return undefined; } - if (simplifiedResult) { - return definitions.map(function (def) { - var defScriptInfo = project.getScriptInfo(def.fileName); - return { - file: def.fileName, - start: defScriptInfo.positionToLineOffset(def.textSpan.start), - end: defScriptInfo.positionToLineOffset(ts.textSpanEnd(def.textSpan)) - }; - }); - } - else { - return definitions; - } + return definitions.map(function (def) { return ({ + file: def.fileName, + start: compilerService.host.positionToLineOffset(def.fileName, def.textSpan.start), + end: compilerService.host.positionToLineOffset(def.fileName, ts.textSpanEnd(def.textSpan)) + }); }); }; - Session.prototype.getTypeDefinition = function (args) { - var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, scriptInfo); - var definitions = project.getLanguageService().getTypeDefinitionAtPosition(file, position); + Session.prototype.getTypeDefinition = function (line, offset, fileName) { + var file = ts.normalizePath(fileName); + var project = this.projectService.getProjectForFile(file); + if (!project || project.languageServiceDiabled) { + throw Errors.NoProject; + } + var compilerService = project.compilerService; + var position = compilerService.host.lineOffsetToPosition(file, line, offset); + var definitions = compilerService.languageService.getTypeDefinitionAtPosition(file, position); if (!definitions) { return undefined; } - return definitions.map(function (def) { - var defScriptInfo = project.getScriptInfo(def.fileName); - return { - file: def.fileName, - start: defScriptInfo.positionToLineOffset(def.textSpan.start), - end: defScriptInfo.positionToLineOffset(ts.textSpanEnd(def.textSpan)) - }; - }); + return definitions.map(function (def) { return ({ + file: def.fileName, + start: compilerService.host.positionToLineOffset(def.fileName, def.textSpan.start), + end: compilerService.host.positionToLineOffset(def.fileName, ts.textSpanEnd(def.textSpan)) + }); }); }; - Session.prototype.getOccurrences = function (args) { - var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, scriptInfo); - var occurrences = project.getLanguageService().getOccurrencesAtPosition(file, position); + Session.prototype.getOccurrences = function (line, offset, fileName) { + fileName = ts.normalizePath(fileName); + var project = this.projectService.getProjectForFile(fileName); + if (!project || project.languageServiceDiabled) { + throw Errors.NoProject; + } + var compilerService = project.compilerService; + var position = compilerService.host.lineOffsetToPosition(fileName, line, offset); + var occurrences = compilerService.languageService.getOccurrencesAtPosition(fileName, position); if (!occurrences) { return undefined; } return occurrences.map(function (occurrence) { var fileName = occurrence.fileName, isWriteAccess = occurrence.isWriteAccess, textSpan = occurrence.textSpan; - var scriptInfo = project.getScriptInfo(fileName); - var start = scriptInfo.positionToLineOffset(textSpan.start); - var end = scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan)); + var start = compilerService.host.positionToLineOffset(fileName, textSpan.start); + var end = compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(textSpan)); return { start: start, end: end, @@ -54415,142 +50157,115 @@ var ts; }; }); }; + Session.prototype.getDiagnosticsWorker = function (args, selector) { + var file = ts.normalizePath(args.file); + var project = this.projectService.getProjectForFile(file); + if (!project) { + throw Errors.NoProject; + } + if (project.languageServiceDiabled) { + throw Errors.ProjectLanguageServiceDisabled; + } + var diagnostics = selector(project, file); + return ts.map(diagnostics, function (originalDiagnostic) { return formatDiag(file, project, originalDiagnostic); }); + }; Session.prototype.getSyntacticDiagnosticsSync = function (args) { - return this.getDiagnosticsWorker(args, function (project, file) { return project.getLanguageService().getSyntacticDiagnostics(file); }, args.includeLinePosition); + return this.getDiagnosticsWorker(args, function (project, file) { return project.compilerService.languageService.getSyntacticDiagnostics(file); }); }; Session.prototype.getSemanticDiagnosticsSync = function (args) { - return this.getDiagnosticsWorker(args, function (project, file) { return project.getLanguageService().getSemanticDiagnostics(file); }, args.includeLinePosition); + return this.getDiagnosticsWorker(args, function (project, file) { return project.compilerService.languageService.getSemanticDiagnostics(file); }); }; - Session.prototype.getDocumentHighlights = function (args, simplifiedResult) { - var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, scriptInfo); - var documentHighlights = project.getLanguageService().getDocumentHighlights(file, position, args.filesToSearch); + Session.prototype.getDocumentHighlights = function (line, offset, fileName, filesToSearch) { + fileName = ts.normalizePath(fileName); + var project = this.projectService.getProjectForFile(fileName); + if (!project || project.languageServiceDiabled) { + throw Errors.NoProject; + } + var compilerService = project.compilerService; + var position = compilerService.host.lineOffsetToPosition(fileName, line, offset); + var documentHighlights = compilerService.languageService.getDocumentHighlights(fileName, position, filesToSearch); if (!documentHighlights) { return undefined; } - if (simplifiedResult) { - return documentHighlights.map(convertToDocumentHighlightsItem); - } - else { - return documentHighlights; - } + return documentHighlights.map(convertToDocumentHighlightsItem); function convertToDocumentHighlightsItem(documentHighlights) { var fileName = documentHighlights.fileName, highlightSpans = documentHighlights.highlightSpans; - var scriptInfo = project.getScriptInfo(fileName); return { file: fileName, highlightSpans: highlightSpans.map(convertHighlightSpan) }; function convertHighlightSpan(highlightSpan) { var textSpan = highlightSpan.textSpan, kind = highlightSpan.kind; - var start = scriptInfo.positionToLineOffset(textSpan.start); - var end = scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan)); + var start = compilerService.host.positionToLineOffset(fileName, textSpan.start); + var end = compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(textSpan)); return { start: start, end: end, kind: kind }; } } }; - Session.prototype.setCompilerOptionsForInferredProjects = function (args) { - this.projectService.setCompilerOptionsForInferredProjects(args.options); - }; - Session.prototype.getProjectInfo = function (args) { - return this.getProjectInfoWorker(args.file, args.projectFileName, args.needFileNameList); - }; - Session.prototype.getProjectInfoWorker = function (uncheckedFileName, projectFileName, needFileNameList) { - var project = this.getFileAndProjectWorker(uncheckedFileName, projectFileName, true, true).project; + Session.prototype.getProjectInfo = function (fileName, needFileNameList) { + fileName = ts.normalizePath(fileName); + var project = this.projectService.getProjectForFile(fileName); + if (!project) { + throw Errors.NoProject; + } var projectInfo = { - configFileName: project.getProjectName(), - languageServiceDisabled: !project.languageServiceEnabled, - fileNames: needFileNameList ? project.getFileNames() : undefined + configFileName: project.projectFilename, + languageServiceDisabled: project.languageServiceDiabled }; + if (needFileNameList) { + projectInfo.fileNames = project.getFileNames(); + } return projectInfo; }; - Session.prototype.getRenameInfo = function (args) { - var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, scriptInfo); - return project.getLanguageService().getRenameInfo(file, position); - }; - Session.prototype.getProjects = function (args) { - var projects; - if (args.projectFileName) { - var project = this.getProject(args.projectFileName); - if (project) { - projects = [project]; - } + Session.prototype.getRenameLocations = function (line, offset, fileName, findInComments, findInStrings) { + var file = ts.normalizePath(fileName); + var info = this.projectService.getScriptInfo(file); + var projects = this.projectService.findReferencingProjects(info); + var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; }); + if (projectsWithLanguageServiceEnabeld.length === 0) { + throw Errors.NoProject; } - else { - var scriptInfo = this.projectService.getScriptInfo(args.file); - projects = scriptInfo.containingProjects; + var defaultProject = projectsWithLanguageServiceEnabeld[0]; + var defaultProjectCompilerService = defaultProject.compilerService; + var position = defaultProjectCompilerService.host.lineOffsetToPosition(file, line, offset); + var renameInfo = defaultProjectCompilerService.languageService.getRenameInfo(file, position); + if (!renameInfo) { + return undefined; } - projects = ts.filter(projects, function (p) { return p.languageServiceEnabled; }); - if (!projects || !projects.length) { - return server.Errors.ThrowNoProject(); + if (!renameInfo.canRename) { + return { + info: renameInfo, + locs: [] + }; } - return projects; - }; - Session.prototype.getRenameLocations = function (args, simplifiedResult) { - var file = server.toNormalizedPath(args.file); - var info = this.projectService.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, info); - var projects = this.getProjects(args); - if (simplifiedResult) { - var defaultProject = projects[0]; - var renameInfo = defaultProject.getLanguageService().getRenameInfo(file, position); - if (!renameInfo) { - return undefined; + var fileSpans = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) { + var compilerService = project.compilerService; + var renameLocations = compilerService.languageService.findRenameLocations(file, position, findInStrings, findInComments); + if (!renameLocations) { + return []; } - if (!renameInfo.canRename) { - return { - info: renameInfo, - locs: [] - }; - } - var fileSpans = server.combineProjectOutput(projects, function (project) { - var renameLocations = project.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); - if (!renameLocations) { - return []; + return renameLocations.map(function (location) { return ({ + file: location.fileName, + start: compilerService.host.positionToLineOffset(location.fileName, location.textSpan.start), + end: compilerService.host.positionToLineOffset(location.fileName, ts.textSpanEnd(location.textSpan)) + }); }); + }, compareRenameLocation, function (a, b) { return a.file === b.file && a.start.line === b.start.line && a.start.offset === b.start.offset; }); + var locs = fileSpans.reduce(function (accum, cur) { + var curFileAccum; + if (accum.length > 0) { + curFileAccum = accum[accum.length - 1]; + if (curFileAccum.file !== cur.file) { + curFileAccum = undefined; } - return renameLocations.map(function (location) { - var locationScriptInfo = project.getScriptInfo(location.fileName); - return { - file: location.fileName, - start: locationScriptInfo.positionToLineOffset(location.textSpan.start), - end: locationScriptInfo.positionToLineOffset(ts.textSpanEnd(location.textSpan)) - }; - }); - }, compareRenameLocation, function (a, b) { return a.file === b.file && a.start.line === b.start.line && a.start.offset === b.start.offset; }); - var locs = fileSpans.reduce(function (accum, cur) { - var curFileAccum; - if (accum.length > 0) { - curFileAccum = accum[accum.length - 1]; - if (curFileAccum.file !== cur.file) { - curFileAccum = undefined; - } - } - if (!curFileAccum) { - curFileAccum = { file: cur.file, locs: [] }; - accum.push(curFileAccum); - } - curFileAccum.locs.push({ start: cur.start, end: cur.end }); - return accum; - }, []); - return { info: renameInfo, locs: locs }; - } - else { - return server.combineProjectOutput(projects, function (p) { return p.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); }, undefined, renameLocationIsEqualTo); - } - function renameLocationIsEqualTo(a, b) { - if (a === b) { - return true; } - if (!a || !b) { - return false; + if (!curFileAccum) { + curFileAccum = { file: cur.file, locs: [] }; + accum.push(curFileAccum); } - return a.fileName === b.fileName && - a.textSpan.start === b.textSpan.start && - a.textSpan.length === b.textSpan.length; - } + curFileAccum.locs.push({ start: cur.start, end: cur.end }); + return accum; + }, []); + return { info: renameInfo, locs: locs }; function compareRenameLocation(a, b) { if (a.file < b.file) { return -1; @@ -54571,51 +50286,51 @@ var ts; } } }; - Session.prototype.getReferences = function (args, simplifiedResult) { - var file = server.toNormalizedPath(args.file); - var projects = this.getProjects(args); - var defaultProject = projects[0]; - var scriptInfo = defaultProject.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, scriptInfo); - if (simplifiedResult) { - var nameInfo = defaultProject.getLanguageService().getQuickInfoAtPosition(file, position); - if (!nameInfo) { - return undefined; + Session.prototype.getReferences = function (line, offset, fileName) { + var file = ts.normalizePath(fileName); + var info = this.projectService.getScriptInfo(file); + var projects = this.projectService.findReferencingProjects(info); + var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; }); + if (projectsWithLanguageServiceEnabeld.length === 0) { + throw Errors.NoProject; + } + var defaultProject = projectsWithLanguageServiceEnabeld[0]; + var position = defaultProject.compilerService.host.lineOffsetToPosition(file, line, offset); + var nameInfo = defaultProject.compilerService.languageService.getQuickInfoAtPosition(file, position); + if (!nameInfo) { + return undefined; + } + var displayString = ts.displayPartsToString(nameInfo.displayParts); + var nameSpan = nameInfo.textSpan; + var nameColStart = defaultProject.compilerService.host.positionToLineOffset(file, nameSpan.start).offset; + var nameText = defaultProject.compilerService.host.getScriptSnapshot(file).getText(nameSpan.start, ts.textSpanEnd(nameSpan)); + var refs = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) { + var compilerService = project.compilerService; + var references = compilerService.languageService.getReferencesAtPosition(file, position); + if (!references) { + return []; } - var displayString = ts.displayPartsToString(nameInfo.displayParts); - var nameSpan = nameInfo.textSpan; - var nameColStart = scriptInfo.positionToLineOffset(nameSpan.start).offset; - var nameText = scriptInfo.snap().getText(nameSpan.start, ts.textSpanEnd(nameSpan)); - var refs = server.combineProjectOutput(projects, function (project) { - var references = project.getLanguageService().getReferencesAtPosition(file, position); - if (!references) { - return []; - } - return references.map(function (ref) { - var refScriptInfo = project.getScriptInfo(ref.fileName); - var start = refScriptInfo.positionToLineOffset(ref.textSpan.start); - var refLineSpan = refScriptInfo.lineToTextSpan(start.line - 1); - var lineText = refScriptInfo.snap().getText(refLineSpan.start, ts.textSpanEnd(refLineSpan)).replace(/\r|\n/g, ""); - return { - file: ref.fileName, - start: start, - lineText: lineText, - end: refScriptInfo.positionToLineOffset(ts.textSpanEnd(ref.textSpan)), - isWriteAccess: ref.isWriteAccess, - isDefinition: ref.isDefinition - }; - }); - }, compareFileStart, areReferencesResponseItemsForTheSameLocation); - return { - refs: refs, - symbolName: nameText, - symbolStartOffset: nameColStart, - symbolDisplayString: displayString - }; - } - else { - return server.combineProjectOutput(projects, function (project) { return project.getLanguageService().findReferences(file, position); }, undefined, undefined); - } + return references.map(function (ref) { + var start = compilerService.host.positionToLineOffset(ref.fileName, ref.textSpan.start); + var refLineSpan = compilerService.host.lineToTextSpan(ref.fileName, start.line - 1); + var snap = compilerService.host.getScriptSnapshot(ref.fileName); + var lineText = snap.getText(refLineSpan.start, ts.textSpanEnd(refLineSpan)).replace(/\r|\n/g, ""); + return { + file: ref.fileName, + start: start, + lineText: lineText, + end: compilerService.host.positionToLineOffset(ref.fileName, ts.textSpanEnd(ref.textSpan)), + isWriteAccess: ref.isWriteAccess, + isDefinition: ref.isDefinition + }; + }); + }, compareFileStart, areReferencesResponseItemsForTheSameLocation); + return { + refs: refs, + symbolName: nameText, + symbolStartOffset: nameColStart, + symbolDisplayString: displayString + }; function areReferencesResponseItemsForTheSameLocation(a, b) { if (a && b) { return a.file === b.file && @@ -54626,152 +50341,102 @@ var ts; } }; Session.prototype.openClientFile = function (fileName, fileContent, scriptKind) { - var _a = this.projectService.openClientFileWithNormalizedPath(fileName, fileContent, scriptKind), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors; + var file = ts.normalizePath(fileName); + var _a = this.projectService.openClientFile(file, fileContent, scriptKind), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors; if (configFileErrors) { this.configFileDiagnosticEvent(fileName, configFileName, configFileErrors); } }; - Session.prototype.getPosition = function (args, scriptInfo) { - return args.position !== undefined ? args.position : scriptInfo.lineOffsetToPosition(args.line, args.offset); - }; - Session.prototype.getFileAndProject = function (args, errorOnMissingProject) { - if (errorOnMissingProject === void 0) { errorOnMissingProject = true; } - return this.getFileAndProjectWorker(args.file, args.projectFileName, true, errorOnMissingProject); - }; - Session.prototype.getFileAndProjectWithoutRefreshingInferredProjects = function (args, errorOnMissingProject) { - if (errorOnMissingProject === void 0) { errorOnMissingProject = true; } - return this.getFileAndProjectWorker(args.file, args.projectFileName, false, errorOnMissingProject); - }; - Session.prototype.getFileAndProjectWorker = function (uncheckedFileName, projectFileName, refreshInferredProjects, errorOnMissingProject) { - var file = server.toNormalizedPath(uncheckedFileName); - var project = this.getProject(projectFileName) || this.projectService.getDefaultProjectForFile(file, refreshInferredProjects); - if (!project && errorOnMissingProject) { - return server.Errors.ThrowNoProject(); + Session.prototype.getQuickInfo = function (line, offset, fileName) { + var file = ts.normalizePath(fileName); + var project = this.projectService.getProjectForFile(file); + if (!project || project.languageServiceDiabled) { + throw Errors.NoProject; } - return { file: file, project: project }; - }; - Session.prototype.getOutliningSpans = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - return project.getLanguageService(false).getOutliningSpans(file); - }; - Session.prototype.getTodoComments = function (args) { - var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - return project.getLanguageService().getTodoComments(file, args.descriptors); - }; - Session.prototype.getDocCommentTemplate = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, scriptInfo); - return project.getLanguageService(false).getDocCommentTemplateAtPosition(file, position); - }; - Session.prototype.getIndentation = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); - var options = args.options || this.projectService.getFormatCodeOptions(file); - var indentation = project.getLanguageService(false).getIndentationAtPosition(file, position, options); - return { position: position, indentation: indentation }; - }; - Session.prototype.getBreakpointStatement = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); - return project.getLanguageService(false).getBreakpointStatementAtPosition(file, position); - }; - Session.prototype.getNameOrDottedNameSpan = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); - return project.getLanguageService(false).getNameOrDottedNameSpan(file, position, position); - }; - Session.prototype.isValidBraceCompletion = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); - return project.getLanguageService(false).isValidBraceCompletionAtPosition(file, position, args.openingBrace.charCodeAt(0)); - }; - Session.prototype.getQuickInfoWorker = function (args, simplifiedResult) { - var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var quickInfo = project.getLanguageService().getQuickInfoAtPosition(file, this.getPosition(args, scriptInfo)); + var compilerService = project.compilerService; + var position = compilerService.host.lineOffsetToPosition(file, line, offset); + var quickInfo = compilerService.languageService.getQuickInfoAtPosition(file, position); if (!quickInfo) { return undefined; } - if (simplifiedResult) { - var displayString = ts.displayPartsToString(quickInfo.displayParts); - var docString = ts.displayPartsToString(quickInfo.documentation); - return { - kind: quickInfo.kind, - kindModifiers: quickInfo.kindModifiers, - start: scriptInfo.positionToLineOffset(quickInfo.textSpan.start), - end: scriptInfo.positionToLineOffset(ts.textSpanEnd(quickInfo.textSpan)), - displayString: displayString, - documentation: docString - }; - } - else { - return quickInfo; - } + var displayString = ts.displayPartsToString(quickInfo.displayParts); + var docString = ts.displayPartsToString(quickInfo.documentation); + return { + kind: quickInfo.kind, + kindModifiers: quickInfo.kindModifiers, + start: compilerService.host.positionToLineOffset(file, quickInfo.textSpan.start), + end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(quickInfo.textSpan)), + displayString: displayString, + documentation: docString + }; }; - Session.prototype.getFormattingEditsForRange = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var startPosition = scriptInfo.lineOffsetToPosition(args.line, args.offset); - var endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); - var edits = project.getLanguageService(false).getFormattingEditsForRange(file, startPosition, endPosition, this.projectService.getFormatCodeOptions(file)); + Session.prototype.getFormattingEditsForRange = function (line, offset, endLine, endOffset, fileName) { + var file = ts.normalizePath(fileName); + var project = this.projectService.getProjectForFile(file); + if (!project || project.languageServiceDiabled) { + throw Errors.NoProject; + } + var compilerService = project.compilerService; + var startPosition = compilerService.host.lineOffsetToPosition(file, line, offset); + var endPosition = compilerService.host.lineOffsetToPosition(file, endLine, endOffset); + var edits = compilerService.languageService.getFormattingEditsForRange(file, startPosition, endPosition, this.projectService.getFormatCodeOptions(file)); if (!edits) { return undefined; } return edits.map(function (edit) { return { - start: scriptInfo.positionToLineOffset(edit.span.start), - end: scriptInfo.positionToLineOffset(ts.textSpanEnd(edit.span)), + start: compilerService.host.positionToLineOffset(file, edit.span.start), + end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(edit.span)), newText: edit.newText ? edit.newText : "" }; }); }; - Session.prototype.getFormattingEditsForRangeFull = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var options = args.options || this.projectService.getFormatCodeOptions(file); - return project.getLanguageService(false).getFormattingEditsForRange(file, args.position, args.endPosition, options); - }; - Session.prototype.getFormattingEditsForDocumentFull = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var options = args.options || this.projectService.getFormatCodeOptions(file); - return project.getLanguageService(false).getFormattingEditsForDocument(file, options); - }; - Session.prototype.getFormattingEditsAfterKeystrokeFull = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var options = args.options || this.projectService.getFormatCodeOptions(file); - return project.getLanguageService(false).getFormattingEditsAfterKeystroke(file, args.position, args.key, options); - }; - Session.prototype.getFormattingEditsAfterKeystroke = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var position = scriptInfo.lineOffsetToPosition(args.line, args.offset); + Session.prototype.getFormattingEditsAfterKeystroke = function (line, offset, key, fileName) { + var file = ts.normalizePath(fileName); + var project = this.projectService.getProjectForFile(file); + if (!project || project.languageServiceDiabled) { + throw Errors.NoProject; + } + var compilerService = project.compilerService; + var position = compilerService.host.lineOffsetToPosition(file, line, offset); var formatOptions = this.projectService.getFormatCodeOptions(file); - var edits = project.getLanguageService(false).getFormattingEditsAfterKeystroke(file, position, args.key, formatOptions); - if ((args.key == "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) { - var lineInfo = scriptInfo.getLineInfo(args.line); - if (lineInfo && (lineInfo.leaf) && (lineInfo.leaf.text)) { - var lineText = lineInfo.leaf.text; - if (lineText.search("\\S") < 0) { - var preferredIndent = project.getLanguageService(false).getIndentationAtPosition(file, position, formatOptions); - var hasIndent = 0; - var i = void 0, len = void 0; - for (i = 0, len = lineText.length; i < len; i++) { - if (lineText.charAt(i) == " ") { - hasIndent++; + var edits = compilerService.languageService.getFormattingEditsAfterKeystroke(file, position, key, formatOptions); + if ((key == "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) { + var scriptInfo = compilerService.host.getScriptInfo(file); + if (scriptInfo) { + var lineInfo = scriptInfo.getLineInfo(line); + if (lineInfo && (lineInfo.leaf) && (lineInfo.leaf.text)) { + var lineText = lineInfo.leaf.text; + if (lineText.search("\\S") < 0) { + var editorOptions = { + BaseIndentSize: formatOptions.BaseIndentSize, + IndentSize: formatOptions.IndentSize, + TabSize: formatOptions.TabSize, + NewLineCharacter: formatOptions.NewLineCharacter, + ConvertTabsToSpaces: formatOptions.ConvertTabsToSpaces, + IndentStyle: ts.IndentStyle.Smart + }; + var preferredIndent = compilerService.languageService.getIndentationAtPosition(file, position, editorOptions); + var hasIndent = 0; + var i = void 0, len = void 0; + for (i = 0, len = lineText.length; i < len; i++) { + if (lineText.charAt(i) == " ") { + hasIndent++; + } + else if (lineText.charAt(i) == "\t") { + hasIndent += editorOptions.TabSize; + } + else { + break; + } } - else if (lineText.charAt(i) == "\t") { - hasIndent += formatOptions.tabSize; + if (preferredIndent !== hasIndent) { + var firstNoWhiteSpacePosition = lineInfo.offset + i; + edits.push({ + span: ts.createTextSpanFromBounds(lineInfo.offset, firstNoWhiteSpacePosition), + newText: generateIndentString(preferredIndent, editorOptions) + }); } - else { - break; - } - } - if (preferredIndent !== hasIndent) { - var firstNoWhiteSpacePosition = lineInfo.offset + i; - edits.push({ - span: ts.createTextSpanFromBounds(lineInfo.offset, firstNoWhiteSpacePosition), - newText: ts.formatting.getIndentationString(preferredIndent, formatOptions) - }); } } } @@ -54781,111 +50446,81 @@ var ts; } return edits.map(function (edit) { return { - start: scriptInfo.positionToLineOffset(edit.span.start), - end: scriptInfo.positionToLineOffset(ts.textSpanEnd(edit.span)), + start: compilerService.host.positionToLineOffset(file, edit.span.start), + end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(edit.span)), newText: edit.newText ? edit.newText : "" }; }); }; - Session.prototype.getCompletions = function (args, simplifiedResult) { - var prefix = args.prefix || ""; - var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, scriptInfo); - var completions = project.getLanguageService().getCompletionsAtPosition(file, position); + Session.prototype.getCompletions = function (line, offset, prefix, fileName) { + if (!prefix) { + prefix = ""; + } + var file = ts.normalizePath(fileName); + var project = this.projectService.getProjectForFile(file); + if (!project || project.languageServiceDiabled) { + throw Errors.NoProject; + } + var compilerService = project.compilerService; + var position = compilerService.host.lineOffsetToPosition(file, line, offset); + var completions = compilerService.languageService.getCompletionsAtPosition(file, position); if (!completions) { return undefined; } - if (simplifiedResult) { - return completions.entries.reduce(function (result, entry) { - if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) { - var name_44 = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan; - var convertedSpan = undefined; - if (replacementSpan) { - convertedSpan = { - start: scriptInfo.positionToLineOffset(replacementSpan.start), - end: scriptInfo.positionToLineOffset(replacementSpan.start + replacementSpan.length) - }; - } - result.push({ name: name_44, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan }); - } - return result; - }, []).sort(function (a, b) { return a.name.localeCompare(b.name); }); - } - else { - return completions; - } + return completions.entries.reduce(function (result, entry) { + if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) { + result.push(entry); + } + return result; + }, []).sort(function (a, b) { return a.name.localeCompare(b.name); }); }; - Session.prototype.getCompletionEntryDetails = function (args) { - var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, scriptInfo); - return args.entryNames.reduce(function (accum, entryName) { - var details = project.getLanguageService().getCompletionEntryDetails(file, position, entryName); + Session.prototype.getCompletionEntryDetails = function (line, offset, entryNames, fileName) { + var file = ts.normalizePath(fileName); + var project = this.projectService.getProjectForFile(file); + if (!project || project.languageServiceDiabled) { + throw Errors.NoProject; + } + var compilerService = project.compilerService; + var position = compilerService.host.lineOffsetToPosition(file, line, offset); + return entryNames.reduce(function (accum, entryName) { + var details = compilerService.languageService.getCompletionEntryDetails(file, position, entryName); if (details) { accum.push(details); } return accum; }, []); }; - Session.prototype.getCompileOnSaveAffectedFileList = function (args) { - var info = this.projectService.getScriptInfo(args.file); - var result = []; - if (!info) { - return []; + Session.prototype.getSignatureHelpItems = function (line, offset, fileName) { + var file = ts.normalizePath(fileName); + var project = this.projectService.getProjectForFile(file); + if (!project || project.languageServiceDiabled) { + throw Errors.NoProject; } - var projectsToSearch = args.projectFileName ? [this.projectService.findProject(args.projectFileName)] : info.containingProjects; - for (var _i = 0, projectsToSearch_1 = projectsToSearch; _i < projectsToSearch_1.length; _i++) { - var project = projectsToSearch_1[_i]; - if (project.compileOnSaveEnabled && project.languageServiceEnabled) { - result.push({ - projectFileName: project.getProjectName(), - fileNames: project.getCompileOnSaveAffectedFileList(info) - }); - } - } - return result; - }; - Session.prototype.emitFile = function (args) { - var _this = this; - var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - if (!project) { - server.Errors.ThrowNoProject(); - } - var scriptInfo = project.getScriptInfo(file); - return project.builder.emitFile(scriptInfo, function (path, data, writeByteOrderMark) { return _this.host.writeFile(path, data, writeByteOrderMark); }); - }; - Session.prototype.getSignatureHelpItems = function (args, simplifiedResult) { - var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, scriptInfo); - var helpItems = project.getLanguageService().getSignatureHelpItems(file, position); + var compilerService = project.compilerService; + var position = compilerService.host.lineOffsetToPosition(file, line, offset); + var helpItems = compilerService.languageService.getSignatureHelpItems(file, position); if (!helpItems) { return undefined; } - if (simplifiedResult) { - var span = helpItems.applicableSpan; - return { - items: helpItems.items, - applicableSpan: { - start: scriptInfo.positionToLineOffset(span.start), - end: scriptInfo.positionToLineOffset(span.start + span.length) - }, - selectedItemIndex: helpItems.selectedItemIndex, - argumentIndex: helpItems.argumentIndex, - argumentCount: helpItems.argumentCount - }; - } - else { - return helpItems; - } + var span = helpItems.applicableSpan; + var result = { + items: helpItems.items, + applicableSpan: { + start: compilerService.host.positionToLineOffset(file, span.start), + end: compilerService.host.positionToLineOffset(file, span.start + span.length) + }, + selectedItemIndex: helpItems.selectedItemIndex, + argumentIndex: helpItems.argumentIndex, + argumentCount: helpItems.argumentCount + }; + return result; }; Session.prototype.getDiagnostics = function (delay, fileNames) { var _this = this; - var checkList = fileNames.reduce(function (accum, uncheckedFileName) { - var fileName = server.toNormalizedPath(uncheckedFileName); - var project = _this.projectService.getDefaultProjectForFile(fileName, true); - if (project) { + var checkList = fileNames.reduce(function (accum, fileName) { + fileName = ts.normalizePath(fileName); + var project = _this.projectService.getProjectForFile(fileName); + if (project && !project.languageServiceDiabled) { accum.push({ fileName: fileName, project: project }); } return accum; @@ -54894,34 +50529,40 @@ var ts; this.updateErrorCheck(checkList, this.changeSeq, function (n) { return n === _this.changeSeq; }, delay); } }; - Session.prototype.change = function (args) { + Session.prototype.change = function (line, offset, endLine, endOffset, insertString, fileName) { var _this = this; - var _a = this.getFileAndProject(args, false), file = _a.file, project = _a.project; - if (project) { - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var start = scriptInfo.lineOffsetToPosition(args.line, args.offset); - var end = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + var file = ts.normalizePath(fileName); + var project = this.projectService.getProjectForFile(file); + if (project && !project.languageServiceDiabled) { + var compilerService = project.compilerService; + var start = compilerService.host.lineOffsetToPosition(file, line, offset); + var end = compilerService.host.lineOffsetToPosition(file, endLine, endOffset); if (start >= 0) { - scriptInfo.editContent(start, end, args.insertString); + compilerService.host.editScript(file, start, end, insertString); this.changeSeq++; } this.updateProjectStructure(this.changeSeq, function (n) { return n === _this.changeSeq; }); } }; - Session.prototype.reload = function (args, reqSeq) { - var file = server.toNormalizedPath(args.file); - var project = this.projectService.getDefaultProjectForFile(file, true); - if (project) { + Session.prototype.reload = function (fileName, tempFileName, reqSeq) { + var _this = this; + if (reqSeq === void 0) { reqSeq = 0; } + var file = ts.normalizePath(fileName); + var tmpfile = ts.normalizePath(tempFileName); + var project = this.projectService.getProjectForFile(file); + if (project && !project.languageServiceDiabled) { this.changeSeq++; - if (project.reloadScript(file)) { - this.output(undefined, CommandNames.Reload, reqSeq); - } + project.compilerService.host.reloadScript(file, tmpfile, function () { + _this.output(undefined, CommandNames.Reload, reqSeq); + }); } }; Session.prototype.saveToTmp = function (fileName, tempFileName) { - var scriptInfo = this.projectService.getScriptInfo(fileName); - if (scriptInfo) { - scriptInfo.saveTo(tempFileName); + var file = ts.normalizePath(fileName); + var tmpfile = ts.normalizePath(tempFileName); + var project = this.projectService.getProjectForFile(file); + if (project && !project.languageServiceDiabled) { + project.compilerService.host.saveTo(file, tmpfile); } }; Session.prototype.closeClientFile = function (fileName) { @@ -54931,90 +50572,77 @@ var ts; var file = ts.normalizePath(fileName); this.projectService.closeClientFile(file); }; - Session.prototype.decorateNavigationBarItem = function (project, fileName, items) { + Session.prototype.decorateNavigationBarItem = function (project, fileName, items, lineIndex) { var _this = this; if (!items) { return undefined; } - var scriptInfo = project.getScriptInfoForNormalizedPath(fileName); + var compilerService = project.compilerService; return items.map(function (item) { return ({ text: item.text, kind: item.kind, kindModifiers: item.kindModifiers, spans: item.spans.map(function (span) { return ({ - start: scriptInfo.positionToLineOffset(span.start), - end: scriptInfo.positionToLineOffset(ts.textSpanEnd(span)) + start: compilerService.host.positionToLineOffset(fileName, span.start, lineIndex), + end: compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(span), lineIndex) }); }), - childItems: _this.decorateNavigationBarItem(project, fileName, item.childItems), + childItems: _this.decorateNavigationBarItem(project, fileName, item.childItems, lineIndex), indent: item.indent }); }); }; - Session.prototype.getNavigationBarItems = function (args, simplifiedResult) { - var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var items = project.getLanguageService().getNavigationBarItems(file); + Session.prototype.getNavigationBarItems = function (fileName) { + var file = ts.normalizePath(fileName); + var project = this.projectService.getProjectForFile(file); + if (!project || project.languageServiceDiabled) { + throw Errors.NoProject; + } + var compilerService = project.compilerService; + var items = compilerService.languageService.getNavigationBarItems(file); if (!items) { return undefined; } - return simplifiedResult - ? this.decorateNavigationBarItem(project, file, items) - : items; + return this.decorateNavigationBarItem(project, fileName, items, compilerService.host.getLineIndex(fileName)); }; - Session.prototype.getNavigateToItems = function (args, simplifiedResult) { - var projects = this.getProjects(args); - if (simplifiedResult) { - return server.combineProjectOutput(projects, function (project) { - var navItems = project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, project.isJsOnlyProject()); - if (!navItems) { - return []; + Session.prototype.getNavigateToItems = function (searchValue, fileName, maxResultCount) { + var file = ts.normalizePath(fileName); + var info = this.projectService.getScriptInfo(file); + var projects = this.projectService.findReferencingProjects(info); + var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; }); + if (projectsWithLanguageServiceEnabeld.length === 0) { + throw Errors.NoProject; + } + var allNavToItems = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) { + var compilerService = project.compilerService; + var navItems = compilerService.languageService.getNavigateToItems(searchValue, maxResultCount); + if (!navItems) { + return []; + } + return navItems.map(function (navItem) { + var start = compilerService.host.positionToLineOffset(navItem.fileName, navItem.textSpan.start); + var end = compilerService.host.positionToLineOffset(navItem.fileName, ts.textSpanEnd(navItem.textSpan)); + var bakedItem = { + name: navItem.name, + kind: navItem.kind, + file: navItem.fileName, + start: start, + end: end + }; + if (navItem.kindModifiers && (navItem.kindModifiers !== "")) { + bakedItem.kindModifiers = navItem.kindModifiers; } - return navItems.map(function (navItem) { - var scriptInfo = project.getScriptInfo(navItem.fileName); - var start = scriptInfo.positionToLineOffset(navItem.textSpan.start); - var end = scriptInfo.positionToLineOffset(ts.textSpanEnd(navItem.textSpan)); - var bakedItem = { - name: navItem.name, - kind: navItem.kind, - file: navItem.fileName, - start: start, - end: end - }; - if (navItem.kindModifiers && (navItem.kindModifiers !== "")) { - bakedItem.kindModifiers = navItem.kindModifiers; - } - if (navItem.matchKind !== "none") { - bakedItem.matchKind = navItem.matchKind; - } - if (navItem.containerName && (navItem.containerName.length > 0)) { - bakedItem.containerName = navItem.containerName; - } - if (navItem.containerKind && (navItem.containerKind.length > 0)) { - bakedItem.containerKind = navItem.containerKind; - } - return bakedItem; - }); - }, undefined, areNavToItemsForTheSameLocation); - } - else { - return server.combineProjectOutput(projects, function (project) { return project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, project.isJsOnlyProject()); }, undefined, navigateToItemIsEqualTo); - } - function navigateToItemIsEqualTo(a, b) { - if (a === b) { - return true; - } - if (!a || !b) { - return false; - } - return a.containerKind === b.containerKind && - a.containerName === b.containerName && - a.fileName === b.fileName && - a.isCaseSensitive === b.isCaseSensitive && - a.kind === b.kind && - a.kindModifiers === b.containerName && - a.matchKind === b.matchKind && - a.name === b.name && - a.textSpan.start === b.textSpan.start && - a.textSpan.length === b.textSpan.length; - } + if (navItem.matchKind !== "none") { + bakedItem.matchKind = navItem.matchKind; + } + if (navItem.containerName && (navItem.containerName.length > 0)) { + bakedItem.containerName = navItem.containerName; + } + if (navItem.containerKind && (navItem.containerKind.length > 0)) { + bakedItem.containerKind = navItem.containerKind; + } + return bakedItem; + }); + }, undefined, areNavToItemsForTheSameLocation); + return allNavToItems; function areNavToItemsForTheSameLocation(a, b) { if (a && b) { return a.file === b.file && @@ -55024,27 +50652,26 @@ var ts; return false; } }; - Session.prototype.getBraceMatching = function (args, simplifiedResult) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, scriptInfo); - var spans = project.getLanguageService(false).getBraceMatchingAtPosition(file, position); + Session.prototype.getBraceMatching = function (line, offset, fileName) { + var file = ts.normalizePath(fileName); + var project = this.projectService.getProjectForFile(file); + if (!project || project.languageServiceDiabled) { + throw Errors.NoProject; + } + var compilerService = project.compilerService; + var position = compilerService.host.lineOffsetToPosition(file, line, offset); + var spans = compilerService.languageService.getBraceMatchingAtPosition(file, position); if (!spans) { return undefined; } - if (simplifiedResult) { - return spans.map(function (span) { return ({ - start: scriptInfo.positionToLineOffset(span.start), - end: scriptInfo.positionToLineOffset(span.start + span.length) - }); }); - } - else { - return spans; - } + return spans.map(function (span) { return ({ + start: compilerService.host.positionToLineOffset(file, span.start), + end: compilerService.host.positionToLineOffset(file, span.start + span.length) + }); }); }; Session.prototype.getDiagnosticsForProject = function (delay, fileName) { var _this = this; - var _a = this.getProjectInfoWorker(fileName, undefined, true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled; + var _a = this.getProjectInfo(fileName, true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled; if (languageServiceDisabled) { return; } @@ -55053,8 +50680,8 @@ var ts; var mediumPriorityFiles = []; var lowPriorityFiles = []; var veryLowPriorityFiles = []; - var normalizedFileName = server.toNormalizedPath(fileName); - var project = this.projectService.getDefaultProjectForFile(normalizedFileName, true); + var normalizedFileName = ts.normalizePath(fileName); + var project = this.projectService.getProjectForFile(normalizedFileName); for (var _i = 0, fileNamesInProject_1 = fileNamesInProject; _i < fileNamesInProject_1.length; _i++) { var fileNameInProject = fileNamesInProject_1[_i]; if (this.getCanonicalFileName(fileNameInProject) == this.getCanonicalFileName(fileName)) @@ -55073,7 +50700,10 @@ var ts; } fileNamesInProject = highPriorityFiles.concat(mediumPriorityFiles).concat(lowPriorityFiles).concat(veryLowPriorityFiles); if (fileNamesInProject.length > 0) { - var checkList = fileNamesInProject.map(function (fileName) { return ({ fileName: fileName, project: project }); }); + var checkList = fileNamesInProject.map(function (fileName) { + var normalizedFileName = ts.normalizePath(fileName); + return { fileName: normalizedFileName, project: project }; + }); this.updateErrorCheck(checkList, this.changeSeq, function (n) { return n == _this.changeSeq; }, delay, 200, false); } }; @@ -55083,14 +50713,11 @@ var ts; }; Session.prototype.exit = function () { }; - Session.prototype.notRequired = function () { - return { responseRequired: false }; - }; Session.prototype.requiredResponse = function (response) { return { response: response, responseRequired: true }; }; Session.prototype.addProtocolHandler = function (command, handler) { - if (command in this.handlers) { + if (this.handlers[command]) { throw new Error("Protocol handler already exists for command \"" + command + "\""); } this.handlers[command] = handler; @@ -55101,32 +50728,31 @@ var ts; return handler(request); } else { - this.logger.msg("Unrecognized JSON command: " + JSON.stringify(request), server.Msg.Err); + this.projectService.log("Unrecognized JSON command: " + JSON.stringify(request)); this.output(undefined, CommandNames.Unknown, request.seq, "Unrecognized JSON command: " + request.command); return { responseRequired: false }; } }; Session.prototype.onMessage = function (message) { - this.gcTimer.scheduleCollect(); var start; - if (this.logger.hasLevel(server.LogLevel.requestTime)) { + if (this.logger.isVerbose()) { + this.logger.info("request: " + message); start = this.hrtime(); - if (this.logger.hasLevel(server.LogLevel.verbose)) { - this.logger.info("request: " + message); - } } var request; try { request = JSON.parse(message); var _a = this.executeCommand(request), response = _a.response, responseRequired = _a.responseRequired; - if (this.logger.hasLevel(server.LogLevel.requestTime)) { - var elapsedTime = hrTimeToMilliseconds(this.hrtime(start)).toFixed(4); - if (responseRequired) { - this.logger.perftrc(request.seq + "::" + request.command + ": elapsed time (in milliseconds) " + elapsedTime); - } - else { - this.logger.perftrc(request.seq + "::" + request.command + ": async elapsed time (in milliseconds) " + elapsedTime); + if (this.logger.isVerbose()) { + var elapsed = this.hrtime(start); + var seconds = elapsed[0]; + var nanoseconds = elapsed[1]; + var elapsedMs = ((1e9 * seconds) + nanoseconds) / 1000000.0; + var leader = "Elapsed time (in milliseconds)"; + if (!responseRequired) { + leader = "Async elapsed time (in milliseconds)"; } + this.logger.msg(leader + ": " + elapsedMs.toFixed(4).toString(), "Perf"); } if (response) { this.output(response, request.command, request.seq); @@ -55137,8 +50763,6 @@ var ts; } catch (err) { if (err instanceof ts.OperationCanceledException) { - this.output({ canceled: true }, request.command, request.seq); - return; } this.logError(err, message); this.output(undefined, request ? request.command : CommandNames.Unknown, request ? request.seq : 0, "Error processing request. " + err.message + "\n" + err.stack); @@ -55154,6 +50778,1220 @@ var ts; var server; (function (server) { var lineCollectionCapacity = 4; + function mergeFormatOptions(formatCodeOptions, formatOptions) { + var hasOwnProperty = Object.prototype.hasOwnProperty; + Object.keys(formatOptions).forEach(function (key) { + var codeKey = key.charAt(0).toUpperCase() + key.substring(1); + if (hasOwnProperty.call(formatCodeOptions, codeKey)) { + formatCodeOptions[codeKey] = formatOptions[key]; + } + }); + } + server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; + var ScriptInfo = (function () { + function ScriptInfo(host, fileName, content, isOpen) { + if (isOpen === void 0) { isOpen = false; } + this.host = host; + this.fileName = fileName; + this.content = content; + this.isOpen = isOpen; + this.children = []; + this.formatCodeOptions = ts.clone(CompilerService.getDefaultFormatCodeOptions(this.host)); + this.path = ts.toPath(fileName, host.getCurrentDirectory(), ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames)); + this.svc = ScriptVersionCache.fromString(host, content); + } + ScriptInfo.prototype.setFormatOptions = function (formatOptions) { + if (formatOptions) { + mergeFormatOptions(this.formatCodeOptions, formatOptions); + } + }; + ScriptInfo.prototype.close = function () { + this.isOpen = false; + }; + ScriptInfo.prototype.addChild = function (childInfo) { + this.children.push(childInfo); + }; + ScriptInfo.prototype.snap = function () { + return this.svc.getSnapshot(); + }; + ScriptInfo.prototype.getText = function () { + var snap = this.snap(); + return snap.getText(0, snap.getLength()); + }; + ScriptInfo.prototype.getLineInfo = function (line) { + var snap = this.snap(); + return snap.index.lineNumberToInfo(line); + }; + ScriptInfo.prototype.editContent = function (start, end, newText) { + this.svc.edit(start, end - start, newText); + }; + ScriptInfo.prototype.getTextChangeRangeBetweenVersions = function (startVersion, endVersion) { + return this.svc.getTextChangesBetweenVersions(startVersion, endVersion); + }; + ScriptInfo.prototype.getChangeRange = function (oldSnapshot) { + return this.snap().getChangeRange(oldSnapshot); + }; + return ScriptInfo; + }()); + server.ScriptInfo = ScriptInfo; + var LSHost = (function () { + function LSHost(host, project) { + var _this = this; + this.host = host; + this.project = project; + this.roots = []; + this.getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + this.resolvedModuleNames = ts.createFileMap(); + this.resolvedTypeReferenceDirectives = ts.createFileMap(); + this.filenameToScript = ts.createFileMap(); + this.moduleResolutionHost = { + fileExists: function (fileName) { return _this.fileExists(fileName); }, + readFile: function (fileName) { return _this.host.readFile(fileName); }, + directoryExists: function (directoryName) { return _this.host.directoryExists(directoryName); } + }; + } + LSHost.prototype.resolveNamesWithLocalCache = function (names, containingFile, cache, loader, getResult) { + var path = ts.toPath(containingFile, this.host.getCurrentDirectory(), this.getCanonicalFileName); + var currentResolutionsInFile = cache.get(path); + var newResolutions = {}; + var resolvedModules = []; + var compilerOptions = this.getCompilationSettings(); + for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { + var name_43 = names_2[_i]; + var resolution = ts.lookUp(newResolutions, name_43); + if (!resolution) { + var existingResolution = currentResolutionsInFile && ts.lookUp(currentResolutionsInFile, name_43); + if (moduleResolutionIsValid(existingResolution)) { + resolution = existingResolution; + } + else { + resolution = loader(name_43, containingFile, compilerOptions, this.moduleResolutionHost); + resolution.lastCheckTime = Date.now(); + newResolutions[name_43] = resolution; + } + } + ts.Debug.assert(resolution !== undefined); + resolvedModules.push(getResult(resolution)); + } + cache.set(path, newResolutions); + return resolvedModules; + function moduleResolutionIsValid(resolution) { + if (!resolution) { + return false; + } + if (getResult(resolution)) { + return true; + } + return resolution.failedLookupLocations.length === 0; + } + }; + LSHost.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { + return this.resolveNamesWithLocalCache(typeDirectiveNames, containingFile, this.resolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, function (m) { return m.resolvedTypeReferenceDirective; }); + }; + LSHost.prototype.resolveModuleNames = function (moduleNames, containingFile) { + return this.resolveNamesWithLocalCache(moduleNames, containingFile, this.resolvedModuleNames, ts.resolveModuleName, function (m) { return m.resolvedModule; }); + }; + LSHost.prototype.getDefaultLibFileName = function () { + var nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.host.getExecutingFilePath())); + return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilationSettings)); + }; + LSHost.prototype.getScriptSnapshot = function (filename) { + var scriptInfo = this.getScriptInfo(filename); + if (scriptInfo) { + return scriptInfo.snap(); + } + }; + LSHost.prototype.setCompilationSettings = function (opt) { + this.compilationSettings = opt; + this.resolvedModuleNames.clear(); + this.resolvedTypeReferenceDirectives.clear(); + }; + LSHost.prototype.lineAffectsRefs = function (filename, line) { + var info = this.getScriptInfo(filename); + var lineInfo = info.getLineInfo(line); + if (lineInfo && lineInfo.text) { + var regex = /reference|import|\/\*|\*\//; + return regex.test(lineInfo.text); + } + }; + LSHost.prototype.getCompilationSettings = function () { + return this.compilationSettings; + }; + LSHost.prototype.getScriptFileNames = function () { + return this.roots.map(function (root) { return root.fileName; }); + }; + LSHost.prototype.getScriptKind = function (fileName) { + var info = this.getScriptInfo(fileName); + if (!info) { + return undefined; + } + if (!info.scriptKind) { + info.scriptKind = ts.getScriptKindFromFileName(fileName); + } + return info.scriptKind; + }; + LSHost.prototype.getScriptVersion = function (filename) { + return this.getScriptInfo(filename).svc.latestVersion().toString(); + }; + LSHost.prototype.getCurrentDirectory = function () { + return ""; + }; + LSHost.prototype.getScriptIsOpen = function (filename) { + return this.getScriptInfo(filename).isOpen; + }; + LSHost.prototype.removeReferencedFile = function (info) { + if (!info.isOpen) { + this.filenameToScript.remove(info.path); + this.resolvedModuleNames.remove(info.path); + this.resolvedTypeReferenceDirectives.remove(info.path); + } + }; + LSHost.prototype.getScriptInfo = function (filename) { + var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); + var scriptInfo = this.filenameToScript.get(path); + if (!scriptInfo) { + scriptInfo = this.project.openReferencedFile(filename); + if (scriptInfo) { + this.filenameToScript.set(path, scriptInfo); + } + } + return scriptInfo; + }; + LSHost.prototype.addRoot = function (info) { + if (!this.filenameToScript.contains(info.path)) { + this.filenameToScript.set(info.path, info); + this.roots.push(info); + } + }; + LSHost.prototype.removeRoot = function (info) { + if (this.filenameToScript.contains(info.path)) { + this.filenameToScript.remove(info.path); + this.roots = copyListRemovingItem(info, this.roots); + this.resolvedModuleNames.remove(info.path); + this.resolvedTypeReferenceDirectives.remove(info.path); + } + }; + LSHost.prototype.saveTo = function (filename, tmpfilename) { + var script = this.getScriptInfo(filename); + if (script) { + var snap = script.snap(); + this.host.writeFile(tmpfilename, snap.getText(0, snap.getLength())); + } + }; + LSHost.prototype.reloadScript = function (filename, tmpfilename, cb) { + var script = this.getScriptInfo(filename); + if (script) { + script.svc.reloadFromFile(tmpfilename, cb); + } + }; + LSHost.prototype.editScript = function (filename, start, end, newText) { + var script = this.getScriptInfo(filename); + if (script) { + script.editContent(start, end, newText); + return; + } + throw new Error("No script with name '" + filename + "'"); + }; + LSHost.prototype.resolvePath = function (path) { + var result = this.host.resolvePath(path); + return result; + }; + LSHost.prototype.fileExists = function (path) { + var result = this.host.fileExists(path); + return result; + }; + LSHost.prototype.directoryExists = function (path) { + return this.host.directoryExists(path); + }; + LSHost.prototype.getDirectories = function (path) { + return this.host.getDirectories(path); + }; + LSHost.prototype.lineToTextSpan = function (filename, line) { + var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); + var script = this.filenameToScript.get(path); + var index = script.snap().index; + var lineInfo = index.lineNumberToInfo(line + 1); + var len; + if (lineInfo.leaf) { + len = lineInfo.leaf.text.length; + } + else { + var nextLineInfo = index.lineNumberToInfo(line + 2); + len = nextLineInfo.offset - lineInfo.offset; + } + return ts.createTextSpan(lineInfo.offset, len); + }; + LSHost.prototype.lineOffsetToPosition = function (filename, line, offset) { + var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); + var script = this.filenameToScript.get(path); + var index = script.snap().index; + var lineInfo = index.lineNumberToInfo(line); + return (lineInfo.offset + offset - 1); + }; + LSHost.prototype.positionToLineOffset = function (filename, position, lineIndex) { + lineIndex = lineIndex || this.getLineIndex(filename); + var lineOffset = lineIndex.charOffsetToLineNumberAndPos(position); + return { line: lineOffset.line, offset: lineOffset.offset + 1 }; + }; + LSHost.prototype.getLineIndex = function (filename) { + var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); + var script = this.filenameToScript.get(path); + return script.snap().index; + }; + return LSHost; + }()); + server.LSHost = LSHost; + var Project = (function () { + function Project(projectService, projectOptions, languageServiceDiabled) { + if (languageServiceDiabled === void 0) { languageServiceDiabled = false; } + this.projectService = projectService; + this.projectOptions = projectOptions; + this.languageServiceDiabled = languageServiceDiabled; + this.directoriesWatchedForTsconfig = []; + this.filenameToSourceFile = {}; + this.updateGraphSeq = 0; + this.openRefCount = 0; + if (projectOptions && projectOptions.files) { + projectOptions.compilerOptions.allowNonTsExtensions = true; + } + if (!languageServiceDiabled) { + this.compilerService = new CompilerService(this, projectOptions && projectOptions.compilerOptions); + } + } + Project.prototype.enableLanguageService = function () { + if (this.languageServiceDiabled) { + this.compilerService = new CompilerService(this, this.projectOptions && this.projectOptions.compilerOptions); + } + this.languageServiceDiabled = false; + }; + Project.prototype.disableLanguageService = function () { + this.languageServiceDiabled = true; + }; + Project.prototype.addOpenRef = function () { + this.openRefCount++; + }; + Project.prototype.deleteOpenRef = function () { + this.openRefCount--; + return this.openRefCount; + }; + Project.prototype.openReferencedFile = function (filename) { + return this.projectService.openFile(filename, false); + }; + Project.prototype.getRootFiles = function () { + if (this.languageServiceDiabled) { + return this.projectOptions ? this.projectOptions.files : undefined; + } + return this.compilerService.host.roots.map(function (info) { return info.fileName; }); + }; + Project.prototype.getFileNames = function () { + if (this.languageServiceDiabled) { + if (!this.projectOptions) { + return undefined; + } + var fileNames = []; + if (this.projectOptions && this.projectOptions.compilerOptions) { + fileNames.push(ts.getDefaultLibFilePath(this.projectOptions.compilerOptions)); + } + ts.addRange(fileNames, this.projectOptions.files); + return fileNames; + } + var sourceFiles = this.program.getSourceFiles(); + return sourceFiles.map(function (sourceFile) { return sourceFile.fileName; }); + }; + Project.prototype.getSourceFile = function (info) { + if (this.languageServiceDiabled) { + return undefined; + } + return this.filenameToSourceFile[info.fileName]; + }; + Project.prototype.getSourceFileFromName = function (filename, requireOpen) { + if (this.languageServiceDiabled) { + return undefined; + } + var info = this.projectService.getScriptInfo(filename); + if (info) { + if ((!requireOpen) || info.isOpen) { + return this.getSourceFile(info); + } + } + }; + Project.prototype.isRoot = function (info) { + if (this.languageServiceDiabled) { + return undefined; + } + return this.compilerService.host.roots.some(function (root) { return root === info; }); + }; + Project.prototype.removeReferencedFile = function (info) { + if (this.languageServiceDiabled) { + return; + } + this.compilerService.host.removeReferencedFile(info); + this.updateGraph(); + }; + Project.prototype.updateFileMap = function () { + if (this.languageServiceDiabled) { + return; + } + this.filenameToSourceFile = {}; + var sourceFiles = this.program.getSourceFiles(); + for (var i = 0, len = sourceFiles.length; i < len; i++) { + var normFilename = ts.normalizePath(sourceFiles[i].fileName); + this.filenameToSourceFile[normFilename] = sourceFiles[i]; + } + }; + Project.prototype.finishGraph = function () { + if (this.languageServiceDiabled) { + return; + } + this.updateGraph(); + this.compilerService.languageService.getNavigateToItems(".*"); + }; + Project.prototype.updateGraph = function () { + if (this.languageServiceDiabled) { + return; + } + this.program = this.compilerService.languageService.getProgram(); + this.updateFileMap(); + }; + Project.prototype.isConfiguredProject = function () { + return this.projectFilename; + }; + Project.prototype.addRoot = function (info) { + if (this.languageServiceDiabled) { + return; + } + this.compilerService.host.addRoot(info); + }; + Project.prototype.removeRoot = function (info) { + if (this.languageServiceDiabled) { + return; + } + this.compilerService.host.removeRoot(info); + }; + Project.prototype.filesToString = function () { + if (this.languageServiceDiabled) { + if (this.projectOptions) { + var strBuilder_1 = ""; + ts.forEach(this.projectOptions.files, function (file) { strBuilder_1 += file + "\n"; }); + return strBuilder_1; + } + } + var strBuilder = ""; + ts.forEachValue(this.filenameToSourceFile, function (sourceFile) { strBuilder += sourceFile.fileName + "\n"; }); + return strBuilder; + }; + Project.prototype.setProjectOptions = function (projectOptions) { + this.projectOptions = projectOptions; + if (projectOptions.compilerOptions) { + projectOptions.compilerOptions.allowNonTsExtensions = true; + if (!this.languageServiceDiabled) { + this.compilerService.setCompilerOptions(projectOptions.compilerOptions); + } + } + }; + return Project; + }()); + server.Project = Project; + function copyListRemovingItem(item, list) { + var copiedList = []; + for (var i = 0, len = list.length; i < len; i++) { + if (list[i] != item) { + copiedList.push(list[i]); + } + } + return copiedList; + } + function combineProjectOutput(projects, action, comparer, areEqual) { + var result = projects.reduce(function (previous, current) { return ts.concatenate(previous, action(current)); }, []).sort(comparer); + return projects.length > 1 ? ts.deduplicate(result, areEqual) : result; + } + server.combineProjectOutput = combineProjectOutput; + var ProjectService = (function () { + function ProjectService(host, psLogger, eventHandler) { + this.host = host; + this.psLogger = psLogger; + this.eventHandler = eventHandler; + this.filenameToScriptInfo = {}; + this.openFileRoots = []; + this.inferredProjects = []; + this.configuredProjects = []; + this.openFilesReferenced = []; + this.openFileRootsConfigured = []; + this.directoryWatchersForTsconfig = {}; + this.directoryWatchersRefCount = {}; + this.timerForDetectingProjectFileListChanges = {}; + this.addDefaultHostConfiguration(); + } + ProjectService.prototype.addDefaultHostConfiguration = function () { + this.hostConfiguration = { + formatCodeOptions: ts.clone(CompilerService.getDefaultFormatCodeOptions(this.host)), + hostInfo: "Unknown host" + }; + }; + ProjectService.prototype.getFormatCodeOptions = function (file) { + if (file) { + var info = this.filenameToScriptInfo[file]; + if (info) { + return info.formatCodeOptions; + } + } + return this.hostConfiguration.formatCodeOptions; + }; + ProjectService.prototype.watchedFileChanged = function (fileName) { + var info = this.filenameToScriptInfo[fileName]; + if (!info) { + this.psLogger.info("Error: got watch notification for unknown file: " + fileName); + } + if (!this.host.fileExists(fileName)) { + this.fileDeletedInFilesystem(info); + } + else { + if (info && (!info.isOpen)) { + info.svc.reloadFromFile(info.fileName); + } + } + }; + ProjectService.prototype.directoryWatchedForSourceFilesChanged = function (project, fileName) { + if (fileName && !ts.isSupportedSourceFileName(fileName, project.projectOptions ? project.projectOptions.compilerOptions : undefined)) { + return; + } + this.log("Detected source file changes: " + fileName); + this.startTimerForDetectingProjectFileListChanges(project); + }; + ProjectService.prototype.startTimerForDetectingProjectFileListChanges = function (project) { + var _this = this; + if (this.timerForDetectingProjectFileListChanges[project.projectFilename]) { + this.host.clearTimeout(this.timerForDetectingProjectFileListChanges[project.projectFilename]); + } + this.timerForDetectingProjectFileListChanges[project.projectFilename] = this.host.setTimeout(function () { return _this.handleProjectFileListChanges(project); }, 250); + }; + ProjectService.prototype.handleProjectFileListChanges = function (project) { + var _this = this; + var projectOptions = this.configFileToProjectOptions(project.projectFilename).projectOptions; + var newRootFiles = projectOptions.files.map((function (f) { return _this.getCanonicalFileName(f); })); + var currentRootFiles = project.getRootFiles().map((function (f) { return _this.getCanonicalFileName(f); })); + if (!ts.arrayIsEqualTo(currentRootFiles && currentRootFiles.sort(), newRootFiles && newRootFiles.sort())) { + this.updateConfiguredProject(project); + this.updateProjectStructure(); + } + }; + ProjectService.prototype.directoryWatchedForTsconfigChanged = function (fileName) { + var _this = this; + if (ts.getBaseFileName(fileName) != "tsconfig.json") { + this.log(fileName + " is not tsconfig.json"); + return; + } + this.log("Detected newly added tsconfig file: " + fileName); + var projectOptions = this.configFileToProjectOptions(fileName).projectOptions; + var rootFilesInTsconfig = projectOptions.files.map(function (f) { return _this.getCanonicalFileName(f); }); + var openFileRoots = this.openFileRoots.map(function (s) { return _this.getCanonicalFileName(s.fileName); }); + for (var _i = 0, openFileRoots_1 = openFileRoots; _i < openFileRoots_1.length; _i++) { + var openFileRoot = openFileRoots_1[_i]; + if (rootFilesInTsconfig.indexOf(openFileRoot) >= 0) { + this.reloadProjects(); + return; + } + } + }; + ProjectService.prototype.getCanonicalFileName = function (fileName) { + var name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + return ts.normalizePath(name); + }; + ProjectService.prototype.watchedProjectConfigFileChanged = function (project) { + this.log("Config file changed: " + project.projectFilename); + this.updateConfiguredProject(project); + this.updateProjectStructure(); + }; + ProjectService.prototype.log = function (msg, type) { + if (type === void 0) { type = "Err"; } + this.psLogger.msg(msg, type); + }; + ProjectService.prototype.setHostConfiguration = function (args) { + if (args.file) { + var info = this.filenameToScriptInfo[args.file]; + if (info) { + info.setFormatOptions(args.formatOptions); + this.log("Host configuration update for file " + args.file, "Info"); + } + } + else { + if (args.hostInfo !== undefined) { + this.hostConfiguration.hostInfo = args.hostInfo; + this.log("Host information " + args.hostInfo, "Info"); + } + if (args.formatOptions) { + mergeFormatOptions(this.hostConfiguration.formatCodeOptions, args.formatOptions); + this.log("Format host information updated", "Info"); + } + } + }; + ProjectService.prototype.closeLog = function () { + this.psLogger.close(); + }; + ProjectService.prototype.createInferredProject = function (root) { + var _this = this; + var project = new Project(this); + project.addRoot(root); + var currentPath = ts.getDirectoryPath(root.fileName); + var parentPath = ts.getDirectoryPath(currentPath); + while (currentPath != parentPath) { + if (!project.projectService.directoryWatchersForTsconfig[currentPath]) { + this.log("Add watcher for: " + currentPath); + project.projectService.directoryWatchersForTsconfig[currentPath] = + this.host.watchDirectory(currentPath, function (fileName) { return _this.directoryWatchedForTsconfigChanged(fileName); }); + project.projectService.directoryWatchersRefCount[currentPath] = 1; + } + else { + project.projectService.directoryWatchersRefCount[currentPath] += 1; + } + project.directoriesWatchedForTsconfig.push(currentPath); + currentPath = parentPath; + parentPath = ts.getDirectoryPath(parentPath); + } + project.finishGraph(); + this.inferredProjects.push(project); + return project; + }; + ProjectService.prototype.fileDeletedInFilesystem = function (info) { + this.psLogger.info(info.fileName + " deleted"); + if (info.fileWatcher) { + info.fileWatcher.close(); + info.fileWatcher = undefined; + } + if (!info.isOpen) { + this.filenameToScriptInfo[info.fileName] = undefined; + var referencingProjects = this.findReferencingProjects(info); + if (info.defaultProject) { + info.defaultProject.removeRoot(info); + } + for (var i = 0, len = referencingProjects.length; i < len; i++) { + referencingProjects[i].removeReferencedFile(info); + } + for (var j = 0, flen = this.openFileRoots.length; j < flen; j++) { + var openFile = this.openFileRoots[j]; + if (this.eventHandler) { + this.eventHandler("context", openFile.defaultProject, openFile.fileName); + } + } + for (var j = 0, flen = this.openFilesReferenced.length; j < flen; j++) { + var openFile = this.openFilesReferenced[j]; + if (this.eventHandler) { + this.eventHandler("context", openFile.defaultProject, openFile.fileName); + } + } + } + this.printProjects(); + }; + ProjectService.prototype.updateConfiguredProjectList = function () { + var configuredProjects = []; + for (var i = 0, len = this.configuredProjects.length; i < len; i++) { + if (this.configuredProjects[i].openRefCount > 0) { + configuredProjects.push(this.configuredProjects[i]); + } + } + this.configuredProjects = configuredProjects; + }; + ProjectService.prototype.removeProject = function (project) { + this.log("remove project: " + project.getRootFiles().toString()); + if (project.isConfiguredProject()) { + project.projectFileWatcher.close(); + project.directoryWatcher.close(); + ts.forEachValue(project.directoriesWatchedForWildcards, function (watcher) { watcher.close(); }); + delete project.directoriesWatchedForWildcards; + this.configuredProjects = copyListRemovingItem(project, this.configuredProjects); + } + else { + for (var _i = 0, _a = project.directoriesWatchedForTsconfig; _i < _a.length; _i++) { + var directory = _a[_i]; + project.projectService.directoryWatchersRefCount[directory]--; + if (!project.projectService.directoryWatchersRefCount[directory]) { + this.log("Close directory watcher for: " + directory); + project.projectService.directoryWatchersForTsconfig[directory].close(); + delete project.projectService.directoryWatchersForTsconfig[directory]; + } + } + this.inferredProjects = copyListRemovingItem(project, this.inferredProjects); + } + var fileNames = project.getFileNames(); + for (var _b = 0, fileNames_3 = fileNames; _b < fileNames_3.length; _b++) { + var fileName = fileNames_3[_b]; + var info = this.getScriptInfo(fileName); + if (info.defaultProject == project) { + info.defaultProject = undefined; + } + } + }; + ProjectService.prototype.setConfiguredProjectRoot = function (info) { + for (var i = 0, len = this.configuredProjects.length; i < len; i++) { + var configuredProject = this.configuredProjects[i]; + if (configuredProject.isRoot(info)) { + info.defaultProject = configuredProject; + configuredProject.addOpenRef(); + return true; + } + } + return false; + }; + ProjectService.prototype.addOpenFile = function (info) { + if (this.setConfiguredProjectRoot(info)) { + this.openFileRootsConfigured.push(info); + } + else { + this.findReferencingProjects(info); + if (info.defaultProject) { + info.defaultProject.addOpenRef(); + this.openFilesReferenced.push(info); + } + else { + info.defaultProject = this.createInferredProject(info); + var openFileRoots = []; + for (var i = 0, len = this.openFileRoots.length; i < len; i++) { + var r = this.openFileRoots[i]; + if (info.defaultProject.getSourceFile(r)) { + this.removeProject(r.defaultProject); + this.openFilesReferenced.push(r); + r.defaultProject = info.defaultProject; + } + else { + openFileRoots.push(r); + } + } + this.openFileRoots = openFileRoots; + this.openFileRoots.push(info); + } + } + this.updateConfiguredProjectList(); + }; + ProjectService.prototype.closeOpenFile = function (info) { + info.svc.reloadFromFile(info.fileName); + var openFileRoots = []; + var removedProject; + for (var i = 0, len = this.openFileRoots.length; i < len; i++) { + if (info === this.openFileRoots[i]) { + removedProject = info.defaultProject; + } + else { + openFileRoots.push(this.openFileRoots[i]); + } + } + this.openFileRoots = openFileRoots; + if (!removedProject) { + var openFileRootsConfigured = []; + for (var i = 0, len = this.openFileRootsConfigured.length; i < len; i++) { + if (info === this.openFileRootsConfigured[i]) { + if (info.defaultProject.deleteOpenRef() === 0) { + removedProject = info.defaultProject; + } + } + else { + openFileRootsConfigured.push(this.openFileRootsConfigured[i]); + } + } + this.openFileRootsConfigured = openFileRootsConfigured; + } + if (removedProject) { + this.removeProject(removedProject); + var openFilesReferenced = []; + var orphanFiles = []; + for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) { + var f = this.openFilesReferenced[i]; + if (f.defaultProject === removedProject || !f.defaultProject) { + f.defaultProject = undefined; + orphanFiles.push(f); + } + else { + openFilesReferenced.push(f); + } + } + this.openFilesReferenced = openFilesReferenced; + for (var i = 0, len = orphanFiles.length; i < len; i++) { + this.addOpenFile(orphanFiles[i]); + } + } + else { + this.openFilesReferenced = copyListRemovingItem(info, this.openFilesReferenced); + } + info.close(); + }; + ProjectService.prototype.findReferencingProjects = function (info, excludedProject) { + var referencingProjects = []; + info.defaultProject = undefined; + for (var i = 0, len = this.inferredProjects.length; i < len; i++) { + var inferredProject = this.inferredProjects[i]; + inferredProject.updateGraph(); + if (inferredProject !== excludedProject) { + if (inferredProject.getSourceFile(info)) { + info.defaultProject = inferredProject; + referencingProjects.push(inferredProject); + } + } + } + for (var i = 0, len = this.configuredProjects.length; i < len; i++) { + var configuredProject = this.configuredProjects[i]; + configuredProject.updateGraph(); + if (configuredProject.getSourceFile(info)) { + info.defaultProject = configuredProject; + referencingProjects.push(configuredProject); + } + } + return referencingProjects; + }; + ProjectService.prototype.reloadProjects = function () { + this.log("reload projects."); + for (var _i = 0, _a = this.openFileRoots; _i < _a.length; _i++) { + var info = _a[_i]; + this.openOrUpdateConfiguredProjectForFile(info.fileName); + } + this.updateProjectStructure(); + }; + ProjectService.prototype.updateProjectStructure = function () { + this.log("updating project structure from ...", "Info"); + this.printProjects(); + var unattachedOpenFiles = []; + var openFileRootsConfigured = []; + for (var _i = 0, _a = this.openFileRootsConfigured; _i < _a.length; _i++) { + var info = _a[_i]; + var project = info.defaultProject; + if (!project || !(project.getSourceFile(info))) { + info.defaultProject = undefined; + unattachedOpenFiles.push(info); + } + else { + openFileRootsConfigured.push(info); + } + } + this.openFileRootsConfigured = openFileRootsConfigured; + var openFilesReferenced = []; + for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) { + var referencedFile = this.openFilesReferenced[i]; + referencedFile.defaultProject.updateGraph(); + var sourceFile = referencedFile.defaultProject.getSourceFile(referencedFile); + if (sourceFile) { + openFilesReferenced.push(referencedFile); + } + else { + unattachedOpenFiles.push(referencedFile); + } + } + this.openFilesReferenced = openFilesReferenced; + var openFileRoots = []; + for (var i = 0, len = this.openFileRoots.length; i < len; i++) { + var rootFile = this.openFileRoots[i]; + var rootedProject = rootFile.defaultProject; + var referencingProjects = this.findReferencingProjects(rootFile, rootedProject); + if (rootFile.defaultProject && rootFile.defaultProject.isConfiguredProject()) { + if (!rootedProject.isConfiguredProject()) { + this.removeProject(rootedProject); + } + this.openFileRootsConfigured.push(rootFile); + } + else { + if (referencingProjects.length === 0) { + rootFile.defaultProject = rootedProject; + openFileRoots.push(rootFile); + } + else { + this.removeProject(rootedProject); + this.openFilesReferenced.push(rootFile); + } + } + } + this.openFileRoots = openFileRoots; + for (var i = 0, len = unattachedOpenFiles.length; i < len; i++) { + this.addOpenFile(unattachedOpenFiles[i]); + } + this.printProjects(); + }; + ProjectService.prototype.getScriptInfo = function (filename) { + filename = ts.normalizePath(filename); + return ts.lookUp(this.filenameToScriptInfo, filename); + }; + ProjectService.prototype.openFile = function (fileName, openedByClient, fileContent, scriptKind) { + var _this = this; + fileName = ts.normalizePath(fileName); + var info = ts.lookUp(this.filenameToScriptInfo, fileName); + if (!info) { + var content = void 0; + if (this.host.fileExists(fileName)) { + content = fileContent || this.host.readFile(fileName); + } + if (!content) { + if (openedByClient) { + content = ""; + } + } + if (content !== undefined) { + info = new ScriptInfo(this.host, fileName, content, openedByClient); + info.scriptKind = scriptKind; + info.setFormatOptions(this.getFormatCodeOptions()); + this.filenameToScriptInfo[fileName] = info; + if (!info.isOpen) { + info.fileWatcher = this.host.watchFile(fileName, function (_) { _this.watchedFileChanged(fileName); }); + } + } + } + if (info) { + if (fileContent) { + info.svc.reload(fileContent); + } + if (openedByClient) { + info.isOpen = true; + } + } + return info; + }; + ProjectService.prototype.findConfigFile = function (searchPath) { + while (true) { + var tsconfigFileName = ts.combinePaths(searchPath, "tsconfig.json"); + if (this.host.fileExists(tsconfigFileName)) { + return tsconfigFileName; + } + var jsconfigFileName = ts.combinePaths(searchPath, "jsconfig.json"); + if (this.host.fileExists(jsconfigFileName)) { + return jsconfigFileName; + } + var parentPath = ts.getDirectoryPath(searchPath); + if (parentPath === searchPath) { + break; + } + searchPath = parentPath; + } + return undefined; + }; + ProjectService.prototype.openClientFile = function (fileName, fileContent, scriptKind) { + var _a = this.openOrUpdateConfiguredProjectForFile(fileName), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors; + var info = this.openFile(fileName, true, fileContent, scriptKind); + this.addOpenFile(info); + this.printProjects(); + return { configFileName: configFileName, configFileErrors: configFileErrors }; + }; + ProjectService.prototype.openOrUpdateConfiguredProjectForFile = function (fileName) { + var searchPath = ts.normalizePath(ts.getDirectoryPath(fileName)); + this.log("Search path: " + searchPath, "Info"); + var configFileName = this.findConfigFile(searchPath); + if (configFileName) { + this.log("Config file name: " + configFileName, "Info"); + var project = this.findConfiguredProjectByConfigFile(configFileName); + if (!project) { + var configResult = this.openConfigFile(configFileName, fileName); + if (!configResult.success) { + return { configFileName: configFileName, configFileErrors: configResult.errors }; + } + else { + this.log("Opened configuration file " + configFileName, "Info"); + this.configuredProjects.push(configResult.project); + if (configResult.errors && configResult.errors.length > 0) { + return { configFileName: configFileName, configFileErrors: configResult.errors }; + } + } + } + else { + this.updateConfiguredProject(project); + } + } + else { + this.log("No config files found."); + } + return configFileName ? { configFileName: configFileName } : {}; + }; + ProjectService.prototype.closeClientFile = function (filename) { + var info = ts.lookUp(this.filenameToScriptInfo, filename); + if (info) { + this.closeOpenFile(info); + info.isOpen = false; + } + this.printProjects(); + }; + ProjectService.prototype.getProjectForFile = function (filename) { + var scriptInfo = ts.lookUp(this.filenameToScriptInfo, filename); + if (scriptInfo) { + return scriptInfo.defaultProject; + } + }; + ProjectService.prototype.printProjectsForFile = function (filename) { + var scriptInfo = ts.lookUp(this.filenameToScriptInfo, filename); + if (scriptInfo) { + this.psLogger.startGroup(); + this.psLogger.info("Projects for " + filename); + var projects = this.findReferencingProjects(scriptInfo); + for (var i = 0, len = projects.length; i < len; i++) { + this.psLogger.info("Project " + i.toString()); + } + this.psLogger.endGroup(); + } + else { + this.psLogger.info(filename + " not in any project"); + } + }; + ProjectService.prototype.printProjects = function () { + if (!this.psLogger.isVerbose()) { + return; + } + this.psLogger.startGroup(); + for (var i = 0, len = this.inferredProjects.length; i < len; i++) { + var project = this.inferredProjects[i]; + project.updateGraph(); + this.psLogger.info("Project " + i.toString()); + this.psLogger.info(project.filesToString()); + this.psLogger.info("-----------------------------------------------"); + } + for (var i = 0, len = this.configuredProjects.length; i < len; i++) { + var project = this.configuredProjects[i]; + project.updateGraph(); + this.psLogger.info("Project (configured) " + (i + this.inferredProjects.length).toString()); + this.psLogger.info(project.filesToString()); + this.psLogger.info("-----------------------------------------------"); + } + this.psLogger.info("Open file roots of inferred projects: "); + for (var i = 0, len = this.openFileRoots.length; i < len; i++) { + this.psLogger.info(this.openFileRoots[i].fileName); + } + this.psLogger.info("Open files referenced by inferred or configured projects: "); + for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) { + var fileInfo = this.openFilesReferenced[i].fileName; + if (this.openFilesReferenced[i].defaultProject.isConfiguredProject()) { + fileInfo += " (configured)"; + } + this.psLogger.info(fileInfo); + } + this.psLogger.info("Open file roots of configured projects: "); + for (var i = 0, len = this.openFileRootsConfigured.length; i < len; i++) { + this.psLogger.info(this.openFileRootsConfigured[i].fileName); + } + this.psLogger.endGroup(); + }; + ProjectService.prototype.configProjectIsActive = function (fileName) { + return this.findConfiguredProjectByConfigFile(fileName) === undefined; + }; + ProjectService.prototype.findConfiguredProjectByConfigFile = function (configFileName) { + for (var i = 0, len = this.configuredProjects.length; i < len; i++) { + if (this.configuredProjects[i].projectFilename == configFileName) { + return this.configuredProjects[i]; + } + } + return undefined; + }; + ProjectService.prototype.configFileToProjectOptions = function (configFilename) { + configFilename = ts.normalizePath(configFilename); + var dirPath = ts.getDirectoryPath(configFilename); + var contents = this.host.readFile(configFilename); + var rawConfig = ts.parseConfigFileTextToJson(configFilename, contents); + if (rawConfig.error) { + return { succeeded: false, errors: [rawConfig.error] }; + } + else { + var parsedCommandLine = ts.parseJsonConfigFileContent(rawConfig.config, this.host, dirPath, {}, configFilename); + ts.Debug.assert(!!parsedCommandLine.fileNames); + if (parsedCommandLine.errors && (parsedCommandLine.errors.length > 0)) { + return { succeeded: false, errors: parsedCommandLine.errors }; + } + else if (parsedCommandLine.fileNames.length === 0) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename); + return { succeeded: false, errors: [error] }; + } + else { + var projectOptions = { + files: parsedCommandLine.fileNames, + wildcardDirectories: parsedCommandLine.wildcardDirectories, + compilerOptions: parsedCommandLine.options + }; + return { succeeded: true, projectOptions: projectOptions }; + } + } + }; + ProjectService.prototype.exceedTotalNonTsFileSizeLimit = function (fileNames) { + var totalNonTsFileSize = 0; + if (!this.host.getFileSize) { + return false; + } + for (var _i = 0, fileNames_4 = fileNames; _i < fileNames_4.length; _i++) { + var fileName = fileNames_4[_i]; + if (ts.hasTypeScriptFileExtension(fileName)) { + continue; + } + totalNonTsFileSize += this.host.getFileSize(fileName); + if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles) { + return true; + } + } + return false; + }; + ProjectService.prototype.openConfigFile = function (configFilename, clientFileName) { + var _this = this; + var _a = this.configFileToProjectOptions(configFilename), succeeded = _a.succeeded, projectOptions = _a.projectOptions, errors = _a.errors; + if (!succeeded) { + return { success: false, errors: errors }; + } + else { + if (!projectOptions.compilerOptions.disableSizeLimit && projectOptions.compilerOptions.allowJs) { + if (this.exceedTotalNonTsFileSizeLimit(projectOptions.files)) { + var project_1 = this.createProject(configFilename, projectOptions, true); + project_1.projectFileWatcher = this.host.watchFile(ts.toPath(configFilename, configFilename, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), function (_) { return _this.watchedProjectConfigFileChanged(project_1); }); + return { success: true, project: project_1 }; + } + } + var project_2 = this.createProject(configFilename, projectOptions); + var errors_1; + for (var _i = 0, _b = projectOptions.files; _i < _b.length; _i++) { + var rootFilename = _b[_i]; + if (this.host.fileExists(rootFilename)) { + var info = this.openFile(rootFilename, clientFileName == rootFilename); + project_2.addRoot(info); + } + else { + (errors_1 || (errors_1 = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, rootFilename)); + } + } + project_2.finishGraph(); + project_2.projectFileWatcher = this.host.watchFile(configFilename, function (_) { return _this.watchedProjectConfigFileChanged(project_2); }); + var configDirectoryPath_1 = ts.getDirectoryPath(configFilename); + this.log("Add recursive watcher for: " + configDirectoryPath_1); + project_2.directoryWatcher = this.host.watchDirectory(configDirectoryPath_1, function (path) { return _this.directoryWatchedForSourceFilesChanged(project_2, path); }, true); + project_2.directoriesWatchedForWildcards = ts.reduceProperties(projectOptions.wildcardDirectories, function (watchers, flag, directory) { + if (ts.comparePaths(configDirectoryPath_1, directory, ".", !_this.host.useCaseSensitiveFileNames) !== 0) { + var recursive = (flag & 1) !== 0; + _this.log("Add " + (recursive ? "recursive " : "") + "watcher for: " + directory); + watchers[directory] = _this.host.watchDirectory(directory, function (path) { return _this.directoryWatchedForSourceFilesChanged(project_2, path); }, recursive); + } + return watchers; + }, {}); + return { success: true, project: project_2, errors: errors_1 }; + } + }; + ProjectService.prototype.updateConfiguredProject = function (project) { + var _this = this; + if (!this.host.fileExists(project.projectFilename)) { + this.log("Config file deleted"); + this.removeProject(project); + } + else { + var _a = this.configFileToProjectOptions(project.projectFilename), succeeded = _a.succeeded, projectOptions = _a.projectOptions, errors = _a.errors; + if (!succeeded) { + return errors; + } + else { + if (projectOptions.compilerOptions && !projectOptions.compilerOptions.disableSizeLimit && this.exceedTotalNonTsFileSizeLimit(projectOptions.files)) { + project.setProjectOptions(projectOptions); + if (project.languageServiceDiabled) { + return; + } + project.disableLanguageService(); + if (project.directoryWatcher) { + project.directoryWatcher.close(); + project.directoryWatcher = undefined; + } + return; + } + if (project.languageServiceDiabled) { + project.setProjectOptions(projectOptions); + project.enableLanguageService(); + project.directoryWatcher = this.host.watchDirectory(ts.getDirectoryPath(project.projectFilename), function (path) { return _this.directoryWatchedForSourceFilesChanged(project, path); }, true); + for (var _i = 0, _b = projectOptions.files; _i < _b.length; _i++) { + var rootFilename = _b[_i]; + if (this.host.fileExists(rootFilename)) { + var info = this.openFile(rootFilename, false); + project.addRoot(info); + } + } + project.finishGraph(); + return; + } + var oldFileNames_1 = project.projectOptions ? project.projectOptions.files : project.compilerService.host.roots.map(function (info) { return info.fileName; }); + var newFileNames_1 = ts.filter(projectOptions.files, function (f) { return _this.host.fileExists(f); }); + var fileNamesToRemove = oldFileNames_1.filter(function (f) { return newFileNames_1.indexOf(f) < 0; }); + var fileNamesToAdd = newFileNames_1.filter(function (f) { return oldFileNames_1.indexOf(f) < 0; }); + for (var _c = 0, fileNamesToRemove_1 = fileNamesToRemove; _c < fileNamesToRemove_1.length; _c++) { + var fileName = fileNamesToRemove_1[_c]; + var info = this.getScriptInfo(fileName); + if (info) { + project.removeRoot(info); + } + } + for (var _d = 0, fileNamesToAdd_1 = fileNamesToAdd; _d < fileNamesToAdd_1.length; _d++) { + var fileName = fileNamesToAdd_1[_d]; + var info = this.getScriptInfo(fileName); + if (!info) { + info = this.openFile(fileName, false); + } + else { + if (info.isOpen) { + if (this.openFileRoots.indexOf(info) >= 0) { + this.openFileRoots = copyListRemovingItem(info, this.openFileRoots); + if (info.defaultProject && !info.defaultProject.isConfiguredProject()) { + this.removeProject(info.defaultProject); + } + } + if (this.openFilesReferenced.indexOf(info) >= 0) { + this.openFilesReferenced = copyListRemovingItem(info, this.openFilesReferenced); + } + this.openFileRootsConfigured.push(info); + info.defaultProject = project; + } + } + project.addRoot(info); + } + project.setProjectOptions(projectOptions); + project.finishGraph(); + } + } + }; + ProjectService.prototype.createProject = function (projectFilename, projectOptions, languageServiceDisabled) { + var project = new Project(this, projectOptions, languageServiceDisabled); + project.projectFilename = projectFilename; + return project; + }; + return ProjectService; + }()); + server.ProjectService = ProjectService; + var CompilerService = (function () { + function CompilerService(project, opt) { + this.project = project; + this.documentRegistry = ts.createDocumentRegistry(); + this.host = new LSHost(project.projectService.host, project); + if (opt) { + this.setCompilerOptions(opt); + } + else { + var defaultOpts = ts.getDefaultCompilerOptions(); + defaultOpts.allowNonTsExtensions = true; + defaultOpts.allowJs = true; + this.setCompilerOptions(defaultOpts); + } + this.languageService = ts.createLanguageService(this.host, this.documentRegistry); + this.classifier = ts.createClassifier(); + } + CompilerService.prototype.setCompilerOptions = function (opt) { + this.settings = opt; + this.host.setCompilationSettings(opt); + }; + CompilerService.prototype.isExternalModule = function (filename) { + var sourceFile = this.languageService.getNonBoundSourceFile(filename); + return ts.isExternalModule(sourceFile); + }; + CompilerService.getDefaultFormatCodeOptions = function (host) { + return ts.clone({ + BaseIndentSize: 0, + IndentSize: 4, + TabSize: 4, + NewLineCharacter: host.newLine || "\n", + ConvertTabsToSpaces: true, + IndentStyle: ts.IndentStyle.Smart, + InsertSpaceAfterCommaDelimiter: true, + InsertSpaceAfterSemicolonInForStatements: true, + InsertSpaceBeforeAndAfterBinaryOperators: true, + InsertSpaceAfterKeywordsInControlFlowStatements: true, + InsertSpaceAfterFunctionKeywordForAnonymousFunctions: false, + InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, + InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, + InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, + PlaceOpenBraceOnNewLineForFunctions: false, + PlaceOpenBraceOnNewLineForControlBlocks: false + }); + }; + return CompilerService; + }()); + server.CompilerService = CompilerService; (function (CharRangeSection) { CharRangeSection[CharRangeSection["PreStart"] = 0] = "PreStart"; CharRangeSection[CharRangeSection["Start"] = 1] = "Start"; @@ -55371,19 +52209,10 @@ var ts; var ScriptVersionCache = (function () { function ScriptVersionCache() { this.changes = []; - this.versions = new Array(ScriptVersionCache.maxVersions); + this.versions = []; this.minVersion = 0; this.currentVersion = 0; } - ScriptVersionCache.prototype.versionToIndex = function (version) { - if (version < this.minVersion || version > this.currentVersion) { - return undefined; - } - return version % ScriptVersionCache.maxVersions; - }; - ScriptVersionCache.prototype.currentVersionToIndex = function () { - return this.currentVersion % ScriptVersionCache.maxVersions; - }; ScriptVersionCache.prototype.edit = function (pos, deleteLen, insertedText) { this.changes[this.changes.length] = new TextChange(pos, deleteLen, insertedText); if ((this.changes.length > ScriptVersionCache.changeNumberThreshold) || @@ -55393,7 +52222,7 @@ var ts; } }; ScriptVersionCache.prototype.latest = function () { - return this.versions[this.currentVersionToIndex()]; + return this.versions[this.currentVersion]; }; ScriptVersionCache.prototype.latestVersion = function () { if (this.changes.length > 0) { @@ -55401,30 +52230,32 @@ var ts; } return this.currentVersion; }; - ScriptVersionCache.prototype.reloadFromFile = function (filename) { + ScriptVersionCache.prototype.reloadFromFile = function (filename, cb) { var content = this.host.readFile(filename); if (!content) { content = ""; } this.reload(content); + if (cb) + cb(); }; ScriptVersionCache.prototype.reload = function (script) { this.currentVersion++; this.changes = []; var snap = new LineIndexSnapshot(this.currentVersion, this); - for (var i = 0; i < this.versions.length; i++) { - this.versions[i] = undefined; - } - this.versions[this.currentVersionToIndex()] = snap; + this.versions[this.currentVersion] = snap; snap.index = new LineIndex(); var lm = LineIndex.linesFromText(script); snap.index.load(lm.lines); + for (var i = this.minVersion; i < this.currentVersion; i++) { + this.versions[i] = undefined; + } this.minVersion = this.currentVersion; }; ScriptVersionCache.prototype.getSnapshot = function () { - var snap = this.versions[this.currentVersionToIndex()]; + var snap = this.versions[this.currentVersion]; if (this.changes.length > 0) { - var snapIndex = snap.index; + var snapIndex = this.latest().index; for (var i = 0, len = this.changes.length; i < len; i++) { var change = this.changes[i]; snapIndex = snapIndex.edit(change.pos, change.deleteLen, change.insertedText); @@ -55433,10 +52264,14 @@ var ts; snap.index = snapIndex; snap.changesSincePreviousVersion = this.changes; this.currentVersion = snap.version; - this.versions[this.currentVersionToIndex()] = snap; + this.versions[snap.version] = snap; this.changes = []; if ((this.currentVersion - this.minVersion) >= ScriptVersionCache.maxVersions) { + var oldMin = this.minVersion; this.minVersion = (this.currentVersion - ScriptVersionCache.maxVersions) + 1; + for (var j = oldMin; j < this.minVersion; j++) { + this.versions[j] = undefined; + } } } return snap; @@ -55446,7 +52281,7 @@ var ts; if (oldVersion >= this.minVersion) { var textChangeRanges = []; for (var i = oldVersion + 1; i <= newVersion; i++) { - var snap = this.versions[this.versionToIndex(i)]; + var snap = this.versions[i]; for (var j = 0, len = snap.changesSincePreviousVersion.length; j < len; j++) { var textChange = snap.changesSincePreviousVersion[j]; textChangeRanges[textChangeRanges.length] = textChange.getTextChangeRange(); @@ -55597,7 +52432,7 @@ var ts; return source.substring(0, s) + nt + source.substring(s + dl, source.length); } if (this.root.charCount() === 0) { - if (newText !== undefined) { + if (newText) { this.load(LineIndex.linesFromText(newText).lines); return this; } @@ -55977,6 +52812,12 @@ var ts; function LineLeaf(text) { this.text = text; } + LineLeaf.prototype.setUdata = function (data) { + this.udata = data; + }; + LineLeaf.prototype.getUdata = function () { + return this.udata; + }; LineLeaf.prototype.isLeaf = function () { return true; }; @@ -55998,25 +52839,6 @@ var ts; (function (ts) { var server; (function (server) { - var net = require("net"); - var childProcess = require("child_process"); - var os = require("os"); - function getGlobalTypingsCacheLocation() { - var basePath; - switch (process.platform) { - case "win32": - basePath = process.env.LOCALAPPDATA || process.env.APPDATA || os.homedir(); - break; - case "linux": - basePath = os.homedir(); - break; - case "darwin": - basePath = ts.combinePaths(os.homedir(), "Library/Application Support/"); - break; - } - ts.Debug.assert(basePath !== undefined); - return ts.combinePaths(ts.normalizeSlashes(basePath), "Microsoft/TypeScript"); - } var readline = require("readline"); var fs = require("fs"); var rl = readline.createInterface({ @@ -56025,9 +52847,8 @@ var ts; terminal: false }); var Logger = (function () { - function Logger(logFilename, traceToConsole, level) { + function Logger(logFilename, level) { this.logFilename = logFilename; - this.traceToConsole = traceToConsole; this.level = level; this.fd = -1; this.seq = 0; @@ -56042,14 +52863,11 @@ var ts; fs.close(this.fd); } }; - Logger.prototype.getLogFileName = function () { - return this.logFilename; - }; Logger.prototype.perftrc = function (s) { - this.msg(s, server.Msg.Perf); + this.msg(s, "Perf"); }; Logger.prototype.info = function (s) { - this.msg(s, server.Msg.Info); + this.msg(s, "Info"); }; Logger.prototype.startGroup = function () { this.inGroup = true; @@ -56061,19 +52879,19 @@ var ts; this.firstInGroup = true; }; Logger.prototype.loggingEnabled = function () { - return !!this.logFilename || this.traceToConsole; + return !!this.logFilename; }; - Logger.prototype.hasLevel = function (level) { - return this.loggingEnabled() && this.level >= level; + Logger.prototype.isVerbose = function () { + return this.loggingEnabled() && (this.level == "verbose"); }; Logger.prototype.msg = function (s, type) { - if (type === void 0) { type = server.Msg.Err; } + if (type === void 0) { type = "Err"; } if (this.fd < 0) { if (this.logFilename) { this.fd = fs.openSync(this.logFilename, "w"); } } - if (this.fd >= 0 || this.traceToConsole) { + if (this.fd >= 0) { s = s + "\n"; var prefix = Logger.padStringRight(type + " " + this.seq.toString(), " "); if (this.firstInGroup) { @@ -56084,88 +52902,19 @@ var ts; this.seq++; this.firstInGroup = true; } - if (this.fd >= 0) { - var buf = new Buffer(s); - fs.writeSync(this.fd, buf, 0, buf.length, null); - } - if (this.traceToConsole) { - console.warn(s); - } + var buf = new Buffer(s); + fs.writeSync(this.fd, buf, 0, buf.length, null); } }; return Logger; }()); - var NodeTypingsInstaller = (function () { - function NodeTypingsInstaller(logger, eventPort, globalTypingsCacheLocation, newLine) { - var _this = this; - this.logger = logger; - this.eventPort = eventPort; - this.globalTypingsCacheLocation = globalTypingsCacheLocation; - this.newLine = newLine; - if (eventPort) { - var s_1 = net.connect({ port: eventPort }, function () { - _this.socket = s_1; - }); - } - } - NodeTypingsInstaller.prototype.attach = function (projectService) { - var _this = this; - this.projectService = projectService; - if (this.logger.hasLevel(server.LogLevel.requestTime)) { - this.logger.info("Binding..."); - } - var args = ["--globalTypingsCacheLocation", this.globalTypingsCacheLocation]; - if (this.logger.loggingEnabled() && this.logger.getLogFileName()) { - args.push("--logFile", ts.combinePaths(ts.getDirectoryPath(ts.normalizeSlashes(this.logger.getLogFileName())), "ti-" + process.pid + ".log")); - } - var execArgv = []; - { - for (var _i = 0, _a = process.execArgv; _i < _a.length; _i++) { - var arg = _a[_i]; - var match = /^--(debug|inspect)(=(\d+))?$/.exec(arg); - if (match) { - var currentPort = match[3] !== undefined - ? +match[3] - : match[1] === "debug" ? 5858 : 9229; - execArgv.push("--" + match[1] + "=" + (currentPort + 1)); - break; - } - } - } - this.installer = childProcess.fork(ts.combinePaths(__dirname, "typingsInstaller.js"), args, { execArgv: execArgv }); - this.installer.on("message", function (m) { return _this.handleMessage(m); }); - process.on("exit", function () { - _this.installer.kill(); - }); - }; - NodeTypingsInstaller.prototype.onProjectClosed = function (p) { - this.installer.send({ projectName: p.getProjectName(), kind: "closeProject" }); - }; - NodeTypingsInstaller.prototype.enqueueInstallTypingsRequest = function (project, typingOptions) { - var request = server.createInstallTypingsRequest(project, typingOptions); - if (this.logger.hasLevel(server.LogLevel.verbose)) { - this.logger.info("Sending request: " + JSON.stringify(request)); - } - this.installer.send(request); - }; - NodeTypingsInstaller.prototype.handleMessage = function (response) { - if (this.logger.hasLevel(server.LogLevel.verbose)) { - this.logger.info("Received response: " + JSON.stringify(response)); - } - this.projectService.updateTypingsForProject(response); - if (response.kind == "set" && this.socket) { - this.socket.write(server.formatMessage({ seq: 0, type: "event", message: response }, this.logger, Buffer.byteLength, this.newLine), "utf8"); - } - }; - return NodeTypingsInstaller; - }()); var IOSession = (function (_super) { __extends(IOSession, _super); - function IOSession(host, cancellationToken, installerEventPort, canUseEvents, useSingleInferredProject, globalTypingsCacheLocation, logger) { - _super.call(this, host, cancellationToken, useSingleInferredProject, new NodeTypingsInstaller(logger, installerEventPort, globalTypingsCacheLocation, host.newLine), Buffer.byteLength, process.hrtime, logger, canUseEvents); + function IOSession(host, logger) { + _super.call(this, host, Buffer.byteLength, process.hrtime, logger); } IOSession.prototype.exit = function () { - this.logger.info("Exiting..."); + this.projectService.log("Exiting...", "Info"); this.projectService.closeLog(); process.exit(0); }; @@ -56182,7 +52931,7 @@ var ts; return IOSession; }(server.Session)); function parseLoggingEnvironmentString(logEnvStr) { - var logEnv = { logToFile: true }; + var logEnv = {}; var args = logEnvStr.split(" "); for (var i = 0, len = args.length; i < (len - 1); i += 2) { var option = args[i]; @@ -56190,17 +52939,10 @@ var ts; if (option && value) { switch (option) { case "-file": - logEnv.file = ts.stripQuotes(value); + logEnv.file = value; break; case "-level": - var level = server.LogLevel[value]; - logEnv.detailLevel = typeof level === "number" ? level : server.LogLevel.normal; - break; - case "-traceToConsole": - logEnv.traceToConsole = value.toLowerCase() === "true"; - break; - case "-logToFile": - logEnv.logToFile = value.toLowerCase() === "true"; + logEnv.detailLevel = value; break; } } @@ -56209,25 +52951,21 @@ var ts; } function createLoggerFromEnv() { var fileName = undefined; - var detailLevel = server.LogLevel.normal; - var traceToConsole = false; + var detailLevel = "normal"; var logEnvStr = process.env["TSS_LOG"]; if (logEnvStr) { var logEnv = parseLoggingEnvironmentString(logEnvStr); - if (logEnv.logToFile) { - if (logEnv.file) { - fileName = logEnv.file; - } - else { - fileName = __dirname + "/.log" + process.pid.toString(); - } + if (logEnv.file) { + fileName = logEnv.file; + } + else { + fileName = __dirname + "/.log" + process.pid.toString(); } if (logEnv.detailLevel) { detailLevel = logEnv.detailLevel; } - traceToConsole = logEnv.traceToConsole; } - return new Logger(fileName, traceToConsole, detailLevel); + return new Logger(fileName, detailLevel); } function createPollingWatchedFileSet(interval, chunkSize) { if (interval === void 0) { interval = 2500; } @@ -56299,13 +53037,13 @@ var ts; var logger = createLoggerFromEnv(); var pending = []; var canWrite = true; - function writeMessage(buf) { + function writeMessage(s) { if (!canWrite) { - pending.push(buf); + pending.push(s); } else { canWrite = false; - process.stdout.write(buf, setCanWriteFlagAndWriteMessageIfNecessary); + process.stdout.write(new Buffer(s, "utf8"), setCanWriteFlagAndWriteMessageIfNecessary); } } function setCanWriteFlagAndWriteMessageIfNecessary() { @@ -56315,7 +53053,7 @@ var ts; } } var sys = ts.sys; - sys.write = function (s) { return writeMessage(new Buffer(s, "utf8")); }; + sys.write = function (s) { return writeMessage(s); }; sys.watchFile = function (fileName, callback) { var watchedFile = pollingWatchedFileSet.addFile(fileName, callback); return { @@ -56324,41 +53062,14 @@ var ts; }; sys.setTimeout = setTimeout; sys.clearTimeout = clearTimeout; - sys.setImmediate = setImmediate; - sys.clearImmediate = clearImmediate; - if (typeof global !== "undefined" && global.gc) { - sys.gc = function () { return global.gc(); }; - } - var cancellationToken; - try { - var factory = require("./cancellationToken"); - cancellationToken = factory(sys.args); - } - catch (e) { - cancellationToken = { - isCancellationRequested: function () { return false; } - }; - } - ; - var eventPort; - { - var index = sys.args.indexOf("--eventPort"); - if (index >= 0 && index < sys.args.length - 1) { - var v = parseInt(sys.args[index + 1]); - if (!isNaN(v)) { - eventPort = v; - } - } - } - var useSingleInferredProject = sys.args.indexOf("--useSingleInferredProject") >= 0; - var ioSession = new IOSession(sys, cancellationToken, eventPort, eventPort === undefined, useSingleInferredProject, getGlobalTypingsCacheLocation(), logger); + var ioSession = new IOSession(sys, logger); process.on("uncaughtException", function (err) { ioSession.logError(err, "unknown"); }); ioSession.listen(); })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); -var debugObjectHost = new Function("return this")(); +var debugObjectHost = this; var ts; (function (ts) { function logInternalError(logger, err) { @@ -56402,7 +53113,7 @@ var ts; this.resolveModuleNames = function (moduleNames, containingFile) { var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile)); return ts.map(moduleNames, function (name) { - var result = ts.getProperty(resolutionsInFile, name); + var result = ts.lookUp(resolutionsInFile, name); return result ? { resolvedFileName: result } : undefined; }); }; @@ -56413,7 +53124,7 @@ var ts; if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) { this.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { var typeDirectivesForFile = JSON.parse(_this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile)); - return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); }); + return ts.map(typeDirectiveNames, function (name) { return ts.lookUp(typeDirectivesForFile, name); }); }; } } @@ -56436,12 +53147,6 @@ var ts; } return this.shimHost.getProjectVersion(); }; - LanguageServiceShimHostAdapter.prototype.getTypeRootsVersion = function () { - if (!this.shimHost.getTypeRootsVersion) { - return 0; - } - return this.shimHost.getTypeRootsVersion(); - }; LanguageServiceShimHostAdapter.prototype.useCaseSensitiveFileNames = function () { return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; }; @@ -56492,21 +53197,11 @@ var ts; return this.shimHost.getCurrentDirectory(); }; LanguageServiceShimHostAdapter.prototype.getDirectories = function (path) { - return JSON.parse(this.shimHost.getDirectories(path)); + return this.shimHost.getDirectories(path); }; LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) { return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); }; - LanguageServiceShimHostAdapter.prototype.readDirectory = function (path, extensions, exclude, include, depth) { - var pattern = ts.getFileMatcherPatterns(path, extensions, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); - return JSON.parse(this.shimHost.readDirectory(path, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); - }; - LanguageServiceShimHostAdapter.prototype.readFile = function (path, encoding) { - return this.shimHost.readFile(path, encoding); - }; - LanguageServiceShimHostAdapter.prototype.fileExists = function (path) { - return this.shimHost.fileExists(path); - }; return LanguageServiceShimHostAdapter; }()); ts.LanguageServiceShimHostAdapter = LanguageServiceShimHostAdapter; @@ -56516,7 +53211,7 @@ var ts; this.lastCancellationCheckTime = 0; } ThrottledCancellationToken.prototype.isCancellationRequested = function () { - var time = ts.timestamp(); + var time = Date.now(); var duration = Math.abs(time - this.lastCancellationCheckTime); if (duration > 10) { this.lastCancellationCheckTime = time; @@ -56566,9 +53261,6 @@ var ts; CoreServicesShimHostAdapter.prototype.readDirectoryFallback = function (rootDir, extension, exclude) { return JSON.parse(this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude))); }; - CoreServicesShimHostAdapter.prototype.getDirectories = function (path) { - return JSON.parse(this.shimHost.getDirectories(path)); - }; return CoreServicesShimHostAdapter; }()); ts.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter; @@ -56576,11 +53268,11 @@ var ts; var start; if (logPerformance) { logger.log(actionDescription); - start = ts.timestamp(); + start = Date.now(); } var result = action(); if (logPerformance) { - var end = ts.timestamp(); + var end = Date.now(); logger.log(actionDescription + " completed in " + (end - start) + " msec"); if (typeof result === "string") { var str = result; @@ -56619,6 +53311,19 @@ var ts; }; return ShimBase; }()); + function realizeDiagnostics(diagnostics, newLine) { + return diagnostics.map(function (d) { return realizeDiagnostic(d, newLine); }); + } + ts.realizeDiagnostics = realizeDiagnostics; + function realizeDiagnostic(diagnostic, newLine) { + return { + message: ts.flattenDiagnosticMessageText(diagnostic.messageText, newLine), + start: diagnostic.start, + length: diagnostic.length, + category: ts.DiagnosticCategory[diagnostic.category].toLowerCase(), + code: diagnostic.code + }; + } var LanguageServiceShimObject = (function (_super) { __extends(LanguageServiceShimObject, _super); function LanguageServiceShimObject(factory, host, languageService) { @@ -56894,13 +53599,6 @@ var ts; }; }); }; - CoreServicesShimObject.prototype.getAutomaticTypeDirectiveNames = function (compilerOptionsJson) { - var _this = this; - return this.forwardJSONCall("getAutomaticTypeDirectiveNames('" + compilerOptionsJson + "')", function () { - var compilerOptions = JSON.parse(compilerOptionsJson); - return ts.getAutomaticTypeDirectiveNames(compilerOptions, _this.host); - }); - }; CoreServicesShimObject.prototype.convertFileReferences = function (refs) { if (!refs) { return undefined; @@ -56927,7 +53625,7 @@ var ts; typingOptions: {}, files: [], raw: {}, - errors: [ts.realizeDiagnostic(result.error, "\r\n")] + errors: [realizeDiagnostic(result.error, "\r\n")] }; } var normalizedFileName = ts.normalizeSlashes(fileName); @@ -56937,7 +53635,7 @@ var ts; typingOptions: configFile.typingOptions, files: configFile.fileNames, raw: configFile.raw, - errors: ts.realizeDiagnostics(configFile.errors, "\r\n") + errors: realizeDiagnostics(configFile.errors, "\r\n") }; }); }; @@ -57024,4 +53722,4 @@ var TypeScript; Services.TypeScriptServicesFactory = ts.TypeScriptServicesFactory; })(Services = TypeScript.Services || (TypeScript.Services = {})); })(TypeScript || (TypeScript = {})); -var toolsVersion = "2.0"; +var toolsVersion = "1.9"; diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index 7ad94d4c292..2c9fffcfcfb 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -1,12 +1,8 @@ -/// /// declare namespace ts { - interface MapLike { + interface Map { [index: string]: T; } - interface Map extends MapLike { - __mapBrand: any; - } type Path = string & { __pathBrand: any; }; @@ -16,7 +12,6 @@ declare namespace ts { contains(fileName: Path): boolean; remove(fileName: Path): void; forEachValue(f: (key: Path, v: T) => void): void; - getKeys(): Path[]; clear(): void; } interface TextRange { @@ -190,7 +185,7 @@ declare namespace ts { IntersectionType = 163, ParenthesizedType = 164, ThisType = 165, - LiteralType = 166, + StringLiteralType = 166, ObjectBindingPattern = 167, ArrayBindingPattern = 168, BindingElement = 169, @@ -306,12 +301,8 @@ declare namespace ts { JSDocTypedefTag = 279, JSDocPropertyTag = 280, JSDocTypeLiteral = 281, - JSDocLiteralType = 282, - JSDocNullKeyword = 283, - JSDocUndefinedKeyword = 284, - JSDocNeverKeyword = 285, - SyntaxList = 286, - Count = 287, + SyntaxList = 282, + Count = 283, FirstAssignment = 56, LastAssignment = 68, FirstReservedWord = 70, @@ -336,9 +327,9 @@ declare namespace ts { LastBinaryOperator = 68, FirstNode = 139, FirstJSDocNode = 257, - LastJSDocNode = 282, + LastJSDocNode = 281, FirstJSDocTagNode = 273, - LastJSDocTagNode = 285, + LastJSDocTagNode = 281, } const enum NodeFlags { None = 0, @@ -414,10 +405,7 @@ declare namespace ts { interface ModifiersArray extends NodeArray { flags: NodeFlags; } - interface Token extends Node { - __tokenTag: any; - } - interface Modifier extends Token { + interface Modifier extends Node { } interface Identifier extends PrimaryExpression { text: string; @@ -604,9 +592,8 @@ declare namespace ts { interface ParenthesizedTypeNode extends TypeNode { type: TypeNode; } - interface LiteralTypeNode extends TypeNode { + interface StringLiteralTypeNode extends LiteralLikeNode, TypeNode { _stringLiteralTypeBrand: any; - literal: Expression; } interface StringLiteral extends LiteralExpression { _stringLiteralBrand: any; @@ -715,16 +702,11 @@ declare namespace ts { properties: NodeArray; multiLine?: boolean; } - type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression; - type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; interface PropertyAccessExpression extends MemberExpression, Declaration { expression: LeftHandSideExpression; name: Identifier; } - interface PropertyAccessEntityNameExpression extends PropertyAccessExpression { - _propertyAccessExpressionLikeQualifiedNameBrand?: any; - expression: EntityNameExpression; - } + type IdentifierOrPropertyAccess = Identifier | PropertyAccessExpression; interface ElementAccessExpression extends MemberExpression { expression: LeftHandSideExpression; argumentExpression?: Expression; @@ -1037,9 +1019,6 @@ declare namespace ts { interface JSDocThisType extends JSDocType { type: JSDocType; } - interface JSDocLiteralType extends JSDocType { - literal: LiteralTypeNode; - } type JSDocTypeReferencingNode = JSDocThisType | JSDocConstructorType | JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType; interface JSDocRecordMember extends PropertySignature { name: Identifier | LiteralExpression; @@ -1118,11 +1097,6 @@ declare namespace ts { clauseEnd: number; antecedent: FlowNode; } - type FlowType = Type | IncompleteType; - interface IncompleteType { - flags: TypeFlags; - type: Type; - } interface AmdDependency { path: string; name: string; @@ -1182,7 +1156,7 @@ declare namespace ts { interface Program extends ScriptReferenceHost { getRootFileNames(): string[]; getSourceFiles(): SourceFile[]; - emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean): EmitResult; + emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult; getOptionsDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; getGlobalDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; @@ -1191,7 +1165,6 @@ declare namespace ts { getTypeChecker(): TypeChecker; getCommonSourceDirectory(): string; getDiagnosticsProducingTypeChecker(): TypeChecker; - dropDiagnosticsProducingTypeChecker(): void; getClassifiableNames(): Map; getNodeCount(): number; getIdentifierCount(): number; @@ -1275,7 +1248,6 @@ declare namespace ts { getJsxElementAttributesType(elementNode: JsxOpeningLikeElement): Type; getJsxIntrinsicTagNames(): Symbol[]; isOptionalParameter(node: ParameterDeclaration): boolean; - getAmbientModules(): Symbol[]; getDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; getGlobalDiagnostics(): Diagnostic[]; getEmitResolver(sourceFile?: SourceFile, cancellationToken?: CancellationToken): EmitResolver; @@ -1322,8 +1294,6 @@ declare namespace ts { InElementType = 64, UseFullyQualifiedType = 128, InFirstTypeArgument = 256, - InTypeAlias = 512, - UseTypeAliasValue = 1024, } const enum SymbolFormatFlags { None = 0, @@ -1391,7 +1361,7 @@ declare namespace ts { writeTypeOfExpression(expr: Expression, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void; writeBaseConstructorTypeOfClass(node: ClassLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void; isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags): SymbolAccessibilityResult; - isEntityNameVisible(entityName: EntityNameOrEntityNameExpression, enclosingDeclaration: Node): SymbolVisibilityResult; + isEntityNameVisible(entityName: EntityName | Expression, enclosingDeclaration: Node): SymbolVisibilityResult; getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number; getReferencedValueDeclaration(reference: Identifier): Declaration; getTypeReferenceSerializationKind(typeName: EntityName): TypeReferenceSerializationKind; @@ -1399,7 +1369,7 @@ declare namespace ts { moduleExportsSomeValue(moduleReferenceExpression: Expression): boolean; isArgumentsLocalBinding(node: Identifier): boolean; getExternalModuleFileFromDeclaration(declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration | ModuleDeclaration): SourceFile; - getTypeReferenceDirectivesForEntityName(name: EntityNameOrEntityNameExpression): string[]; + getTypeReferenceDirectivesForEntityName(name: EntityName | PropertyAccessExpression): string[]; getTypeReferenceDirectivesForSymbol(symbol: Symbol, meaning?: SymbolFlags): string[]; } const enum SymbolFlags { @@ -1438,18 +1408,18 @@ declare namespace ts { Enum = 384, Variable = 3, Value = 107455, - Type = 793064, - Namespace = 1920, + Type = 793056, + Namespace = 1536, Module = 1536, Accessor = 98304, FunctionScopedVariableExcludes = 107454, BlockScopedVariableExcludes = 107455, ParameterExcludes = 107455, PropertyExcludes = 0, - EnumMemberExcludes = 900095, + EnumMemberExcludes = 107455, FunctionExcludes = 106927, ClassExcludes = 899519, - InterfaceExcludes = 792968, + InterfaceExcludes = 792960, RegularEnumExcludes = 899327, ConstEnumExcludes = 899967, ValueModuleExcludes = 106639, @@ -1457,8 +1427,8 @@ declare namespace ts { MethodExcludes = 99263, GetAccessorExcludes = 41919, SetAccessorExcludes = 74687, - TypeParameterExcludes = 530920, - TypeAliasExcludes = 793064, + TypeParameterExcludes = 530912, + TypeAliasExcludes = 793056, AliasExcludes = 8388608, ModuleMember = 8914931, ExportHasLocal = 944, @@ -1485,8 +1455,6 @@ declare namespace ts { exportSymbol?: Symbol; constEnumOnlyModule?: boolean; isReferenced?: boolean; - isReplaceableByMethod?: boolean; - isAssigned?: boolean; } interface SymbolLinks { target?: Symbol; @@ -1498,8 +1466,6 @@ declare namespace ts { mapper?: TypeMapper; referenced?: boolean; containingType?: UnionOrIntersectionType; - hasCommonType?: boolean; - isDiscriminantProperty?: boolean; resolvedExports?: SymbolTable; exportsChecked?: boolean; isDeclarationWithCollidingName?: boolean; @@ -1508,7 +1474,9 @@ declare namespace ts { } interface TransientSymbol extends Symbol, SymbolLinks { } - type SymbolTable = Map; + interface SymbolTable { + [index: string]: Symbol; + } interface Pattern { prefix: string; suffix: string; @@ -1535,14 +1503,13 @@ declare namespace ts { ClassWithBodyScopedClassBinding = 524288, BodyScopedClassBinding = 1048576, NeedsLoopOutParameter = 2097152, - AssignmentsMarked = 4194304, } interface NodeLinks { - flags?: NodeCheckFlags; resolvedType?: Type; resolvedSignature?: Signature; resolvedSymbol?: Symbol; resolvedIndexInfo?: IndexInfo; + flags?: NodeCheckFlags; enumMemberValue?: number; isVisible?: boolean; hasReportedStatementInAmbientContext?: boolean; @@ -1557,50 +1524,42 @@ declare namespace ts { String = 2, Number = 4, Boolean = 8, - Enum = 16, - StringLiteral = 32, - NumberLiteral = 64, - BooleanLiteral = 128, - EnumLiteral = 256, - ESSymbol = 512, - Void = 1024, - Undefined = 2048, - Null = 4096, - Never = 8192, - TypeParameter = 16384, - Class = 32768, - Interface = 65536, - Reference = 131072, - Tuple = 262144, - Union = 524288, - Intersection = 1048576, - Anonymous = 2097152, - Instantiated = 4194304, - ObjectLiteral = 8388608, - FreshObjectLiteral = 16777216, - ContainsWideningType = 33554432, - ContainsObjectLiteral = 67108864, - ContainsAnyFunctionType = 134217728, - ThisType = 268435456, - ObjectLiteralPatternWithComputedProperties = 536870912, - Nullable = 6144, - Literal = 480, - DefinitelyFalsy = 7392, - PossiblyFalsy = 7406, - Intrinsic = 16015, - Primitive = 8190, - StringLike = 34, - NumberLike = 340, - BooleanLike = 136, - EnumLike = 272, - ObjectType = 2588672, - UnionOrIntersection = 1572864, - StructuredType = 4161536, - StructuredOrTypeParameter = 4177920, - Narrowable = 4178943, - NotUnionOrUnit = 2589191, - RequiresWidening = 100663296, - PropagatingFlags = 234881024, + Void = 16, + Undefined = 32, + Null = 64, + Enum = 128, + StringLiteral = 256, + TypeParameter = 512, + Class = 1024, + Interface = 2048, + Reference = 4096, + Tuple = 8192, + Union = 16384, + Intersection = 32768, + Anonymous = 65536, + Instantiated = 131072, + FromSignature = 262144, + ObjectLiteral = 524288, + FreshObjectLiteral = 1048576, + ContainsWideningType = 2097152, + ContainsObjectLiteral = 4194304, + ContainsAnyFunctionType = 8388608, + ESSymbol = 16777216, + ThisType = 33554432, + ObjectLiteralPatternWithComputedProperties = 67108864, + Never = 134217728, + Nullable = 96, + Falsy = 112, + Intrinsic = 150995071, + Primitive = 16777726, + StringLike = 258, + NumberLike = 132, + ObjectType = 80896, + UnionOrIntersection = 49152, + StructuredType = 130048, + Narrowable = 16908175, + RequiresWidening = 6291456, + PropagatingFlags = 14680064, } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; interface Type { @@ -1608,21 +1567,13 @@ declare namespace ts { id: number; symbol?: Symbol; pattern?: DestructuringPattern; - aliasSymbol?: Symbol; - aliasTypeArguments?: Type[]; } interface IntrinsicType extends Type { intrinsicName: string; } - interface LiteralType extends Type { + interface StringLiteralType extends Type { text: string; } - interface EnumType extends Type { - memberTypes: Map; - } - interface EnumLiteralType extends LiteralType { - baseType: EnumType & UnionType; - } interface ObjectType extends Type { } interface InterfaceType extends ObjectType { @@ -1647,10 +1598,13 @@ declare namespace ts { interface GenericType extends InterfaceType, TypeReference { instantiations: Map; } + interface TupleType extends ObjectType { + elementTypes: Type[]; + } interface UnionOrIntersectionType extends Type { types: Type[]; + reducedType: Type; resolvedProperties: SymbolTable; - couldContainTypeParameters: boolean; } interface UnionType extends UnionOrIntersectionType { } @@ -1693,7 +1647,7 @@ declare namespace ts { resolvedReturnType: Type; minArgumentCount: number; hasRestParameter: boolean; - hasLiteralTypes: boolean; + hasStringLiterals: boolean; target?: Signature; mapper?: TypeMapper; unionSignatures?: Signature[]; @@ -1713,7 +1667,6 @@ declare namespace ts { interface TypeMapper { (t: TypeParameter): Type; mappedTypes?: Type[]; - targetTypes?: Type[]; instantiations?: Type[]; context?: InferenceContext; } @@ -1767,7 +1720,7 @@ declare namespace ts { NodeJs = 2, } type RootPaths = string[]; - type PathSubstitutions = MapLike; + type PathSubstitutions = Map; type TsConfigOnlyOptions = RootPaths | PathSubstitutions; type CompilerOptionsValue = string | number | boolean | (string | number)[] | TsConfigOnlyOptions; interface CompilerOptions { @@ -1782,7 +1735,6 @@ declare namespace ts { declaration?: boolean; declarationDir?: string; diagnostics?: boolean; - extendedDiagnostics?: boolean; disableSizeLimit?: boolean; emitBOM?: boolean; emitDecoratorMetadata?: boolean; @@ -1908,8 +1860,7 @@ declare namespace ts { fileNames: string[]; raw?: any; errors: Diagnostic[]; - wildcardDirectories?: MapLike; - compileOnSave?: boolean; + wildcardDirectories?: Map; } const enum WatchDirectoryFlags { None = 0, @@ -1917,7 +1868,7 @@ declare namespace ts { } interface ExpandResult { fileNames: string[]; - wildcardDirectories: MapLike; + wildcardDirectories: Map; } interface CommandLineOptionBase { name: string; @@ -2076,7 +2027,6 @@ declare namespace ts { directoryExists?(directoryName: string): boolean; realpath?(path: string): string; getCurrentDirectory?(): string; - getDirectories?(path: string): string[]; } interface ResolvedModule { resolvedFileName: string; @@ -2100,6 +2050,7 @@ declare namespace ts { getCancellationToken?(): CancellationToken; getDefaultLibFileName(options: CompilerOptions): string; getDefaultLibLocation?(): string; + getDefaultTypeDirectiveNames?(rootPath: string): string[]; writeFile: WriteFileCallback; getCurrentDirectory(): string; getDirectories(path: string): string[]; @@ -2128,25 +2079,12 @@ declare namespace ts { _children: Node[]; } } -declare namespace ts { - const timestamp: () => number; -} -declare namespace ts.performance { - function mark(markName: string): void; - function measure(measureName: string, startMarkName?: string, endMarkName?: string): void; - function getCount(markName: string): number; - function getDuration(measureName: string): number; - function forEachMeasure(cb: (measureName: string, duration: number) => void): void; - function enable(): void; - function disable(): void; -} declare namespace ts { const enum Ternary { False = 0, Maybe = 1, True = -1, } - function createMap(template?: MapLike): Map; function createFileMap(keyMapper?: (key: string) => string): FileMap; function toPath(fileName: string, basePath: string, getCanonicalFileName: (path: string) => string): Path; const enum Comparison { @@ -2154,15 +2092,12 @@ declare namespace ts { EqualTo = 0, GreaterThan = 1, } - function forEach(array: T[] | undefined, callback: (element: T, index: number) => U | undefined): U | undefined; - function find(array: T[], predicate: (element: T, index: number) => boolean): T | undefined; - function findMap(array: T[], callback: (element: T, index: number) => U | undefined): U; - function contains(array: T[], value: T): boolean; + function forEach(array: T[], callback: (element: T, index: number) => U): U; + function contains(array: T[], value: T, areEqual?: (a: T, b: T) => boolean): boolean; function indexOf(array: T[], value: T): number; function indexOfAnyCharCode(text: string, charCodes: number[], start?: number): number; function countWhere(array: T[], predicate: (x: T) => boolean): number; function filter(array: T[], f: (x: T) => boolean): T[]; - function removeWhere(array: T[], f: (x: T) => boolean): boolean; function filterMutate(array: T[], f: (x: T) => boolean): void; function map(array: T[], f: (x: T) => U): U[]; function concatenate(array1: T[], array2: T[]): T[]; @@ -2171,25 +2106,23 @@ declare namespace ts { function addRange(to: T[], from: T[]): void; function rangeEquals(array1: T[], array2: T[], pos: number, end: number): boolean; function lastOrUndefined(array: T[]): T; - function binarySearch(array: T[], value: T, comparer?: (v1: T, v2: T) => number): number; + function binarySearch(array: number[], value: number): number; function reduceLeft(array: T[], f: (a: T, x: T) => T): T; function reduceLeft(array: T[], f: (a: U, x: T) => U, initial: U): U; function reduceRight(array: T[], f: (a: T, x: T) => T): T; function reduceRight(array: T[], f: (a: U, x: T) => U, initial: U): U; - function hasProperty(map: MapLike, key: string): boolean; - function getProperty(map: MapLike, key: string): T | undefined; - function getOwnKeys(map: MapLike): string[]; - function forEachProperty(map: Map, callback: (value: T, key: string) => U): U; - function someProperties(map: Map, predicate?: (value: T, key: string) => boolean): boolean; - function copyProperties(source: Map, target: MapLike): void; - function reduceProperties(map: Map, callback: (aggregate: U, value: T, key: string) => U, initial: U): U; - function reduceOwnProperties(map: MapLike, callback: (aggregate: U, value: T, key: string) => U, initial: U): U; - function equalOwnProperties(left: MapLike, right: MapLike, equalityComparer?: (left: T, right: T) => boolean): boolean; - function arrayToMap(array: T[], makeKey: (value: T) => string): Map; - function arrayToMap(array: T[], makeKey: (value: T) => string, makeValue: (value: T) => U): Map; - function cloneMap(map: Map): Map; + function hasProperty(map: Map, key: string): boolean; + function getKeys(map: Map): string[]; + function getProperty(map: Map, key: string): T; + function isEmpty(map: Map): boolean; function clone(object: T): T; - function extend(first: T1, second: T2): T1 & T2; + function extend, T2 extends Map<{}>>(first: T1, second: T2): T1 & T2; + function forEachValue(map: Map, callback: (value: T) => U): U; + function forEachKey(map: Map, callback: (key: string) => U): U; + function lookUp(map: Map, key: string): T; + function copyMap(source: Map, target: Map): void; + function arrayToMap(array: T[], makeKey: (value: T) => string): Map; + function reduceProperties(map: Map, callback: (aggregate: U, value: T, key: string) => U, initial: U): U; function isArray(value: any): value is any[]; function memoize(callback: () => T): () => T; let localizedDiagnosticMessages: Map; @@ -2223,8 +2156,6 @@ declare namespace ts { function ensureTrailingDirectorySeparator(path: string): string; function comparePaths(a: string, b: string, currentDirectory: string, ignoreCase?: boolean): Comparison; function containsPath(parent: string, child: string, currentDirectory: string, ignoreCase?: boolean): boolean; - function startsWith(str: string, prefix: string): boolean; - function endsWith(str: string, suffix: string): boolean; function fileExtensionIs(path: string, extension: string): boolean; function fileExtensionIsAny(path: string, extensions: string[]): boolean; function getRegularExpressionForWildcard(specs: string[], basePath: string, usage: "files" | "directories" | "exclude"): string; @@ -2243,11 +2174,8 @@ declare namespace ts { function ensureScriptKind(fileName: string, scriptKind?: ScriptKind): ScriptKind; function getScriptKindFromFileName(fileName: string): ScriptKind; const supportedTypeScriptExtensions: string[]; - const supportedTypescriptExtensionsForExtractExtension: string[]; const supportedJavascriptExtensions: string[]; function getSupportedExtensions(options?: CompilerOptions): string[]; - function hasJavaScriptFileExtension(fileName: string): boolean; - function hasTypeScriptFileExtension(fileName: string): boolean; function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions): boolean; const enum ExtensionPriority { TypeScriptFiles = 0, @@ -2260,14 +2188,11 @@ declare namespace ts { function adjustExtensionPriority(extensionPriority: ExtensionPriority): ExtensionPriority; function getNextLowestExtensionPriority(extensionPriority: ExtensionPriority): ExtensionPriority; function removeFileExtension(path: string): string; - function tryRemoveExtension(path: string, extension: string): string | undefined; - function removeExtension(path: string, extension: string): string; + function tryRemoveExtension(path: string, extension: string): string; function isJsxOrTsxExtension(ext: string): boolean; function changeExtension(path: T, newExtension: string): T; interface ObjectAllocator { getNodeConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => Node; - getTokenConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => Token; - getIdentifierConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => Token; getSourceFileConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => SourceFile; getSymbolConstructor(): new (flags: SymbolFlags, name: string) => Symbol; getTypeConstructor(): new (checker: TypeChecker, flags: TypeFlags) => Type; @@ -2287,24 +2212,6 @@ declare namespace ts { } function copyListRemovingItem(item: T, list: T[]): T[]; function createGetCanonicalFileName(useCaseSensitivefileNames: boolean): (fileName: string) => string; - function trace(host: ModuleResolutionHost, message: DiagnosticMessage, ...args: any[]): void; - function isTraceEnabled(compilerOptions: CompilerOptions, host: ModuleResolutionHost): boolean; - function hasZeroOrOneAsteriskCharacter(str: string): boolean; - function createResolvedModule(resolvedFileName: string, isExternalLibraryImport: boolean, failedLookupLocations: string[]): ResolvedModuleWithFailedLookupLocations; - function isExternalModuleNameRelative(moduleName: string): boolean; - interface ModuleResolutionState { - host: ModuleResolutionHost; - compilerOptions: CompilerOptions; - traceEnabled: boolean; - skipTsx: boolean; - } - function readJson(path: string, host: ModuleResolutionHost): { - typings?: string; - types?: string; - main?: string; - }; - function getEmitModuleKind(compilerOptions: CompilerOptions): ModuleKind; - function getEmitScriptTarget(compilerOptions: CompilerOptions): ScriptTarget; } declare namespace ts { type FileWatcherCallback = (fileName: string, removed?: boolean) => void; @@ -4983,12 +4890,6 @@ declare namespace ts { key: string; message: string; }; - Enum_type_0_has_members_with_initializers_that_are_not_literals: { - code: number; - category: DiagnosticCategory; - key: string; - message: string; - }; JSX_element_attributes_type_0_may_not_be_a_union_type: { code: number; category: DiagnosticCategory; @@ -5271,24 +5172,6 @@ declare namespace ts { key: string; message: string; }; - A_class_must_be_declared_after_its_base_class: { - code: number; - category: DiagnosticCategory; - key: string; - message: string; - }; - An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: { - code: number; - category: DiagnosticCategory; - key: string; - message: string; - }; - _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: { - code: number; - category: DiagnosticCategory; - key: string; - message: string; - }; Import_declaration_0_is_using_private_name_1: { code: number; category: DiagnosticCategory; @@ -5709,7 +5592,7 @@ declare namespace ts { key: string; message: string; }; - Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: { + Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_to_resolve_this_conflict: { code: number; category: DiagnosticCategory; key: string; @@ -5877,12 +5760,6 @@ declare namespace ts { key: string; message: string; }; - Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: { - code: number; - category: DiagnosticCategory; - key: string; - message: string; - }; Concatenate_and_emit_output_to_single_file: { code: number; category: DiagnosticCategory; @@ -6579,13 +6456,13 @@ declare namespace ts { key: string; message: string; }; - Report_errors_on_unused_locals: { + Report_Errors_on_Unused_Locals: { code: number; category: DiagnosticCategory; key: string; message: string; }; - Report_errors_on_unused_parameters: { + Report_Errors_on_Unused_Parameters: { code: number; category: DiagnosticCategory; key: string; @@ -6603,18 +6480,6 @@ declare namespace ts { key: string; message: string; }; - Property_0_is_declared_but_never_used: { - code: number; - category: DiagnosticCategory; - key: string; - message: string; - }; - Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { - code: number; - category: DiagnosticCategory; - key: string; - message: string; - }; Variable_0_implicitly_has_an_1_type: { code: number; category: DiagnosticCategory; @@ -6663,6 +6528,12 @@ declare namespace ts { key: string; message: string; }; + Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; Index_signature_of_object_type_implicitly_has_an_any_type: { code: number; category: DiagnosticCategory; @@ -6747,18 +6618,6 @@ declare namespace ts { key: string; message: string; }; - Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { - code: number; - category: DiagnosticCategory; - key: string; - message: string; - }; - Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { - code: number; - category: DiagnosticCategory; - key: string; - message: string; - }; You_cannot_rename_this_element: { code: number; category: DiagnosticCategory; @@ -6991,137 +6850,35 @@ declare namespace ts { function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; } declare namespace ts { - const compileOnSaveCommandLineOption: CommandLineOption; const optionDeclarations: CommandLineOption[]; let typingOptionDeclarations: CommandLineOption[]; interface OptionNameMap { optionNameMap: Map; shortOptionNames: Map; } - const defaultInitCompilerOptions: CompilerOptions; function getOptionNameMap(): OptionNameMap; function createCompilerDiagnosticForInvalidCustomType(opt: CommandLineOptionOfCustomType): Diagnostic; - function parseCustomTypeOption(opt: CommandLineOptionOfCustomType, value: string, errors: Diagnostic[]): string | number; + function parseCustomTypeOption(opt: CommandLineOptionOfCustomType, value: string, errors: Diagnostic[]): number | string; function parseListTypeOption(opt: CommandLineOptionOfListType, value: string, errors: Diagnostic[]): (string | number)[] | undefined; function parseCommandLine(commandLine: string[], readFile?: (path: string) => string): ParsedCommandLine; function readConfigFile(fileName: string, readFile: (path: string) => string): { config?: any; error?: Diagnostic; }; - function parseConfigFileTextToJson(fileName: string, jsonText: string, stripComments?: boolean): { + function parseConfigFileTextToJson(fileName: string, jsonText: string): { config?: any; error?: Diagnostic; }; - function generateTSConfig(options: CompilerOptions, fileNames: string[]): { - compilerOptions: Map; - }; function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string): ParsedCommandLine; - function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; errors: Diagnostic[]; }; function convertTypingOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { - options: TypingOptions; + options: CompilerOptions; errors: Diagnostic[]; }; } -declare namespace ts.JsTyping { - interface TypingResolutionHost { - directoryExists: (path: string) => boolean; - fileExists: (fileName: string) => boolean; - readFile: (path: string, encoding?: string) => string; - readDirectory: (rootDir: string, extensions: string[], excludes: string[], includes: string[], depth?: number) => string[]; - } - function discoverTypings(host: TypingResolutionHost, fileNames: string[], projectRootPath: Path, safeListPath: Path, packageNameToTypingLocation: Map, typingOptions: TypingOptions, compilerOptions: CompilerOptions): { - cachedTypingPaths: string[]; - newTypingNames: string[]; - filesToWatch: string[]; - }; -} -declare namespace ts.server { - enum LogLevel { - terse = 0, - normal = 1, - requestTime = 2, - verbose = 3, - } - const emptyArray: ReadonlyArray; - interface Logger { - close(): void; - hasLevel(level: LogLevel): boolean; - loggingEnabled(): boolean; - perftrc(s: string): void; - info(s: string): void; - startGroup(): void; - endGroup(): void; - msg(s: string, type?: Msg.Types): void; - getLogFileName(): string; - } - namespace Msg { - type Err = "Err"; - const Err: Err; - type Info = "Info"; - const Info: Info; - type Perf = "Perf"; - const Perf: Perf; - type Types = Err | Info | Perf; - } - function createInstallTypingsRequest(project: Project, typingOptions: TypingOptions, cachePath?: string): DiscoverTypings; - namespace Errors { - function ThrowNoProject(): never; - function ThrowProjectLanguageServiceDisabled(): never; - function ThrowProjectDoesNotContainDocument(fileName: string, project: Project): never; - } - function getDefaultFormatCodeSettings(host: ServerHost): FormatCodeSettings; - function mergeMaps(target: MapLike, source: MapLike): void; - function removeItemFromSet(items: T[], itemToRemove: T): void; - type NormalizedPath = string & { - __normalizedPathTag: any; - }; - function toNormalizedPath(fileName: string): NormalizedPath; - function normalizedPathToPath(normalizedPath: NormalizedPath, currentDirectory: string, getCanonicalFileName: (f: string) => string): Path; - function asNormalizedPath(fileName: string): NormalizedPath; - interface NormalizedPathMap { - get(path: NormalizedPath): T; - set(path: NormalizedPath, value: T): void; - contains(path: NormalizedPath): boolean; - remove(path: NormalizedPath): void; - } - function createNormalizedPathMap(): NormalizedPathMap; - const nullLanguageService: LanguageService; - interface ServerLanguageServiceHost { - setCompilationSettings(options: CompilerOptions): void; - notifyFileRemoved(info: ScriptInfo): void; - } - const nullLanguageServiceHost: ServerLanguageServiceHost; - interface ProjectOptions { - configHasFilesProperty?: boolean; - files?: string[]; - wildcardDirectories?: Map; - compilerOptions?: CompilerOptions; - typingOptions?: TypingOptions; - compileOnSave?: boolean; - } - function isInferredProjectName(name: string): boolean; - function makeInferredProjectName(counter: number): string; - class ThrottledOperations { - private readonly host; - private pendingTimeouts; - constructor(host: ServerHost); - schedule(operationId: string, delay: number, cb: () => void): void; - private static run(self, operationId, cb); - } - class GcTimer { - private readonly host; - private readonly delay; - private readonly logger; - private timerId; - constructor(host: ServerHost, delay: number, logger: Logger); - scheduleCollect(): void; - private static run(self); - } -} declare namespace ts { interface ReferencePathMatchResult { fileReference?: FileReference; @@ -7150,7 +6907,8 @@ declare namespace ts { function getSingleLineStringWriter(): StringSymbolWriter; function releaseStringWriter(writer: StringSymbolWriter): void; function getFullWidth(node: Node): number; - function arrayIsEqualTo(array1: ReadonlyArray, array2: ReadonlyArray, equaler?: (a: T, b: T) => boolean): boolean; + function mapIsEqualTo(map1: Map, map2: Map): boolean; + function arrayIsEqualTo(array1: T[], array2: T[], equaler?: (a: T, b: T) => boolean): boolean; function hasResolvedModule(sourceFile: SourceFile, moduleNameText: string): boolean; function getResolvedModule(sourceFile: SourceFile, moduleNameText: string): ResolvedModule; function setResolvedModule(sourceFile: SourceFile, moduleNameText: string, resolvedModule: ResolvedModule): void; @@ -7169,7 +6927,6 @@ declare namespace ts { function nodeIsPresent(node: Node): boolean; function getTokenPosOfNode(node: Node, sourceFile?: SourceFile, includeJsDocComment?: boolean): number; function isJSDocNode(node: Node): boolean; - function isJSDocTag(node: Node): boolean; function getNonDecoratorTokenPosOfNode(node: Node, sourceFile?: SourceFile): number; function getSourceTextOfNodeFromSourceFile(sourceFile: SourceFile, node: Node, includeTrivia?: boolean): string; function getTextOfNodeFromSourceText(sourceText: string, node: Node): string; @@ -7179,7 +6936,7 @@ declare namespace ts { function makeIdentifierFromModuleName(moduleName: string): string; function isBlockOrCatchScoped(declaration: Declaration): boolean; function isAmbientModule(node: Node): boolean; - function isShorthandAmbientModuleSymbol(moduleSymbol: Symbol): boolean; + function isShorthandAmbientModule(node: Node): boolean; function isBlockScopedContainerTopLevel(node: Node): boolean; function isGlobalScopeAugmentation(module: ModuleDeclaration): boolean; function isExternalModuleAugmentation(node: Node): boolean; @@ -7225,7 +6982,7 @@ declare namespace ts { function getSuperContainer(node: Node, stopOnFunctions: boolean): Node; function getImmediatelyInvokedFunctionExpression(func: Node): CallExpression; function isSuperPropertyOrElementAccess(node: Node): boolean; - function getEntityNameFromTypeNode(node: TypeNode): EntityNameOrEntityNameExpression; + function getEntityNameFromTypeNode(node: TypeNode): EntityName | Expression; function getInvokedExpression(node: CallLikeExpression): Expression; function nodeCanBeDecorated(node: Node): boolean; function nodeIsDecorated(node: Node): boolean; @@ -7233,6 +6990,7 @@ declare namespace ts { function isElementAccessExpression(node: Node): node is ElementAccessExpression; function isJSXTagName(node: Node): boolean; function isExpression(node: Node): boolean; + function isExternalModuleNameRelative(moduleName: string): boolean; function isInstantiatedModule(node: ModuleDeclaration, preserveConstEnums: boolean): boolean; function isExternalModuleImportEqualsDeclaration(node: Node): boolean; function getExternalModuleImportEqualsDeclarationExpression(node: Node): Expression; @@ -7268,7 +7026,6 @@ declare namespace ts { function isLiteralComputedPropertyDeclarationName(node: Node): boolean; function isIdentifierName(node: Identifier): boolean; function isAliasSymbolDeclaration(node: Node): boolean; - function exportAssignmentIsAlias(node: ExportAssignment): boolean; function getClassExtendsHeritageClauseElement(node: ClassLikeDeclaration | InterfaceDeclaration): ExpressionWithTypeArguments; function getClassImplementsHeritageClauseElements(node: ClassLikeDeclaration): NodeArray; function getInterfaceBaseTypeNodes(node: InterfaceDeclaration): NodeArray; @@ -7321,12 +7078,14 @@ declare namespace ts { function getExternalModuleNameFromPath(host: EmitHost, fileName: string): string; function getOwnEmitOutputFilePath(sourceFile: SourceFile, host: EmitHost, extension: string): string; function getDeclarationEmitOutputFilePath(sourceFile: SourceFile, host: EmitHost): string; + function getEmitScriptTarget(compilerOptions: CompilerOptions): ScriptTarget; + function getEmitModuleKind(compilerOptions: CompilerOptions): ModuleKind; interface EmitFileNames { jsFilePath: string; sourceMapFilePath: string; declarationFilePath: string; } - function forEachExpectedEmitFile(host: EmitHost, action: (emitFileNames: EmitFileNames, sourceFiles: SourceFile[], isBundledEmit: boolean, emitOnlyDtsFiles: boolean) => void, targetSourceFile?: SourceFile, emitOnlyDtsFiles?: boolean): void; + function forEachExpectedEmitFile(host: EmitHost, action: (emitFileNames: EmitFileNames, sourceFiles: SourceFile[], isBundledEmit: boolean) => void, targetSourceFile?: SourceFile): void; function getSourceFilePathInNewDir(sourceFile: SourceFile, host: EmitHost, newDirPath: string): string; function writeFile(host: EmitHost, diagnostics: DiagnosticCollection, fileName: string, data: string, writeByteOrderMark: boolean, sourceFiles?: SourceFile[]): void; function getLineOfLocalPosition(currentSourceFile: SourceFile, pos: number): number; @@ -7350,11 +7109,12 @@ declare namespace ts { function isLeftHandSideExpression(expr: Expression): boolean; function isAssignmentOperator(token: SyntaxKind): boolean; function isExpressionWithTypeArgumentsInClassExtendsClause(node: Node): boolean; - function isEntityNameExpression(node: Expression): node is EntityNameExpression; + function isSupportedExpressionWithTypeArguments(node: ExpressionWithTypeArguments): boolean; function isRightSideOfQualifiedNameOrPropertyAccess(node: Node): boolean; function isEmptyObjectLiteralOrArrayLiteral(expression: Node): boolean; function getLocalSymbolForExportDefault(symbol: Symbol): Symbol; - function tryExtractTypeScriptExtension(fileName: string): string | undefined; + function hasJavaScriptFileExtension(fileName: string): boolean; + function hasTypeScriptFileExtension(fileName: string): boolean; const stringify: (value: any) => string; function convertToBase64(input: string): string; function convertToRelativePath(absoluteOrRelativePath: string, basePath: string, getCanonicalFileName: (path: string) => string): string; @@ -7383,21 +7143,11 @@ declare namespace ts { function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange; function getTypeParameterOwner(d: Declaration): Declaration; function isParameterPropertyDeclaration(node: ParameterDeclaration): boolean; + function startsWith(str: string, prefix: string): boolean; + function endsWith(str: string, suffix: string): boolean; } declare namespace ts { - function loadNodeModuleFromDirectory(extensions: string[], candidate: string, failedLookupLocation: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): string; - function loadModuleFromNodeModules(moduleName: string, directory: string, failedLookupLocations: string[], state: ModuleResolutionState, checkOneLevel: boolean): string; - function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function findBestPatternMatch(values: T[], getPattern: (value: T) => Pattern, candidate: string): T | undefined; - function tryParsePattern(pattern: string): Pattern | undefined; - function directoryProbablyExists(directoryName: string, host: { - directoryExists?: (directoryName: string) => boolean; - }): boolean; - function pathToPackageJson(directory: string): string; -} -declare namespace ts { + let parseTime: number; function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T; function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile; @@ -7411,9 +7161,9 @@ declare namespace ts { jsDocTypeExpression: JSDocTypeExpression; diagnostics: Diagnostic[]; }; - function fixupParentReferences(rootNode: Node): void; } declare namespace ts { + let bindTime: number; const enum ModuleInstanceState { NonInstantiated = 0, Instantiated = 1, @@ -7424,6 +7174,7 @@ declare namespace ts { } declare namespace ts { function getNodeId(node: Node): number; + let checkTime: number; function getSymbolId(symbol: Symbol): number; function createTypeChecker(host: TypeCheckerHost, produceDiagnostics: boolean): TypeChecker; } @@ -7445,33 +7196,37 @@ declare namespace ts { } declare namespace ts { function getDeclarationDiagnostics(host: EmitHost, resolver: EmitResolver, targetSourceFile: SourceFile): Diagnostic[]; - function writeDeclarationFile(declarationFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean, host: EmitHost, resolver: EmitResolver, emitterDiagnostics: DiagnosticCollection, emitOnlyDtsFiles: boolean): boolean; + function writeDeclarationFile(declarationFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean, host: EmitHost, resolver: EmitResolver, emitterDiagnostics: DiagnosticCollection): boolean; } declare namespace ts { function getResolvedExternalModuleName(host: EmitHost, file: SourceFile): string; function getExternalModuleNameFromDeclaration(host: EmitHost, resolver: EmitResolver, declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration): string; - function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFile: SourceFile, emitOnlyDtsFiles?: boolean): EmitResult; + function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFile: SourceFile): EmitResult; } declare namespace ts { + let programTime: number; + let emitTime: number; + let ioReadTime: number; + let ioWriteTime: number; const version: string; - function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string; + function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean): string; function resolveTripleslashReference(moduleName: string, containingFile: string): string; function computeCommonSourceDirectoryOfFilenames(fileNames: string[], currentDirectory: string, getCanonicalFileName: (fileName: string) => string): string; - function getEffectiveTypeRoots(options: CompilerOptions, host: { - directoryExists?(directoryName: string): boolean; - getCurrentDirectory?(): string; - }): string[] | undefined; + function hasZeroOrOneAsteriskCharacter(str: string): boolean; function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; + function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function findBestPatternMatch(values: T[], getPattern: (value: T) => Pattern, candidate: string): T | undefined; + function tryParsePattern(pattern: string): Pattern | undefined; + function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function directoryProbablyExists(directoryName: string, host: { + directoryExists?: (directoryName: string) => boolean; + }): boolean; + function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + const defaultInitCompilerOptions: CompilerOptions; function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; - interface FormatDiagnosticsHost { - getCurrentDirectory(): string; - getCanonicalFileName(fileName: string): string; - getNewLine(): string; - } - function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; - function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; + function getAutomaticTypeDirectiveNames(options: CompilerOptions, rootFiles: string[], host: CompilerHost): string[]; function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } declare namespace ts.BreakpointResolver { @@ -7481,7 +7236,7 @@ declare namespace ts.OutliningElementsCollector { function collectElements(sourceFile: SourceFile): OutliningSpan[]; } declare namespace ts.NavigateTo { - function getNavigateToItems(program: Program, checker: TypeChecker, cancellationToken: CancellationToken, searchValue: string, maxResultCount: number, excludeDts: boolean): NavigateToItem[]; + function getNavigateToItems(program: Program, checker: TypeChecker, cancellationToken: CancellationToken, searchValue: string, maxResultCount: number): NavigateToItem[]; } declare namespace ts.NavigationBar { function getNavigationBarItems(sourceFile: SourceFile): NavigationBarItem[]; @@ -7566,9 +7321,6 @@ declare namespace ts { function isAccessibilityModifier(kind: SyntaxKind): boolean; function compareDataObjects(dst: any, src: any): boolean; function isArrayLiteralOrObjectLiteralDestructuringPattern(node: Node): boolean; - function hasTrailingDirectorySeparator(path: string): boolean; - function isInReferenceComment(sourceFile: SourceFile, position: number): boolean; - function isInNonReferenceComment(sourceFile: SourceFile, position: number): boolean; } declare namespace ts { function isFirstDeclarationOfSymbolParameter(symbol: Symbol): boolean; @@ -7591,9 +7343,18 @@ declare namespace ts { function stripQuotes(name: string): string; function scriptKindIs(fileName: string, host: LanguageServiceHost, ...scriptKinds: ScriptKind[]): boolean; function getScriptKind(fileName: string, host?: LanguageServiceHost): ScriptKind; - function sanitizeConfigFile(configFileName: string, content: string): { - configJsonObject: any; - diagnostics: Diagnostic[]; +} +declare namespace ts.JsTyping { + interface TypingResolutionHost { + directoryExists: (path: string) => boolean; + fileExists: (fileName: string) => boolean; + readFile: (path: string, encoding?: string) => string; + readDirectory: (rootDir: string, extensions: string[], excludes: string[], includes: string[], depth?: number) => string[]; + } + function discoverTypings(host: TypingResolutionHost, fileNames: string[], projectRootPath: Path, safeListPath: Path, packageNameToTypingLocation: Map, typingOptions: TypingOptions, compilerOptions: CompilerOptions): { + cachedTypingPaths: string[]; + newTypingNames: string[]; + filesToWatch: string[]; }; } declare namespace ts.formatting { @@ -7815,11 +7576,6 @@ declare namespace ts.formatting { SpaceAfterOpenBraceInJsxExpression: Rule; NoSpaceBeforeCloseBraceInJsxExpression: Rule; SpaceBeforeCloseBraceInJsxExpression: Rule; - SpaceBeforeJsxAttribute: Rule; - SpaceBeforeSlashInJsxOpeningElement: Rule; - NoSpaceBeforeGreaterThanTokenInJsxOpeningElement: Rule; - NoSpaceBeforeEqualInJsxAttribute: Rule; - NoSpaceAfterEqualInJsxAttribute: Rule; constructor(); static IsForContext(context: FormattingContext): boolean; static IsNotForContext(context: FormattingContext): boolean; @@ -7847,11 +7603,8 @@ declare namespace ts.formatting { static IsNextTokenNotCloseBracket(context: FormattingContext): boolean; static IsArrowFunctionContext(context: FormattingContext): boolean; static IsNonJsxSameLineTokenContext(context: FormattingContext): boolean; - static IsNonJsxElementContext(context: FormattingContext): boolean; - static IsJsxExpressionContext(context: FormattingContext): boolean; - static IsNextTokenParentJsxAttribute(context: FormattingContext): boolean; - static IsJsxAttributeContext(context: FormattingContext): boolean; - static IsJsxSelfClosingElementContext(context: FormattingContext): boolean; + static isNonJsxElementContext(context: FormattingContext): boolean; + static isJsxExpressionContext(context: FormattingContext): boolean; static IsNotBeforeBlockInFunctionDeclarationContext(context: FormattingContext): boolean; static IsEndOfDecoratorContextOnSameLine(context: FormattingContext): boolean; static NodeIsInDecoratorContext(node: Node): boolean; @@ -7964,7 +7717,7 @@ declare namespace ts.formatting { getRuleName(rule: Rule): string; getRuleByName(name: string): Rule; getRulesMap(): RulesMap; - ensureUpToDate(options: ts.FormatCodeSettings): void; + ensureUpToDate(options: ts.FormatCodeOptions): void; private createActiveRules(options); } } @@ -7977,24 +7730,24 @@ declare namespace ts.formatting { token: TextRangeWithKind; trailingTrivia: TextRangeWithKind[]; } - function formatOnEnter(position: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeSettings): TextChange[]; - function formatOnSemicolon(position: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeSettings): TextChange[]; - function formatOnClosingCurly(position: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeSettings): TextChange[]; - function formatDocument(sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeSettings): TextChange[]; - function formatSelection(start: number, end: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeSettings): TextChange[]; - function getIndentationString(indentation: number, options: EditorSettings): string; + function formatOnEnter(position: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeOptions): TextChange[]; + function formatOnSemicolon(position: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeOptions): TextChange[]; + function formatOnClosingCurly(position: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeOptions): TextChange[]; + function formatDocument(sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeOptions): TextChange[]; + function formatSelection(start: number, end: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeOptions): TextChange[]; + function getIndentationString(indentation: number, options: FormatCodeOptions): string; } declare namespace ts.formatting { namespace SmartIndenter { - function getIndentation(position: number, sourceFile: SourceFile, options: EditorSettings): number; - function getIndentationForNode(n: Node, ignoreActualIndentationRange: TextRange, sourceFile: SourceFile, options: EditorSettings): number; - function getBaseIndentation(options: EditorSettings): number; + function getIndentation(position: number, sourceFile: SourceFile, options: EditorOptions): number; + function getBaseIndentation(options: EditorOptions): number; + function getIndentationForNode(n: Node, ignoreActualIndentationRange: TextRange, sourceFile: SourceFile, options: FormatCodeOptions): number; function childStartsOnTheSameLineWithElseInIfStatement(parent: Node, child: TextRangeWithKind, childStartLine: number, sourceFile: SourceFile): boolean; - function findFirstNonWhitespaceCharacterAndColumn(startPos: number, endPos: number, sourceFile: SourceFile, options: EditorSettings): { + function findFirstNonWhitespaceCharacterAndColumn(startPos: number, endPos: number, sourceFile: SourceFile, options: EditorOptions): { column: number; character: number; }; - function findFirstNonWhitespaceColumn(startPos: number, endPos: number, sourceFile: SourceFile, options: EditorSettings): number; + function findFirstNonWhitespaceColumn(startPos: number, endPos: number, sourceFile: SourceFile, options: EditorOptions): number; function nodeWillIndentChild(parent: TextRangeWithKind, child: TextRangeWithKind, indentByDefault: boolean): boolean; function shouldIndentChildNode(parent: TextRangeWithKind, child?: TextRangeWithKind): boolean; } @@ -8056,7 +7809,7 @@ declare namespace ts { interface IScriptSnapshot { getText(start: number, end: number): string; getLength(): number; - getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange | undefined; + getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange; dispose?(): void; } namespace ScriptSnapshot { @@ -8069,20 +7822,6 @@ declare namespace ts { ambientExternalModules: string[]; isLibFile: boolean; } - function realizeDiagnostics(diagnostics: Diagnostic[], newLine: string): { - message: string; - start: number; - length: number; - category: string; - code: number; - }[]; - function realizeDiagnostic(diagnostic: Diagnostic, newLine: string): { - message: string; - start: number; - length: number; - category: string; - code: number; - }; interface HostCancellationToken { isCancellationRequested(): boolean; } @@ -8102,10 +7841,6 @@ declare namespace ts { trace?(s: string): void; error?(s: string): void; useCaseSensitiveFileNames?(): boolean; - readDirectory?(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[]; - readFile?(path: string, encoding?: string): string; - fileExists?(path: string): boolean; - getTypeRootsVersion?(): number; resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; directoryExists?(directoryName: string): boolean; @@ -8134,18 +7869,18 @@ declare namespace ts { findReferences(fileName: string, position: number): ReferencedSymbol[]; getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[]; getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[]; - getNavigateToItems(searchValue: string, maxResultCount?: number, excludeDts?: boolean): NavigateToItem[]; + getNavigateToItems(searchValue: string, maxResultCount?: number): NavigateToItem[]; getNavigationBarItems(fileName: string): NavigationBarItem[]; getOutliningSpans(fileName: string): OutliningSpan[]; getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[]; getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[]; - getIndentationAtPosition(fileName: string, position: number, options: EditorOptions | EditorSettings): number; - getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; - getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; - getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; + getIndentationAtPosition(fileName: string, position: number, options: EditorOptions): number; + getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions): TextChange[]; + getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions): TextChange[]; + getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): TextChange[]; getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; - getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; + getEmitOutput(fileName: string): EmitOutput; getProgram(): Program; getNonBoundSourceFile(fileName: string): SourceFile; dispose(): void; @@ -8229,14 +7964,6 @@ declare namespace ts { ConvertTabsToSpaces: boolean; IndentStyle: IndentStyle; } - interface EditorSettings { - baseIndentSize?: number; - indentSize: number; - tabSize: number; - newLineCharacter: string; - convertTabsToSpaces: boolean; - indentStyle: IndentStyle; - } enum IndentStyle { None = 0, Block = 1, @@ -8254,22 +7981,8 @@ declare namespace ts { InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; PlaceOpenBraceOnNewLineForFunctions: boolean; PlaceOpenBraceOnNewLineForControlBlocks: boolean; + [s: string]: boolean | number | string | undefined; } - interface FormatCodeSettings extends EditorSettings { - insertSpaceAfterCommaDelimiter: boolean; - insertSpaceAfterSemicolonInForStatements: boolean; - insertSpaceBeforeAndAfterBinaryOperators: boolean; - insertSpaceAfterKeywordsInControlFlowStatements: boolean; - insertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean; - insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: boolean; - insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: boolean; - insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: boolean; - insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: boolean; - placeOpenBraceOnNewLineForFunctions: boolean; - placeOpenBraceOnNewLineForControlBlocks: boolean; - } - function toEditorSettings(options: FormatCodeOptions | FormatCodeSettings): FormatCodeSettings; - function toEditorSettings(options: EditorOptions | EditorSettings): EditorSettings; interface DefinitionInfo { fileName: string; textSpan: TextSpan; @@ -8278,11 +7991,8 @@ declare namespace ts { containerKind: string; containerName: string; } - interface ReferencedSymbolDefinitionInfo extends DefinitionInfo { - displayParts: SymbolDisplayPart[]; - } interface ReferencedSymbol { - definition: ReferencedSymbolDefinitionInfo; + definition: DefinitionInfo; references: ReferenceEntry[]; } enum SymbolDisplayPartKind { @@ -8360,7 +8070,6 @@ declare namespace ts { kind: string; kindModifiers: string; sortText: string; - replacementSpan?: TextSpan; } interface CompletionEntryDetails { name: string; @@ -8445,7 +8154,6 @@ declare namespace ts { const interfaceElement: string; const typeElement: string; const enumElement: string; - const enumMemberElement: string; const variableElement: string; const localVariableElement: string; const functionElement: string; @@ -8465,8 +8173,6 @@ declare namespace ts { const alias: string; const constElement: string; const letElement: string; - const directory: string; - const externalModuleName: string; } namespace ScriptElementKindModifier { const none: string; @@ -8539,7 +8245,7 @@ declare namespace ts { fileName?: string; reportDiagnostics?: boolean; moduleName?: string; - renamedDependencies?: MapLike; + renamedDependencies?: Map; } interface TranspileOutput { outputText: string; @@ -8561,498 +8267,99 @@ declare namespace ts { function getDefaultLibFilePath(options: CompilerOptions): string; } declare namespace ts.server { - class ScriptInfo { - private readonly host; - readonly fileName: NormalizedPath; - readonly scriptKind: ScriptKind; - isOpen: boolean; - hasMixedContent: boolean; - readonly containingProjects: Project[]; - private formatCodeSettings; - readonly path: Path; - private fileWatcher; - private svc; - constructor(host: ServerHost, fileName: NormalizedPath, content: string, scriptKind: ScriptKind, isOpen?: boolean, hasMixedContent?: boolean); - getFormatCodeSettings(): FormatCodeSettings; - attachToProject(project: Project): boolean; - isAttached(project: Project): boolean; - detachFromProject(project: Project): void; - detachAllProjects(): void; - getDefaultProject(): Project; - setFormatOptions(formatSettings: protocol.FormatOptions): void; - setWatcher(watcher: FileWatcher): void; - stopWatcher(): void; - getLatestVersion(): string; - reload(script: string): void; - saveTo(fileName: string): void; - reloadFromFile(): void; - snap(): LineIndexSnapshot; - getLineInfo(line: number): ILineInfo; - editContent(start: number, end: number, newText: string): void; - markContainingProjectsAsDirty(): void; - lineToTextSpan(line: number): TextSpan; - lineOffsetToPosition(line: number, offset: number): number; - positionToLineOffset(position: number): ILineInfo; - } -} -declare namespace ts.server { - class LSHost implements ts.LanguageServiceHost, ModuleResolutionHost, ServerLanguageServiceHost { - private readonly host; - private readonly project; - private readonly cancellationToken; - private compilationSettings; - private readonly resolvedModuleNames; - private readonly resolvedTypeReferenceDirectives; - private readonly getCanonicalFileName; - private readonly resolveModuleName; - readonly trace: (s: string) => void; - constructor(host: ServerHost, project: Project, cancellationToken: HostCancellationToken); - private resolveNamesWithLocalCache(names, containingFile, cache, loader, getResult); - getProjectVersion(): string; - getCompilationSettings(): CompilerOptions; - useCaseSensitiveFileNames(): boolean; - getCancellationToken(): HostCancellationToken; - resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; - resolveModuleNames(moduleNames: string[], containingFile: string): ResolvedModule[]; - getDefaultLibFileName(): string; - getScriptSnapshot(filename: string): ts.IScriptSnapshot; - getScriptFileNames(): string[]; - getTypeRootsVersion(): number; - getScriptKind(fileName: string): ScriptKind; - getScriptVersion(filename: string): string; - getCurrentDirectory(): string; - resolvePath(path: string): string; - fileExists(path: string): boolean; - directoryExists(path: string): boolean; - readFile(fileName: string): string; - getDirectories(path: string): string[]; - notifyFileRemoved(info: ScriptInfo): void; - setCompilationSettings(opt: ts.CompilerOptions): void; - } -} -declare namespace ts.server { - interface ITypingsInstaller { - enqueueInstallTypingsRequest(p: Project, typingOptions: TypingOptions): void; - attach(projectService: ProjectService): void; - onProjectClosed(p: Project): void; - readonly globalTypingsCacheLocation: string; - } - const nullTypingsInstaller: ITypingsInstaller; - interface TypingsArray extends ReadonlyArray { - " __typingsArrayBrand": any; - } - class TypingsCache { - private readonly installer; - private readonly perProjectCache; - constructor(installer: ITypingsInstaller); - getTypingsForProject(project: Project, forceRefresh: boolean): TypingsArray; - invalidateCachedTypingsForProject(project: Project): void; - updateTypingsForProject(projectName: string, compilerOptions: CompilerOptions, typingOptions: TypingOptions, newTypings: string[]): void; - onProjectClosed(project: Project): void; - } -} -declare namespace ts.server { - function shouldEmitFile(scriptInfo: ScriptInfo): boolean; - class BuilderFileInfo { - readonly scriptInfo: ScriptInfo; - readonly project: Project; - private lastCheckedShapeSignature; - constructor(scriptInfo: ScriptInfo, project: Project); - isExternalModuleOrHasOnlyAmbientExternalModules(): boolean; - private containsOnlyAmbientModules(sourceFile); - private computeHash(text); - private getSourceFile(); - updateShapeSignature(): boolean; - } - interface Builder { - readonly project: Project; - getFilesAffectedBy(scriptInfo: ScriptInfo): string[]; - onProjectUpdateGraph(): void; - emitFile(scriptInfo: ScriptInfo, writeFile: (path: string, data: string, writeByteOrderMark?: boolean) => void): boolean; - } - function createBuilder(project: Project): Builder; -} -declare namespace ts.server { - enum ProjectKind { - Inferred = 0, - Configured = 1, - External = 2, - } - function allRootFilesAreJsOrDts(project: Project): boolean; - function allFilesAreJsOrDts(project: Project): boolean; - interface ProjectFilesWithTSDiagnostics extends protocol.ProjectFiles { - projectErrors: Diagnostic[]; - } - abstract class Project { - readonly projectKind: ProjectKind; - readonly projectService: ProjectService; - private documentRegistry; - languageServiceEnabled: boolean; - private compilerOptions; - compileOnSaveEnabled: boolean; - private rootFiles; - private rootFilesMap; - private lsHost; - private program; - private languageService; - builder: Builder; - private lastReportedFileNames; - private lastReportedVersion; - private projectStructureVersion; - private projectStateVersion; - private typingFiles; - protected projectErrors: Diagnostic[]; - typesVersion: number; - isJsOnlyProject(): boolean; - constructor(projectKind: ProjectKind, projectService: ProjectService, documentRegistry: ts.DocumentRegistry, hasExplicitListOfFiles: boolean, languageServiceEnabled: boolean, compilerOptions: CompilerOptions, compileOnSaveEnabled: boolean); - getProjectErrors(): Diagnostic[]; - getLanguageService(ensureSynchronized?: boolean): LanguageService; - getCompileOnSaveAffectedFileList(scriptInfo: ScriptInfo): string[]; - getProjectVersion(): string; - enableLanguageService(): void; - disableLanguageService(): void; - abstract getProjectName(): string; - abstract getProjectRootPath(): string | undefined; - abstract getTypingOptions(): TypingOptions; - getSourceFile(path: Path): SourceFile; - updateTypes(): void; - close(): void; - getCompilerOptions(): CompilerOptions; - hasRoots(): boolean; - getRootFiles(): NormalizedPath[]; - getRootFilesLSHost(): string[]; - getRootScriptInfos(): ScriptInfo[]; - getScriptInfos(): ScriptInfo[]; - getFileEmitOutput(info: ScriptInfo, emitOnlyDtsFiles: boolean): EmitOutput; - getFileNames(): NormalizedPath[]; - getAllEmittableFiles(): string[]; - containsScriptInfo(info: ScriptInfo): boolean; - containsFile(filename: NormalizedPath, requireOpen?: boolean): boolean; - isRoot(info: ScriptInfo): boolean; - addRoot(info: ScriptInfo): void; - removeFile(info: ScriptInfo, detachFromProject?: boolean): void; - markAsDirty(): void; - updateGraph(): boolean; - private setTypings(typings); - private updateGraphWorker(); - getScriptInfoLSHost(fileName: string): ScriptInfo; - getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo; - getScriptInfo(uncheckedFileName: string): ScriptInfo; - filesToString(): string; - setCompilerOptions(compilerOptions: CompilerOptions): void; - reloadScript(filename: NormalizedPath): boolean; - getChangesSinceVersion(lastKnownVersion?: number): ProjectFilesWithTSDiagnostics; - getReferencedFiles(path: Path): Path[]; - private removeRootFileIfNecessary(info); - } - class InferredProject extends Project { - compileOnSaveEnabled: boolean; - private static NextId; - private readonly inferredProjectName; - directoriesWatchedForTsconfig: string[]; - constructor(projectService: ProjectService, documentRegistry: ts.DocumentRegistry, languageServiceEnabled: boolean, compilerOptions: CompilerOptions, compileOnSaveEnabled: boolean); - getProjectName(): string; - getProjectRootPath(): string; - close(): void; - getTypingOptions(): TypingOptions; - } - class ConfiguredProject extends Project { - readonly configFileName: NormalizedPath; - private wildcardDirectories; - compileOnSaveEnabled: boolean; - private typingOptions; - private projectFileWatcher; - private directoryWatcher; - private directoriesWatchedForWildcards; - private typeRootsWatchers; - openRefCount: number; - constructor(configFileName: NormalizedPath, projectService: ProjectService, documentRegistry: ts.DocumentRegistry, hasExplicitListOfFiles: boolean, compilerOptions: CompilerOptions, wildcardDirectories: Map, languageServiceEnabled: boolean, compileOnSaveEnabled: boolean); - getProjectRootPath(): string; - setProjectErrors(projectErrors: Diagnostic[]): void; - setTypingOptions(newTypingOptions: TypingOptions): void; - getTypingOptions(): TypingOptions; - getProjectName(): string & { - __normalizedPathTag: any; - }; - watchConfigFile(callback: (project: ConfiguredProject) => void): void; - watchTypeRoots(callback: (project: ConfiguredProject, path: string) => void): void; - watchConfigDirectory(callback: (project: ConfiguredProject, path: string) => void): void; - watchWildcards(callback: (project: ConfiguredProject, path: string) => void): void; - stopWatchingDirectory(): void; - close(): void; - addOpenRef(): void; - deleteOpenRef(): number; - getEffectiveTypeRoots(): string[]; - } - class ExternalProject extends Project { - readonly externalProjectName: string; - compileOnSaveEnabled: boolean; - private readonly projectFilePath; - private typingOptions; - constructor(externalProjectName: string, projectService: ProjectService, documentRegistry: ts.DocumentRegistry, compilerOptions: CompilerOptions, languageServiceEnabled: boolean, compileOnSaveEnabled: boolean, projectFilePath?: string); - getProjectRootPath(): string; - getTypingOptions(): TypingOptions; - setProjectErrors(projectErrors: Diagnostic[]): void; - setTypingOptions(newTypingOptions: TypingOptions): void; - getProjectName(): string; - } -} -declare namespace ts.server { - const maxProgramSizeForNonTsFiles: number; - type ProjectServiceEvent = { - eventName: "context"; - data: { - project: Project; - fileName: NormalizedPath; - }; - } | { - eventName: "configFileDiag"; - data: { - triggerFile?: string; - configFileName: string; - diagnostics: Diagnostic[]; - }; - }; - interface ProjectServiceEventHandler { - (event: ProjectServiceEvent): void; - } - function combineProjectOutput(projects: Project[], action: (project: Project) => T[], comparer?: (a: T, b: T) => number, areEqual?: (a: T, b: T) => boolean): T[]; - interface HostConfiguration { - formatCodeOptions: FormatCodeSettings; - hostInfo: string; - } - interface OpenConfiguredProjectResult { - configFileName?: string; - configFileErrors?: Diagnostic[]; - } - class ProjectService { - readonly host: ServerHost; - readonly logger: Logger; - readonly cancellationToken: HostCancellationToken; - readonly useSingleInferredProject: boolean; - readonly typingsInstaller: ITypingsInstaller; - private readonly eventHandler; - readonly typingsCache: TypingsCache; - private readonly documentRegistry; - private readonly filenameToScriptInfo; - private readonly externalProjectToConfiguredProjectMap; - readonly externalProjects: ExternalProject[]; - readonly inferredProjects: InferredProject[]; - readonly configuredProjects: ConfiguredProject[]; - readonly openFiles: ScriptInfo[]; - private compilerOptionsForInferredProjects; - private compileOnSaveForInferredProjects; - private readonly directoryWatchers; - private readonly throttledOperations; - private readonly hostConfiguration; - private changedFiles; - private toCanonicalFileName; - constructor(host: ServerHost, logger: Logger, cancellationToken: HostCancellationToken, useSingleInferredProject: boolean, typingsInstaller?: ITypingsInstaller, eventHandler?: ProjectServiceEventHandler); - getChangedFiles_TestOnly(): ScriptInfo[]; - ensureInferredProjectsUpToDate_TestOnly(): void; - updateTypingsForProject(response: SetTypings | InvalidateCachedTypings): void; - setCompilerOptionsForInferredProjects(projectCompilerOptions: protocol.ExternalProjectCompilerOptions): void; - stopWatchingDirectory(directory: string): void; - findProject(projectName: string): Project; - getDefaultProjectForFile(fileName: NormalizedPath, refreshInferredProjects: boolean): Project; - private ensureInferredProjectsUpToDate(); - private findContainingExternalProject(fileName); - getFormatCodeOptions(file?: NormalizedPath): FormatCodeSettings; - private updateProjectGraphs(projects); - private onSourceFileChanged(fileName); - private handleDeletedFile(info); - private onTypeRootFileChanged(project, fileName); - private onSourceFileInDirectoryChangedForConfiguredProject(project, fileName); - private handleChangeInSourceFileForConfiguredProject(project); - private onConfigChangedForConfiguredProject(project); - private onConfigFileAddedForInferredProject(fileName); - private getCanonicalFileName(fileName); - private removeProject(project); - private assignScriptInfoToInferredProjectIfNecessary(info, addToListOfOpenFiles); - private closeOpenFile(info); - private openOrUpdateConfiguredProjectForFile(fileName); - private findConfigFile(searchPath); - private printProjects(); - private findConfiguredProjectByProjectName(configFileName); - private findExternalProjectByProjectName(projectFileName); - private convertConfigFileContentToProjectOptions(configFilename); - private exceededTotalSizeLimitForNonTsFiles(options, fileNames, propertyReader); - private createAndAddExternalProject(projectFileName, files, options, typingOptions); - private reportConfigFileDiagnostics(configFileName, diagnostics, triggerFile?); - private createAndAddConfiguredProject(configFileName, projectOptions, configFileErrors, clientFileName?); - private watchConfigDirectoryForProject(project, options); - private addFilesToProjectAndUpdateGraph(project, files, propertyReader, clientFileName, typingOptions, configFileErrors); - private openConfigFile(configFileName, clientFileName?); - private updateNonInferredProject(project, newUncheckedFiles, propertyReader, newOptions, newTypingOptions, compileOnSave, configFileErrors); - private updateConfiguredProject(project); - createInferredProjectWithRootFileIfNecessary(root: ScriptInfo): InferredProject; - getOrCreateScriptInfo(uncheckedFileName: string, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind): ScriptInfo; - getScriptInfo(uncheckedFileName: string): ScriptInfo; - getOrCreateScriptInfoForNormalizedPath(fileName: NormalizedPath, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean): ScriptInfo; - getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo; - setHostConfiguration(args: protocol.ConfigureRequestArguments): void; - closeLog(): void; - reloadProjects(): void; - refreshInferredProjects(): void; - openClientFile(fileName: string, fileContent?: string, scriptKind?: ScriptKind): OpenConfiguredProjectResult; - openClientFileWithNormalizedPath(fileName: NormalizedPath, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean): OpenConfiguredProjectResult; - closeClientFile(uncheckedFileName: string): void; - private collectChanges(lastKnownProjectVersions, currentProjects, result); - synchronizeProjectList(knownProjects: protocol.ProjectVersionInfo[]): ProjectFilesWithTSDiagnostics[]; - applyChangesInOpenFiles(openFiles: protocol.ExternalFile[], changedFiles: protocol.ChangedOpenFile[], closedFiles: string[]): void; - private closeConfiguredProject(configFile); - closeExternalProject(uncheckedFileName: string, suppressRefresh?: boolean): void; - openExternalProject(proj: protocol.ExternalProject): void; - } -} -declare namespace ts.server { + function generateSpaces(n: number): string; + function generateIndentString(n: number, editorOptions: EditorOptions): string; interface PendingErrorCheck { - fileName: NormalizedPath; + fileName: string; project: Project; } namespace CommandNames { const Brace: string; - const BraceFull: string; - const BraceCompletion: string; const Change: string; const Close: string; const Completions: string; - const CompletionsFull: string; const CompletionDetails: string; - const CompileOnSaveAffectedFileList: string; - const CompileOnSaveEmitFile: string; const Configure: string; const Definition: string; - const DefinitionFull: string; const Exit: string; const Format: string; const Formatonkey: string; - const FormatFull: string; - const FormatonkeyFull: string; - const FormatRangeFull: string; const Geterr: string; const GeterrForProject: string; const SemanticDiagnosticsSync: string; const SyntacticDiagnosticsSync: string; const NavBar: string; - const NavBarFull: string; const Navto: string; - const NavtoFull: string; const Occurrences: string; const DocumentHighlights: string; - const DocumentHighlightsFull: string; const Open: string; const Quickinfo: string; - const QuickinfoFull: string; const References: string; - const ReferencesFull: string; const Reload: string; const Rename: string; - const RenameInfoFull: string; - const RenameLocationsFull: string; const Saveto: string; const SignatureHelp: string; - const SignatureHelpFull: string; const TypeDefinition: string; const ProjectInfo: string; const ReloadProjects: string; const Unknown: string; - const OpenExternalProject: string; - const OpenExternalProjects: string; - const CloseExternalProject: string; - const SynchronizeProjectList: string; - const ApplyChangedToOpenFiles: string; - const EncodedSemanticClassificationsFull: string; - const Cleanup: string; - const OutliningSpans: string; - const TodoComments: string; - const Indentation: string; - const DocCommentTemplate: string; - const CompilerOptionsDiagnosticsFull: string; - const NameOrDottedNameSpan: string; - const BreakpointStatement: string; - const CompilerOptionsForInferredProjects: string; } - function formatMessage(msg: T, logger: server.Logger, byteLength: (s: string, encoding: string) => number, newLine: string): string; + interface ServerHost extends ts.System { + setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; + clearTimeout(timeoutId: any): void; + } class Session { private host; - protected readonly typingsInstaller: ITypingsInstaller; private byteLength; private hrtime; - protected logger: Logger; - protected readonly canUseEvents: boolean; - private readonly gcTimer; + private logger; protected projectService: ProjectService; private errorTimer; private immediateId; private changeSeq; - constructor(host: ServerHost, cancellationToken: HostCancellationToken, useSingleInferredProject: boolean, typingsInstaller: ITypingsInstaller, byteLength: (buf: string, encoding?: string) => number, hrtime: (start?: number[]) => number[], logger: Logger, canUseEvents: boolean); - private handleEvent(event); + constructor(host: ServerHost, byteLength: (buf: string, encoding?: string) => number, hrtime: (start?: number[]) => number[], logger: Logger); + private handleEvent(eventName, project, fileName); logError(err: Error, cmd: string): void; + private sendLineToClient(line); send(msg: protocol.Message): void; configFileDiagnosticEvent(triggerFile: string, configFile: string, diagnostics: ts.Diagnostic[]): void; event(info: any, eventName: string): void; - output(info: any, cmdName: string, reqSeq?: number, errorMsg?: string): void; + private response(info, cmdName, reqSeq?, errorMsg?); + output(body: any, commandName: string, requestSequence?: number, errorMessage?: string): void; private semanticCheck(file, project); private syntacticCheck(file, project); + private reloadProjects(); private updateProjectStructure(seq, matchSeq, ms?); private updateErrorCheck(checkList, seq, matchSeq, ms?, followMs?, requireOpen?); - private cleanProjects(caption, projects); - private cleanup(); - private getEncodedSemanticClassifications(args); - private getProject(projectFileName); - private getCompilerOptionsDiagnostics(args); - private convertToDiagnosticsWithLinePosition(diagnostics, scriptInfo); - private getDiagnosticsWorker(args, selector, includeLinePosition); - private getDefinition(args, simplifiedResult); - private getTypeDefinition(args); - private getOccurrences(args); + private getDefinition(line, offset, fileName); + private getTypeDefinition(line, offset, fileName); + private getOccurrences(line, offset, fileName); + private getDiagnosticsWorker(args, selector); private getSyntacticDiagnosticsSync(args); private getSemanticDiagnosticsSync(args); - private getDocumentHighlights(args, simplifiedResult); - private setCompilerOptionsForInferredProjects(args); - private getProjectInfo(args); - private getProjectInfoWorker(uncheckedFileName, projectFileName, needFileNameList); - private getRenameInfo(args); - private getProjects(args); - private getRenameLocations(args, simplifiedResult); - private getReferences(args, simplifiedResult); + private getDocumentHighlights(line, offset, fileName, filesToSearch); + private getProjectInfo(fileName, needFileNameList); + private getRenameLocations(line, offset, fileName, findInComments, findInStrings); + private getReferences(line, offset, fileName); private openClientFile(fileName, fileContent?, scriptKind?); - private getPosition(args, scriptInfo); - private getFileAndProject(args, errorOnMissingProject?); - private getFileAndProjectWithoutRefreshingInferredProjects(args, errorOnMissingProject?); - private getFileAndProjectWorker(uncheckedFileName, projectFileName, refreshInferredProjects, errorOnMissingProject); - private getOutliningSpans(args); - private getTodoComments(args); - private getDocCommentTemplate(args); - private getIndentation(args); - private getBreakpointStatement(args); - private getNameOrDottedNameSpan(args); - private isValidBraceCompletion(args); - private getQuickInfoWorker(args, simplifiedResult); - private getFormattingEditsForRange(args); - private getFormattingEditsForRangeFull(args); - private getFormattingEditsForDocumentFull(args); - private getFormattingEditsAfterKeystrokeFull(args); - private getFormattingEditsAfterKeystroke(args); - private getCompletions(args, simplifiedResult); - private getCompletionEntryDetails(args); - private getCompileOnSaveAffectedFileList(args); - private emitFile(args); - private getSignatureHelpItems(args, simplifiedResult); + private getQuickInfo(line, offset, fileName); + private getFormattingEditsForRange(line, offset, endLine, endOffset, fileName); + private getFormattingEditsAfterKeystroke(line, offset, key, fileName); + private getCompletions(line, offset, prefix, fileName); + private getCompletionEntryDetails(line, offset, entryNames, fileName); + private getSignatureHelpItems(line, offset, fileName); private getDiagnostics(delay, fileNames); - private change(args); - private reload(args, reqSeq); + private change(line, offset, endLine, endOffset, insertString, fileName); + private reload(fileName, tempFileName, reqSeq?); private saveToTmp(fileName, tempFileName); private closeClientFile(fileName); - private decorateNavigationBarItem(project, fileName, items); - private getNavigationBarItems(args, simplifiedResult); - private getNavigateToItems(args, simplifiedResult); - private getBraceMatching(args, simplifiedResult); + private decorateNavigationBarItem(project, fileName, items, lineIndex); + private getNavigationBarItems(fileName); + private getNavigateToItems(searchValue, fileName, maxResultCount?); + private getBraceMatching(line, offset, fileName); getDiagnosticsForProject(delay: number, fileName: string): void; getCanonicalFileName(fileName: string): string; exit(): void; - private notRequired(); private requiredResponse(response); private handlers; addProtocolHandler(command: string, handler: (request: protocol.Request) => { @@ -9067,6 +8374,214 @@ declare namespace ts.server { } } declare namespace ts.server { + interface Logger { + close(): void; + isVerbose(): boolean; + loggingEnabled(): boolean; + perftrc(s: string): void; + info(s: string): void; + startGroup(): void; + endGroup(): void; + msg(s: string, type?: string): void; + } + const maxProgramSizeForNonTsFiles: number; + class ScriptInfo { + private host; + fileName: string; + content: string; + isOpen: boolean; + svc: ScriptVersionCache; + children: ScriptInfo[]; + defaultProject: Project; + fileWatcher: FileWatcher; + formatCodeOptions: FormatCodeOptions; + path: Path; + scriptKind: ScriptKind; + constructor(host: ServerHost, fileName: string, content: string, isOpen?: boolean); + setFormatOptions(formatOptions: protocol.FormatOptions): void; + close(): void; + addChild(childInfo: ScriptInfo): void; + snap(): LineIndexSnapshot; + getText(): string; + getLineInfo(line: number): ILineInfo; + editContent(start: number, end: number, newText: string): void; + getTextChangeRangeBetweenVersions(startVersion: number, endVersion: number): ts.TextChangeRange; + getChangeRange(oldSnapshot: ts.IScriptSnapshot): ts.TextChangeRange; + } + class LSHost implements ts.LanguageServiceHost { + host: ServerHost; + project: Project; + ls: ts.LanguageService; + compilationSettings: ts.CompilerOptions; + filenameToScript: ts.FileMap; + roots: ScriptInfo[]; + private resolvedModuleNames; + private resolvedTypeReferenceDirectives; + private moduleResolutionHost; + private getCanonicalFileName; + constructor(host: ServerHost, project: Project); + private resolveNamesWithLocalCache(names, containingFile, cache, loader, getResult); + resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + resolveModuleNames(moduleNames: string[], containingFile: string): ResolvedModule[]; + getDefaultLibFileName(): string; + getScriptSnapshot(filename: string): ts.IScriptSnapshot; + setCompilationSettings(opt: ts.CompilerOptions): void; + lineAffectsRefs(filename: string, line: number): boolean; + getCompilationSettings(): CompilerOptions; + getScriptFileNames(): string[]; + getScriptKind(fileName: string): ScriptKind; + getScriptVersion(filename: string): string; + getCurrentDirectory(): string; + getScriptIsOpen(filename: string): boolean; + removeReferencedFile(info: ScriptInfo): void; + getScriptInfo(filename: string): ScriptInfo; + addRoot(info: ScriptInfo): void; + removeRoot(info: ScriptInfo): void; + saveTo(filename: string, tmpfilename: string): void; + reloadScript(filename: string, tmpfilename: string, cb: () => any): void; + editScript(filename: string, start: number, end: number, newText: string): void; + resolvePath(path: string): string; + fileExists(path: string): boolean; + directoryExists(path: string): boolean; + getDirectories(path: string): string[]; + lineToTextSpan(filename: string, line: number): ts.TextSpan; + lineOffsetToPosition(filename: string, line: number, offset: number): number; + positionToLineOffset(filename: string, position: number, lineIndex?: LineIndex): ILineInfo; + getLineIndex(filename: string): LineIndex; + } + interface ProjectOptions { + files?: string[]; + wildcardDirectories?: ts.Map; + compilerOptions?: ts.CompilerOptions; + } + class Project { + projectService: ProjectService; + projectOptions?: ProjectOptions; + languageServiceDiabled: boolean; + compilerService: CompilerService; + projectFilename: string; + projectFileWatcher: FileWatcher; + directoryWatcher: FileWatcher; + directoriesWatchedForWildcards: Map; + directoriesWatchedForTsconfig: string[]; + program: ts.Program; + filenameToSourceFile: ts.Map; + updateGraphSeq: number; + openRefCount: number; + constructor(projectService: ProjectService, projectOptions?: ProjectOptions, languageServiceDiabled?: boolean); + enableLanguageService(): void; + disableLanguageService(): void; + addOpenRef(): void; + deleteOpenRef(): number; + openReferencedFile(filename: string): ScriptInfo; + getRootFiles(): string[]; + getFileNames(): string[]; + getSourceFile(info: ScriptInfo): SourceFile; + getSourceFileFromName(filename: string, requireOpen?: boolean): SourceFile; + isRoot(info: ScriptInfo): boolean; + removeReferencedFile(info: ScriptInfo): void; + updateFileMap(): void; + finishGraph(): void; + updateGraph(): void; + isConfiguredProject(): string; + addRoot(info: ScriptInfo): void; + removeRoot(info: ScriptInfo): void; + filesToString(): string; + setProjectOptions(projectOptions: ProjectOptions): void; + } + interface ProjectOpenResult { + success?: boolean; + errorMsg?: string; + project?: Project; + } + function combineProjectOutput(projects: Project[], action: (project: Project) => T[], comparer?: (a: T, b: T) => number, areEqual?: (a: T, b: T) => boolean): T[]; + interface ProjectServiceEventHandler { + (eventName: string, project: Project, fileName: string): void; + } + interface HostConfiguration { + formatCodeOptions: ts.FormatCodeOptions; + hostInfo: string; + } + class ProjectService { + host: ServerHost; + psLogger: Logger; + eventHandler?: ProjectServiceEventHandler; + filenameToScriptInfo: ts.Map; + openFileRoots: ScriptInfo[]; + inferredProjects: Project[]; + configuredProjects: Project[]; + openFilesReferenced: ScriptInfo[]; + openFileRootsConfigured: ScriptInfo[]; + directoryWatchersForTsconfig: ts.Map; + directoryWatchersRefCount: ts.Map; + hostConfiguration: HostConfiguration; + timerForDetectingProjectFileListChanges: Map; + constructor(host: ServerHost, psLogger: Logger, eventHandler?: ProjectServiceEventHandler); + addDefaultHostConfiguration(): void; + getFormatCodeOptions(file?: string): FormatCodeOptions; + watchedFileChanged(fileName: string): void; + directoryWatchedForSourceFilesChanged(project: Project, fileName: string): void; + startTimerForDetectingProjectFileListChanges(project: Project): void; + handleProjectFileListChanges(project: Project): void; + directoryWatchedForTsconfigChanged(fileName: string): void; + getCanonicalFileName(fileName: string): string; + watchedProjectConfigFileChanged(project: Project): void; + log(msg: string, type?: string): void; + setHostConfiguration(args: ts.server.protocol.ConfigureRequestArguments): void; + closeLog(): void; + createInferredProject(root: ScriptInfo): Project; + fileDeletedInFilesystem(info: ScriptInfo): void; + updateConfiguredProjectList(): void; + removeProject(project: Project): void; + setConfiguredProjectRoot(info: ScriptInfo): boolean; + addOpenFile(info: ScriptInfo): void; + closeOpenFile(info: ScriptInfo): void; + findReferencingProjects(info: ScriptInfo, excludedProject?: Project): Project[]; + reloadProjects(): void; + updateProjectStructure(): void; + getScriptInfo(filename: string): ScriptInfo; + openFile(fileName: string, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind): ScriptInfo; + findConfigFile(searchPath: string): string; + openClientFile(fileName: string, fileContent?: string, scriptKind?: ScriptKind): { + configFileName?: string; + configFileErrors?: Diagnostic[]; + }; + openOrUpdateConfiguredProjectForFile(fileName: string): { + configFileName?: string; + configFileErrors?: Diagnostic[]; + }; + closeClientFile(filename: string): void; + getProjectForFile(filename: string): Project; + printProjectsForFile(filename: string): void; + printProjects(): void; + configProjectIsActive(fileName: string): boolean; + findConfiguredProjectByConfigFile(configFileName: string): Project; + configFileToProjectOptions(configFilename: string): { + succeeded: boolean; + projectOptions?: ProjectOptions; + errors?: Diagnostic[]; + }; + private exceedTotalNonTsFileSizeLimit(fileNames); + openConfigFile(configFilename: string, clientFileName?: string): { + success: boolean; + project?: Project; + errors?: Diagnostic[]; + }; + updateConfiguredProject(project: Project): Diagnostic[]; + createProject(projectFilename: string, projectOptions?: ProjectOptions, languageServiceDisabled?: boolean): Project; + } + class CompilerService { + project: Project; + host: LSHost; + languageService: ts.LanguageService; + classifier: ts.Classifier; + settings: ts.CompilerOptions; + documentRegistry: DocumentRegistry; + constructor(project: Project, opt?: ts.CompilerOptions); + setCompilerOptions(opt: ts.CompilerOptions): void; + isExternalModule(filename: string): boolean; + static getDefaultFormatCodeOptions(host: ServerHost): ts.FormatCodeOptions; + } interface LineCollection { charCount(): number; lineCount(): number; @@ -9097,7 +8612,7 @@ declare namespace ts.server { class TextChange { pos: number; deleteLen: number; - insertedText: string; + insertedText?: string; constructor(pos: number, deleteLen: number, insertedText?: string); getTextChangeRange(): TextChangeRange; } @@ -9105,17 +8620,15 @@ declare namespace ts.server { changes: TextChange[]; versions: LineIndexSnapshot[]; minVersion: number; - private host; private currentVersion; + private host; static changeNumberThreshold: number; static changeLengthThreshold: number; static maxVersions: number; - private versionToIndex(version); - private currentVersionToIndex(); edit(pos: number, deleteLen: number, insertedText?: string): void; latest(): LineIndexSnapshot; latestVersion(): number; - reloadFromFile(filename: string): void; + reloadFromFile(filename: string, cb?: () => any): void; reload(script: string): void; getSnapshot(): LineIndexSnapshot; getTextChangesBetweenVersions(oldVersion: number, newVersion: number): TextChangeRange; @@ -9184,7 +8697,10 @@ declare namespace ts.server { } class LineLeaf implements LineCollection { text: string; + udata: any; constructor(text: string); + setUdata(data: any): void; + getUdata(): any; isLeaf(): boolean; walk(rangeStart: number, rangeLength: number, walkFns: ILineIndexWalker): void; charCount(): number; @@ -9213,29 +8729,20 @@ declare namespace ts { getLocalizedDiagnosticMessages(): string; getCancellationToken(): HostCancellationToken; getCurrentDirectory(): string; - getDirectories(path: string): string; + getDirectories(path: string): string[]; getDefaultLibFileName(options: string): string; getNewLine?(): string; getProjectVersion?(): string; useCaseSensitiveFileNames?(): boolean; - getTypeRootsVersion?(): number; - readDirectory(rootDir: string, extension: string, basePaths?: string, excludeEx?: string, includeFileEx?: string, includeDirEx?: string, depth?: number): string; - readFile(path: string, encoding?: string): string; - fileExists(path: string): boolean; getModuleResolutionsForFile?(fileName: string): string; getTypeReferenceDirectiveResolutionsForFile?(fileName: string): string; directoryExists(directoryName: string): boolean; } - interface CoreServicesShimHost extends Logger { - directoryExists(directoryName: string): boolean; - fileExists(fileName: string): boolean; - getCurrentDirectory(): string; - getDirectories(path: string): string; + interface CoreServicesShimHost extends Logger, ModuleResolutionHost { readDirectory(rootDir: string, extension: string, basePaths?: string, excludeEx?: string, includeFileEx?: string, includeDirEx?: string, depth?: number): string; - readFile(fileName: string): string; - realpath?(path: string): string; - trace(s: string): void; useCaseSensitiveFileNames?(): boolean; + getCurrentDirectory(): string; + trace(s: string): void; } interface IFileReference { path: string; @@ -9294,7 +8801,6 @@ declare namespace ts { getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent?: boolean): string; } interface CoreServicesShim extends Shim { - getAutomaticTypeDirectiveNames(compilerOptionsJson: string): string; getPreProcessedFileInfo(fileName: string, sourceText: IScriptSnapshot): string; getTSConfigFileInfo(fileName: string, sourceText: IScriptSnapshot): string; getDefaultCompilationSettings(): string; @@ -9313,7 +8819,6 @@ declare namespace ts { trace(s: string): void; error(s: string): void; getProjectVersion(): string; - getTypeRootsVersion(): number; useCaseSensitiveFileNames(): boolean; getCompilationSettings(): CompilerOptions; getScriptFileNames(): string[]; @@ -9325,9 +8830,6 @@ declare namespace ts { getCurrentDirectory(): string; getDirectories(path: string): string[]; getDefaultLibFileName(options: CompilerOptions): string; - readDirectory(path: string, extensions?: string[], exclude?: string[], include?: string[], depth?: number): string[]; - readFile(path: string, encoding?: string): string; - fileExists(path: string): boolean; } class CoreServicesShimHostAdapter implements ParseConfigHost, ModuleResolutionHost { private shimHost; @@ -9339,8 +8841,14 @@ declare namespace ts { fileExists(fileName: string): boolean; readFile(fileName: string): string; private readDirectoryFallback(rootDir, extension, exclude); - getDirectories(path: string): string[]; } + function realizeDiagnostics(diagnostics: Diagnostic[], newLine: string): { + message: string; + start: number; + length: number; + category: string; + code: number; + }[]; class TypeScriptServicesFactory implements ShimFactory { private _shims; private documentRegistry; diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 41acf8505eb..5dafd5528a8 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -69,87 +69,14 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); }; -})(ts || (ts = {})); -var ts; -(function (ts) { - var performance; - (function (performance) { - var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true - ? onProfilerEvent - : function (markName) { }; - var enabled = false; - var profilerStart = 0; - var counts; - var marks; - var measures; - function mark(markName) { - if (enabled) { - marks[markName] = ts.timestamp(); - counts[markName] = (counts[markName] || 0) + 1; - profilerEvent(markName); - } - } - performance.mark = mark; - function measure(measureName, startMarkName, endMarkName) { - if (enabled) { - var end = endMarkName && marks[endMarkName] || ts.timestamp(); - var start = startMarkName && marks[startMarkName] || profilerStart; - measures[measureName] = (measures[measureName] || 0) + (end - start); - } - } - performance.measure = measure; - function getCount(markName) { - return counts && counts[markName] || 0; - } - performance.getCount = getCount; - function getDuration(measureName) { - return measures && measures[measureName] || 0; - } - performance.getDuration = getDuration; - function forEachMeasure(cb) { - for (var key in measures) { - cb(key, measures[key]); - } - } - performance.forEachMeasure = forEachMeasure; - function enable() { - counts = ts.createMap(); - marks = ts.createMap(); - measures = ts.createMap(); - enabled = true; - profilerStart = ts.timestamp(); - } - performance.enable = enable; - function disable() { - enabled = false; - } - performance.disable = disable; - })(performance = ts.performance || (ts.performance = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - var createObject = Object.create; - function createMap(template) { - var map = createObject(null); - map["__"] = undefined; - delete map["__"]; - for (var key in template) - if (hasOwnProperty.call(template, key)) { - map[key] = template[key]; - } - return map; - } - ts.createMap = createMap; function createFileMap(keyMapper) { - var files = createMap(); + var files = {}; return { get: get, set: set, contains: contains, remove: remove, forEachValue: forEachValueInMap, - getKeys: getKeys, clear: clear }; function forEachValueInMap(f) { @@ -157,13 +84,6 @@ var ts; f(key, files[key]); } } - function getKeys() { - var keys = []; - for (var key in files) { - keys.push(key); - } - return keys; - } function get(path) { return files[toKey(path)]; } @@ -171,14 +91,14 @@ var ts; files[toKey(path)] = value; } function contains(path) { - return toKey(path) in files; + return hasProperty(files, toKey(path)); } function remove(path) { var key = toKey(path); delete files[key]; } function clear() { - files = createMap(); + files = {}; } function toKey(path) { return keyMapper ? keyMapper(path) : path; @@ -204,31 +124,11 @@ var ts; return undefined; } ts.forEach = forEach; - function find(array, predicate) { - for (var i = 0, len = array.length; i < len; i++) { - var value = array[i]; - if (predicate(value, i)) { - return value; - } - } - return undefined; - } - ts.find = find; - function findMap(array, callback) { - for (var i = 0, len = array.length; i < len; i++) { - var result = callback(array[i], i); - if (result) { - return result; - } - } - Debug.fail(); - } - ts.findMap = findMap; - function contains(array, value) { + function contains(array, value, areEqual) { if (array) { for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { var v = array_1[_i]; - if (v === value) { + if (areEqual ? areEqual(v, value) : v === value) { return true; } } @@ -270,43 +170,19 @@ var ts; } ts.countWhere = countWhere; function filter(array, f) { + var result; if (array) { - var len = array.length; - var i = 0; - while (i < len && f(array[i])) - i++; - if (i < len) { - var result = array.slice(0, i); - i++; - while (i < len) { - var item = array[i]; - if (f(item)) { - result.push(item); - } - i++; + result = []; + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var item = array_3[_i]; + if (f(item)) { + result.push(item); } - return result; } } - return array; + return result; } ts.filter = filter; - function removeWhere(array, f) { - var outIndex = 0; - for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { - var item = array_3[_i]; - if (!f(item)) { - array[outIndex] = item; - outIndex++; - } - } - if (outIndex !== array.length) { - array.length = outIndex; - return true; - } - return false; - } - ts.removeWhere = removeWhere; function filterMutate(array, f) { var outIndex = 0; for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { @@ -343,15 +219,11 @@ var ts; var result; if (array) { result = []; - loop: for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { var item = array_6[_i]; - for (var _a = 0, result_1 = result; _a < result_1.length; _a++) { - var res = result_1[_a]; - if (areEqual ? areEqual(res, item) : res === item) { - continue loop; - } + if (!contains(result, item, areEqual)) { + result.push(item); } - result.push(item); } } return result; @@ -392,22 +264,16 @@ var ts; return array[array.length - 1]; } ts.lastOrUndefined = lastOrUndefined; - function binarySearch(array, value, comparer) { - if (!array || array.length === 0) { - return -1; - } + function binarySearch(array, value) { var low = 0; var high = array.length - 1; - comparer = comparer !== undefined - ? comparer - : function (v1, v2) { return (v1 < v2 ? -1 : (v1 > v2 ? 1 : 0)); }; while (low <= high) { var middle = low + ((high - low) >> 1); var midValue = array[middle]; - if (comparer(midValue, value) === 0) { + if (midValue === value) { return middle; } - else if (comparer(midValue, value) > 0) { + else if (midValue > value) { high = middle - 1; } else { @@ -467,117 +333,96 @@ var ts; return hasOwnProperty.call(map, key); } ts.hasProperty = hasProperty; + function getKeys(map) { + var keys = []; + for (var key in map) { + keys.push(key); + } + return keys; + } + ts.getKeys = getKeys; function getProperty(map, key) { return hasOwnProperty.call(map, key) ? map[key] : undefined; } ts.getProperty = getProperty; - function getOwnKeys(map) { - var keys = []; - for (var key in map) - if (hasOwnProperty.call(map, key)) { - keys.push(key); + function isEmpty(map) { + for (var id in map) { + if (hasProperty(map, id)) { + return false; } - return keys; - } - ts.getOwnKeys = getOwnKeys; - function forEachProperty(map, callback) { - var result; - for (var key in map) { - if (result = callback(map[key], key)) - break; } - return result; - } - ts.forEachProperty = forEachProperty; - function someProperties(map, predicate) { - for (var key in map) { - if (!predicate || predicate(map[key], key)) - return true; - } - return false; - } - ts.someProperties = someProperties; - function copyProperties(source, target) { - for (var key in source) { - target[key] = source[key]; - } - } - ts.copyProperties = copyProperties; - function reduceProperties(map, callback, initial) { - var result = initial; - for (var key in map) { - result = callback(result, map[key], String(key)); - } - return result; - } - ts.reduceProperties = reduceProperties; - function reduceOwnProperties(map, callback, initial) { - var result = initial; - for (var key in map) - if (hasOwnProperty.call(map, key)) { - result = callback(result, map[key], String(key)); - } - return result; - } - ts.reduceOwnProperties = reduceOwnProperties; - function equalOwnProperties(left, right, equalityComparer) { - if (left === right) - return true; - if (!left || !right) - return false; - for (var key in left) - if (hasOwnProperty.call(left, key)) { - if (!hasOwnProperty.call(right, key) === undefined) - return false; - if (equalityComparer ? !equalityComparer(left[key], right[key]) : left[key] !== right[key]) - return false; - } - for (var key in right) - if (hasOwnProperty.call(right, key)) { - if (!hasOwnProperty.call(left, key)) - return false; - } return true; } - ts.equalOwnProperties = equalOwnProperties; - function arrayToMap(array, makeKey, makeValue) { - var result = createMap(); - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var value = array_8[_i]; - result[makeKey(value)] = makeValue ? makeValue(value) : value; - } - return result; - } - ts.arrayToMap = arrayToMap; - function cloneMap(map) { - var clone = createMap(); - copyProperties(map, clone); - return clone; - } - ts.cloneMap = cloneMap; + ts.isEmpty = isEmpty; function clone(object) { var result = {}; for (var id in object) { - if (hasOwnProperty.call(object, id)) { - result[id] = object[id]; - } + result[id] = object[id]; } return result; } ts.clone = clone; function extend(first, second) { var result = {}; - for (var id in second) - if (hasOwnProperty.call(second, id)) { + for (var id in first) { + result[id] = first[id]; + } + for (var id in second) { + if (!hasProperty(result, id)) { result[id] = second[id]; } - for (var id in first) - if (hasOwnProperty.call(first, id)) { - result[id] = first[id]; - } + } return result; } ts.extend = extend; + function forEachValue(map, callback) { + var result; + for (var id in map) { + if (result = callback(map[id])) + break; + } + return result; + } + ts.forEachValue = forEachValue; + function forEachKey(map, callback) { + var result; + for (var id in map) { + if (result = callback(id)) + break; + } + return result; + } + ts.forEachKey = forEachKey; + function lookUp(map, key) { + return hasProperty(map, key) ? map[key] : undefined; + } + ts.lookUp = lookUp; + function copyMap(source, target) { + for (var p in source) { + target[p] = source[p]; + } + } + ts.copyMap = copyMap; + function arrayToMap(array, makeKey) { + var result = {}; + forEach(array, function (value) { + result[makeKey(value)] = value; + }); + return result; + } + ts.arrayToMap = arrayToMap; + function reduceProperties(map, callback, initial) { + var result = initial; + if (map) { + for (var key in map) { + if (hasProperty(map, key)) { + result = callback(result, map[key], String(key)); + } + } + } + return result; + } + ts.reduceProperties = reduceProperties; function isArray(value) { return Array.isArray ? Array.isArray(value) : value instanceof Array; } @@ -599,7 +444,9 @@ var ts; } ts.localizedDiagnosticMessages = undefined; function getLocaleSpecificMessage(message) { - return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message; + return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] + ? ts.localizedDiagnosticMessages[message.key] + : message.message; } ts.getLocaleSpecificMessage = getLocaleSpecificMessage; function createFileDiagnostic(file, start, length, message) { @@ -983,17 +830,10 @@ var ts; return true; } ts.containsPath = containsPath; - function startsWith(str, prefix) { - return str.lastIndexOf(prefix, 0) === 0; - } - ts.startsWith = startsWith; - function endsWith(str, suffix) { - var expectedPos = str.length - suffix.length; - return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; - } - ts.endsWith = endsWith; function fileExtensionIs(path, extension) { - return path.length > extension.length && endsWith(path, extension); + var pathLen = path.length; + var extLen = extension.length; + return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension; } ts.fileExtensionIs = fileExtensionIs; function fileExtensionIsAny(path, extensions) { @@ -1008,15 +848,10 @@ var ts; ts.fileExtensionIsAny = fileExtensionIsAny; var reservedCharacterPattern = /[^\w\s\/]/g; var wildcardCharCodes = [42, 63]; - var singleAsteriskRegexFragmentFiles = "([^./]|(\\.(?!min\\.js$))?)*"; - var singleAsteriskRegexFragmentOther = "[^/]*"; function getRegularExpressionForWildcard(specs, basePath, usage) { if (specs === undefined || specs.length === 0) { return undefined; } - var replaceWildcardCharacter = usage === "files" ? replaceWildCardCharacterFiles : replaceWildCardCharacterOther; - var singleAsteriskRegexFragment = usage === "files" ? singleAsteriskRegexFragmentFiles : singleAsteriskRegexFragmentOther; - var doubleAsteriskRegexFragment = usage === "exclude" ? "(/.+?)?" : "(/[^/.][^/]*)*?"; var pattern = ""; var hasWrittenSubpattern = false; spec: for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { @@ -1039,7 +874,7 @@ var ts; if (hasRecursiveDirectoryWildcard) { continue spec; } - subpattern += doubleAsteriskRegexFragment; + subpattern += "(/.+?)?"; hasRecursiveDirectoryWildcard = true; hasWrittenComponent = true; } @@ -1051,16 +886,6 @@ var ts; if (hasWrittenComponent) { subpattern += ts.directorySeparator; } - if (usage !== "exclude") { - if (component.charCodeAt(0) === 42) { - subpattern += "([^./]" + singleAsteriskRegexFragment + ")?"; - component = component.substr(1); - } - else if (component.charCodeAt(0) === 63) { - subpattern += "[^./]"; - component = component.substr(1); - } - } subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); hasWrittenComponent = true; } @@ -1081,14 +906,8 @@ var ts; return "^(" + pattern + (usage === "exclude" ? ")($|/)" : ")$"); } ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; - function replaceWildCardCharacterFiles(match) { - return replaceWildcardCharacter(match, singleAsteriskRegexFragmentFiles); - } - function replaceWildCardCharacterOther(match) { - return replaceWildcardCharacter(match, singleAsteriskRegexFragmentOther); - } - function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { - return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; + function replaceWildcardCharacter(match) { + return match === "*" ? "[^/]*" : match === "?" ? "[^/]" : "\\" + match; } function getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { path = normalizePath(path); @@ -1187,21 +1006,12 @@ var ts; } ts.getScriptKindFromFileName = getScriptKindFromFileName; ts.supportedTypeScriptExtensions = [".ts", ".tsx", ".d.ts"]; - ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"]; ts.supportedJavascriptExtensions = [".js", ".jsx"]; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); function getSupportedExtensions(options) { return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } ts.getSupportedExtensions = getSupportedExtensions; - function hasJavaScriptFileExtension(fileName) { - return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); - } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); - } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; function isSupportedSourceFileName(fileName, compilerOptions) { if (!fileName) { return false; @@ -1258,13 +1068,9 @@ var ts; } ts.removeFileExtension = removeFileExtension; function tryRemoveExtension(path, extension) { - return fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined; + return fileExtensionIs(path, extension) ? path.substring(0, path.length - extension.length) : undefined; } ts.tryRemoveExtension = tryRemoveExtension; - function removeExtension(path, extension) { - return path.substring(0, path.length - extension.length); - } - ts.removeExtension = removeExtension; function isJsxOrTsxExtension(ext) { return ext === ".jsx" || ext === ".tsx"; } @@ -1292,8 +1098,6 @@ var ts; } ts.objectAllocator = { getNodeConstructor: function () { return Node; }, - getTokenConstructor: function () { return Node; }, - getIdentifierConstructor: function () { return Node; }, getSourceFileConstructor: function () { return Node; }, getSymbolConstructor: function () { return Symbol; }, getTypeConstructor: function () { return Type; }, @@ -1339,57 +1143,6 @@ var ts; : (function (fileName) { return fileName.toLowerCase(); }); } ts.createGetCanonicalFileName = createGetCanonicalFileName; - function trace(host, message) { - host.trace(formatMessage.apply(undefined, arguments)); - } - ts.trace = trace; - function isTraceEnabled(compilerOptions, host) { - return compilerOptions.traceResolution && host.trace !== undefined; - } - ts.isTraceEnabled = isTraceEnabled; - function hasZeroOrOneAsteriskCharacter(str) { - var seenAsterisk = false; - for (var i = 0; i < str.length; i++) { - if (str.charCodeAt(i) === 42) { - if (!seenAsterisk) { - seenAsterisk = true; - } - else { - return false; - } - } - } - return true; - } - ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; - } - ts.createResolvedModule = createResolvedModule; - function isExternalModuleNameRelative(moduleName) { - return /^\.\.?($|[\\/])/.test(moduleName); - } - ts.isExternalModuleNameRelative = isExternalModuleNameRelative; - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - return jsonText ? JSON.parse(jsonText) : {}; - } - catch (e) { - return {}; - } - } - ts.readJson = readJson; - function getEmitModuleKind(compilerOptions) { - return typeof compilerOptions.module === "number" ? - compilerOptions.module : - getEmitScriptTarget(compilerOptions) === 2 ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; - } - ts.getEmitModuleKind = getEmitModuleKind; - function getEmitScriptTarget(compilerOptions) { - return compilerOptions.target || 0; - } - ts.getEmitScriptTarget = getEmitScriptTarget; })(ts || (ts = {})); var ts; (function (ts) { @@ -1476,7 +1229,7 @@ var ts; function readDirectory(path, extensions, excludes, includes) { return ts.matchFiles(path, extensions, excludes, includes, false, shell.CurrentDirectory, getAccessibleFileSystemEntries); } - var wscriptSystem = { + return { args: args, newLine: "\r\n", useCaseSensitiveFileNames: false, @@ -1495,7 +1248,7 @@ var ts; return fso.FolderExists(path); }, createDirectory: function (directoryName) { - if (!wscriptSystem.directoryExists(directoryName)) { + if (!this.directoryExists(directoryName)) { fso.CreateFolder(directoryName); } }, @@ -1515,7 +1268,6 @@ var ts; } } }; - return wscriptSystem; } function getNodeSystem() { var _fs = require("fs"); @@ -1524,13 +1276,13 @@ var ts; var _crypto = require("crypto"); var useNonPollingWatchers = process.env["TSC_NONPOLLING_WATCHER"]; function createWatchedFileSet() { - var dirWatchers = ts.createMap(); - var fileWatcherCallbacks = ts.createMap(); + var dirWatchers = {}; + var fileWatcherCallbacks = {}; return { addFile: addFile, removeFile: removeFile }; function reduceDirWatcherRefCountForFile(fileName) { var dirName = ts.getDirectoryPath(fileName); - var watcher = dirWatchers[dirName]; - if (watcher) { + if (ts.hasProperty(dirWatchers, dirName)) { + var watcher = dirWatchers[dirName]; watcher.referenceCount -= 1; if (watcher.referenceCount <= 0) { watcher.close(); @@ -1539,18 +1291,23 @@ var ts; } } function addDirWatcher(dirPath) { - var watcher = dirWatchers[dirPath]; - if (watcher) { - watcher.referenceCount += 1; + if (ts.hasProperty(dirWatchers, dirPath)) { + var watcher_1 = dirWatchers[dirPath]; + watcher_1.referenceCount += 1; return; } - watcher = _fs.watch(dirPath, { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); + var watcher = _fs.watch(dirPath, { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); watcher.referenceCount = 1; dirWatchers[dirPath] = watcher; return; } function addFileWatcherCallback(filePath, callback) { - (fileWatcherCallbacks[filePath] || (fileWatcherCallbacks[filePath] = [])).push(callback); + if (ts.hasProperty(fileWatcherCallbacks, filePath)) { + fileWatcherCallbacks[filePath].push(callback); + } + else { + fileWatcherCallbacks[filePath] = [callback]; + } } function addFile(fileName, callback) { addFileWatcherCallback(fileName, callback); @@ -1562,9 +1319,8 @@ var ts; reduceDirWatcherRefCountForFile(watchedFile.fileName); } function removeFileWatcherCallback(filePath, callback) { - var callbacks = fileWatcherCallbacks[filePath]; - if (callbacks) { - var newCallbacks = ts.copyListRemovingItem(callback, callbacks); + if (ts.hasProperty(fileWatcherCallbacks, filePath)) { + var newCallbacks = ts.copyListRemovingItem(callback, fileWatcherCallbacks[filePath]); if (newCallbacks.length === 0) { delete fileWatcherCallbacks[filePath]; } @@ -1577,7 +1333,7 @@ var ts; var fileName = typeof relativeFileName !== "string" ? undefined : ts.getNormalizedAbsolutePath(relativeFileName, baseDirPath); - if ((eventName === "change" || eventName === "rename") && fileWatcherCallbacks[fileName]) { + if ((eventName === "change" || eventName === "rename") && ts.hasProperty(fileWatcherCallbacks, fileName)) { for (var _i = 0, _a = fileWatcherCallbacks[fileName]; _i < _a.length; _i++) { var fileCallback = _a[_i]; fileCallback(fileName); @@ -1684,7 +1440,7 @@ var ts; function getDirectories(path) { return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1); }); } - var nodeSystem = { + return { args: process.argv.slice(2), newLine: _os.EOL, useCaseSensitiveFileNames: useCaseSensitiveFileNames, @@ -1734,7 +1490,7 @@ var ts; fileExists: fileExists, directoryExists: directoryExists, createDirectory: function (directoryName) { - if (!nodeSystem.directoryExists(directoryName)) { + if (!this.directoryExists(directoryName)) { _fs.mkdirSync(directoryName); } }, @@ -1782,7 +1538,6 @@ var ts; return _fs.realpathSync(path); } }; - return nodeSystem; } function getChakraSystem() { var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); }); @@ -1815,37 +1570,18 @@ var ts; realpath: realpath }; } - function recursiveCreateDirectory(directoryPath, sys) { - var basePath = ts.getDirectoryPath(directoryPath); - var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath); - if (shouldCreateParent) { - recursiveCreateDirectory(basePath, sys); - } - if (shouldCreateParent || !sys.directoryExists(directoryPath)) { - sys.createDirectory(directoryPath); - } - } - var sys; if (typeof ChakraHost !== "undefined") { - sys = getChakraSystem(); + return getChakraSystem(); } else if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { - sys = getWScriptSystem(); + return getWScriptSystem(); } else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") { - sys = getNodeSystem(); + return getNodeSystem(); } - if (sys) { - var originalWriteFile_1 = sys.writeFile; - sys.writeFile = function (path, data, writeBom) { - var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path)); - if (directoryPath && !sys.directoryExists(directoryPath)) { - recursiveCreateDirectory(directoryPath, sys); - } - originalWriteFile_1.call(sys, path, data, writeBom); - }; + else { + return undefined; } - return sys; })(); })(ts || (ts = {})); var ts; @@ -2290,7 +2026,6 @@ var ts; Object_is_possibly_undefined: { code: 2532, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_undefined_2532", message: "Object is possibly 'undefined'." }, Object_is_possibly_null_or_undefined: { code: 2533, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_null_or_undefined_2533", message: "Object is possibly 'null' or 'undefined'." }, A_function_returning_never_cannot_have_a_reachable_end_point: { code: 2534, category: ts.DiagnosticCategory.Error, key: "A_function_returning_never_cannot_have_a_reachable_end_point_2534", message: "A function returning 'never' cannot have a reachable end point." }, - Enum_type_0_has_members_with_initializers_that_are_not_literals: { code: 2535, category: ts.DiagnosticCategory.Error, key: "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", message: "Enum type '{0}' has members with initializers that are not literals." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "The return type of a JSX element constructor must return an object type." }, JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -2338,9 +2073,6 @@ var ts; All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, - A_class_must_be_declared_after_its_base_class: { code: 2690, category: ts.DiagnosticCategory.Error, key: "A_class_must_be_declared_after_its_base_class_2690", message: "A class must be declared after its base class." }, - An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: { code: 2691, category: ts.DiagnosticCategory.Error, key: "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691", message: "An import path cannot end with a '{0}' extension. Consider importing '{1}' instead." }, - _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: { code: 2692, category: ts.DiagnosticCategory.Error, key: "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", message: "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible." }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -2411,7 +2143,7 @@ var ts; Parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4078, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", message: "Parameter '{0}' of exported function has or is using private name '{1}'." }, Exported_type_alias_0_has_or_is_using_private_name_1: { code: 4081, category: ts.DiagnosticCategory.Error, key: "Exported_type_alias_0_has_or_is_using_private_name_1_4081", message: "Exported type alias '{0}' has or is using private name '{1}'." }, Default_export_of_the_module_has_or_is_using_private_name_0: { code: 4082, category: ts.DiagnosticCategory.Error, key: "Default_export_of_the_module_has_or_is_using_private_name_0_4082", message: "Default export of the module has or is using private name '{0}'." }, - Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", message: "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict." }, + Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_to_resolve_this_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_t_4090", message: "Conflicting library definitions for '{0}' found at '{1}' and '{2}'. Copy the correct file to the 'typings' folder to resolve this conflict." }, The_current_host_does_not_support_the_0_option: { code: 5001, category: ts.DiagnosticCategory.Error, key: "The_current_host_does_not_support_the_0_option_5001", message: "The current host does not support the '{0}' option." }, Cannot_find_the_common_subdirectory_path_for_the_input_files: { code: 5009, category: ts.DiagnosticCategory.Error, key: "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", message: "Cannot find the common subdirectory path for the input files." }, File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5010, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", message: "File specification cannot end in a recursive directory wildcard ('**'): '{0}'." }, @@ -2439,7 +2171,6 @@ var ts; Substitutions_for_pattern_0_should_be_an_array: { code: 5063, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_should_be_an_array_5063", message: "Substitutions for pattern '{0}' should be an array." }, Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: { code: 5064, category: ts.DiagnosticCategory.Error, key: "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", message: "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'." }, File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5065, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", message: "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'." }, - Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: { code: 5066, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", message: "Substitutions for pattern '{0}' shouldn't be an empty array." }, Concatenate_and_emit_output_to_single_file: { code: 6001, category: ts.DiagnosticCategory.Message, key: "Concatenate_and_emit_output_to_single_file_6001", message: "Concatenate and emit output to single file." }, Generates_corresponding_d_ts_file: { code: 6002, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_d_ts_file_6002", message: "Generates corresponding '.d.ts' file." }, Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: ts.DiagnosticCategory.Message, key: "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", message: "Specify the location where debugger should locate map files instead of generated locations." }, @@ -2556,12 +2287,10 @@ var ts; Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." }, File_name_0_has_a_1_extension_stripping_it: { code: 6132, category: ts.DiagnosticCategory.Message, key: "File_name_0_has_a_1_extension_stripping_it_6132", message: "File name '{0}' has a '{1}' extension - stripping it" }, _0_is_declared_but_never_used: { code: 6133, category: ts.DiagnosticCategory.Error, key: "_0_is_declared_but_never_used_6133", message: "'{0}' is declared but never used." }, - Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, - Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, + Report_Errors_on_Unused_Locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Locals_6134", message: "Report Errors on Unused Locals." }, + Report_Errors_on_Unused_Parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Parameters_6135", message: "Report Errors on Unused Parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" }, No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" }, - Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, - Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6139, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6139", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -2570,6 +2299,7 @@ var ts; Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: { code: 7011, category: ts.DiagnosticCategory.Error, key: "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", message: "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type." }, Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7013, category: ts.DiagnosticCategory.Error, key: "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", message: "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type." }, Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: { code: 7015, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", message: "Element implicitly has an 'any' type because index expression is not of type 'number'." }, + Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation: { code: 7016, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation_7016", message: "Property '{0}' implicitly has type 'any', because its 'set' accessor lacks a type annotation." }, Index_signature_of_object_type_implicitly_has_an_any_type: { code: 7017, category: ts.DiagnosticCategory.Error, key: "Index_signature_of_object_type_implicitly_has_an_any_type_7017", message: "Index signature of object type implicitly has an 'any' type." }, Object_literal_s_property_0_implicitly_has_an_1_type: { code: 7018, category: ts.DiagnosticCategory.Error, key: "Object_literal_s_property_0_implicitly_has_an_1_type_7018", message: "Object literal's property '{0}' implicitly has an '{1}' type." }, Rest_parameter_0_implicitly_has_an_any_type: { code: 7019, category: ts.DiagnosticCategory.Error, key: "Rest_parameter_0_implicitly_has_an_any_type_7019", message: "Rest parameter '{0}' implicitly has an 'any[]' type." }, @@ -2584,8 +2314,6 @@ var ts; Fallthrough_case_in_switch: { code: 7029, category: ts.DiagnosticCategory.Error, key: "Fallthrough_case_in_switch_7029", message: "Fallthrough case in switch." }, Not_all_code_paths_return_a_value: { code: 7030, category: ts.DiagnosticCategory.Error, key: "Not_all_code_paths_return_a_value_7030", message: "Not all code paths return a value." }, Binding_element_0_implicitly_has_an_1_type: { code: 7031, category: ts.DiagnosticCategory.Error, key: "Binding_element_0_implicitly_has_an_1_type_7031", message: "Binding element '{0}' implicitly has an '{1}' type." }, - Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { code: 7032, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", message: "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation." }, - Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { code: 7033, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", message: "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation." }, You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, @@ -2622,7 +2350,7 @@ var ts; return token >= 69; } ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; - var textToToken = ts.createMap({ + var textToToken = { "abstract": 115, "any": 117, "as": 116, @@ -2746,7 +2474,7 @@ var ts; "|=": 67, "^=": 68, "@": 55 - }); + }; var unicodeES3IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; var unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; var unicodeES5IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6263, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516, 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7401, 7404, 7406, 7409, 7413, 7414, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11823, 11823, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42647, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43648, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; @@ -2787,7 +2515,9 @@ var ts; function makeReverseMap(source) { var result = []; for (var name_4 in source) { - result[source[name_4]] = name_4; + if (source.hasOwnProperty(name_4)) { + result[source[name_4]] = name_4; + } } return result; } @@ -4107,13 +3837,11 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; ts.optionDeclarations = [ { name: "charset", type: "string" }, - ts.compileOnSaveCommandLineOption, { name: "declaration", shortName: "d", @@ -4130,10 +3858,6 @@ var ts; name: "diagnostics", type: "boolean" }, - { - name: "extendedDiagnostics", - type: "boolean" - }, { name: "emitBOM", type: "boolean" @@ -4164,10 +3888,10 @@ var ts; }, { name: "jsx", - type: ts.createMap({ + type: { "preserve": 1, "react": 2 - }), + }, paramType: ts.Diagnostics.KIND, description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react }, @@ -4194,7 +3918,7 @@ var ts; { name: "module", shortName: "m", - type: ts.createMap({ + type: { "none": ts.ModuleKind.None, "commonjs": ts.ModuleKind.CommonJS, "amd": ts.ModuleKind.AMD, @@ -4202,16 +3926,16 @@ var ts; "umd": ts.ModuleKind.UMD, "es6": ts.ModuleKind.ES6, "es2015": ts.ModuleKind.ES2015 - }), + }, description: ts.Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015, paramType: ts.Diagnostics.KIND }, { name: "newLine", - type: ts.createMap({ + type: { "crlf": 0, "lf": 1 - }), + }, description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix, paramType: ts.Diagnostics.NEWLINE }, @@ -4229,10 +3953,6 @@ var ts; type: "boolean", description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported }, - { - name: "noErrorTruncation", - type: "boolean" - }, { name: "noImplicitAny", type: "boolean", @@ -4246,12 +3966,12 @@ var ts; { name: "noUnusedLocals", type: "boolean", - description: ts.Diagnostics.Report_errors_on_unused_locals + description: ts.Diagnostics.Report_Errors_on_Unused_Locals }, { name: "noUnusedParameters", type: "boolean", - description: ts.Diagnostics.Report_errors_on_unused_parameters + description: ts.Diagnostics.Report_Errors_on_Unused_Parameters }, { name: "noLib", @@ -4356,12 +4076,12 @@ var ts; { name: "target", shortName: "t", - type: ts.createMap({ + type: { "es3": 0, "es5": 1, "es6": 2, "es2015": 2 - }), + }, description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015, paramType: ts.Diagnostics.VERSION }, @@ -4390,10 +4110,10 @@ var ts; }, { name: "moduleResolution", - type: ts.createMap({ + type: { "node": ts.ModuleResolutionKind.NodeJs, "classic": ts.ModuleResolutionKind.Classic - }), + }, description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6 }, { @@ -4494,7 +4214,7 @@ var ts; type: "list", element: { name: "lib", - type: ts.createMap({ + type: { "es5": "lib.es5.d.ts", "es6": "lib.es2015.d.ts", "es2015": "lib.es2015.d.ts", @@ -4516,7 +4236,7 @@ var ts; "es2016.array.include": "lib.es2016.array.include.d.ts", "es2017.object": "lib.es2017.object.d.ts", "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts" - }) + } }, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon }, @@ -4552,19 +4272,13 @@ var ts; } } ]; - ts.defaultInitCompilerOptions = { - module: ts.ModuleKind.CommonJS, - target: 1, - noImplicitAny: false, - sourceMap: false - }; var optionNameMapCache; function getOptionNameMap() { if (optionNameMapCache) { return optionNameMapCache; } - var optionNameMap = ts.createMap(); - var shortOptionNames = ts.createMap(); + var optionNameMap = {}; + var shortOptionNames = {}; ts.forEach(ts.optionDeclarations, function (option) { optionNameMap[option.name.toLowerCase()] = option; if (option.shortName) { @@ -4577,16 +4291,16 @@ var ts; ts.getOptionNameMap = getOptionNameMap; function createCompilerDiagnosticForInvalidCustomType(opt) { var namesOfType = []; - for (var key in opt.type) { + ts.forEachKey(opt.type, function (key) { namesOfType.push(" '" + key + "'"); - } + }); return ts.createCompilerDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); } ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; function parseCustomTypeOption(opt, value, errors) { var key = trimString((value || "")).toLowerCase(); var map = opt.type; - if (key in map) { + if (ts.hasProperty(map, key)) { return map[key]; } else { @@ -4635,10 +4349,10 @@ var ts; } else if (s.charCodeAt(0) === 45) { s = s.slice(s.charCodeAt(1) === 45 ? 2 : 1).toLowerCase(); - if (s in shortOptionNames) { + if (ts.hasProperty(shortOptionNames, s)) { s = shortOptionNames[s]; } - if (s in optionNameMap) { + if (ts.hasProperty(optionNameMap, s)) { var opt = optionNameMap[s]; if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -4729,87 +4443,16 @@ var ts; return parseConfigFileTextToJson(fileName, text); } ts.readConfigFile = readConfigFile; - function parseConfigFileTextToJson(fileName, jsonText, stripComments) { - if (stripComments === void 0) { stripComments = true; } + function parseConfigFileTextToJson(fileName, jsonText) { try { - var jsonTextToParse = stripComments ? removeComments(jsonText) : jsonText; - return { config: /\S/.test(jsonTextToParse) ? JSON.parse(jsonTextToParse) : {} }; + var jsonTextWithoutComments = removeComments(jsonText); + return { config: /\S/.test(jsonTextWithoutComments) ? JSON.parse(jsonTextWithoutComments) : {} }; } catch (e) { return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) }; } } ts.parseConfigFileTextToJson = parseConfigFileTextToJson; - function generateTSConfig(options, fileNames) { - var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); - var configurations = { - compilerOptions: serializeCompilerOptions(compilerOptions) - }; - if (fileNames && fileNames.length) { - configurations.files = fileNames; - } - return configurations; - function getCustomTypeMapOfCommandLineOption(optionDefinition) { - if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { - return undefined; - } - else if (optionDefinition.type === "list") { - return getCustomTypeMapOfCommandLineOption(optionDefinition.element); - } - else { - return optionDefinition.type; - } - } - function getNameOfCompilerOptionValue(value, customTypeMap) { - for (var key in customTypeMap) { - if (customTypeMap[key] === value) { - return key; - } - } - return undefined; - } - function serializeCompilerOptions(options) { - var result = ts.createMap(); - var optionsNameMap = getOptionNameMap().optionNameMap; - for (var name_5 in options) { - if (ts.hasProperty(options, name_5)) { - switch (name_5) { - case "init": - case "watch": - case "version": - case "help": - case "project": - break; - default: - var value = options[name_5]; - var optionDefinition = optionsNameMap[name_5.toLowerCase()]; - if (optionDefinition) { - var customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition); - if (!customTypeMap) { - result[name_5] = value; - } - else { - if (optionDefinition.type === "list") { - var convertedValue = []; - for (var _i = 0, _a = value; _i < _a.length; _i++) { - var element = _a[_i]; - convertedValue.push(getNameOfCompilerOptionValue(element, customTypeMap)); - } - result[name_5] = convertedValue; - } - else { - result[name_5] = getNameOfCompilerOptionValue(value, customTypeMap); - } - } - } - break; - } - } - } - return result; - } - } - ts.generateTSConfig = generateTSConfig; function removeComments(jsonText) { var output = ""; var scanner = ts.createScanner(1, false, 0, jsonText); @@ -4827,6 +4470,7 @@ var ts; } return output; } + var ignoreFileNamePattern = /(\.min\.js$)|([\\/]\.[\w.])/; function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName) { if (existingOptions === void 0) { existingOptions = {}; } var errors = []; @@ -4835,15 +4479,13 @@ var ts; var typingOptions = convertTypingOptionsFromJsonWorker(json["typingOptions"], basePath, errors, configFileName); options.configFilePath = configFileName; var _a = getFileNames(errors), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; - var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); return { options: options, fileNames: fileNames, typingOptions: typingOptions, raw: json, errors: errors, - wildcardDirectories: wildcardDirectories, - compileOnSave: compileOnSave + wildcardDirectories: wildcardDirectories }; function getFileNames(errors) { var fileNames; @@ -4890,17 +4532,6 @@ var ts; } } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; - function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { - if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { - return false; - } - var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); - if (typeof result === "boolean" && result) { - return result; - } - return false; - } - ts.convertCompileOnSaveOptionFromJson = convertCompileOnSaveOptionFromJson; function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { var errors = []; var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); @@ -4914,7 +4545,7 @@ var ts; } ts.convertTypingOptionsFromJson = convertTypingOptionsFromJson; function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2 } : {}; + var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true } : {}; convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); return options; } @@ -4931,7 +4562,7 @@ var ts; } var optionNameMap = ts.arrayToMap(optionDeclarations, function (opt) { return opt.name; }); for (var id in jsonOptions) { - if (id in optionNameMap) { + if (ts.hasProperty(optionNameMap, id)) { var opt = optionNameMap[id]; defaultOptions[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors); } @@ -4966,7 +4597,7 @@ var ts; } function convertJsonOptionOfCustomType(opt, value, errors) { var key = value.toLowerCase(); - if (key in opt.type) { + if (ts.hasProperty(opt.type, key)) { return opt.type[key]; } else { @@ -4987,8 +4618,8 @@ var ts; function matchFileNames(fileNames, include, exclude, basePath, options, host, errors) { basePath = ts.normalizePath(basePath); var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; - var literalFileMap = ts.createMap(); - var wildcardFileMap = ts.createMap(); + var literalFileMap = {}; + var wildcardFileMap = {}; if (include) { include = validateSpecs(include, errors, false); } @@ -5010,9 +4641,12 @@ var ts; if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { continue; } + if (ignoreFileNamePattern.test(file)) { + continue; + } removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); var key = keyMapper(file); - if (!(key in literalFileMap) && !(key in wildcardFileMap)) { + if (!ts.hasProperty(literalFileMap, key) && !ts.hasProperty(wildcardFileMap, key)) { wildcardFileMap[key] = file; } } @@ -5047,20 +4681,20 @@ var ts; function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) { var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); - var wildcardDirectories = ts.createMap(); + var wildcardDirectories = {}; if (include !== undefined) { var recursiveKeys = []; for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { var file = include_1[_i]; - var name_6 = ts.normalizePath(ts.combinePaths(path, file)); - if (excludeRegex && excludeRegex.test(name_6)) { + var name_5 = ts.normalizePath(ts.combinePaths(path, file)); + if (excludeRegex && excludeRegex.test(name_5)) { continue; } - var match = wildcardDirectoryPattern.exec(name_6); + var match = wildcardDirectoryPattern.exec(name_5); if (match) { var key = useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(); - var flags = watchRecursivePattern.test(name_6) ? 1 : 0; - var existingFlags = wildcardDirectories[key]; + var flags = watchRecursivePattern.test(name_5) ? 1 : 0; + var existingFlags = ts.getProperty(wildcardDirectories, key); if (existingFlags === undefined || existingFlags < flags) { wildcardDirectories[key] = flags; if (flags === 1) { @@ -5070,10 +4704,12 @@ var ts; } } for (var key in wildcardDirectories) { - for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { - var recursiveKey = recursiveKeys_1[_a]; - if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { - delete wildcardDirectories[key]; + if (ts.hasProperty(wildcardDirectories, key)) { + for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { + var recursiveKey = recursiveKeys_1[_a]; + if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { + delete wildcardDirectories[key]; + } } } } @@ -5086,7 +4722,7 @@ var ts; for (var i = 0; i < adjustedExtensionPriority; i++) { var higherPriorityExtension = extensions[i]; var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); - if (higherPriorityPath in literalFiles || higherPriorityPath in wildcardFiles) { + if (ts.hasProperty(literalFiles, higherPriorityPath) || ts.hasProperty(wildcardFiles, higherPriorityPath)) { return true; } } @@ -5113,378 +4749,6 @@ var ts; } })(ts || (ts = {})); var ts; -(function (ts) { - var JsTyping; - (function (JsTyping) { - ; - ; - var safeList; - var EmptySafeList = ts.createMap(); - function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typingOptions, compilerOptions) { - var inferredTypings = ts.createMap(); - if (!typingOptions || !typingOptions.enableAutoDiscovery) { - return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; - } - fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { - var kind = ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)); - return kind === 1 || kind === 2; - }); - if (!safeList) { - var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); - safeList = result.config ? ts.createMap(result.config) : EmptySafeList; - } - var filesToWatch = []; - var searchDirs = []; - var exclude = []; - mergeTypings(typingOptions.include); - exclude = typingOptions.exclude || []; - var possibleSearchDirs = ts.map(fileNames, ts.getDirectoryPath); - if (projectRootPath !== undefined) { - possibleSearchDirs.push(projectRootPath); - } - searchDirs = ts.deduplicate(possibleSearchDirs); - for (var _i = 0, searchDirs_1 = searchDirs; _i < searchDirs_1.length; _i++) { - var searchDir = searchDirs_1[_i]; - var packageJsonPath = ts.combinePaths(searchDir, "package.json"); - getTypingNamesFromJson(packageJsonPath, filesToWatch); - var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); - getTypingNamesFromJson(bowerJsonPath, filesToWatch); - var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); - getTypingNamesFromNodeModuleFolder(nodeModulesPath); - } - getTypingNamesFromSourceFileNames(fileNames); - for (var name_7 in packageNameToTypingLocation) { - if (name_7 in inferredTypings && !inferredTypings[name_7]) { - inferredTypings[name_7] = packageNameToTypingLocation[name_7]; - } - } - for (var _a = 0, exclude_1 = exclude; _a < exclude_1.length; _a++) { - var excludeTypingName = exclude_1[_a]; - delete inferredTypings[excludeTypingName]; - } - var newTypingNames = []; - var cachedTypingPaths = []; - for (var typing in inferredTypings) { - if (inferredTypings[typing] !== undefined) { - cachedTypingPaths.push(inferredTypings[typing]); - } - else { - newTypingNames.push(typing); - } - } - return { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; - function mergeTypings(typingNames) { - if (!typingNames) { - return; - } - for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) { - var typing = typingNames_1[_i]; - if (!(typing in inferredTypings)) { - inferredTypings[typing] = undefined; - } - } - } - function getTypingNamesFromJson(jsonPath, filesToWatch) { - var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }); - if (result.config) { - var jsonConfig = result.config; - filesToWatch.push(jsonPath); - if (jsonConfig.dependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.dependencies)); - } - if (jsonConfig.devDependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.devDependencies)); - } - if (jsonConfig.optionalDependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.optionalDependencies)); - } - if (jsonConfig.peerDependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.peerDependencies)); - } - } - } - function getTypingNamesFromSourceFileNames(fileNames) { - var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension); - var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); }); - var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); }); - if (safeList !== EmptySafeList) { - mergeTypings(ts.filter(cleanedTypingNames, function (f) { return f in safeList; })); - } - var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)) === 2; }); - if (hasJsxFile) { - mergeTypings(["react"]); - } - } - function getTypingNamesFromNodeModuleFolder(nodeModulesPath) { - if (!host.directoryExists(nodeModulesPath)) { - return; - } - var typingNames = []; - var fileNames = host.readDirectory(nodeModulesPath, [".json"], undefined, undefined, 2); - for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { - var fileName = fileNames_2[_i]; - var normalizedFileName = ts.normalizePath(fileName); - if (ts.getBaseFileName(normalizedFileName) !== "package.json") { - continue; - } - var result = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - if (!result.config) { - continue; - } - var packageJson = result.config; - if (packageJson._requiredBy && - ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { - continue; - } - if (!packageJson.name) { - continue; - } - if (packageJson.typings) { - var absolutePath = ts.getNormalizedAbsolutePath(packageJson.typings, ts.getDirectoryPath(normalizedFileName)); - inferredTypings[packageJson.name] = absolutePath; - } - else { - typingNames.push(packageJson.name); - } - } - mergeTypings(typingNames); - } - } - JsTyping.discoverTypings = discoverTypings; - })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - var server; - (function (server) { - (function (LogLevel) { - LogLevel[LogLevel["terse"] = 0] = "terse"; - LogLevel[LogLevel["normal"] = 1] = "normal"; - LogLevel[LogLevel["requestTime"] = 2] = "requestTime"; - LogLevel[LogLevel["verbose"] = 3] = "verbose"; - })(server.LogLevel || (server.LogLevel = {})); - var LogLevel = server.LogLevel; - server.emptyArray = []; - var Msg; - (function (Msg) { - Msg.Err = "Err"; - Msg.Info = "Info"; - Msg.Perf = "Perf"; - })(Msg = server.Msg || (server.Msg = {})); - function getProjectRootPath(project) { - switch (project.projectKind) { - case server.ProjectKind.Configured: - return ts.getDirectoryPath(project.getProjectName()); - case server.ProjectKind.Inferred: - return ""; - case server.ProjectKind.External: - var projectName = ts.normalizeSlashes(project.getProjectName()); - return project.projectService.host.fileExists(projectName) ? ts.getDirectoryPath(projectName) : projectName; - } - } - function createInstallTypingsRequest(project, typingOptions, cachePath) { - return { - projectName: project.getProjectName(), - fileNames: project.getFileNames(), - compilerOptions: project.getCompilerOptions(), - typingOptions: typingOptions, - projectRootPath: getProjectRootPath(project), - cachePath: cachePath, - kind: "discover" - }; - } - server.createInstallTypingsRequest = createInstallTypingsRequest; - var Errors; - (function (Errors) { - function ThrowNoProject() { - throw new Error("No Project."); - } - Errors.ThrowNoProject = ThrowNoProject; - function ThrowProjectLanguageServiceDisabled() { - throw new Error("The project's language service is disabled."); - } - Errors.ThrowProjectLanguageServiceDisabled = ThrowProjectLanguageServiceDisabled; - function ThrowProjectDoesNotContainDocument(fileName, project) { - throw new Error("Project '" + project.getProjectName() + "' does not contain document '" + fileName + "'"); - } - Errors.ThrowProjectDoesNotContainDocument = ThrowProjectDoesNotContainDocument; - })(Errors = server.Errors || (server.Errors = {})); - function getDefaultFormatCodeSettings(host) { - return { - indentSize: 4, - tabSize: 4, - newLineCharacter: host.newLine || "\n", - convertTabsToSpaces: true, - indentStyle: ts.IndentStyle.Smart, - insertSpaceAfterCommaDelimiter: true, - insertSpaceAfterSemicolonInForStatements: true, - insertSpaceBeforeAndAfterBinaryOperators: true, - insertSpaceAfterKeywordsInControlFlowStatements: true, - insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, - insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, - insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, - placeOpenBraceOnNewLineForFunctions: false, - placeOpenBraceOnNewLineForControlBlocks: false - }; - } - server.getDefaultFormatCodeSettings = getDefaultFormatCodeSettings; - function mergeMaps(target, source) { - for (var key in source) { - if (ts.hasProperty(source, key)) { - target[key] = source[key]; - } - } - } - server.mergeMaps = mergeMaps; - function removeItemFromSet(items, itemToRemove) { - if (items.length === 0) { - return; - } - var index = items.indexOf(itemToRemove); - if (index < 0) { - return; - } - if (index === items.length - 1) { - items.pop(); - } - else { - items[index] = items.pop(); - } - } - server.removeItemFromSet = removeItemFromSet; - function toNormalizedPath(fileName) { - return ts.normalizePath(fileName); - } - server.toNormalizedPath = toNormalizedPath; - function normalizedPathToPath(normalizedPath, currentDirectory, getCanonicalFileName) { - var f = ts.isRootedDiskPath(normalizedPath) ? normalizedPath : ts.getNormalizedAbsolutePath(normalizedPath, currentDirectory); - return getCanonicalFileName(f); - } - server.normalizedPathToPath = normalizedPathToPath; - function asNormalizedPath(fileName) { - return fileName; - } - server.asNormalizedPath = asNormalizedPath; - function createNormalizedPathMap() { - var map = Object.create(null); - return { - get: function (path) { - return map[path]; - }, - set: function (path, value) { - map[path] = value; - }, - contains: function (path) { - return ts.hasProperty(map, path); - }, - remove: function (path) { - delete map[path]; - } - }; - } - server.createNormalizedPathMap = createNormalizedPathMap; - function throwLanguageServiceIsDisabledError() { - throw new Error("LanguageService is disabled"); - } - server.nullLanguageService = { - cleanupSemanticCache: function () { return throwLanguageServiceIsDisabledError(); }, - getSyntacticDiagnostics: function () { return throwLanguageServiceIsDisabledError(); }, - getSemanticDiagnostics: function () { return throwLanguageServiceIsDisabledError(); }, - getCompilerOptionsDiagnostics: function () { return throwLanguageServiceIsDisabledError(); }, - getSyntacticClassifications: function () { return throwLanguageServiceIsDisabledError(); }, - getEncodedSyntacticClassifications: function () { return throwLanguageServiceIsDisabledError(); }, - getSemanticClassifications: function () { return throwLanguageServiceIsDisabledError(); }, - getEncodedSemanticClassifications: function () { return throwLanguageServiceIsDisabledError(); }, - getCompletionsAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - findReferences: function () { return throwLanguageServiceIsDisabledError(); }, - getCompletionEntryDetails: function () { return throwLanguageServiceIsDisabledError(); }, - getQuickInfoAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - findRenameLocations: function () { return throwLanguageServiceIsDisabledError(); }, - getNameOrDottedNameSpan: function () { return throwLanguageServiceIsDisabledError(); }, - getBreakpointStatementAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - getBraceMatchingAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - getSignatureHelpItems: function () { return throwLanguageServiceIsDisabledError(); }, - getDefinitionAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - getRenameInfo: function () { return throwLanguageServiceIsDisabledError(); }, - getTypeDefinitionAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - getReferencesAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - getDocumentHighlights: function () { return throwLanguageServiceIsDisabledError(); }, - getOccurrencesAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - getNavigateToItems: function () { return throwLanguageServiceIsDisabledError(); }, - getNavigationBarItems: function () { return throwLanguageServiceIsDisabledError(); }, - getOutliningSpans: function () { return throwLanguageServiceIsDisabledError(); }, - getTodoComments: function () { return throwLanguageServiceIsDisabledError(); }, - getIndentationAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - getFormattingEditsForRange: function () { return throwLanguageServiceIsDisabledError(); }, - getFormattingEditsForDocument: function () { return throwLanguageServiceIsDisabledError(); }, - getFormattingEditsAfterKeystroke: function () { return throwLanguageServiceIsDisabledError(); }, - getDocCommentTemplateAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - isValidBraceCompletionAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - getEmitOutput: function () { return throwLanguageServiceIsDisabledError(); }, - getProgram: function () { return throwLanguageServiceIsDisabledError(); }, - getNonBoundSourceFile: function () { return throwLanguageServiceIsDisabledError(); }, - dispose: function () { return throwLanguageServiceIsDisabledError(); } - }; - server.nullLanguageServiceHost = { - setCompilationSettings: function () { return undefined; }, - notifyFileRemoved: function () { return undefined; } - }; - function isInferredProjectName(name) { - return /dev\/null\/inferredProject\d+\*/.test(name); - } - server.isInferredProjectName = isInferredProjectName; - function makeInferredProjectName(counter) { - return "/dev/null/inferredProject" + counter + "*"; - } - server.makeInferredProjectName = makeInferredProjectName; - var ThrottledOperations = (function () { - function ThrottledOperations(host) { - this.host = host; - this.pendingTimeouts = ts.createMap(); - } - ThrottledOperations.prototype.schedule = function (operationId, delay, cb) { - if (ts.hasProperty(this.pendingTimeouts, operationId)) { - this.host.clearTimeout(this.pendingTimeouts[operationId]); - } - this.pendingTimeouts[operationId] = this.host.setTimeout(ThrottledOperations.run, delay, this, operationId, cb); - }; - ThrottledOperations.run = function (self, operationId, cb) { - delete self.pendingTimeouts[operationId]; - cb(); - }; - return ThrottledOperations; - }()); - server.ThrottledOperations = ThrottledOperations; - var GcTimer = (function () { - function GcTimer(host, delay, logger) { - this.host = host; - this.delay = delay; - this.logger = logger; - } - GcTimer.prototype.scheduleCollect = function () { - if (!this.host.gc || this.timerId != undefined) { - return; - } - this.timerId = this.host.setTimeout(GcTimer.run, this.delay, this); - }; - GcTimer.run = function (self) { - self.timerId = undefined; - var log = self.logger.hasLevel(LogLevel.requestTime); - var before = log && self.host.getMemoryUsage(); - self.host.gc(); - if (log) { - var after = self.host.getMemoryUsage(); - self.logger.perftrc("GC::before " + before + ", after " + after); - } - }; - return GcTimer; - }()); - server.GcTimer = GcTimer; - })(server = ts.server || (ts.server = {})); -})(ts || (ts = {})); -var ts; (function (ts) { function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; @@ -5533,6 +4797,24 @@ var ts; return node.end - node.pos; } ts.getFullWidth = getFullWidth; + function mapIsEqualTo(map1, map2) { + if (!map1 || !map2) { + return map1 === map2; + } + return containsAll(map1, map2) && containsAll(map2, map1); + } + ts.mapIsEqualTo = mapIsEqualTo; + function containsAll(map, other) { + for (var key in map) { + if (!ts.hasProperty(map, key)) { + continue; + } + if (!ts.hasProperty(other, key) || map[key] !== other[key]) { + return false; + } + } + return true; + } function arrayIsEqualTo(array1, array2, equaler) { if (!array1 || !array2) { return array1 === array2; @@ -5550,7 +4832,7 @@ var ts; } ts.arrayIsEqualTo = arrayIsEqualTo; function hasResolvedModule(sourceFile, moduleNameText) { - return !!(sourceFile.resolvedModules && sourceFile.resolvedModules[moduleNameText]); + return sourceFile.resolvedModules && ts.hasProperty(sourceFile.resolvedModules, moduleNameText); } ts.hasResolvedModule = hasResolvedModule; function getResolvedModule(sourceFile, moduleNameText) { @@ -5559,14 +4841,14 @@ var ts; ts.getResolvedModule = getResolvedModule; function setResolvedModule(sourceFile, moduleNameText, resolvedModule) { if (!sourceFile.resolvedModules) { - sourceFile.resolvedModules = ts.createMap(); + sourceFile.resolvedModules = {}; } sourceFile.resolvedModules[moduleNameText] = resolvedModule; } ts.setResolvedModule = setResolvedModule; function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) { if (!sourceFile.resolvedTypeReferenceDirectiveNames) { - sourceFile.resolvedTypeReferenceDirectiveNames = ts.createMap(); + sourceFile.resolvedTypeReferenceDirectiveNames = {}; } sourceFile.resolvedTypeReferenceDirectiveNames[typeReferenceDirectiveName] = resolvedTypeReferenceDirective; } @@ -5585,7 +4867,7 @@ var ts; } for (var i = 0; i < names.length; i++) { var newResolution = newResolutions[i]; - var oldResolution = oldResolutions && oldResolutions[names[i]]; + var oldResolution = oldResolutions && ts.hasProperty(oldResolutions, names[i]) ? oldResolutions[names[i]] : undefined; var changed = oldResolution ? !newResolution || !comparer(oldResolution, newResolution) : newResolution; @@ -5685,20 +4967,16 @@ var ts; if (includeJsDocComment && node.jsDocComments && node.jsDocComments.length > 0) { return getTokenPosOfNode(node.jsDocComments[0]); } - if (node.kind === 286 && node._children.length > 0) { + if (node.kind === 282 && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDocComment); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); } ts.getTokenPosOfNode = getTokenPosOfNode; function isJSDocNode(node) { - return node.kind >= 257 && node.kind <= 282; + return node.kind >= 257 && node.kind <= 281; } ts.isJSDocNode = isJSDocNode; - function isJSDocTag(node) { - return node.kind >= 273 && node.kind <= 285; - } - ts.isJSDocTag = isJSDocTag; function getNonDecoratorTokenPosOfNode(node, sourceFile) { if (nodeIsMissing(node) || !node.decorators) { return getTokenPosOfNode(node, sourceFile); @@ -5749,13 +5027,10 @@ var ts; (node.name.kind === 9 || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; - function isShorthandAmbientModuleSymbol(moduleSymbol) { - return isShorthandAmbientModule(moduleSymbol.valueDeclaration); - } - ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; function isShorthandAmbientModule(node) { return node.kind === 225 && (!node.body); } + ts.isShorthandAmbientModule = isShorthandAmbientModule; function isBlockScopedContainerTopLevel(node) { return node.kind === 256 || node.kind === 225 || @@ -6084,9 +5359,9 @@ var ts; return; default: if (isFunctionLike(node)) { - var name_8 = node.name; - if (name_8 && name_8.kind === 140) { - traverse(name_8.expression); + var name_6 = node.name; + if (name_6 && name_6.kind === 140) { + traverse(name_6.expression); return; } } @@ -6315,7 +5590,6 @@ var ts; case 155: return node.typeName; case 194: - ts.Debug.assert(isEntityNameExpression(node.expression)); return node.expression; case 69: case 139: @@ -6479,6 +5753,10 @@ var ts; return false; } ts.isExpression = isExpression; + function isExternalModuleNameRelative(moduleName) { + return moduleName.substr(0, 2) === "./" || moduleName.substr(0, 3) === "../" || moduleName.substr(0, 2) === ".\\" || moduleName.substr(0, 3) === "..\\"; + } + ts.isExternalModuleNameRelative = isExternalModuleNameRelative; function isInstantiatedModule(node, preserveConstEnums) { var moduleState = ts.getModuleInstanceState(node); return moduleState === 1 || @@ -6673,8 +5951,8 @@ var ts; var tag = _b[_a]; if (tag.kind === 275) { var parameterTag = tag; - var name_9 = parameterTag.preParameterName || parameterTag.postParameterName; - if (name_9.text === parameterName) { + var name_7 = parameterTag.preParameterName || parameterTag.postParameterName; + if (name_7.text === parameterName) { return parameterTag; } } @@ -6741,7 +6019,7 @@ var ts; continue; } return parent_5.kind === 187 && - isAssignmentOperator(parent_5.operatorToken.kind) && + parent_5.operatorToken.kind === 56 && parent_5.left === node || (parent_5.kind === 207 || parent_5.kind === 208) && parent_5.initializer === node; @@ -6788,7 +6066,6 @@ var ts; case 146: case 225: case 232: - case 228: case 142: case 253: case 145: @@ -6905,13 +6182,9 @@ var ts; node.kind === 232 || node.kind === 234 || node.kind === 238 || - node.kind === 235 && exportAssignmentIsAlias(node); + node.kind === 235 && node.expression.kind === 69; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; - function exportAssignmentIsAlias(node) { - return isEntityNameExpression(node.expression); - } - ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getClassExtendsHeritageClauseElement(node) { var heritageClause = getHeritageClause(node.heritageClauses, 83); return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; @@ -7131,7 +6404,7 @@ var ts; ts.createSynthesizedNodeArray = createSynthesizedNodeArray; function createDiagnosticCollection() { var nonFileDiagnostics = []; - var fileDiagnostics = ts.createMap(); + var fileDiagnostics = {}; var diagnosticsModified = false; var modificationCount = 0; return { @@ -7145,12 +6418,12 @@ var ts; return modificationCount; } function reattachFileDiagnostics(newFile) { - var diagnostics = fileDiagnostics[newFile.fileName]; - if (diagnostics) { - for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { - var diagnostic = diagnostics_1[_i]; - diagnostic.file = newFile; - } + if (!ts.hasProperty(fileDiagnostics, newFile.fileName)) { + return; + } + for (var _i = 0, _a = fileDiagnostics[newFile.fileName]; _i < _a.length; _i++) { + var diagnostic = _a[_i]; + diagnostic.file = newFile; } } function add(diagnostic) { @@ -7184,7 +6457,9 @@ var ts; } ts.forEach(nonFileDiagnostics, pushDiagnostic); for (var key in fileDiagnostics) { - ts.forEach(fileDiagnostics[key], pushDiagnostic); + if (ts.hasProperty(fileDiagnostics, key)) { + ts.forEach(fileDiagnostics[key], pushDiagnostic); + } } return ts.sortAndDeduplicateDiagnostics(allDiagnostics); } @@ -7195,13 +6470,15 @@ var ts; diagnosticsModified = false; nonFileDiagnostics = ts.sortAndDeduplicateDiagnostics(nonFileDiagnostics); for (var key in fileDiagnostics) { - fileDiagnostics[key] = ts.sortAndDeduplicateDiagnostics(fileDiagnostics[key]); + if (ts.hasProperty(fileDiagnostics, key)) { + fileDiagnostics[key] = ts.sortAndDeduplicateDiagnostics(fileDiagnostics[key]); + } } } } ts.createDiagnosticCollection = createDiagnosticCollection; var escapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; - var escapedCharsMap = ts.createMap({ + var escapedCharsMap = { "\0": "\\0", "\t": "\\t", "\v": "\\v", @@ -7214,7 +6491,7 @@ var ts; "\u2028": "\\u2028", "\u2029": "\\u2029", "\u0085": "\\u0085" - }); + }; function escapeString(s) { s = escapedCharsRegExp.test(s) ? s.replace(escapedCharsRegExp, getReplacement) : s; return s; @@ -7344,13 +6621,25 @@ var ts; function getDeclarationEmitOutputFilePath(sourceFile, host) { var options = host.getCompilerOptions(); var outputDir = options.declarationDir || options.outDir; - var path = outputDir - ? getSourceFilePathInNewDir(sourceFile, host, outputDir) - : sourceFile.fileName; - return ts.removeFileExtension(path) + ".d.ts"; + if (options.declaration) { + var path = outputDir + ? getSourceFilePathInNewDir(sourceFile, host, outputDir) + : sourceFile.fileName; + return ts.removeFileExtension(path) + ".d.ts"; + } } ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; - function forEachExpectedEmitFile(host, action, targetSourceFile, emitOnlyDtsFiles) { + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return typeof compilerOptions.module === "number" ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) === 2 ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; + } + ts.getEmitModuleKind = getEmitModuleKind; + function forEachExpectedEmitFile(host, action, targetSourceFile) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { onBundledEmit(host); @@ -7377,19 +6666,18 @@ var ts; } } var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); - var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; var emitFileNames = { jsFilePath: jsFilePath, sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), - declarationFilePath: declarationFilePath + declarationFilePath: !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined }; - action(emitFileNames, [sourceFile], false, emitOnlyDtsFiles); + action(emitFileNames, [sourceFile], false); } function onBundledEmit(host) { var bundledSources = ts.filter(host.getSourceFiles(), function (sourceFile) { return !isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile) && (!ts.isExternalModule(sourceFile) || - !!ts.getEmitModuleKind(options)); }); + !!getEmitModuleKind(options)); }); if (bundledSources.length) { var jsFilePath = options.outFile || options.out; var emitFileNames = { @@ -7397,7 +6685,7 @@ var ts; sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), declarationFilePath: options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined }; - action(emitFileNames, bundledSources, true, emitOnlyDtsFiles); + action(emitFileNames, bundledSources, true); } } function getSourceMapFilePath(jsFilePath, options) { @@ -7684,11 +6972,21 @@ var ts; isClassLike(node.parent.parent); } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; - function isEntityNameExpression(node) { - return node.kind === 69 || - node.kind === 172 && isEntityNameExpression(node.expression); + function isSupportedExpressionWithTypeArguments(node) { + return isSupportedExpressionWithTypeArgumentsRest(node.expression); + } + ts.isSupportedExpressionWithTypeArguments = isSupportedExpressionWithTypeArguments; + function isSupportedExpressionWithTypeArgumentsRest(node) { + if (node.kind === 69) { + return true; + } + else if (isPropertyAccessExpression(node)) { + return isSupportedExpressionWithTypeArgumentsRest(node.expression); + } + else { + return false; + } } - ts.isEntityNameExpression = isEntityNameExpression; function isRightSideOfQualifiedNameOrPropertyAccess(node) { return (node.parent.kind === 139 && node.parent.right === node) || (node.parent.kind === 172 && node.parent.name === node); @@ -7709,10 +7007,14 @@ var ts; return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & 512) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; - function tryExtractTypeScriptExtension(fileName) { - return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function hasJavaScriptFileExtension(fileName) { + return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; + ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; + function hasTypeScriptFileExtension(fileName) { + return ts.forEach(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; function getExpandedCharCodes(input) { var output = []; var length = input.length; @@ -7769,7 +7071,7 @@ var ts; return (memo ? memo + "," : memo) + stringifyValue(value); } function stringifyObject(value) { - return "{" + ts.reduceOwnProperties(value, stringifyProperty, "") + "}"; + return "{" + ts.reduceProperties(value, stringifyProperty, "") + "}"; } function stringifyProperty(memo, value, key) { return value === undefined || typeof value === "function" || key === "__cycle" ? memo @@ -7960,451 +7262,25 @@ var ts; return node.flags & 92 && node.parent.kind === 148 && ts.isClassLike(node.parent.parent); } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; + function startsWith(str, prefix) { + return str.lastIndexOf(prefix, 0) === 0; + } + ts.startsWith = startsWith; + function endsWith(str, suffix) { + var expectedPos = str.length - suffix.length; + return str.indexOf(suffix, expectedPos) === expectedPos; + } + ts.endsWith = endsWith; })(ts || (ts = {})); var ts; (function (ts) { - function tryReadTypesSection(packageJsonPath, baseDirectory, state) { - var jsonContent = ts.readJson(packageJsonPath, state.host); - function tryReadFromField(fieldName) { - if (ts.hasProperty(jsonContent, fieldName)) { - var typesFile = jsonContent[fieldName]; - if (typeof typesFile === "string") { - var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1); - } - return typesFilePath_1; - } - else { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); - } - } - } - } - var typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); - if (typesFilePath) { - return typesFilePath; - } - if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); - } - var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); - return mainFilePath; - } - return undefined; - } - function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures && state.host.fileExists(fileName)) { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); - } - return fileName; - } - else { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); - } - failedLookupLocation.push(fileName); - return undefined; - } - } - function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures) { - var directory = ts.getDirectoryPath(candidate); - if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); - } - } - return ts.forEach(extensions, function (ext) { - return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); - }); - } - function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); - if (resolvedByAddingExtension) { - return resolvedByAddingExtension; - } - if (ts.hasJavaScriptFileExtension(candidate)) { - var extensionless = ts.removeFileExtension(candidate); - if (state.traceEnabled) { - var extension = candidate.substring(extensionless.length); - ts.trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); - } - return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); - } - } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { - var packageJsonPath = pathToPackageJson(candidate); - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - if (directoryExists && state.host.fileExists(packageJsonPath)) { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); - if (typesFile) { - var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); - var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) || - tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state); - if (result) { - return result; - } - } - else { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field); - } - } - } - else { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); - } - failedLookupLocation.push(packageJsonPath); - } - return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); - } - ts.loadNodeModuleFromDirectory = loadNodeModuleFromDirectory; - function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { - var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions); - var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - } - function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state, checkOneLevel) { - directory = ts.normalizeSlashes(directory); - while (true) { - var baseName = ts.getBaseFileName(directory); - if (baseName !== "node_modules") { - var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); - if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { - return packageResult; - } - else { - var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); - if (typesResult || packageResult) { - return typesResult || packageResult; - } - } - } - var parentPath = ts.getDirectoryPath(directory); - if (parentPath === directory || checkOneLevel) { - break; - } - directory = parentPath; - } - return undefined; - } - ts.loadModuleFromNodeModules = loadModuleFromNodeModules; - function moduleHasNonRelativeName(moduleName) { - return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); - } - function classicNameResolver(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = ts.isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; - var failedLookupLocations = []; - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var containingDirectory = ts.getDirectoryPath(containingFile); - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); - if (resolvedFileName) { - return ts.createResolvedModule(resolvedFileName, false, failedLookupLocations); - } - var referencedSourceFile; - if (moduleHasNonRelativeName(moduleName)) { - while (true) { - var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state); - if (referencedSourceFile) { - break; - } - var parentPath = ts.getDirectoryPath(containingDirectory); - if (parentPath === containingDirectory) { - break; - } - containingDirectory = parentPath; - } - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, false, state); - } - return referencedSourceFile - ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } - : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; - } - ts.classicNameResolver = classicNameResolver; - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { - var containingDirectory = ts.getDirectoryPath(containingFile); - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var traceEnabled = ts.isTraceEnabled(compilerOptions, host); - var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); - var isExternalLibraryImport = false; - if (!resolvedFileName) { - if (moduleHasNonRelativeName(moduleName)) { - if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); - } - resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state, false); - isExternalLibraryImport = resolvedFileName !== undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, false, state); - } - } - if (resolvedFileName && host.realpath) { - var originalFileName = resolvedFileName; - resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName)); - if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); - } - } - return ts.createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; - function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); - } - var resolvedFileName = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); - return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); - } - function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.rootDirs) { - return undefined; - } - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); - } - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var matchedRootDir; - var matchedNormalizedPrefix; - for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { - var rootDir = _a[_i]; - var normalizedRoot = ts.normalizePath(rootDir); - if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { - normalizedRoot += ts.directorySeparator; - } - var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && - (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); - } - if (isLongestMatchingPrefix) { - matchedNormalizedPrefix = normalizedRoot; - matchedRootDir = rootDir; - } - } - if (matchedNormalizedPrefix) { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); - } - var suffix = candidate.substr(matchedNormalizedPrefix.length); - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); - } - for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { - var rootDir = _c[_b]; - if (rootDir === matchedRootDir) { - continue; - } - var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); - } - var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); - if (resolvedFileName_1) { - return resolvedFileName_1; - } - } - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); - } - } - return undefined; - } - function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.baseUrl) { - return undefined; - } - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); - } - var matchedPattern = undefined; - if (state.compilerOptions.paths) { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); - } - matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName); - var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern); - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); - } - for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) { - var subst = _a[_i]; - var path = matchedStar ? subst.replace("*", matchedStar) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - } - return undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - } - } - function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (moduleHasNonRelativeName(moduleName)) { - return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); - } - else { - return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); - } - } - function resolveModuleName(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = ts.isTraceEnabled(compilerOptions, host); - if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); - } - var moduleResolution = compilerOptions.moduleResolution; - if (moduleResolution === undefined) { - moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; - if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - else { - if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - var result; - switch (moduleResolution) { - case ts.ModuleResolutionKind.NodeJs: - result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); - break; - case ts.ModuleResolutionKind.Classic: - result = classicNameResolver(moduleName, containingFile, compilerOptions, host); - break; - } - if (traceEnabled) { - if (result.resolvedModule) { - ts.trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); - } - else { - ts.trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); - } - } - return result; - } - ts.resolveModuleName = resolveModuleName; - function matchPatternOrExact(patternStrings, candidate) { - var patterns = []; - for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { - var patternString = patternStrings_1[_i]; - var pattern = tryParsePattern(patternString); - if (pattern) { - patterns.push(pattern); - } - else if (patternString === candidate) { - return patternString; - } - } - return findBestPatternMatch(patterns, function (_) { return _; }, candidate); - } - function patternText(_a) { - var prefix = _a.prefix, suffix = _a.suffix; - return prefix + "*" + suffix; - } - function matchedText(pattern, candidate) { - ts.Debug.assert(isPatternMatch(pattern, candidate)); - return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); - } - function findBestPatternMatch(values, getPattern, candidate) { - var matchedValue = undefined; - var longestMatchPrefixLength = -1; - for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { - var v = values_1[_i]; - var pattern = getPattern(v); - if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { - longestMatchPrefixLength = pattern.prefix.length; - matchedValue = v; - } - } - return matchedValue; - } - ts.findBestPatternMatch = findBestPatternMatch; - function isPatternMatch(_a, candidate) { - var prefix = _a.prefix, suffix = _a.suffix; - return candidate.length >= prefix.length + suffix.length && - ts.startsWith(candidate, prefix) && - ts.endsWith(candidate, suffix); - } - function tryParsePattern(pattern) { - ts.Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern)); - var indexOfStar = pattern.indexOf("*"); - return indexOfStar === -1 ? undefined : { - prefix: pattern.substr(0, indexOfStar), - suffix: pattern.substr(indexOfStar + 1) - }; - } - ts.tryParsePattern = tryParsePattern; - function directoryProbablyExists(directoryName, host) { - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - ts.pathToPackageJson = pathToPackageJson; -})(ts || (ts = {})); -var ts; -(function (ts) { + ts.parseTime = 0; var NodeConstructor; - var TokenConstructor; - var IdentifierConstructor; var SourceFileConstructor; function createNode(kind, pos, end) { if (kind === 256) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); } - else if (kind === 69) { - return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); - } - else if (kind < 139) { - return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end); - } else { return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end); } @@ -8513,8 +7389,6 @@ var ts; return visitNodes(cbNodes, node.types); case 164: return visitNode(cbNode, node.type); - case 166: - return visitNode(cbNode, node.literal); case 167: case 168: return visitNodes(cbNodes, node.elements); @@ -8793,17 +7667,14 @@ var ts; case 280: return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); - case 282: - return visitNode(cbNode, node.literal); } } ts.forEachChild = forEachChild; function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { if (setParentNodes === void 0) { setParentNodes = false; } - ts.performance.mark("beforeParse"); + var start = new Date().getTime(); var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, scriptKind); - ts.performance.mark("afterParse"); - ts.performance.measure("Parse", "beforeParse", "afterParse"); + ts.parseTime += new Date().getTime() - start; return result; } ts.createSourceFile = createSourceFile; @@ -8818,7 +7689,7 @@ var ts; function parseIsolatedJSDocComment(content, start, length) { var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length); if (result && result.jsDocComment) { - fixupParentReferences(result.jsDocComment); + Parser.fixupParentReferences(result.jsDocComment); } return result; } @@ -8827,41 +7698,16 @@ var ts; return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length); } ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; - function fixupParentReferences(rootNode) { - var parent = rootNode; - forEachChild(rootNode, visitNode); - return; - function visitNode(n) { - if (n.parent !== parent) { - n.parent = parent; - var saveParent = parent; - parent = n; - forEachChild(n, visitNode); - if (n.jsDocComments) { - for (var _i = 0, _a = n.jsDocComments; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - jsDocComment.parent = n; - parent = jsDocComment; - forEachChild(jsDocComment, visitNode); - } - } - parent = saveParent; - } - } - } - ts.fixupParentReferences = fixupParentReferences; var Parser; (function (Parser) { var scanner = ts.createScanner(2, true); var disallowInAndDecoratorContext = 4194304 | 16777216; var NodeConstructor; - var TokenConstructor; - var IdentifierConstructor; var SourceFileConstructor; var sourceFile; var parseDiagnostics; var syntaxCursor; - var currentToken; + var token; var sourceText; var nodeCount; var identifiers; @@ -8882,14 +7728,12 @@ var ts; } function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind) { NodeConstructor = ts.objectAllocator.getNodeConstructor(); - TokenConstructor = ts.objectAllocator.getTokenConstructor(); - IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor(); SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor(); sourceText = _sourceText; syntaxCursor = _syntaxCursor; parseDiagnostics = []; parsingContext = 0; - identifiers = ts.createMap(); + identifiers = {}; identifierCount = 0; nodeCount = 0; contextFlags = scriptKind === 1 || scriptKind === 2 ? 134217728 : 0; @@ -8911,10 +7755,10 @@ var ts; function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) { sourceFile = createSourceFile(fileName, languageVersion, scriptKind); sourceFile.flags = contextFlags; - nextToken(); + token = nextToken(); processReferenceComments(sourceFile); sourceFile.statements = parseList(0, parseStatement); - ts.Debug.assert(token() === 1); + ts.Debug.assert(token === 1); sourceFile.endOfFileToken = parseTokenNode(); setExternalModuleIndicator(sourceFile); sourceFile.nodeCount = nodeCount; @@ -8945,6 +7789,29 @@ var ts; } return node; } + function fixupParentReferences(rootNode) { + var parent = rootNode; + forEachChild(rootNode, visitNode); + return; + function visitNode(n) { + if (n.parent !== parent) { + n.parent = parent; + var saveParent = parent; + parent = n; + forEachChild(n, visitNode); + if (n.jsDocComments) { + for (var _i = 0, _a = n.jsDocComments; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + jsDocComment.parent = n; + parent = jsDocComment; + forEachChild(jsDocComment, visitNode); + } + } + parent = saveParent; + } + } + } + Parser.fixupParentReferences = fixupParentReferences; function createSourceFile(fileName, languageVersion, scriptKind) { var sourceFile = new SourceFileConstructor(256, 0, sourceText.length); nodeCount++; @@ -9055,29 +7922,26 @@ var ts; function getNodeEnd() { return scanner.getStartPos(); } - function token() { - return currentToken; - } function nextToken() { - return currentToken = scanner.scan(); + return token = scanner.scan(); } function reScanGreaterToken() { - return currentToken = scanner.reScanGreaterToken(); + return token = scanner.reScanGreaterToken(); } function reScanSlashToken() { - return currentToken = scanner.reScanSlashToken(); + return token = scanner.reScanSlashToken(); } function reScanTemplateToken() { - return currentToken = scanner.reScanTemplateToken(); + return token = scanner.reScanTemplateToken(); } function scanJsxIdentifier() { - return currentToken = scanner.scanJsxIdentifier(); + return token = scanner.scanJsxIdentifier(); } function scanJsxText() { - return currentToken = scanner.scanJsxToken(); + return token = scanner.scanJsxToken(); } function speculationHelper(callback, isLookAhead) { - var saveToken = currentToken; + var saveToken = token; var saveParseDiagnosticsLength = parseDiagnostics.length; var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; var saveContextFlags = contextFlags; @@ -9086,7 +7950,7 @@ var ts; : scanner.tryScan(callback); ts.Debug.assert(saveContextFlags === contextFlags); if (!result || isLookAhead) { - currentToken = saveToken; + token = saveToken; parseDiagnostics.length = saveParseDiagnosticsLength; parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; } @@ -9099,20 +7963,20 @@ var ts; return speculationHelper(callback, false); } function isIdentifier() { - if (token() === 69) { + if (token === 69) { return true; } - if (token() === 114 && inYieldContext()) { + if (token === 114 && inYieldContext()) { return false; } - if (token() === 119 && inAwaitContext()) { + if (token === 119 && inAwaitContext()) { return false; } - return token() > 105; + return token > 105; } function parseExpected(kind, diagnosticMessage, shouldAdvance) { if (shouldAdvance === void 0) { shouldAdvance = true; } - if (token() === kind) { + if (token === kind) { if (shouldAdvance) { nextToken(); } @@ -9127,14 +7991,14 @@ var ts; return false; } function parseOptional(t) { - if (token() === t) { + if (token === t) { nextToken(); return true; } return false; } function parseOptionalToken(t) { - if (token() === t) { + if (token === t) { return parseTokenNode(); } return undefined; @@ -9144,19 +8008,19 @@ var ts; createMissingNode(t, reportAtCurrentPosition, diagnosticMessage, arg0); } function parseTokenNode() { - var node = createNode(token()); + var node = createNode(token); nextToken(); return finishNode(node); } function canParseSemicolon() { - if (token() === 23) { + if (token === 23) { return true; } - return token() === 16 || token() === 1 || scanner.hasPrecedingLineBreak(); + return token === 16 || token === 1 || scanner.hasPrecedingLineBreak(); } function parseSemicolon() { if (canParseSemicolon()) { - if (token() === 23) { + if (token === 23) { nextToken(); } return true; @@ -9170,9 +8034,7 @@ var ts; if (!(pos >= 0)) { pos = scanner.getStartPos(); } - return kind >= 139 ? new NodeConstructor(kind, pos, pos) : - kind === 69 ? new IdentifierConstructor(kind, pos, pos) : - new TokenConstructor(kind, pos, pos); + return new NodeConstructor(kind, pos, pos); } function finishNode(node, end) { node.end = end === undefined ? scanner.getStartPos() : end; @@ -9198,14 +8060,14 @@ var ts; } function internIdentifier(text) { text = ts.escapeIdentifier(text); - return identifiers[text] || (identifiers[text] = text); + return ts.hasProperty(identifiers, text) ? identifiers[text] : (identifiers[text] = text); } function createIdentifier(isIdentifier, diagnosticMessage) { identifierCount++; if (isIdentifier) { var node = createNode(69); - if (token() !== 69) { - node.originalKeywordKind = token(); + if (token !== 69) { + node.originalKeywordKind = token; } node.text = internIdentifier(scanner.getTokenValue()); nextToken(); @@ -9217,18 +8079,18 @@ var ts; return createIdentifier(isIdentifier(), diagnosticMessage); } function parseIdentifierName() { - return createIdentifier(ts.tokenIsIdentifierOrKeyword(token())); + return createIdentifier(ts.tokenIsIdentifierOrKeyword(token)); } function isLiteralPropertyName() { - return ts.tokenIsIdentifierOrKeyword(token()) || - token() === 9 || - token() === 8; + return ts.tokenIsIdentifierOrKeyword(token) || + token === 9 || + token === 8; } function parsePropertyNameWorker(allowComputedPropertyNames) { - if (token() === 9 || token() === 8) { + if (token === 9 || token === 8) { return parseLiteralNode(true); } - if (allowComputedPropertyNames && token() === 19) { + if (allowComputedPropertyNames && token === 19) { return parseComputedPropertyName(); } return parseIdentifierName(); @@ -9240,7 +8102,7 @@ var ts; return parsePropertyNameWorker(false); } function isSimplePropertyName() { - return token() === 9 || token() === 8 || ts.tokenIsIdentifierOrKeyword(token()); + return token === 9 || token === 8 || ts.tokenIsIdentifierOrKeyword(token); } function parseComputedPropertyName() { var node = createNode(140); @@ -9250,7 +8112,7 @@ var ts; return finishNode(node); } function parseContextualModifier(t) { - return token() === t && tryParse(nextTokenCanFollowModifier); + return token === t && tryParse(nextTokenCanFollowModifier); } function nextTokenIsOnSameLineAndCanFollowModifier() { nextToken(); @@ -9260,39 +8122,39 @@ var ts; return canFollowModifier(); } function nextTokenCanFollowModifier() { - if (token() === 74) { + if (token === 74) { return nextToken() === 81; } - if (token() === 82) { + if (token === 82) { nextToken(); - if (token() === 77) { + if (token === 77) { return lookAhead(nextTokenIsClassOrFunctionOrAsync); } - return token() !== 37 && token() !== 116 && token() !== 15 && canFollowModifier(); + return token !== 37 && token !== 116 && token !== 15 && canFollowModifier(); } - if (token() === 77) { + if (token === 77) { return nextTokenIsClassOrFunctionOrAsync(); } - if (token() === 113) { + if (token === 113) { nextToken(); return canFollowModifier(); } return nextTokenIsOnSameLineAndCanFollowModifier(); } function parseAnyContextualModifier() { - return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); + return ts.isModifierKind(token) && tryParse(nextTokenCanFollowModifier); } function canFollowModifier() { - return token() === 19 - || token() === 15 - || token() === 37 - || token() === 22 + return token === 19 + || token === 15 + || token === 37 + || token === 22 || isLiteralPropertyName(); } function nextTokenIsClassOrFunctionOrAsync() { nextToken(); - return token() === 73 || token() === 87 || - (token() === 118 && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); + return token === 73 || token === 87 || + (token === 118 && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); } function isListElement(parsingContext, inErrorRecovery) { var node = currentNode(parsingContext); @@ -9303,21 +8165,21 @@ var ts; case 0: case 1: case 3: - return !(token() === 23 && inErrorRecovery) && isStartOfStatement(); + return !(token === 23 && inErrorRecovery) && isStartOfStatement(); case 2: - return token() === 71 || token() === 77; + return token === 71 || token === 77; case 4: return lookAhead(isTypeMemberStart); case 5: - return lookAhead(isClassMemberStart) || (token() === 23 && !inErrorRecovery); + return lookAhead(isClassMemberStart) || (token === 23 && !inErrorRecovery); case 6: - return token() === 19 || isLiteralPropertyName(); + return token === 19 || isLiteralPropertyName(); case 12: - return token() === 19 || token() === 37 || isLiteralPropertyName(); + return token === 19 || token === 37 || isLiteralPropertyName(); case 9: - return token() === 19 || isLiteralPropertyName(); + return token === 19 || isLiteralPropertyName(); case 7: - if (token() === 15) { + if (token === 15) { return lookAhead(isValidHeritageClauseObjectLiteral); } if (!inErrorRecovery) { @@ -9329,23 +8191,23 @@ var ts; case 8: return isIdentifierOrPattern(); case 10: - return token() === 24 || token() === 22 || isIdentifierOrPattern(); + return token === 24 || token === 22 || isIdentifierOrPattern(); case 17: return isIdentifier(); case 11: case 15: - return token() === 24 || token() === 22 || isStartOfExpression(); + return token === 24 || token === 22 || isStartOfExpression(); case 16: return isStartOfParameter(); case 18: case 19: - return token() === 24 || isStartOfType(); + return token === 24 || isStartOfType(); case 20: return isHeritageClause(); case 21: - return ts.tokenIsIdentifierOrKeyword(token()); + return ts.tokenIsIdentifierOrKeyword(token); case 13: - return ts.tokenIsIdentifierOrKeyword(token()) || token() === 15; + return ts.tokenIsIdentifierOrKeyword(token) || token === 15; case 14: return true; case 22: @@ -9358,7 +8220,7 @@ var ts; ts.Debug.fail("Non-exhaustive case in 'isListElement'."); } function isValidHeritageClauseObjectLiteral() { - ts.Debug.assert(token() === 15); + ts.Debug.assert(token === 15); if (nextToken() === 16) { var next = nextToken(); return next === 24 || next === 15 || next === 83 || next === 106; @@ -9371,11 +8233,11 @@ var ts; } function nextTokenIsIdentifierOrKeyword() { nextToken(); - return ts.tokenIsIdentifierOrKeyword(token()); + return ts.tokenIsIdentifierOrKeyword(token); } function isHeritageClauseExtendsOrImplementsKeyword() { - if (token() === 106 || - token() === 83) { + if (token === 106 || + token === 83) { return lookAhead(nextTokenIsStartOfExpression); } return false; @@ -9385,7 +8247,7 @@ var ts; return isStartOfExpression(); } function isListTerminator(kind) { - if (token() === 1) { + if (token === 1) { return true; } switch (kind) { @@ -9397,49 +8259,49 @@ var ts; case 12: case 9: case 21: - return token() === 16; + return token === 16; case 3: - return token() === 16 || token() === 71 || token() === 77; + return token === 16 || token === 71 || token === 77; case 7: - return token() === 15 || token() === 83 || token() === 106; + return token === 15 || token === 83 || token === 106; case 8: return isVariableDeclaratorListTerminator(); case 17: - return token() === 27 || token() === 17 || token() === 15 || token() === 83 || token() === 106; + return token === 27 || token === 17 || token === 15 || token === 83 || token === 106; case 11: - return token() === 18 || token() === 23; + return token === 18 || token === 23; case 15: case 19: case 10: - return token() === 20; + return token === 20; case 16: - return token() === 18 || token() === 20; + return token === 18 || token === 20; case 18: - return token() === 27 || token() === 17; + return token === 27 || token === 17; case 20: - return token() === 15 || token() === 16; + return token === 15 || token === 16; case 13: - return token() === 27 || token() === 39; + return token === 27 || token === 39; case 14: - return token() === 25 && lookAhead(nextTokenIsSlash); + return token === 25 && lookAhead(nextTokenIsSlash); case 22: - return token() === 18 || token() === 54 || token() === 16; + return token === 18 || token === 54 || token === 16; case 23: - return token() === 27 || token() === 16; + return token === 27 || token === 16; case 25: - return token() === 20 || token() === 16; + return token === 20 || token === 16; case 24: - return token() === 16; + return token === 16; } } function isVariableDeclaratorListTerminator() { if (canParseSemicolon()) { return true; } - if (isInOrOfKeyword(token())) { + if (isInOrOfKeyword(token)) { return true; } - if (token() === 34) { + if (token === 34) { return true; } return false; @@ -9694,7 +8556,7 @@ var ts; break; } parseExpected(24); - if (considerSemicolonAsDelimiter && token() === 23 && !scanner.hasPrecedingLineBreak()) { + if (considerSemicolonAsDelimiter && token === 23 && !scanner.hasPrecedingLineBreak()) { nextToken(); } continue; @@ -9739,7 +8601,7 @@ var ts; return entity; } function parseRightSideOfDot(allowIdentifierNames) { - if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) { + if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token)) { var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); if (matchesPattern) { return createMissingNode(69, true, ts.Diagnostics.Identifier_expected); @@ -9764,7 +8626,7 @@ var ts; var span = createNode(197); span.expression = allowInAnd(parseExpression); var literal; - if (token() === 16) { + if (token === 16) { reScanTemplateToken(); literal = parseTemplateLiteralFragment(); } @@ -9774,11 +8636,14 @@ var ts; span.literal = literal; return finishNode(span); } + function parseStringLiteralTypeNode() { + return parseLiteralLikeNode(166, true); + } function parseLiteralNode(internName) { - return parseLiteralLikeNode(token(), internName); + return parseLiteralLikeNode(token, internName); } function parseTemplateLiteralFragment() { - return parseLiteralLikeNode(token(), false); + return parseLiteralLikeNode(token, false); } function parseLiteralLikeNode(kind, internName) { var node = createNode(kind); @@ -9804,7 +8669,7 @@ var ts; var typeName = parseEntityName(false, ts.Diagnostics.Type_expected); var node = createNode(155, typeName.pos); node.typeName = typeName; - if (!scanner.hasPrecedingLineBreak() && token() === 25) { + if (!scanner.hasPrecedingLineBreak() && token === 25) { node.typeArguments = parseBracketedList(18, parseType, 25, 27); } return finishNode(node); @@ -9841,7 +8706,7 @@ var ts; return finishNode(node); } function parseTypeParameters() { - if (token() === 25) { + if (token === 25) { return parseBracketedList(17, parseTypeParameter, 25, 27); } } @@ -9852,7 +8717,7 @@ var ts; return undefined; } function isStartOfParameter() { - return token() === 22 || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 55 || token() === 97; + return token === 22 || isIdentifierOrPattern() || ts.isModifierKind(token) || token === 55 || token === 97; } function setModifiers(node, modifiers) { if (modifiers) { @@ -9862,7 +8727,7 @@ var ts; } function parseParameter() { var node = createNode(142); - if (token() === 97) { + if (token === 97) { node.name = createIdentifier(true, undefined); node.type = parseParameterType(); return finishNode(node); @@ -9871,7 +8736,7 @@ var ts; setModifiers(node, parseModifiers()); node.dotDotDotToken = parseOptionalToken(22); node.name = parseIdentifierOrPattern(); - if (ts.getFullWidth(node.name) === 0 && node.flags === 0 && ts.isModifierKind(token())) { + if (ts.getFullWidth(node.name) === 0 && node.flags === 0 && ts.isModifierKind(token)) { nextToken(); } node.questionToken = parseOptionalToken(53); @@ -9929,17 +8794,17 @@ var ts; return finishNode(node); } function isIndexSignature() { - if (token() !== 19) { + if (token !== 19) { return false; } return lookAhead(isUnambiguouslyIndexSignature); } function isUnambiguouslyIndexSignature() { nextToken(); - if (token() === 22 || token() === 20) { + if (token === 22 || token === 20) { return true; } - if (ts.isModifierKind(token())) { + if (ts.isModifierKind(token)) { nextToken(); if (isIdentifier()) { return true; @@ -9951,14 +8816,14 @@ var ts; else { nextToken(); } - if (token() === 54 || token() === 24) { + if (token === 54 || token === 24) { return true; } - if (token() !== 53) { + if (token !== 53) { return false; } nextToken(); - return token() === 54 || token() === 24 || token() === 20; + return token === 54 || token === 24 || token === 20; } function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { var node = createNode(153, fullStart); @@ -9972,7 +8837,7 @@ var ts; function parsePropertyOrMethodSignature(fullStart, modifiers) { var name = parsePropertyName(); var questionToken = parseOptionalToken(53); - if (token() === 17 || token() === 25) { + if (token === 17 || token === 25) { var method = createNode(146, fullStart); setModifiers(method, modifiers); method.name = name; @@ -9987,7 +8852,7 @@ var ts; property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); - if (token() === 56) { + if (token === 56) { property.initializer = parseNonParameterInitializer(); } parseTypeMemberSemicolon(); @@ -9996,35 +8861,34 @@ var ts; } function isTypeMemberStart() { var idToken; - if (token() === 17 || token() === 25) { + if (token === 17 || token === 25) { return true; } - while (ts.isModifierKind(token())) { - idToken = token(); + while (ts.isModifierKind(token)) { + idToken = token; nextToken(); } - if (token() === 19) { + if (token === 19) { return true; } if (isLiteralPropertyName()) { - idToken = token(); + idToken = token; nextToken(); } if (idToken) { - return token() === 17 || - token() === 25 || - token() === 53 || - token() === 54 || - token() === 24 || + return token === 17 || + token === 25 || + token === 53 || + token === 54 || canParseSemicolon(); } return false; } function parseTypeMember() { - if (token() === 17 || token() === 25) { + if (token === 17 || token === 25) { return parseSignatureMember(151); } - if (token() === 92 && lookAhead(isStartOfConstructSignature)) { + if (token === 92 && lookAhead(isStartOfConstructSignature)) { return parseSignatureMember(152); } var fullStart = getNodePos(); @@ -10036,7 +8900,7 @@ var ts; } function isStartOfConstructSignature() { nextToken(); - return token() === 17 || token() === 25; + return token === 17 || token === 25; } function parseTypeLiteral() { var node = createNode(159); @@ -10076,19 +8940,10 @@ var ts; } function parseKeywordAndNoDot() { var node = parseTokenNode(); - return token() === 21 ? undefined : node; - } - function parseLiteralTypeNode() { - var node = createNode(166); - node.literal = parseSimpleUnaryExpression(); - finishNode(node); - return node; - } - function nextTokenIsNumericLiteral() { - return nextToken() === 8; + return token === 21 ? undefined : node; } function parseNonArrayType() { - switch (token()) { + switch (token) { case 117: case 132: case 130: @@ -10099,18 +8954,13 @@ var ts; var node = tryParse(parseKeywordAndNoDot); return node || parseTypeReference(); case 9: - case 8: - case 99: - case 84: - return parseLiteralTypeNode(); - case 36: - return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode() : parseTypeReference(); + return parseStringLiteralTypeNode(); case 103: case 93: return parseTokenNode(); case 97: { var thisKeyword = parseThisTypeNode(); - if (token() === 124 && !scanner.hasPrecedingLineBreak()) { + if (token === 124 && !scanner.hasPrecedingLineBreak()) { return parseThisTypePredicate(thisKeyword); } else { @@ -10130,7 +8980,7 @@ var ts; } } function isStartOfType() { - switch (token()) { + switch (token) { case 117: case 132: case 130: @@ -10147,12 +8997,7 @@ var ts; case 25: case 92: case 9: - case 8: - case 99: - case 84: return true; - case 36: - return lookAhead(nextTokenIsNumericLiteral); case 17: return lookAhead(isStartOfParenthesizedOrFunctionType); default: @@ -10161,7 +9006,7 @@ var ts; } function isStartOfParenthesizedOrFunctionType() { nextToken(); - return token() === 18 || isStartOfParameter() || isStartOfType(); + return token === 18 || isStartOfParameter() || isStartOfType(); } function parseArrayTypeOrHigher() { var type = parseNonArrayType(); @@ -10175,7 +9020,7 @@ var ts; } function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { var type = parseConstituentType(); - if (token() === operator) { + if (token === operator) { var types = [type]; types.pos = type.pos; while (parseOptional(operator)) { @@ -10195,20 +9040,20 @@ var ts; return parseUnionOrIntersectionType(162, parseIntersectionTypeOrHigher, 47); } function isStartOfFunctionType() { - if (token() === 25) { + if (token === 25) { return true; } - return token() === 17 && lookAhead(isUnambiguouslyStartOfFunctionType); + return token === 17 && lookAhead(isUnambiguouslyStartOfFunctionType); } function skipParameterStart() { - if (ts.isModifierKind(token())) { + if (ts.isModifierKind(token)) { parseModifiers(); } - if (isIdentifier() || token() === 97) { + if (isIdentifier() || token === 97) { nextToken(); return true; } - if (token() === 19 || token() === 15) { + if (token === 19 || token === 15) { var previousErrorCount = parseDiagnostics.length; parseIdentifierOrPattern(); return previousErrorCount === parseDiagnostics.length; @@ -10217,17 +9062,17 @@ var ts; } function isUnambiguouslyStartOfFunctionType() { nextToken(); - if (token() === 18 || token() === 22) { + if (token === 18 || token === 22) { return true; } if (skipParameterStart()) { - if (token() === 54 || token() === 24 || - token() === 53 || token() === 56) { + if (token === 54 || token === 24 || + token === 53 || token === 56) { return true; } - if (token() === 18) { + if (token === 18) { nextToken(); - if (token() === 34) { + if (token === 34) { return true; } } @@ -10249,7 +9094,7 @@ var ts; } function parseTypePredicatePrefix() { var id = parseIdentifier(); - if (token() === 124 && !scanner.hasPrecedingLineBreak()) { + if (token === 124 && !scanner.hasPrecedingLineBreak()) { nextToken(); return id; } @@ -10261,7 +9106,7 @@ var ts; if (isStartOfFunctionType()) { return parseFunctionOrConstructorType(156); } - if (token() === 92) { + if (token === 92) { return parseFunctionOrConstructorType(157); } return parseUnionTypeOrHigher(); @@ -10270,7 +9115,7 @@ var ts; return parseOptional(54) ? parseType() : undefined; } function isStartOfLeftHandSideExpression() { - switch (token()) { + switch (token) { case 97: case 95: case 93: @@ -10298,7 +9143,7 @@ var ts; if (isStartOfLeftHandSideExpression()) { return true; } - switch (token()) { + switch (token) { case 35: case 36: case 50: @@ -10320,10 +9165,10 @@ var ts; } } function isStartOfExpressionStatement() { - return token() !== 15 && - token() !== 87 && - token() !== 73 && - token() !== 55 && + return token !== 15 && + token !== 87 && + token !== 73 && + token !== 55 && isStartOfExpression(); } function parseExpression() { @@ -10342,8 +9187,8 @@ var ts; return expr; } function parseInitializer(inParameter) { - if (token() !== 56) { - if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 15) || !isStartOfExpression()) { + if (token !== 56) { + if (scanner.hasPrecedingLineBreak() || (inParameter && token === 15) || !isStartOfExpression()) { return undefined; } } @@ -10359,7 +9204,7 @@ var ts; return arrowExpression; } var expr = parseBinaryExpressionOrHigher(0); - if (expr.kind === 69 && token() === 34) { + if (expr.kind === 69 && token === 34) { return parseSimpleArrowFunctionExpression(expr); } if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { @@ -10368,7 +9213,7 @@ var ts; return parseConditionalExpressionRest(expr); } function isYieldExpression() { - if (token() === 114) { + if (token === 114) { if (inYieldContext()) { return true; } @@ -10384,7 +9229,7 @@ var ts; var node = createNode(190); nextToken(); if (!scanner.hasPrecedingLineBreak() && - (token() === 37 || isStartOfExpression())) { + (token === 37 || isStartOfExpression())) { node.asteriskToken = parseOptionalToken(37); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); @@ -10394,7 +9239,7 @@ var ts; } } function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { - ts.Debug.assert(token() === 34, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + ts.Debug.assert(token === 34, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); var node; if (asyncModifier) { node = createNode(180, asyncModifier.pos); @@ -10425,7 +9270,7 @@ var ts; return undefined; } var isAsync = !!(arrowFunction.flags & 256); - var lastToken = token(); + var lastToken = token; arrowFunction.equalsGreaterThanToken = parseExpectedToken(34, false, ts.Diagnostics._0_expected, "=>"); arrowFunction.body = (lastToken === 34 || lastToken === 15) ? parseArrowFunctionExpressionBody(isAsync) @@ -10433,25 +9278,25 @@ var ts; return finishNode(arrowFunction); } function isParenthesizedArrowFunctionExpression() { - if (token() === 17 || token() === 25 || token() === 118) { + if (token === 17 || token === 25 || token === 118) { return lookAhead(isParenthesizedArrowFunctionExpressionWorker); } - if (token() === 34) { + if (token === 34) { return 1; } return 0; } function isParenthesizedArrowFunctionExpressionWorker() { - if (token() === 118) { + if (token === 118) { nextToken(); if (scanner.hasPrecedingLineBreak()) { return 0; } - if (token() !== 17 && token() !== 25) { + if (token !== 17 && token !== 25) { return 0; } } - var first = token(); + var first = token; var second = nextToken(); if (first === 17) { if (second === 18) { @@ -10514,7 +9359,7 @@ var ts; return parseParenthesizedArrowFunctionExpressionHead(false); } function tryParseAsyncSimpleArrowFunctionExpression() { - if (token() === 118) { + if (token === 118) { var isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker); if (isUnParenthesizedAsyncArrowFunction === 1) { var asyncModifier = parseModifiersForArrowFunction(); @@ -10525,13 +9370,13 @@ var ts; return undefined; } function isUnParenthesizedAsyncArrowFunctionWorker() { - if (token() === 118) { + if (token === 118) { nextToken(); - if (scanner.hasPrecedingLineBreak() || token() === 34) { + if (scanner.hasPrecedingLineBreak() || token === 34) { return 0; } var expr = parseBinaryExpressionOrHigher(0); - if (!scanner.hasPrecedingLineBreak() && expr.kind === 69 && token() === 34) { + if (!scanner.hasPrecedingLineBreak() && expr.kind === 69 && token === 34) { return 1; } } @@ -10545,18 +9390,18 @@ var ts; if (!node.parameters) { return undefined; } - if (!allowAmbiguity && token() !== 34 && token() !== 15) { + if (!allowAmbiguity && token !== 34 && token !== 15) { return undefined; } return node; } function parseArrowFunctionExpressionBody(isAsync) { - if (token() === 15) { + if (token === 15) { return parseFunctionBlock(false, isAsync, false); } - if (token() !== 23 && - token() !== 87 && - token() !== 73 && + if (token !== 23 && + token !== 87 && + token !== 73 && isStartOfStatement() && !isStartOfExpressionStatement()) { return parseFunctionBlock(false, isAsync, true); @@ -10589,16 +9434,16 @@ var ts; while (true) { reScanGreaterToken(); var newPrecedence = getBinaryOperatorPrecedence(); - var consumeCurrentOperator = token() === 38 ? + var consumeCurrentOperator = token === 38 ? newPrecedence >= precedence : newPrecedence > precedence; if (!consumeCurrentOperator) { break; } - if (token() === 90 && inDisallowInContext()) { + if (token === 90 && inDisallowInContext()) { break; } - if (token() === 116) { + if (token === 116) { if (scanner.hasPrecedingLineBreak()) { break; } @@ -10614,13 +9459,13 @@ var ts; return leftOperand; } function isBinaryOperator() { - if (inDisallowInContext() && token() === 90) { + if (inDisallowInContext() && token === 90) { return false; } return getBinaryOperatorPrecedence() > 0; } function getBinaryOperatorPrecedence() { - switch (token()) { + switch (token) { case 52: return 1; case 51: @@ -10675,7 +9520,7 @@ var ts; } function parsePrefixUnaryExpression() { var node = createNode(185); - node.operator = token(); + node.operator = token; nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); @@ -10699,7 +9544,7 @@ var ts; return finishNode(node); } function isAwaitExpression() { - if (token() === 119) { + if (token === 119) { if (inAwaitContext()) { return true; } @@ -10714,15 +9559,18 @@ var ts; return finishNode(node); } function parseUnaryExpressionOrHigher() { - if (isUpdateExpression()) { + if (isAwaitExpression()) { + return parseAwaitExpression(); + } + if (isIncrementExpression()) { var incrementExpression = parseIncrementExpression(); - return token() === 38 ? + return token === 38 ? parseBinaryExpressionRest(getBinaryOperatorPrecedence(), incrementExpression) : incrementExpression; } - var unaryOperator = token(); + var unaryOperator = token; var simpleUnaryExpression = parseSimpleUnaryExpression(); - if (token() === 38) { + if (token === 38) { var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); if (simpleUnaryExpression.kind === 177) { parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); @@ -10734,7 +9582,7 @@ var ts; return simpleUnaryExpression; } function parseSimpleUnaryExpression() { - switch (token()) { + switch (token) { case 35: case 36: case 50: @@ -10748,16 +9596,12 @@ var ts; return parseVoidExpression(); case 25: return parseTypeAssertion(); - case 119: - if (isAwaitExpression()) { - return parseAwaitExpression(); - } default: return parseIncrementExpression(); } } - function isUpdateExpression() { - switch (token()) { + function isIncrementExpression() { + switch (token) { case 35: case 36: case 50: @@ -10765,7 +9609,6 @@ var ts; case 78: case 101: case 103: - case 119: return false; case 25: if (sourceFile.languageVariant !== 1) { @@ -10776,29 +9619,29 @@ var ts; } } function parseIncrementExpression() { - if (token() === 41 || token() === 42) { + if (token === 41 || token === 42) { var node = createNode(185); - node.operator = token(); + node.operator = token; nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); return finishNode(node); } - else if (sourceFile.languageVariant === 1 && token() === 25 && lookAhead(nextTokenIsIdentifierOrKeyword)) { + else if (sourceFile.languageVariant === 1 && token === 25 && lookAhead(nextTokenIsIdentifierOrKeyword)) { return parseJsxElementOrSelfClosingElement(true); } var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); - if ((token() === 41 || token() === 42) && !scanner.hasPrecedingLineBreak()) { + if ((token === 41 || token === 42) && !scanner.hasPrecedingLineBreak()) { var node = createNode(186, expression.pos); node.operand = expression; - node.operator = token(); + node.operator = token; nextToken(); return finishNode(node); } return expression; } function parseLeftHandSideExpressionOrHigher() { - var expression = token() === 95 + var expression = token === 95 ? parseSuperExpression() : parseMemberExpressionOrHigher(); return parseCallExpressionRest(expression); @@ -10809,7 +9652,7 @@ var ts; } function parseSuperExpression() { var expression = parseTokenNode(); - if (token() === 17 || token() === 21 || token() === 19) { + if (token === 17 || token === 21 || token === 19) { return expression; } var node = createNode(172, expression.pos); @@ -10848,7 +9691,7 @@ var ts; ts.Debug.assert(opening.kind === 242); result = opening; } - if (inExpressionContext && token() === 25) { + if (inExpressionContext && token === 25) { var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); @@ -10865,11 +9708,11 @@ var ts; } function parseJsxText() { var node = createNode(244, scanner.getStartPos()); - currentToken = scanner.scanJsxToken(); + token = scanner.scanJsxToken(); return finishNode(node); } function parseJsxChild() { - switch (token()) { + switch (token) { case 244: return parseJsxText(); case 15: @@ -10877,7 +9720,7 @@ var ts; case 25: return parseJsxElementOrSelfClosingElement(false); } - ts.Debug.fail("Unknown JSX child kind " + token()); + ts.Debug.fail("Unknown JSX child kind " + token); } function parseJsxChildren(openingTagName) { var result = []; @@ -10885,11 +9728,11 @@ var ts; var saveParsingContext = parsingContext; parsingContext |= 1 << 14; while (true) { - currentToken = scanner.reScanJsxToken(); - if (token() === 26) { + token = scanner.reScanJsxToken(); + if (token === 26) { break; } - else if (token() === 1) { + else if (token === 1) { parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); break; } @@ -10905,7 +9748,7 @@ var ts; var tagName = parseJsxElementName(); var attributes = parseList(13, parseJsxAttribute); var node; - if (token() === 27) { + if (token === 27) { node = createNode(243, fullStart); scanJsxText(); } @@ -10926,7 +9769,7 @@ var ts; } function parseJsxElementName() { scanJsxIdentifier(); - var expression = token() === 97 ? + var expression = token === 97 ? parseTokenNode() : parseIdentifierName(); while (parseOptional(21)) { var propertyAccess = createNode(172, expression.pos); @@ -10939,7 +9782,7 @@ var ts; function parseJsxExpression(inExpressionContext) { var node = createNode(248); parseExpected(15); - if (token() !== 16) { + if (token !== 16) { node.expression = parseAssignmentExpressionOrHigher(); } if (inExpressionContext) { @@ -10952,14 +9795,14 @@ var ts; return finishNode(node); } function parseJsxAttribute() { - if (token() === 15) { + if (token === 15) { return parseJsxSpreadAttribute(); } scanJsxIdentifier(); var node = createNode(246); node.name = parseIdentifierName(); if (parseOptional(56)) { - switch (token()) { + switch (token) { case 9: node.initializer = parseLiteralNode(); break; @@ -11009,7 +9852,7 @@ var ts; expression = finishNode(propertyAccess); continue; } - if (token() === 49 && !scanner.hasPrecedingLineBreak()) { + if (token === 49 && !scanner.hasPrecedingLineBreak()) { nextToken(); var nonNullExpression = createNode(196, expression.pos); nonNullExpression.expression = expression; @@ -11019,7 +9862,7 @@ var ts; if (!inDecoratorContext() && parseOptional(19)) { var indexedAccess = createNode(173, expression.pos); indexedAccess.expression = expression; - if (token() !== 20) { + if (token !== 20) { indexedAccess.argumentExpression = allowInAnd(parseExpression); if (indexedAccess.argumentExpression.kind === 9 || indexedAccess.argumentExpression.kind === 8) { var literal = indexedAccess.argumentExpression; @@ -11030,10 +9873,10 @@ var ts; expression = finishNode(indexedAccess); continue; } - if (token() === 11 || token() === 12) { + if (token === 11 || token === 12) { var tagExpression = createNode(176, expression.pos); tagExpression.tag = expression; - tagExpression.template = token() === 11 + tagExpression.template = token === 11 ? parseLiteralNode() : parseTemplateExpression(); expression = finishNode(tagExpression); @@ -11045,7 +9888,7 @@ var ts; function parseCallExpressionRest(expression) { while (true) { expression = parseMemberExpressionRest(expression); - if (token() === 25) { + if (token === 25) { var typeArguments = tryParse(parseTypeArgumentsInExpression); if (!typeArguments) { return expression; @@ -11057,7 +9900,7 @@ var ts; expression = finishNode(callExpr); continue; } - else if (token() === 17) { + else if (token === 17) { var callExpr = createNode(174, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); @@ -11086,7 +9929,7 @@ var ts; : undefined; } function canFollowTypeArgumentsInExpression() { - switch (token()) { + switch (token) { case 17: case 21: case 18: @@ -11113,7 +9956,7 @@ var ts; } } function parsePrimaryExpression() { - switch (token()) { + switch (token) { case 8: case 9: case 11: @@ -11166,8 +10009,8 @@ var ts; return finishNode(node); } function parseArgumentOrArrayLiteralElement() { - return token() === 22 ? parseSpreadElement() : - token() === 24 ? createNode(193) : + return token === 22 ? parseSpreadElement() : + token === 24 ? createNode(193) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { @@ -11204,10 +10047,10 @@ var ts; var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); var questionToken = parseOptionalToken(53); - if (asteriskToken || token() === 17 || token() === 25) { + if (asteriskToken || token === 17 || token === 25) { return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); } - var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 24 || token() === 16 || token() === 56); + var isShorthandPropertyAssignment = tokenIsIdentifier && (token === 24 || token === 16 || token === 56); if (isShorthandPropertyAssignment) { var shorthandDeclaration = createNode(254, fullStart); shorthandDeclaration.name = propertyName; @@ -11270,7 +10113,7 @@ var ts; parseExpected(92); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); - if (node.typeArguments || token() === 17) { + if (node.typeArguments || token === 17) { node.arguments = parseArgumentList(); } return finishNode(node); @@ -11343,8 +10186,8 @@ var ts; parseExpected(86); parseExpected(17); var initializer = undefined; - if (token() !== 23) { - if (token() === 102 || token() === 108 || token() === 74) { + if (token !== 23) { + if (token === 102 || token === 108 || token === 74) { initializer = parseVariableDeclarationList(true); } else { @@ -11370,11 +10213,11 @@ var ts; var forStatement = createNode(206, pos); forStatement.initializer = initializer; parseExpected(23); - if (token() !== 23 && token() !== 18) { + if (token !== 23 && token !== 18) { forStatement.condition = allowInAnd(parseExpression); } parseExpected(23); - if (token() !== 18) { + if (token !== 18) { forStatement.incrementor = allowInAnd(parseExpression); } parseExpected(18); @@ -11426,7 +10269,7 @@ var ts; return finishNode(node); } function parseCaseOrDefaultClause() { - return token() === 71 ? parseCaseClause() : parseDefaultClause(); + return token === 71 ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { var node = createNode(213); @@ -11452,8 +10295,8 @@ var ts; var node = createNode(216); parseExpected(100); node.tryBlock = parseBlock(false); - node.catchClause = token() === 72 ? parseCatchClause() : undefined; - if (!node.catchClause || token() === 85) { + node.catchClause = token === 72 ? parseCatchClause() : undefined; + if (!node.catchClause || token === 85) { parseExpected(85); node.finallyBlock = parseBlock(false); } @@ -11493,19 +10336,19 @@ var ts; } function nextTokenIsIdentifierOrKeywordOnSameLine() { nextToken(); - return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak(); + return ts.tokenIsIdentifierOrKeyword(token) && !scanner.hasPrecedingLineBreak(); } function nextTokenIsFunctionKeywordOnSameLine() { nextToken(); - return token() === 87 && !scanner.hasPrecedingLineBreak(); + return token === 87 && !scanner.hasPrecedingLineBreak(); } function nextTokenIsIdentifierOrKeywordOrNumberOnSameLine() { nextToken(); - return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8) && !scanner.hasPrecedingLineBreak(); + return (ts.tokenIsIdentifierOrKeyword(token) || token === 8) && !scanner.hasPrecedingLineBreak(); } function isDeclaration() { while (true) { - switch (token()) { + switch (token) { case 102: case 108: case 74: @@ -11533,16 +10376,16 @@ var ts; continue; case 137: nextToken(); - return token() === 15 || token() === 69 || token() === 82; + return token === 15 || token === 69 || token === 82; case 89: nextToken(); - return token() === 9 || token() === 37 || - token() === 15 || ts.tokenIsIdentifierOrKeyword(token()); + return token === 9 || token === 37 || + token === 15 || ts.tokenIsIdentifierOrKeyword(token); case 82: nextToken(); - if (token() === 56 || token() === 37 || - token() === 15 || token() === 77 || - token() === 116) { + if (token === 56 || token === 37 || + token === 15 || token === 77 || + token === 116) { return true; } continue; @@ -11558,7 +10401,7 @@ var ts; return lookAhead(isDeclaration); } function isStartOfStatement() { - switch (token()) { + switch (token) { case 55: case 23: case 15: @@ -11606,13 +10449,13 @@ var ts; } function nextTokenIsIdentifierOrStartOfDestructuring() { nextToken(); - return isIdentifier() || token() === 15 || token() === 19; + return isIdentifier() || token === 15 || token === 19; } function isLetDeclaration() { return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); } function parseStatement() { - switch (token()) { + switch (token) { case 23: return parseEmptyStatement(); case 15: @@ -11684,7 +10527,7 @@ var ts; var fullStart = getNodePos(); var decorators = parseDecorators(); var modifiers = parseModifiers(); - switch (token()) { + switch (token) { case 102: case 108: case 74: @@ -11707,7 +10550,7 @@ var ts; return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); case 82: nextToken(); - switch (token()) { + switch (token) { case 77: case 56: return parseExportAssignment(fullStart, decorators, modifiers); @@ -11728,17 +10571,17 @@ var ts; } function nextTokenIsIdentifierOrStringLiteralOnSameLine() { nextToken(); - return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9); + return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token === 9); } function parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage) { - if (token() !== 15 && canParseSemicolon()) { + if (token !== 15 && canParseSemicolon()) { parseSemicolon(); return; } return parseFunctionBlock(isGenerator, isAsync, false, diagnosticMessage); } function parseArrayBindingElement() { - if (token() === 24) { + if (token === 24) { return createNode(193); } var node = createNode(169); @@ -11751,7 +10594,7 @@ var ts; var node = createNode(169); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); - if (tokenIsIdentifier && token() !== 54) { + if (tokenIsIdentifier && token !== 54) { node.name = propertyName; } else { @@ -11777,13 +10620,13 @@ var ts; return finishNode(node); } function isIdentifierOrPattern() { - return token() === 15 || token() === 19 || isIdentifier(); + return token === 15 || token === 19 || isIdentifier(); } function parseIdentifierOrPattern() { - if (token() === 19) { + if (token === 19) { return parseArrayBindingPattern(); } - if (token() === 15) { + if (token === 15) { return parseObjectBindingPattern(); } return parseIdentifier(); @@ -11792,14 +10635,14 @@ var ts; var node = createNode(218); node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); - if (!isInOrOfKeyword(token())) { + if (!isInOrOfKeyword(token)) { node.initializer = parseInitializer(false); } return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { var node = createNode(219); - switch (token()) { + switch (token) { case 102: break; case 108: @@ -11812,7 +10655,7 @@ var ts; ts.Debug.fail(); } nextToken(); - if (token() === 138 && lookAhead(canFollowContextualOfKeyword)) { + if (token === 138 && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { @@ -11886,7 +10729,7 @@ var ts; var asteriskToken = parseOptionalToken(37); var name = parsePropertyName(); var questionToken = parseOptionalToken(53); - if (asteriskToken || token() === 17 || token() === 25) { + if (asteriskToken || token === 17 || token === 25) { return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, ts.Diagnostics.or_expected); } else { @@ -11919,31 +10762,31 @@ var ts; } function isClassMemberStart() { var idToken; - if (token() === 55) { + if (token === 55) { return true; } - while (ts.isModifierKind(token())) { - idToken = token(); + while (ts.isModifierKind(token)) { + idToken = token; if (isClassMemberModifier(idToken)) { return true; } nextToken(); } - if (token() === 37) { + if (token === 37) { return true; } if (isLiteralPropertyName()) { - idToken = token(); + idToken = token; nextToken(); } - if (token() === 19) { + if (token === 19) { return true; } if (idToken !== undefined) { if (!ts.isKeyword(idToken) || idToken === 131 || idToken === 123) { return true; } - switch (token()) { + switch (token) { case 17: case 25: case 54: @@ -11981,8 +10824,8 @@ var ts; var modifiers; while (true) { var modifierStart = scanner.getStartPos(); - var modifierKind = token(); - if (token() === 74 && permitInvalidConstAsModifier) { + var modifierKind = token; + if (token === 74 && permitInvalidConstAsModifier) { if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { break; } @@ -12008,9 +10851,9 @@ var ts; function parseModifiersForArrowFunction() { var flags = 0; var modifiers; - if (token() === 118) { + if (token === 118) { var modifierStart = scanner.getStartPos(); - var modifierKind = token(); + var modifierKind = token; nextToken(); modifiers = []; modifiers.pos = modifierStart; @@ -12022,7 +10865,7 @@ var ts; return modifiers; } function parseClassElement() { - if (token() === 23) { + if (token === 23) { var result = createNode(198); nextToken(); return finishNode(result); @@ -12034,22 +10877,22 @@ var ts; if (accessor) { return accessor; } - if (token() === 121) { + if (token === 121) { return parseConstructorDeclaration(fullStart, decorators, modifiers); } if (isIndexSignature()) { return parseIndexSignatureDeclaration(fullStart, decorators, modifiers); } - if (ts.tokenIsIdentifierOrKeyword(token()) || - token() === 9 || - token() === 8 || - token() === 37 || - token() === 19) { + if (ts.tokenIsIdentifierOrKeyword(token) || + token === 9 || + token === 8 || + token === 37 || + token === 19) { return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); } if (decorators || modifiers) { - var name_10 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name_10, undefined); + var name_8 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(fullStart, decorators, modifiers, name_8, undefined); } ts.Debug.fail("Should not have attempted to parse class member declaration."); } @@ -12082,7 +10925,7 @@ var ts; : undefined; } function isImplementsClause() { - return token() === 106 && lookAhead(nextTokenIsIdentifierOrKeyword); + return token === 106 && lookAhead(nextTokenIsIdentifierOrKeyword); } function parseHeritageClauses(isClassHeritageClause) { if (isHeritageClause()) { @@ -12091,9 +10934,9 @@ var ts; return undefined; } function parseHeritageClause() { - if (token() === 83 || token() === 106) { + if (token === 83 || token === 106) { var node = createNode(251); - node.token = token(); + node.token = token; nextToken(); node.types = parseDelimitedList(7, parseExpressionWithTypeArguments); return finishNode(node); @@ -12103,13 +10946,13 @@ var ts; function parseExpressionWithTypeArguments() { var node = createNode(194); node.expression = parseLeftHandSideExpressionOrHigher(); - if (token() === 25) { + if (token === 25) { node.typeArguments = parseBracketedList(18, parseType, 25, 27); } return finishNode(node); } function isHeritageClause() { - return token() === 83 || token() === 106; + return token === 83 || token === 106; } function parseClassMembers() { return parseList(5, parseClassElement); @@ -12185,14 +11028,14 @@ var ts; var node = createNode(225, fullStart); node.decorators = decorators; setModifiers(node, modifiers); - if (token() === 137) { + if (token === 137) { node.name = parseIdentifier(); node.flags |= 131072; } else { node.name = parseLiteralNode(true); } - if (token() === 15) { + if (token === 15) { node.body = parseModuleBlock(); } else { @@ -12202,7 +11045,7 @@ var ts; } function parseModuleDeclaration(fullStart, decorators, modifiers) { var flags = modifiers ? modifiers.flags : 0; - if (token() === 137) { + if (token === 137) { return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } else if (parseOptional(126)) { @@ -12210,14 +11053,14 @@ var ts; } else { parseExpected(125); - if (token() === 9) { + if (token === 9) { return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } } return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); } function isExternalModuleReference() { - return token() === 129 && + return token === 129 && lookAhead(nextTokenIsOpenParen); } function nextTokenIsOpenParen() { @@ -12242,7 +11085,7 @@ var ts; var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token() !== 24 && token() !== 136) { + if (token !== 24 && token !== 136) { var importEqualsDeclaration = createNode(229, fullStart); importEqualsDeclaration.decorators = decorators; setModifiers(importEqualsDeclaration, modifiers); @@ -12257,8 +11100,8 @@ var ts; importDeclaration.decorators = decorators; setModifiers(importDeclaration, modifiers); if (identifier || - token() === 37 || - token() === 15) { + token === 37 || + token === 15) { importDeclaration.importClause = parseImportClause(identifier, afterImportPos); parseExpected(136); } @@ -12273,7 +11116,7 @@ var ts; } if (!importClause.name || parseOptional(24)) { - importClause.namedBindings = token() === 37 ? parseNamespaceImport() : parseNamedImportsOrExports(233); + importClause.namedBindings = token === 37 ? parseNamespaceImport() : parseNamedImportsOrExports(233); } return finishNode(importClause); } @@ -12291,7 +11134,7 @@ var ts; return finishNode(node); } function parseModuleSpecifier() { - if (token() === 9) { + if (token === 9) { var result = parseLiteralNode(); internIdentifier(result.text); return result; @@ -12320,14 +11163,14 @@ var ts; } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); - var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); + var checkIdentifierIsKeyword = ts.isKeyword(token) && !isIdentifier(); var checkIdentifierStart = scanner.getTokenPos(); var checkIdentifierEnd = scanner.getTextPos(); var identifierName = parseIdentifierName(); - if (token() === 116) { + if (token === 116) { node.propertyName = identifierName; parseExpected(116); - checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); + checkIdentifierIsKeyword = ts.isKeyword(token) && !isIdentifier(); checkIdentifierStart = scanner.getTokenPos(); checkIdentifierEnd = scanner.getTextPos(); node.name = parseIdentifierName(); @@ -12350,7 +11193,7 @@ var ts; } else { node.exportClause = parseNamedImportsOrExports(237); - if (token() === 136 || (token() === 9 && !scanner.hasPrecedingLineBreak())) { + if (token === 136 || (token === 9 && !scanner.hasPrecedingLineBreak())) { parseExpected(136); node.moduleSpecifier = parseModuleSpecifier(); } @@ -12449,7 +11292,7 @@ var ts; var JSDocParser; (function (JSDocParser) { function isJSDocType() { - switch (token()) { + switch (token) { case 37: case 53: case 17: @@ -12462,13 +11305,13 @@ var ts; case 97: return true; } - return ts.tokenIsIdentifierOrKeyword(token()); + return ts.tokenIsIdentifierOrKeyword(token); } JSDocParser.isJSDocType = isJSDocType; function parseJSDocTypeExpressionForTests(content, start, length) { initializeState("file.js", content, 2, undefined, 1); scanner.setText(content, start, length); - currentToken = scanner.scan(); + token = scanner.scan(); var jsDocTypeExpression = parseJSDocTypeExpression(); var diagnostics = parseDiagnostics; clearState(); @@ -12486,12 +11329,12 @@ var ts; JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression; function parseJSDocTopLevelType() { var type = parseJSDocType(); - if (token() === 47) { + if (token === 47) { var unionType = createNode(261, type.pos); unionType.types = parseJSDocTypeList(type); type = finishNode(unionType); } - if (token() === 56) { + if (token === 56) { var optionalType = createNode(268, type.pos); nextToken(); optionalType.type = type; @@ -12502,20 +11345,20 @@ var ts; function parseJSDocType() { var type = parseBasicTypeExpression(); while (true) { - if (token() === 19) { + if (token === 19) { var arrayType = createNode(260, type.pos); arrayType.elementType = type; nextToken(); parseExpected(20); type = finishNode(arrayType); } - else if (token() === 53) { + else if (token === 53) { var nullableType = createNode(263, type.pos); nullableType.type = type; nextToken(); type = finishNode(nullableType); } - else if (token() === 49) { + else if (token === 49) { var nonNullableType = createNode(264, type.pos); nonNullableType.type = type; nextToken(); @@ -12528,7 +11371,7 @@ var ts; return type; } function parseBasicTypeExpression() { - switch (token()) { + switch (token) { case 37: return parseJSDocAllType(); case 53: @@ -12555,15 +11398,7 @@ var ts; case 120: case 133: case 103: - case 93: - case 135: - case 127: return parseTokenNode(); - case 9: - case 8: - case 99: - case 84: - return parseJSDocLiteralType(); } return parseJSDocTypeReference(); } @@ -12594,7 +11429,7 @@ var ts; result.parameters = parseDelimitedList(22, parseJSDocParameter); checkForTrailingComma(result.parameters); parseExpected(18); - if (token() === 54) { + if (token === 54) { nextToken(); result.type = parseJSDocType(); } @@ -12611,12 +11446,12 @@ var ts; function parseJSDocTypeReference() { var result = createNode(267); result.name = parseSimplePropertyName(); - if (token() === 25) { + if (token === 25) { result.typeArguments = parseTypeArguments(); } else { while (parseOptional(21)) { - if (token() === 25) { + if (token === 25) { result.typeArguments = parseTypeArguments(); break; } @@ -12659,7 +11494,7 @@ var ts; function parseJSDocRecordMember() { var result = createNode(266); result.name = parseSimplePropertyName(); - if (token() === 54) { + if (token === 54) { nextToken(); result.type = parseJSDocType(); } @@ -12708,20 +11543,15 @@ var ts; nextToken(); return finishNode(result); } - function parseJSDocLiteralType() { - var result = createNode(282); - result.literal = parseLiteralTypeNode(); - return finishNode(result); - } function parseJSDocUnknownOrNullableType() { var pos = scanner.getStartPos(); nextToken(); - if (token() === 24 || - token() === 16 || - token() === 18 || - token() === 27 || - token() === 56 || - token() === 47) { + if (token === 24 || + token === 16 || + token === 18 || + token === 27 || + token === 56 || + token === 47) { var result = createNode(259, pos); return finishNode(result); } @@ -12741,14 +11571,14 @@ var ts; } JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; function parseJSDocComment(parent, start, length) { - var saveToken = currentToken; + var saveToken = token; var saveParseDiagnosticsLength = parseDiagnostics.length; var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; var comment = parseJSDocCommentWorker(start, length); if (comment) { comment.parent = parent; } - currentToken = saveToken; + token = saveToken; parseDiagnostics.length = saveParseDiagnosticsLength; parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; return comment; @@ -12772,8 +11602,8 @@ var ts; var canParseTag = true; var seenAsterisk = true; nextJSDocToken(); - while (token() !== 1) { - switch (token()) { + while (token !== 1) { + switch (token) { case 55: if (canParseTag) { parseTag(); @@ -12811,12 +11641,12 @@ var ts; return finishNode(result, end); } function skipWhitespace() { - while (token() === 5 || token() === 4) { + while (token === 5 || token === 4) { nextJSDocToken(); } } function parseTag() { - ts.Debug.assert(token() === 55); + ts.Debug.assert(token === 55); var atToken = createNode(55, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); @@ -12862,7 +11692,7 @@ var ts; } } function tryParseTypeExpression() { - if (token() !== 15) { + if (token !== 15) { return undefined; } var typeExpression = parseJSDocTypeExpression(); @@ -12881,7 +11711,7 @@ var ts; } parseExpected(20); } - else if (ts.tokenIsIdentifierOrKeyword(token())) { + else if (ts.tokenIsIdentifierOrKeyword(token)) { name = parseJSDocIdentifierName(); } if (!name) { @@ -12954,8 +11784,8 @@ var ts; if (typeExpression.type.kind === 267) { var jsDocTypeReference = typeExpression.type; if (jsDocTypeReference.name.kind === 69) { - var name_11 = jsDocTypeReference.name; - if (name_11.text === "Object") { + var name_9 = jsDocTypeReference.name; + if (name_9.text === "Object") { typedefTag.jsDocTypeLiteral = scanChildTags(); } } @@ -12974,15 +11804,12 @@ var ts; var canParseTag = true; var seenAsterisk = false; var parentTagTerminated = false; - while (token() !== 1 && !parentTagTerminated) { + while (token !== 1 && !parentTagTerminated) { nextJSDocToken(); - switch (token()) { + switch (token) { case 55: if (canParseTag) { parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral); - if (!parentTagTerminated) { - resumePos = scanner.getStartPos(); - } } seenAsterisk = false; break; @@ -13008,7 +11835,7 @@ var ts; } } function tryParseChildTag(parentTag) { - ts.Debug.assert(token() === 55); + ts.Debug.assert(token === 55); var atToken = createNode(55, scanner.getStartPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); @@ -13041,16 +11868,16 @@ var ts; var typeParameters = []; typeParameters.pos = scanner.getStartPos(); while (true) { - var name_12 = parseJSDocIdentifierName(); - if (!name_12) { + var name_10 = parseJSDocIdentifierName(); + if (!name_10) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(141, name_12.pos); - typeParameter.name = name_12; + var typeParameter = createNode(141, name_10.pos); + typeParameter.name = name_10; finishNode(typeParameter); typeParameters.push(typeParameter); - if (token() === 24) { + if (token === 24) { nextJSDocToken(); } else { @@ -13066,10 +11893,10 @@ var ts; return result; } function nextJSDocToken() { - return currentToken = scanner.scanJSDocToken(); + return token = scanner.scanJSDocToken(); } function parseJSDocIdentifierName() { - return createJSDocIdentifier(ts.tokenIsIdentifierOrKeyword(token())); + return createJSDocIdentifier(ts.tokenIsIdentifierOrKeyword(token)); } function createJSDocIdentifier(isIdentifier) { if (!isIdentifier) { @@ -13149,8 +11976,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { - var node = array_9[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } } @@ -13222,8 +12049,8 @@ var ts; array.intersectsChange = true; array._children = undefined; adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_10 = array; _i < array_10.length; _i++) { - var node = array_10[_i]; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; visitNode(node); } return; @@ -13375,6 +12202,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + ts.bindTime = 0; function getModuleInstanceState(node) { if (node.kind === 222 || node.kind === 223) { return 0; @@ -13412,10 +12240,9 @@ var ts; ts.getModuleInstanceState = getModuleInstanceState; var binder = createBinder(); function bindSourceFile(file, options) { - ts.performance.mark("beforeBind"); + var start = new Date().getTime(); binder(file, options); - ts.performance.mark("afterBind"); - ts.performance.measure("Bind", "beforeBind", "afterBind"); + ts.bindTime += new Date().getTime() - start; } ts.bindSourceFile = bindSourceFile; function createBinder() { @@ -13448,7 +12275,7 @@ var ts; options = opts; languageVersion = ts.getEmitScriptTarget(options); inStrictMode = !!file.externalModuleIndicator; - classifiableNames = ts.createMap(); + classifiableNames = {}; symbolCount = 0; Symbol = ts.objectAllocator.getSymbolConstructor(); if (!file.locals) { @@ -13487,10 +12314,10 @@ var ts; } symbol.declarations.push(node); if (symbolFlags & 1952 && !symbol.exports) { - symbol.exports = ts.createMap(); + symbol.exports = {}; } if (symbolFlags & 6240 && !symbol.members) { - symbol.members = ts.createMap(); + symbol.members = {}; } if (symbolFlags & 107455) { var valueDeclaration = symbol.valueDeclaration; @@ -13574,38 +12401,35 @@ var ts; var isDefaultExport = node.flags & 512; var name = isDefaultExport && parent ? "default" : getDeclarationName(node); var symbol; - if (name === undefined) { - symbol = createSymbol(0, "__missing"); - } - else { - symbol = symbolTable[name] || (symbolTable[name] = createSymbol(0, name)); + if (name !== undefined) { + symbol = ts.hasProperty(symbolTable, name) + ? symbolTable[name] + : (symbolTable[name] = createSymbol(0, name)); if (name && (includes & 788448)) { classifiableNames[name] = name; } if (symbol.flags & excludes) { - if (symbol.isReplaceableByMethod) { - symbol = symbolTable[name] = createSymbol(0, name); + if (node.name) { + node.name.parent = node; } - else { - if (node.name) { - node.name.parent = node; + var message_1 = symbol.flags & 2 + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + : ts.Diagnostics.Duplicate_identifier_0; + ts.forEach(symbol.declarations, function (declaration) { + if (declaration.flags & 512) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; } - var message_1 = symbol.flags & 2 - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - ts.forEach(symbol.declarations, function (declaration) { - if (declaration.flags & 512) { - message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; - } - }); - ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); - }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); - symbol = createSymbol(0, name); - } + }); + ts.forEach(symbol.declarations, function (declaration) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); + }); + file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); + symbol = createSymbol(0, name); } } + else { + symbol = createSymbol(0, "__missing"); + } addDeclarationToSymbol(symbol, node, includes); symbol.parent = parent; return symbol; @@ -13623,8 +12447,8 @@ var ts; else { if (!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 8192)) { var exportKind = (symbolFlags & 107455 ? 1048576 : 0) | - (symbolFlags & 793064 ? 2097152 : 0) | - (symbolFlags & 1920 ? 4194304 : 0); + (symbolFlags & 793056 ? 2097152 : 0) | + (symbolFlags & 1536 ? 4194304 : 0); var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; @@ -13641,7 +12465,7 @@ var ts; if (containerFlags & 1) { container = blockScopeContainer = node; if (containerFlags & 32) { - container.locals = ts.createMap(); + container.locals = {}; } addToContainerChain(container); } @@ -13816,9 +12640,15 @@ var ts; } return false; } + function isNarrowingNullCheckOperands(expr1, expr2) { + return (expr1.kind === 93 || expr1.kind === 69 && expr1.text === "undefined") && isNarrowableOperand(expr2); + } function isNarrowingTypeofOperands(expr1, expr2) { return expr1.kind === 182 && isNarrowableOperand(expr1.expression) && expr2.kind === 9; } + function isNarrowingDiscriminant(expr) { + return expr.kind === 172 && isNarrowableReference(expr.expression); + } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { case 56: @@ -13827,8 +12657,9 @@ var ts; case 31: case 32: case 33: - return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || - isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); + return isNarrowingNullCheckOperands(expr.right, expr.left) || isNarrowingNullCheckOperands(expr.left, expr.right) || + isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right) || + isNarrowingDiscriminant(expr.left) || isNarrowingDiscriminant(expr.right); case 91: return isNarrowableOperand(expr.left); case 24: @@ -13850,6 +12681,10 @@ var ts; } return isNarrowableReference(expr); } + function isNarrowingSwitchStatement(switchStatement) { + var expr = switchStatement.expression; + return expr.kind === 172 && isNarrowableReference(expr.expression); + } function createBranchLabel() { return { flags: 4, @@ -13893,7 +12728,7 @@ var ts; }; } function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { - if (!isNarrowingExpression(switchStatement.expression)) { + if (!isNarrowingSwitchStatement(switchStatement)) { return antecedent; } setFlowNodeReferenced(antecedent); @@ -14481,12 +13316,12 @@ var ts; addDeclarationToSymbol(symbol, node, 131072); var typeLiteralSymbol = createSymbol(2048, "__type"); addDeclarationToSymbol(typeLiteralSymbol, node, 2048); - typeLiteralSymbol.members = ts.createMap(); - typeLiteralSymbol.members[symbol.name] = symbol; + typeLiteralSymbol.members = (_a = {}, _a[symbol.name] = symbol, _a); + var _a; } function bindObjectLiteralExpression(node) { if (inStrictMode) { - var seen = ts.createMap(); + var seen = {}; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; if (prop.name.kind !== 69) { @@ -14525,7 +13360,7 @@ var ts; } default: if (!blockScopeContainer.locals) { - blockScopeContainer.locals = ts.createMap(); + blockScopeContainer.locals = {}; addToContainerChain(blockScopeContainer); } declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); @@ -14738,7 +13573,7 @@ var ts; case 154: return checkTypePredicate(node); case 141: - return declareSymbolAndAddToSymbolTable(node, 262144, 530920); + return declareSymbolAndAddToSymbolTable(node, 262144, 530912); case 142: return bindParameter(node); case 218: @@ -14754,7 +13589,7 @@ var ts; case 254: return bindPropertyOrMethodOrAccessor(node, 4, 0); case 255: - return bindPropertyOrMethodOrAccessor(node, 8, 900095); + return bindPropertyOrMethodOrAccessor(node, 8, 107455); case 247: emitFlags |= 1073741824; return; @@ -14796,10 +13631,10 @@ var ts; inStrictMode = true; return bindClassLikeDeclaration(node); case 222: - return bindBlockScopedDeclaration(node, 64, 792968); + return bindBlockScopedDeclaration(node, 64, 792960); case 279: case 223: - return bindBlockScopedDeclaration(node, 524288, 793064); + return bindBlockScopedDeclaration(node, 524288, 793056); case 224: return bindEnumDeclaration(node); case 225: @@ -14848,14 +13683,15 @@ var ts; bindAnonymousDeclaration(file, 512, "\"" + ts.removeFileExtension(file.fileName) + "\""); } function bindExportAssignment(node) { + var boundExpression = node.kind === 235 ? node.expression : node.right; if (!container.symbol || !container.symbol.exports) { bindAnonymousDeclaration(node, 8388608, getDeclarationName(node)); } + else if (boundExpression.kind === 69 && node.kind === 235) { + declareSymbol(container.symbol.exports, container.symbol, node, 8388608, 0 | 8388608); + } else { - var flags = node.kind === 235 && ts.exportAssignmentIsAlias(node) - ? 8388608 - : 4; - declareSymbol(container.symbol.exports, container.symbol, node, flags, 0 | 8388608); + declareSymbol(container.symbol.exports, container.symbol, node, 4, 0 | 8388608); } } function bindNamespaceExportDeclaration(node) { @@ -14877,7 +13713,7 @@ var ts; return; } } - file.symbol.globalExports = file.symbol.globalExports || ts.createMap(); + file.symbol.globalExports = file.symbol.globalExports || {}; declareSymbol(file.symbol.globalExports, file.symbol, node, 8388608, 8388608); } function bindExportDeclaration(node) { @@ -14908,20 +13744,18 @@ var ts; declareSymbol(file.symbol.exports, file.symbol, node, 4 | 7340032 | 512, 0); } function bindThisPropertyAssignment(node) { - ts.Debug.assert(ts.isInJavaScriptFile(node)); - if (container.kind === 220 || container.kind === 179) { - container.symbol.members = container.symbol.members || ts.createMap(); - declareSymbol(container.symbol.members, container.symbol, node, 4, 0 & ~4); + var assignee; + if (container.kind === 220 || container.kind === 220) { + assignee = container; } else if (container.kind === 148) { - var saveContainer = container; - container = container.parent; - var symbol = bindPropertyOrMethodOrAccessor(node, 4, 0); - if (symbol) { - symbol.isReplaceableByMethod = true; - } - container = saveContainer; + assignee = container.parent; } + else { + return; + } + assignee.symbol.members = assignee.symbol.members || {}; + declareSymbol(assignee.symbol.members, assignee.symbol, node, 4, 0 & ~4); } function bindPrototypePropertyAssignment(node) { var leftSideOfAssignment = node.left; @@ -14935,7 +13769,7 @@ var ts; return; } if (!funcSymbol.members) { - funcSymbol.members = ts.createMap(); + funcSymbol.members = {}; } declareSymbol(funcSymbol.members, funcSymbol, leftSideOfAssignment, 4, 0); } @@ -14965,7 +13799,7 @@ var ts; } var symbol = node.symbol; var prototypeSymbol = createSymbol(4 | 134217728, "prototype"); - if (symbol.exports[prototypeSymbol.name]) { + if (ts.hasProperty(symbol.exports, prototypeSymbol.name)) { if (node.name) { node.name.parent = node; } @@ -15090,7 +13924,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var ambientModuleSymbolRegex = /^".+"$/; var nextSymbolId = 1; var nextNodeId = 1; var nextMergeId = 1; @@ -15103,6 +13936,7 @@ var ts; return node.id; } ts.getNodeId = getNodeId; + ts.checkTime = 0; function getSymbolId(symbol) { if (!symbol.id) { symbol.id = nextSymbolId; @@ -15119,7 +13953,7 @@ var ts; var typeCount = 0; var symbolCount = 0; var emptyArray = []; - var emptySymbols = ts.createMap(); + var emptySymbols = {}; var compilerOptions = host.getCompilerOptions(); var languageVersion = compilerOptions.target || 0; var modulekind = ts.getEmitModuleKind(compilerOptions); @@ -15171,43 +14005,34 @@ var ts; getAliasedSymbol: resolveAlias, getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, - getAmbientModules: getAmbientModules, getJsxElementAttributesType: getJsxElementAttributesType, getJsxIntrinsicTagNames: getJsxIntrinsicTagNames, isOptionalParameter: isOptionalParameter }; - var tupleTypes = []; - var unionTypes = ts.createMap(); - var intersectionTypes = ts.createMap(); - var stringLiteralTypes = ts.createMap(); - var numericLiteralTypes = ts.createMap(); var unknownSymbol = createSymbol(4 | 67108864, "unknown"); var resolvingSymbol = createSymbol(67108864, "__resolving__"); var anyType = createIntrinsicType(1, "any"); - var unknownType = createIntrinsicType(1, "unknown"); - var undefinedType = createIntrinsicType(2048, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 | 33554432, "undefined"); - var nullType = createIntrinsicType(4096, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(4096 | 33554432, "null"); var stringType = createIntrinsicType(2, "string"); var numberType = createIntrinsicType(4, "number"); - var trueType = createIntrinsicType(128, "true"); - var falseType = createIntrinsicType(128, "false"); - var booleanType = createBooleanType([trueType, falseType]); - var esSymbolType = createIntrinsicType(512, "symbol"); - var voidType = createIntrinsicType(1024, "void"); - var neverType = createIntrinsicType(8192, "never"); + var booleanType = createIntrinsicType(8, "boolean"); + var esSymbolType = createIntrinsicType(16777216, "symbol"); + var voidType = createIntrinsicType(16, "void"); + var undefinedType = createIntrinsicType(32, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32 | 2097152, "undefined"); + var nullType = createIntrinsicType(64, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(64 | 2097152, "null"); + var unknownType = createIntrinsicType(1, "unknown"); + var neverType = createIntrinsicType(134217728, "never"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - emptyGenericType.instantiations = ts.createMap(); + emptyGenericType.instantiations = {}; var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - anyFunctionType.flags |= 134217728; + anyFunctionType.flags |= 8388608; var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var anySignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, undefined, 0, false, false); var unknownSignature = createSignature(undefined, undefined, undefined, emptyArray, unknownType, undefined, 0, false, false); - var resolvingSignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, undefined, 0, false, false); var enumNumberIndexInfo = createIndexInfo(stringType, true); - var globals = ts.createMap(); + var globals = {}; var patternAmbientModules; var getGlobalESSymbolConstructorSymbol; var getGlobalPromiseConstructorSymbol; @@ -15243,8 +14068,10 @@ var ts; var flowLoopStart = 0; var flowLoopCount = 0; var visitedFlowCount = 0; - var emptyStringType = getLiteralTypeForText(32, ""); - var zeroType = getLiteralTypeForText(64, "0"); + var tupleTypes = {}; + var unionTypes = {}; + var intersectionTypes = {}; + var stringLiteralTypes = {}; var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; @@ -15260,7 +14087,7 @@ var ts; var potentialThisCollisions = []; var awaitedTypeStack = []; var diagnostics = ts.createDiagnosticCollection(); - var typeofEQFacts = ts.createMap({ + var typeofEQFacts = { "string": 1, "number": 2, "boolean": 4, @@ -15268,8 +14095,8 @@ var ts; "undefined": 16384, "object": 16, "function": 32 - }); - var typeofNEFacts = ts.createMap({ + }; + var typeofNEFacts = { "string": 128, "number": 256, "boolean": 512, @@ -15277,16 +14104,16 @@ var ts; "undefined": 131072, "object": 2048, "function": 4096 - }); - var typeofTypesByName = ts.createMap({ + }; + var typeofTypesByName = { "string": stringType, "number": numberType, "boolean": booleanType, "symbol": esSymbolType, "undefined": undefinedType - }); + }; var jsxElementType; - var jsxTypes = ts.createMap(); + var jsxTypes = {}; var JsxNames = { JSX: "JSX", IntrinsicElements: "IntrinsicElements", @@ -15296,14 +14123,15 @@ var ts; IntrinsicAttributes: "IntrinsicAttributes", IntrinsicClassAttributes: "IntrinsicClassAttributes" }; - var subtypeRelation = ts.createMap(); - var assignableRelation = ts.createMap(); - var comparableRelation = ts.createMap(); - var identityRelation = ts.createMap(); - var enumRelation = ts.createMap(); + var subtypeRelation = {}; + var assignableRelation = {}; + var comparableRelation = {}; + var identityRelation = {}; var _displayBuilder; - var builtinGlobals = ts.createMap(); - builtinGlobals[undefinedSymbol.name] = undefinedSymbol; + var builtinGlobals = (_a = {}, + _a[undefinedSymbol.name] = undefinedSymbol, + _a + ); initializeTypeChecker(); return checker; function getEmitResolver(sourceFile, cancellationToken) { @@ -15329,13 +14157,13 @@ var ts; if (flags & 4) result |= 0; if (flags & 8) - result |= 900095; + result |= 107455; if (flags & 16) result |= 106927; if (flags & 32) result |= 899519; if (flags & 64) - result |= 792968; + result |= 792960; if (flags & 256) result |= 899327; if (flags & 128) @@ -15349,9 +14177,9 @@ var ts; if (flags & 65536) result |= 74687; if (flags & 262144) - result |= 530920; + result |= 530912; if (flags & 524288) - result |= 793064; + result |= 793056; if (flags & 8388608) result |= 8388608; return result; @@ -15372,9 +14200,9 @@ var ts; if (symbol.constEnumOnlyModule) result.constEnumOnlyModule = true; if (symbol.members) - result.members = ts.cloneMap(symbol.members); + result.members = cloneSymbolTable(symbol.members); if (symbol.exports) - result.exports = ts.cloneMap(symbol.exports); + result.exports = cloneSymbolTable(symbol.exports); recordMergedSymbol(result, symbol); return result; } @@ -15394,12 +14222,12 @@ var ts; }); if (source.members) { if (!target.members) - target.members = ts.createMap(); + target.members = {}; mergeSymbolTable(target.members, source.members); } if (source.exports) { if (!target.exports) - target.exports = ts.createMap(); + target.exports = {}; mergeSymbolTable(target.exports, source.exports); } recordMergedSymbol(target, source); @@ -15415,17 +14243,28 @@ var ts; }); } } + function cloneSymbolTable(symbolTable) { + var result = {}; + for (var id in symbolTable) { + if (ts.hasProperty(symbolTable, id)) { + result[id] = symbolTable[id]; + } + } + return result; + } function mergeSymbolTable(target, source) { for (var id in source) { - var targetSymbol = target[id]; - if (!targetSymbol) { - target[id] = source[id]; - } - else { - if (!(targetSymbol.flags & 33554432)) { - target[id] = targetSymbol = cloneSymbol(targetSymbol); + if (ts.hasProperty(source, id)) { + if (!ts.hasProperty(target, id)) { + target[id] = source[id]; + } + else { + var symbol = target[id]; + if (!(symbol.flags & 33554432)) { + target[id] = symbol = cloneSymbol(symbol); + } + mergeSymbol(symbol, source[id]); } - mergeSymbol(targetSymbol, source[id]); } } } @@ -15447,7 +14286,7 @@ var ts; return; } mainModule = resolveExternalModuleSymbol(mainModule); - if (mainModule.flags & 1920) { + if (mainModule.flags & 1536) { mainModule = mainModule.flags & 33554432 ? mainModule : cloneSymbol(mainModule); mergeSymbol(mainModule, moduleAugmentation.symbol); } @@ -15458,11 +14297,13 @@ var ts; } function addToSymbolTable(target, source, message) { for (var id in source) { - if (target[id]) { - ts.forEach(target[id].declarations, addDeclarationDiagnostic(id, message)); - } - else { - target[id] = source[id]; + if (ts.hasProperty(source, id)) { + if (ts.hasProperty(target, id)) { + ts.forEach(target[id].declarations, addDeclarationDiagnostic(id, message)); + } + else { + target[id] = source[id]; + } } } function addDeclarationDiagnostic(id, message) { @@ -15477,25 +14318,23 @@ var ts; } function getNodeLinks(node) { var nodeId = getNodeId(node); - return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); + return nodeLinks[nodeId] || (nodeLinks[nodeId] = {}); } function isGlobalSourceFile(node) { return node.kind === 256 && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { - if (meaning) { + if (meaning && ts.hasProperty(symbols, name)) { var symbol = symbols[name]; - if (symbol) { - ts.Debug.assert((symbol.flags & 16777216) === 0, "Should never get an instantiated symbol here."); - if (symbol.flags & meaning) { + ts.Debug.assert((symbol.flags & 16777216) === 0, "Should never get an instantiated symbol here."); + if (symbol.flags & meaning) { + return symbol; + } + if (symbol.flags & 8388608) { + var target = resolveAlias(symbol); + if (target === unknownSymbol || target.flags & meaning) { return symbol; } - if (symbol.flags & 8388608) { - var target = resolveAlias(symbol); - if (target === unknownSymbol || target.flags & meaning) { - return symbol; - } - } } } } @@ -15579,7 +14418,7 @@ var ts; if (result = getSymbol(location.locals, name, meaning)) { var useResult = true; if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { - if (meaning & result.flags & 793064 && lastLocation.kind !== 273) { + if (meaning & result.flags & 793056 && lastLocation.kind !== 273) { useResult = result.flags & 262144 ? lastLocation === location.type || lastLocation.kind === 142 || @@ -15616,7 +14455,7 @@ var ts; } result = undefined; } - if (moduleExports[name] && + if (ts.hasProperty(moduleExports, name) && moduleExports[name].flags === 8388608 && ts.getDeclarationOfKind(moduleExports[name], 238)) { break; @@ -15645,7 +14484,7 @@ var ts; case 221: case 192: case 222: - if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064)) { + if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056)) { if (lastLocation && lastLocation.flags & 32) { error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); return undefined; @@ -15663,7 +14502,7 @@ var ts; case 140: grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 222) { - if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793064)) { + if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793056)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -15714,9 +14553,8 @@ var ts; } if (!result) { if (nameNotFoundMessage) { - if (!errorLocation || - !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && - !checkAndReportErrorForExtendingInterface(errorLocation)) { + if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForExtendingInterface(errorLocation)) { error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); } } @@ -15734,7 +14572,7 @@ var ts; checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } - if (result && isInExternalModule && (meaning & 107455) === 107455) { + if (result && isInExternalModule) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 228) { error(errorLocation, ts.Diagnostics.Identifier_0_must_be_imported_from_a_module, name); @@ -15744,7 +14582,7 @@ var ts; return result; } function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { - if ((errorLocation.kind === 69 && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { + if (!errorLocation || (errorLocation.kind === 69 && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { return false; } var container = ts.getThisContainer(errorLocation, true); @@ -15773,30 +14611,33 @@ var ts; return false; } function checkAndReportErrorForExtendingInterface(errorLocation) { - var expression = getEntityNameForExtendingInterface(errorLocation); - var isError = !!(expression && resolveEntityName(expression, 64, true)); - if (isError) { + var parentClassExpression = errorLocation; + while (parentClassExpression) { + var kind = parentClassExpression.kind; + if (kind === 69 || kind === 172) { + parentClassExpression = parentClassExpression.parent; + continue; + } + if (kind === 194) { + break; + } + return false; + } + if (!parentClassExpression) { + return false; + } + var expression = parentClassExpression.expression; + if (resolveEntityName(expression, 64, true)) { error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); + return true; } - return isError; - } - function getEntityNameForExtendingInterface(node) { - switch (node.kind) { - case 69: - case 172: - return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; - case 194: - ts.Debug.assert(ts.isEntityNameExpression(node.expression)); - return node.expression; - default: - return undefined; - } + return false; } function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert((result.flags & 2) !== 0); var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) ? d : undefined; }); ts.Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined"); - if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 218), errorLocation)) { + if (!isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 218), errorLocation)) { error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); } } @@ -15834,7 +14675,7 @@ var ts; function getTargetOfImportClause(node) { var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { - var exportDefaultSymbol = ts.isShorthandAmbientModuleSymbol(moduleSymbol) ? + var exportDefaultSymbol = ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration) ? moduleSymbol : moduleSymbol.exports["export="] ? getPropertyOfType(getTypeOfSymbol(moduleSymbol.exports["export="]), "default") : @@ -15853,7 +14694,7 @@ var ts; return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier); } function combineValueAndTypeSymbols(valueSymbol, typeSymbol) { - if (valueSymbol.flags & (793064 | 1920)) { + if (valueSymbol.flags & (793056 | 1536)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.name); @@ -15869,9 +14710,9 @@ var ts; } function getExportOfModule(symbol, name) { if (symbol.flags & 1536) { - var exportedSymbol = getExportsOfSymbol(symbol)[name]; - if (exportedSymbol) { - return resolveSymbol(exportedSymbol); + var exports = getExportsOfSymbol(symbol); + if (ts.hasProperty(exports, name)) { + return resolveSymbol(exports[name]); } } } @@ -15887,28 +14728,25 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier); if (targetSymbol) { - var name_13 = specifier.propertyName || specifier.name; - if (name_13.text) { - if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + var name_11 = specifier.propertyName || specifier.name; + if (name_11.text) { + if (ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration)) { return moduleSymbol; } var symbolFromVariable = void 0; if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports["export="]) { - symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_13.text); + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_11.text); } else { - symbolFromVariable = getPropertyOfVariable(targetSymbol, name_13.text); + symbolFromVariable = getPropertyOfVariable(targetSymbol, name_11.text); } symbolFromVariable = resolveSymbol(symbolFromVariable); - var symbolFromModule = getExportOfModule(targetSymbol, name_13.text); - if (!symbolFromModule && allowSyntheticDefaultImports && name_13.text === "default") { - symbolFromModule = resolveExternalModuleSymbol(moduleSymbol) || resolveSymbol(moduleSymbol); - } + var symbolFromModule = getExportOfModule(targetSymbol, name_11.text); var symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - error(name_13, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_13)); + error(name_11, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_11)); } return symbol; } @@ -15923,10 +14761,10 @@ var ts; function getTargetOfExportSpecifier(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 107455 | 793064 | 1920); + resolveEntityName(node.propertyName || node.name, 107455 | 793056 | 1536); } function getTargetOfExportAssignment(node) { - return resolveEntityName(node.expression, 107455 | 793064 | 1920); + return resolveEntityName(node.expression, 107455 | 793056 | 1536); } function getTargetOfAliasDeclaration(node) { switch (node.kind) { @@ -15947,7 +14785,7 @@ var ts; } } function resolveSymbol(symbol) { - return symbol && symbol.flags & 8388608 && !(symbol.flags & (107455 | 793064 | 1920)) ? resolveAlias(symbol) : symbol; + return symbol && symbol.flags & 8388608 && !(symbol.flags & (107455 | 793056 | 1536)) ? resolveAlias(symbol) : symbol; } function resolveAlias(symbol) { ts.Debug.assert((symbol.flags & 8388608) !== 0, "Should only get Alias here."); @@ -15955,7 +14793,6 @@ var ts; if (!links.target) { links.target = resolvingSymbol; var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); var target = getTargetOfAliasDeclaration(node); if (links.target === resolvingSymbol) { links.target = target || unknownSymbol; @@ -15985,7 +14822,6 @@ var ts; if (!links.referenced) { links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); if (node.kind === 235) { checkExpressionCached(node.expression); } @@ -16002,11 +14838,11 @@ var ts; entityName = entityName.parent; } if (entityName.kind === 69 || entityName.parent.kind === 139) { - return resolveEntityName(entityName, 1920, false, dontResolveAlias); + return resolveEntityName(entityName, 1536, false, dontResolveAlias); } else { ts.Debug.assert(entityName.parent.kind === 229); - return resolveEntityName(entityName, 107455 | 793064 | 1920, false, dontResolveAlias); + return resolveEntityName(entityName, 107455 | 793056 | 1536, false, dontResolveAlias); } } function getFullyQualifiedName(symbol) { @@ -16018,7 +14854,7 @@ var ts; } var symbol; if (name.kind === 69) { - var message = meaning === 1920 ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; + var message = meaning === 1536 ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; symbol = resolveName(name, name.text, meaning, ignoreErrors ? undefined : message, name); if (!symbol) { return undefined; @@ -16027,7 +14863,7 @@ var ts; else if (name.kind === 139 || name.kind === 172) { var left = name.kind === 139 ? name.left : name.expression; var right = name.kind === 139 ? name.right : name.name; - var namespace = resolveEntityName(left, 1920, ignoreErrors); + var namespace = resolveEntityName(left, 1536, ignoreErrors); if (!namespace || ts.nodeIsMissing(right)) { return undefined; } @@ -16085,14 +14921,7 @@ var ts; } } if (moduleNotFoundError) { - var tsExtension = ts.tryExtractTypeScriptExtension(moduleName); - if (tsExtension) { - var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; - error(moduleReferenceLiteral, diag, tsExtension, ts.removeExtension(moduleName, tsExtension)); - } - else { - error(moduleReferenceLiteral, moduleNotFoundError, moduleName); - } + error(moduleReferenceLiteral, moduleNotFoundError, moduleName); } return undefined; } @@ -16122,7 +14951,7 @@ var ts; } function extendExportSymbols(target, source, lookupTable, exportNode) { for (var id in source) { - if (id !== "default" && !target[id]) { + if (id !== "default" && !ts.hasProperty(target, id)) { target[id] = source[id]; if (lookupTable && exportNode) { lookupTable[id] = { @@ -16130,7 +14959,7 @@ var ts; }; } } - else if (lookupTable && exportNode && id !== "default" && target[id] && resolveSymbol(target[id]) !== resolveSymbol(source[id])) { + else if (lookupTable && exportNode && id !== "default" && ts.hasProperty(target, id) && resolveSymbol(target[id]) !== resolveSymbol(source[id])) { if (!lookupTable[id].exportsWithDuplicate) { lookupTable[id].exportsWithDuplicate = [exportNode]; } @@ -16148,11 +14977,11 @@ var ts; return; } visitedSymbols.push(symbol); - var symbols = ts.cloneMap(symbol.exports); + var symbols = cloneSymbolTable(symbol.exports); var exportStars = symbol.exports["__export"]; if (exportStars) { - var nestedSymbols = ts.createMap(); - var lookupTable = ts.createMap(); + var nestedSymbols = {}; + var lookupTable = {}; for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { var node = _a[_i]; var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); @@ -16161,7 +14990,7 @@ var ts; } for (var id in lookupTable) { var exportsWithDuplicate = lookupTable[id].exportsWithDuplicate; - if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols[id]) { + if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || ts.hasProperty(symbols, id)) { continue; } for (var _b = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _b < exportsWithDuplicate_1.length; _b++) { @@ -16212,8 +15041,8 @@ var ts; } function createType(flags) { var result = new Type(checker, flags); - typeCount++; result.id = typeCount; + typeCount++; return result; } function createIntrinsicType(kind, intrinsicName) { @@ -16221,12 +15050,6 @@ var ts; type.intrinsicName = intrinsicName; return type; } - function createBooleanType(trueFalseTypes) { - var type = getUnionType(trueFalseTypes); - type.flags |= 8; - type.intrinsicName = "boolean"; - return type; - } function createObjectType(kind, symbol) { var type = createType(kind); type.symbol = symbol; @@ -16241,12 +15064,14 @@ var ts; function getNamedMembers(members) { var result; for (var id in members) { - if (!isReservedMemberName(id)) { - if (!result) - result = []; - var symbol = members[id]; - if (symbolIsValue(symbol)) { - result.push(symbol); + if (ts.hasProperty(members, id)) { + if (!isReservedMemberName(id)) { + if (!result) + result = []; + var symbol = members[id]; + if (symbolIsValue(symbol)) { + result.push(symbol); + } } } } @@ -16264,7 +15089,7 @@ var ts; return type; } function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { - return setObjectTypeMembers(createObjectType(2097152, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + return setObjectTypeMembers(createObjectType(65536, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function forEachSymbolTableInScope(enclosingDeclaration, callback) { var result; @@ -16289,7 +15114,7 @@ var ts; return callback(globals); } function getQualifiedLeftMeaning(rightMeaning) { - return rightMeaning === 107455 ? 107455 : 1920; + return rightMeaning === 107455 ? 107455 : 1536; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { function getAccessibleSymbolChainFromSymbolTable(symbols) { @@ -16306,10 +15131,10 @@ var ts; canQualifySymbol(symbolFromSymbolTable, meaning); } } - if (isAccessible(symbols[symbol.name])) { + if (isAccessible(ts.lookUp(symbols, symbol.name))) { return [symbol]; } - return ts.forEachProperty(symbols, function (symbolFromSymbolTable) { + return ts.forEachValue(symbols, function (symbolFromSymbolTable) { if (symbolFromSymbolTable.flags & 8388608 && symbolFromSymbolTable.name !== "export=" && !ts.getDeclarationOfKind(symbolFromSymbolTable, 238)) { @@ -16336,10 +15161,10 @@ var ts; function needsQualification(symbol, enclosingDeclaration, meaning) { var qualify = false; forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { - var symbolFromSymbolTable = symbolTable[symbol.name]; - if (!symbolFromSymbolTable) { + if (!ts.hasProperty(symbolTable, symbol.name)) { return false; } + var symbolFromSymbolTable = symbolTable[symbol.name]; if (symbolFromSymbolTable === symbol) { return true; } @@ -16382,7 +15207,7 @@ var ts; return { accessibility: 1, errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920) : undefined + errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1536) : undefined }; } return hasAccessibleDeclarations; @@ -16453,10 +15278,10 @@ var ts; } else if (entityName.kind === 139 || entityName.kind === 172 || entityName.parent.kind === 229) { - meaning = 1920; + meaning = 1536; } else { - meaning = 793064; + meaning = 793056; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.text, meaning, undefined, undefined); @@ -16507,31 +15332,6 @@ var ts; ts.releaseStringWriter(writer); return result; } - function formatUnionTypes(types) { - var result = []; - var flags = 0; - for (var i = 0; i < types.length; i++) { - var t = types[i]; - flags |= t.flags; - if (!(t.flags & 6144)) { - if (t.flags & (128 | 256)) { - var baseType = t.flags & 128 ? booleanType : t.baseType; - var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { - result.push(baseType); - i += count - 1; - continue; - } - } - result.push(t); - } - } - if (flags & 4096) - result.push(nullType); - if (flags & 2048) - result.push(undefinedType); - return result || types; - } function visibilityToString(flags) { if (flags === 8) { return "private"; @@ -16654,50 +15454,35 @@ var ts; var inObjectTypeLiteral = false; return writeType(type, globalFlags); function writeType(type, flags) { - var nextFlags = flags & ~512; - if (type.flags & 16015) { + if (type.flags & 150995071) { writer.writeKeyword(!(globalFlags & 16) && isTypeAny(type) ? "any" : type.intrinsicName); } - else if (type.flags & 268435456) { + else if (type.flags & 33554432) { if (inObjectTypeLiteral) { writer.reportInaccessibleThisError(); } writer.writeKeyword("this"); } - else if (type.flags & 131072) { - writeTypeReference(type, nextFlags); + else if (type.flags & 4096) { + writeTypeReference(type, flags); + } + else if (type.flags & (1024 | 2048 | 128 | 512)) { + buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793056, 0, flags); + } + else if (type.flags & 8192) { + writeTupleType(type); + } + else if (type.flags & 49152) { + writeUnionOrIntersectionType(type, flags); + } + else if (type.flags & 65536) { + writeAnonymousType(type, flags); } else if (type.flags & 256) { - buildSymbolDisplay(getParentOfSymbol(type.symbol), writer, enclosingDeclaration, 793064, 0, nextFlags); - writePunctuation(writer, 21); - appendSymbolNameOnly(type.symbol, writer); - } - else if (type.flags & (32768 | 65536 | 16 | 16384)) { - buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); - } - else if (!(flags & 512) && type.flags & (2097152 | 1572864) && type.aliasSymbol) { - if (type.flags & 2097152 || !(flags & 1024)) { - var typeArguments = type.aliasTypeArguments; - writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); - } - else { - writeUnionOrIntersectionType(type, nextFlags); - } - } - else if (type.flags & 1572864) { - writeUnionOrIntersectionType(type, nextFlags); - } - else if (type.flags & 2097152) { - writeAnonymousType(type, nextFlags); - } - else if (type.flags & 32) { writer.writeStringLiteral("\"" + ts.escapeString(type.text) + "\""); } - else if (type.flags & 64) { - writer.writeStringLiteral(type.text); - } else { writePunctuation(writer, 15); writeSpace(writer); @@ -16720,7 +15505,7 @@ var ts; } function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { if (symbol.flags & 32 || !isReservedMemberName(symbol.name)) { - buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064, 0, flags); + buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793056, 0, flags); } if (pos < end) { writePunctuation(writer, 25); @@ -16742,11 +15527,6 @@ var ts; writePunctuation(writer, 19); writePunctuation(writer, 20); } - else if (type.target.flags & 262144) { - writePunctuation(writer, 19); - writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 24); - writePunctuation(writer, 20); - } else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; @@ -16768,16 +15548,16 @@ var ts; writeSymbolTypeReference(type.symbol, typeArguments, i, typeParameterCount, flags); } } + function writeTupleType(type) { + writePunctuation(writer, 19); + writeTypeList(type.elementTypes, 24); + writePunctuation(writer, 20); + } function writeUnionOrIntersectionType(type, flags) { if (flags & 64) { writePunctuation(writer, 17); } - if (type.flags & 524288) { - writeTypeList(formatUnionTypes(type.types), 47); - } - else { - writeTypeList(type.types, 46); - } + writeTypeList(type.types, type.flags & 16384 ? 47 : 46); if (flags & 64) { writePunctuation(writer, 18); } @@ -16794,7 +15574,7 @@ var ts; else if (ts.contains(symbolStack, symbol)) { var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { - buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793064, 0, flags); + buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793056, 0, flags); } else { writeKeyword(writer, 117); @@ -17196,13 +15976,13 @@ var ts; function collectLinkedAliases(node) { var exportSymbol; if (node.parent && node.parent.kind === 235) { - exportSymbol = resolveName(node.parent, node.text, 107455 | 793064 | 1920 | 8388608, ts.Diagnostics.Cannot_find_name_0, node); + exportSymbol = resolveName(node.parent, node.text, 107455 | 793056 | 1536 | 8388608, ts.Diagnostics.Cannot_find_name_0, node); } else if (node.parent.kind === 238) { var exportSpecifier = node.parent; exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : - resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, 107455 | 793064 | 1920 | 8388608); + resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, 107455 | 793056 | 1536 | 8388608); } var result = []; if (exportSymbol) { @@ -17219,7 +15999,7 @@ var ts; if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.text, 107455 | 793064 | 1920, undefined, undefined); + var importSymbol = resolveName(declaration, firstIdentifier.text, 107455 | 793056 | 1536, undefined, undefined); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -17260,7 +16040,7 @@ var ts; return getSymbolLinks(target).declaredType; } if (propertyName === 1) { - ts.Debug.assert(!!(target.flags & 32768)); + ts.Debug.assert(!!(target.flags & 1024)); return target.resolvedBaseConstructorType; } if (propertyName === 3) { @@ -17302,7 +16082,7 @@ var ts; return type && (type.flags & 1) !== 0; } function isTypeNever(type) { - return type && (type.flags & 8192) !== 0; + return type && (type.flags & 134217728) !== 0; } function getTypeForBindingElementParent(node) { var symbol = getSymbolOfNode(node); @@ -17339,19 +16119,19 @@ var ts; } var type; if (pattern.kind === 167) { - var name_14 = declaration.propertyName || declaration.name; - if (isComputedNonLiteralName(name_14)) { + var name_12 = declaration.propertyName || declaration.name; + if (isComputedNonLiteralName(name_12)) { return anyType; } if (declaration.initializer) { getContextualType(declaration.initializer); } - var text = getTextOfPropertyName(name_14); + var text = getTextOfPropertyName(name_12); type = getTypeOfPropertyOfType(parentType, text) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || getIndexTypeOfType(parentType, 0); if (!type) { - error(name_14, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_14)); + error(name_12, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_12)); return unknownType; } } @@ -17364,7 +16144,7 @@ var ts; : elementType; if (!type) { if (isTupleType(parentType)) { - error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); + error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), parentType.elementTypes.length, pattern.elements.length); } else { error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), propName); @@ -17376,12 +16156,10 @@ var ts; type = createArrayType(elementType); } } - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 2048)) { + if (strictNullChecks && declaration.initializer && !(getCombinedTypeFlags(checkExpressionCached(declaration.initializer)) & 32)) { type = getTypeWithFacts(type, 131072); } - return declaration.initializer ? - getUnionType([type, checkExpressionCached(declaration.initializer)], true) : - type; + return type; } function getTypeForVariableLikeDeclarationFromJSDocComment(declaration) { var jsDocType = getJSDocTypeForVariableLikeDeclarationFromJSDocComment(declaration); @@ -17411,7 +16189,7 @@ var ts; return undefined; } function addOptionality(type, optional) { - return strictNullChecks && optional ? includeFalsyTypes(type, 2048) : type; + return strictNullChecks && optional ? addTypeKind(type, 32) : type; } function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { if (declaration.flags & 134217728) { @@ -17446,14 +16224,9 @@ var ts; return getReturnTypeOfSignature(getterSignature); } } - var type = void 0; - if (declaration.symbol.name === "this") { - var thisParameter = getContextualThisParameter(func); - type = thisParameter ? getTypeOfSymbol(thisParameter) : undefined; - } - else { - type = getContextuallyTypedParameterType(declaration); - } + var type = declaration.symbol.name === "this" + ? getContextuallyTypedThisType(func) + : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, declaration.questionToken && includeOptionality); } @@ -17465,24 +16238,26 @@ var ts; return checkIdentifier(declaration.name); } if (ts.isBindingPattern(declaration.name)) { - return getTypeFromBindingPattern(declaration.name, false, true); + return getTypeFromBindingPattern(declaration.name, false); } return undefined; } - function getTypeFromBindingElement(element, includePatternInType, reportErrors) { + function getTypeFromBindingElement(element, includePatternInType) { if (element.initializer) { - return checkExpressionCached(element.initializer); + var type = checkExpressionCached(element.initializer); + reportErrorsFromWidening(element, type); + return getWidenedType(type); } if (ts.isBindingPattern(element.name)) { - return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); + return getTypeFromBindingPattern(element.name, includePatternInType); } - if (reportErrors && compilerOptions.noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { + if (compilerOptions.noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { reportImplicitAnyError(element, anyType); } return anyType; } - function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { - var members = ts.createMap(); + function getTypeFromObjectBindingPattern(pattern, includePatternInType) { + var members = {}; var hasComputedProperties = false; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; @@ -17493,7 +16268,7 @@ var ts; var text = getTextOfPropertyName(name); var flags = 4 | 67108864 | (e.initializer ? 536870912 : 0); var symbol = createSymbol(flags, text); - symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); + symbol.type = getTypeFromBindingElement(e, includePatternInType); symbol.bindingElement = e; members[symbol.name] = symbol; }); @@ -17502,27 +16277,27 @@ var ts; result.pattern = pattern; } if (hasComputedProperties) { - result.flags |= 536870912; + result.flags |= 67108864; } return result; } - function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { + function getTypeFromArrayBindingPattern(pattern, includePatternInType) { var elements = pattern.elements; if (elements.length === 0 || elements[elements.length - 1].dotDotDotToken) { return languageVersion >= 2 ? createIterableType(anyType) : anyArrayType; } - var elementTypes = ts.map(elements, function (e) { return e.kind === 193 ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); }); - var result = createTupleType(elementTypes); + var elementTypes = ts.map(elements, function (e) { return e.kind === 193 ? anyType : getTypeFromBindingElement(e, includePatternInType); }); if (includePatternInType) { - result = cloneTypeReference(result); + var result = createNewTupleType(elementTypes); result.pattern = pattern; + return result; } - return result; + return createTupleType(elementTypes); } - function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { + function getTypeFromBindingPattern(pattern, includePatternInType) { return pattern.kind === 167 - ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) - : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); + ? getTypeFromObjectBindingPattern(pattern, includePatternInType) + : getTypeFromArrayBindingPattern(pattern, includePatternInType); } function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { var type = getTypeForVariableLikeDeclaration(declaration, true); @@ -17561,27 +16336,19 @@ var ts; if (declaration.kind === 235) { return links.type = checkExpression(declaration.expression); } - if (declaration.flags & 134217728 && declaration.kind === 280 && declaration.typeExpression) { - return links.type = getTypeFromTypeNode(declaration.typeExpression.type); - } if (!pushTypeResolution(symbol, 0)) { return unknownType; } - var type = void 0; - if (declaration.kind === 187 || - declaration.kind === 172 && declaration.parent.kind === 187) { - if (declaration.flags & 134217728) { - var typeTag = ts.getJSDocTypeTag(declaration.parent); - if (typeTag && typeTag.typeExpression) { - return links.type = getTypeFromTypeNode(typeTag.typeExpression.type); - } - } - var declaredTypes = ts.map(symbol.declarations, function (decl) { return decl.kind === 187 ? - checkExpressionCached(decl.right) : - checkExpressionCached(decl.parent.right); }); - type = getUnionType(declaredTypes, true); + var type = undefined; + if (declaration.kind === 187) { + type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); })); } - else { + else if (declaration.kind === 172) { + if (declaration.parent.kind === 187) { + type = checkExpressionCached(declaration.parent.right); + } + } + if (type === undefined) { type = getWidenedTypeForVariableLikeDeclaration(declaration, true); } if (!popTypeResolution()) { @@ -17649,13 +16416,7 @@ var ts; } else { if (compilerOptions.noImplicitAny) { - if (setter) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } + error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation, symbolToString(symbol)); } type = anyType; } @@ -17675,13 +16436,13 @@ var ts; function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbol.valueDeclaration.kind === 225 && ts.isShorthandAmbientModuleSymbol(symbol)) { + if (symbol.valueDeclaration.kind === 225 && ts.isShorthandAmbientModule(symbol.valueDeclaration)) { links.type = anyType; } else { - var type = createObjectType(2097152, symbol); + var type = createObjectType(65536, symbol); links.type = strictNullChecks && symbol.flags & 536870912 ? - includeFalsyTypes(type, 2048) : type; + addTypeKind(type, 32) : type; } } return links.type; @@ -17732,7 +16493,7 @@ var ts; return unknownType; } function getTargetType(type) { - return type.flags & 131072 ? type.target : type; + return type.flags & 4096 ? type.target : type; } function hasBaseType(type, checkBase) { return check(type); @@ -17792,7 +16553,7 @@ var ts; return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); } function isConstructorType(type) { - return type.flags & 2588672 && getSignaturesOfType(type, 1).length > 0; + return type.flags & 80896 && getSignaturesOfType(type, 1).length > 0; } function getBaseTypeNodeOfClass(type) { return ts.getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); @@ -17819,7 +16580,7 @@ var ts; return unknownType; } var baseConstructorType = checkExpression(baseTypeNode.expression); - if (baseConstructorType.flags & 2588672) { + if (baseConstructorType.flags & 80896) { resolveStructuredTypeMembers(baseConstructorType); } if (!popTypeResolution()) { @@ -17835,28 +16596,25 @@ var ts; return type.resolvedBaseConstructorType; } function getBaseTypes(type) { + var isClass = type.symbol.flags & 32; + var isInterface = type.symbol.flags & 64; if (!type.resolvedBaseTypes) { - if (type.flags & 262144) { - type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters))]; - } - else if (type.symbol.flags & (32 | 64)) { - if (type.symbol.flags & 32) { - resolveBaseTypesOfClass(type); - } - if (type.symbol.flags & 64) { - resolveBaseTypesOfInterface(type); - } - } - else { + if (!isClass && !isInterface) { ts.Debug.fail("type must be class or interface"); } + if (isClass) { + resolveBaseTypesOfClass(type); + } + if (isInterface) { + resolveBaseTypesOfInterface(type); + } } return type.resolvedBaseTypes; } function resolveBaseTypesOfClass(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; var baseConstructorType = getBaseConstructorTypeOfClass(type); - if (!(baseConstructorType.flags & 2588672)) { + if (!(baseConstructorType.flags & 80896)) { return; } var baseTypeNode = getBaseTypeNodeOfClass(type); @@ -17877,7 +16635,7 @@ var ts; if (baseType === unknownType) { return; } - if (!(getTargetType(baseType).flags & (32768 | 65536))) { + if (!(getTargetType(baseType).flags & (1024 | 2048))) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); return; } @@ -17910,7 +16668,7 @@ var ts; var node = _c[_b]; var baseType = getTypeFromTypeNode(node); if (baseType !== unknownType) { - if (getTargetType(baseType).flags & (32768 | 65536)) { + if (getTargetType(baseType).flags & (1024 | 2048)) { if (type !== baseType && !hasBaseType(baseType, type)) { if (type.resolvedBaseTypes === emptyArray) { type.resolvedBaseTypes = [baseType]; @@ -17942,8 +16700,8 @@ var ts; if (baseTypeNodes) { for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { var node = baseTypeNodes_1[_b]; - if (ts.isEntityNameExpression(node.expression)) { - var baseSymbol = resolveEntityName(node.expression, 793064, true); + if (ts.isSupportedExpressionWithTypeArguments(node)) { + var baseSymbol = resolveEntityName(node.expression, 793056, true); if (!baseSymbol || !(baseSymbol.flags & 64) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -17957,20 +16715,20 @@ var ts; function getDeclaredTypeOfClassOrInterface(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var kind = symbol.flags & 32 ? 32768 : 65536; + var kind = symbol.flags & 32 ? 1024 : 2048; var type = links.declaredType = createObjectType(kind, symbol); var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - if (outerTypeParameters || localTypeParameters || kind === 32768 || !isIndependentInterface(symbol)) { - type.flags |= 131072; + if (outerTypeParameters || localTypeParameters || kind === 1024 || !isIndependentInterface(symbol)) { + type.flags |= 4096; type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); type.outerTypeParameters = outerTypeParameters; type.localTypeParameters = localTypeParameters; - type.instantiations = ts.createMap(); + type.instantiations = {}; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 | 268435456); + type.thisType = createType(512 | 33554432); type.thisType.symbol = symbol; type.thisType.constraint = type; } @@ -17983,9 +16741,8 @@ var ts; if (!pushTypeResolution(symbol, 2)) { return unknownType; } - var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - var declaration = ts.getDeclarationOfKind(symbol, 279); var type = void 0; + var declaration = ts.getDeclarationOfKind(symbol, 279); if (declaration) { if (declaration.jsDocTypeLiteral) { type = getTypeFromTypeNode(declaration.jsDocTypeLiteral); @@ -17996,12 +16753,12 @@ var ts; } else { declaration = ts.getDeclarationOfKind(symbol, 223); - type = getTypeFromTypeNode(declaration.type, symbol, typeParameters); + type = getTypeFromTypeNode(declaration.type); } if (popTypeResolution()) { - links.typeParameters = typeParameters; - if (typeParameters) { - links.instantiations = ts.createMap(); + links.typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (links.typeParameters) { + links.instantiations = {}; links.instantiations[getTypeListId(links.typeParameters)] = type; } } @@ -18013,80 +16770,19 @@ var ts; } return links.declaredType; } - function isLiteralEnumMember(symbol, member) { - var expr = member.initializer; - if (!expr) { - return !ts.isInAmbientContext(member); - } - return expr.kind === 8 || - expr.kind === 185 && expr.operator === 36 && - expr.operand.kind === 8 || - expr.kind === 69 && !!symbol.exports[expr.text]; - } - function enumHasLiteralMembers(symbol) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 224) { - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - if (!isLiteralEnumMember(symbol, member)) { - return false; - } - } - } - } - return true; - } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var enumType = links.declaredType = createType(16); - enumType.symbol = symbol; - if (enumHasLiteralMembers(symbol)) { - var memberTypeList = []; - var memberTypes = ts.createMap(); - for (var _i = 0, _a = enumType.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 224) { - computeEnumMemberValues(declaration); - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - var memberSymbol = getSymbolOfNode(member); - var value = getEnumMemberValue(member); - if (!memberTypes[value]) { - var memberType = memberTypes[value] = createType(256); - memberType.symbol = memberSymbol; - memberType.baseType = enumType; - memberType.text = "" + value; - memberTypeList.push(memberType); - } - } - } - } - enumType.memberTypes = memberTypes; - if (memberTypeList.length > 1) { - enumType.flags |= 524288; - enumType.types = memberTypeList; - unionTypes[getTypeListId(memberTypeList)] = enumType; - } - } - } - return links.declaredType; - } - function getDeclaredTypeOfEnumMember(symbol) { - var links = getSymbolLinks(symbol); - if (!links.declaredType) { - var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); - links.declaredType = enumType.flags & 524288 ? - enumType.memberTypes[getEnumMemberValue(symbol.valueDeclaration)] : - enumType; + var type = createType(128); + type.symbol = symbol; + links.declaredType = type; } return links.declaredType; } function getDeclaredTypeOfTypeParameter(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var type = createType(16384); + var type = createType(512); type.symbol = symbol; if (!ts.getDeclarationOfKind(symbol, 141).constraint) { type.constraint = noConstraintType; @@ -18110,14 +16806,11 @@ var ts; if (symbol.flags & 524288) { return getDeclaredTypeOfTypeAlias(symbol); } - if (symbol.flags & 262144) { - return getDeclaredTypeOfTypeParameter(symbol); - } if (symbol.flags & 384) { return getDeclaredTypeOfEnum(symbol); } - if (symbol.flags & 8) { - return getDeclaredTypeOfEnumMember(symbol); + if (symbol.flags & 262144) { + return getDeclaredTypeOfTypeParameter(symbol); } if (symbol.flags & 8388608) { return getDeclaredTypeOfAlias(symbol); @@ -18188,7 +16881,7 @@ var ts; return false; } function createSymbolTable(symbols) { - var result = ts.createMap(); + var result = {}; for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { var symbol = symbols_1[_i]; result[symbol.name] = symbol; @@ -18196,7 +16889,7 @@ var ts; return result; } function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) { - var result = ts.createMap(); + var result = {}; for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { var symbol = symbols_2[_i]; result[symbol.name] = mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper); @@ -18206,7 +16899,7 @@ var ts; function addInheritedMembers(symbols, baseSymbols) { for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) { var s = baseSymbols_1[_i]; - if (!symbols[s.name]) { + if (!ts.hasProperty(symbols, s.name)) { symbols[s.name] = s; } } @@ -18223,27 +16916,19 @@ var ts; return type; } function getTypeWithThisArgument(type, thisArgument) { - if (type.flags & 131072) { + if (type.flags & 4096) { return createTypeReference(type.target, ts.concatenate(type.typeArguments, [thisArgument || type.target.thisType])); } return type; } function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { - var mapper; - var members; - var callSignatures; - var constructSignatures; - var stringIndexInfo; - var numberIndexInfo; - if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { - mapper = identityMapper; - members = source.symbol ? source.symbol.members : createSymbolTable(source.declaredProperties); - callSignatures = source.declaredCallSignatures; - constructSignatures = source.declaredConstructSignatures; - stringIndexInfo = source.declaredStringIndexInfo; - numberIndexInfo = source.declaredNumberIndexInfo; - } - else { + var mapper = identityMapper; + var members = source.symbol.members; + var callSignatures = source.declaredCallSignatures; + var constructSignatures = source.declaredConstructSignatures; + var stringIndexInfo = source.declaredStringIndexInfo; + var numberIndexInfo = source.declaredNumberIndexInfo; + if (!ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { mapper = createTypeMapper(typeParameters, typeArguments); members = createInstantiatedSymbolTable(source.declaredProperties, mapper, typeParameters.length === 1); callSignatures = instantiateList(source.declaredCallSignatures, mapper, instantiateSignature); @@ -18253,7 +16938,7 @@ var ts; } var baseTypes = getBaseTypes(source); if (baseTypes.length) { - if (source.symbol && members === source.symbol.members) { + if (members === source.symbol.members) { members = createSymbolTable(source.declaredProperties); } var thisArgument = ts.lastOrUndefined(typeArguments); @@ -18279,7 +16964,7 @@ var ts; type.typeArguments : ts.concatenate(type.typeArguments, [type]); resolveObjectTypeMembers(type, source, typeParameters, typeArguments); } - function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasStringLiterals) { var sig = new Signature(checker); sig.declaration = declaration; sig.typeParameters = typeParameters; @@ -18289,11 +16974,11 @@ var ts; sig.typePredicate = typePredicate; sig.minArgumentCount = minArgumentCount; sig.hasRestParameter = hasRestParameter; - sig.hasLiteralTypes = hasLiteralTypes; + sig.hasStringLiterals = hasStringLiterals; return sig; } function cloneSignature(sig) { - return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); + return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); } function getDefaultConstructSignatures(classType) { var baseConstructorType = getBaseConstructorTypeOfClass(classType); @@ -18317,6 +17002,22 @@ var ts; } return result; } + function createTupleTypeMemberSymbols(memberTypes) { + var members = {}; + for (var i = 0; i < memberTypes.length; i++) { + var symbol = createSymbol(4 | 67108864, "" + i); + symbol.type = memberTypes[i]; + members[i] = symbol; + } + return members; + } + function resolveTupleTypeMembers(type) { + var arrayElementType = getUnionType(type.elementTypes, true); + var arrayType = resolveStructuredTypeMembers(createTypeFromGenericGlobalType(globalArrayType, [arrayElementType, type])); + var members = createTupleTypeMemberSymbols(type.elementTypes); + addInheritedMembers(members, arrayType.properties); + setObjectTypeMembers(type, members, arrayType.callSignatures, arrayType.constructSignatures, arrayType.stringIndexInfo, arrayType.numberIndexInfo); + } function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) { for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { var s = signatureList_1[_i]; @@ -18362,7 +17063,7 @@ var ts; if (unionSignatures.length > 1) { s = cloneSignature(signature); if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { - var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; }), true); + var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; })); s.thisParameter = createTransientSymbol(signature.thisParameter, thisType); } s.resolvedReturnType = undefined; @@ -18387,7 +17088,7 @@ var ts; indexTypes.push(indexInfo.type); isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; } - return createIndexInfo(getUnionType(indexTypes, true), isAnyReadonly); + return createIndexInfo(getUnionType(indexTypes), isAnyReadonly); } function resolveUnionTypeMembers(type) { var callSignatures = getUnionSignatures(type.types, 0); @@ -18447,7 +17148,7 @@ var ts; constructSignatures = getDefaultConstructSignatures(classType); } var baseConstructorType = getBaseConstructorTypeOfClass(classType); - if (baseConstructorType.flags & 2588672) { + if (baseConstructorType.flags & 80896) { members = createSymbolTable(getNamedMembers(members)); addInheritedMembers(members, getPropertiesOfObjectType(baseConstructorType)); } @@ -18461,36 +17162,41 @@ var ts; } function resolveStructuredTypeMembers(type) { if (!type.members) { - if (type.flags & 131072) { + if (type.flags & 4096) { resolveTypeReferenceMembers(type); } - else if (type.flags & (32768 | 65536)) { + else if (type.flags & (1024 | 2048)) { resolveClassOrInterfaceMembers(type); } - else if (type.flags & 2097152) { + else if (type.flags & 65536) { resolveAnonymousTypeMembers(type); } - else if (type.flags & 524288) { + else if (type.flags & 8192) { + resolveTupleTypeMembers(type); + } + else if (type.flags & 16384) { resolveUnionTypeMembers(type); } - else if (type.flags & 1048576) { + else if (type.flags & 32768) { resolveIntersectionTypeMembers(type); } } return type; } function getPropertiesOfObjectType(type) { - if (type.flags & 2588672) { + if (type.flags & 80896) { return resolveStructuredTypeMembers(type).properties; } return emptyArray; } function getPropertyOfObjectType(type, name) { - if (type.flags & 2588672) { + if (type.flags & 80896) { var resolved = resolveStructuredTypeMembers(type); - var symbol = resolved.members[name]; - if (symbol && symbolIsValue(symbol)) { - return symbol; + if (ts.hasProperty(resolved.members, name)) { + var symbol = resolved.members[name]; + if (symbolIsValue(symbol)) { + return symbol; + } } } } @@ -18501,7 +17207,7 @@ var ts; var prop = _c[_b]; getPropertyOfUnionOrIntersectionType(type, prop.name); } - if (type.flags & 524288) { + if (type.flags & 16384) { break; } } @@ -18509,12 +17215,12 @@ var ts; } function getPropertiesOfType(type) { type = getApparentType(type); - return type.flags & 1572864 ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); + return type.flags & 49152 ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } function getApparentTypeOfTypeParameter(type) { if (!type.resolvedApparentType) { var constraintType = getConstraintOfTypeParameter(type); - while (constraintType && constraintType.flags & 16384) { + while (constraintType && constraintType.flags & 512) { constraintType = getConstraintOfTypeParameter(constraintType); } type.resolvedApparentType = getTypeWithThisArgument(constraintType || emptyObjectType, type); @@ -18522,19 +17228,19 @@ var ts; return type.resolvedApparentType; } function getApparentType(type) { - if (type.flags & 16384) { + if (type.flags & 512) { type = getApparentTypeOfTypeParameter(type); } - if (type.flags & 34) { + if (type.flags & 258) { type = globalStringType; } - else if (type.flags & 340) { + else if (type.flags & 132) { type = globalNumberType; } - else if (type.flags & 136) { + else if (type.flags & 8) { type = globalBooleanType; } - else if (type.flags & 512) { + else if (type.flags & 16777216) { type = getGlobalESSymbolType(); } return type; @@ -18542,7 +17248,7 @@ var ts; function createUnionOrIntersectionProperty(containingType, name) { var types = containingType.types; var props; - var commonFlags = (containingType.flags & 1048576) ? 536870912 : 0; + var commonFlags = (containingType.flags & 32768) ? 536870912 : 0; var isReadonly = false; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var current = types_2[_i]; @@ -18561,7 +17267,7 @@ var ts; isReadonly = true; } } - else if (containingType.flags & 524288) { + else if (containingType.flags & 16384) { return undefined; } } @@ -18574,20 +17280,11 @@ var ts; } var propTypes = []; var declarations = []; - var commonType = undefined; - var hasCommonType = true; for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { var prop = props_1[_a]; if (prop.declarations) { ts.addRange(declarations, prop.declarations); } - var type = getTypeOfSymbol(prop); - if (!commonType) { - commonType = type; - } - else if (type !== commonType) { - hasCommonType = false; - } propTypes.push(getTypeOfSymbol(prop)); } var result = createSymbol(4 | @@ -18595,46 +17292,47 @@ var ts; 268435456 | commonFlags, name); result.containingType = containingType; - result.hasCommonType = hasCommonType; result.declarations = declarations; result.isReadonly = isReadonly; - result.type = containingType.flags & 524288 ? getUnionType(propTypes) : getIntersectionType(propTypes); + result.type = containingType.flags & 16384 ? getUnionType(propTypes) : getIntersectionType(propTypes); return result; } function getPropertyOfUnionOrIntersectionType(type, name) { - var properties = type.resolvedProperties || (type.resolvedProperties = ts.createMap()); - var property = properties[name]; - if (!property) { - property = createUnionOrIntersectionProperty(type, name); - if (property) { - properties[name] = property; - } + var properties = type.resolvedProperties || (type.resolvedProperties = {}); + if (ts.hasProperty(properties, name)) { + return properties[name]; + } + var property = createUnionOrIntersectionProperty(type, name); + if (property) { + properties[name] = property; } return property; } function getPropertyOfType(type, name) { type = getApparentType(type); - if (type.flags & 2588672) { + if (type.flags & 80896) { var resolved = resolveStructuredTypeMembers(type); - var symbol = resolved.members[name]; - if (symbol && symbolIsValue(symbol)) { - return symbol; + if (ts.hasProperty(resolved.members, name)) { + var symbol = resolved.members[name]; + if (symbolIsValue(symbol)) { + return symbol; + } } if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); - if (symbol_1) { - return symbol_1; + var symbol = getPropertyOfObjectType(globalFunctionType, name); + if (symbol) { + return symbol; } } return getPropertyOfObjectType(globalObjectType, name); } - if (type.flags & 1572864) { + if (type.flags & 49152) { return getPropertyOfUnionOrIntersectionType(type, name); } return undefined; } function getSignaturesOfStructuredType(type, kind) { - if (type.flags & 4161536) { + if (type.flags & 130048) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 ? resolved.callSignatures : resolved.constructSignatures; } @@ -18644,7 +17342,7 @@ var ts; return getSignaturesOfStructuredType(getApparentType(type), kind); } function getIndexInfoOfStructuredType(type, kind) { - if (type.flags & 4161536) { + if (type.flags & 130048) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 ? resolved.stringIndexInfo : resolved.numberIndexInfo; } @@ -18669,7 +17367,7 @@ var ts; } } if (propTypes.length) { - return getUnionType(propTypes, true); + return getUnionType(propTypes); } } return undefined; @@ -18752,7 +17450,7 @@ var ts; var links = getNodeLinks(declaration); if (!links.resolvedSignature) { var parameters = []; - var hasLiteralTypes = false; + var hasStringLiterals = false; var minArgumentCount = -1; var thisParameter = undefined; var hasThisParameter = void 0; @@ -18772,7 +17470,7 @@ var ts; parameters.push(paramSymbol); } if (param.type && param.type.kind === 166) { - hasLiteralTypes = true; + hasStringLiterals = true; } if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { if (minArgumentCount < 0) { @@ -18798,9 +17496,6 @@ var ts; if (isJSConstructSignature) { minArgumentCount--; } - if (!thisParameter && ts.isObjectLiteralMethod(declaration)) { - thisParameter = getContextualThisParameter(declaration); - } var classType = declaration.kind === 148 ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; @@ -18811,7 +17506,7 @@ var ts; var typePredicate = declaration.type && declaration.type.kind === 154 ? createTypePredicateFromTypePredicateNode(declaration.type) : undefined; - links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasLiteralTypes); + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasStringLiterals); } return links.resolvedSignature; } @@ -18896,7 +17591,7 @@ var ts; type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); } else if (signature.unionSignatures) { - type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), true); + type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature)); } else { type = getReturnTypeFromBody(signature.declaration); @@ -18920,7 +17615,7 @@ var ts; function getRestTypeOfSignature(signature) { if (signature.hasRestParameter) { var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); - if (type.flags & 131072 && type.target === globalArrayType) { + if (type.flags & 4096 && type.target === globalArrayType) { return type.typeArguments[0]; } } @@ -18940,7 +17635,7 @@ var ts; function getOrCreateTypeFromSignature(signature) { if (!signature.isolatedSignatureType) { var isConstructor = signature.declaration.kind === 148 || signature.declaration.kind === 152; - var type = createObjectType(2097152); + var type = createObjectType(65536 | 262144); type.members = emptySymbols; type.properties = emptyArray; type.callSignatures = !isConstructor ? [signature] : emptyArray; @@ -18984,7 +17679,7 @@ var ts; } function hasConstraintReferenceTo(type, target) { var checked; - while (type && !(type.flags & 268435456) && type.flags & 16384 && !ts.contains(checked, type)) { + while (type && !(type.flags & 33554432) && type.flags & 512 && !ts.contains(checked, type)) { if (type === target) { return true; } @@ -19016,27 +17711,24 @@ var ts; return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 141).parent); } function getTypeListId(types) { - var result = ""; if (types) { - var length_3 = types.length; - var i = 0; - while (i < length_3) { - var startId = types[i].id; - var count = 1; - while (i + count < length_3 && types[i + count].id === startId + count) { - count++; - } - if (result.length) { - result += ","; - } - result += startId; - if (count > 1) { - result += ":" + count; - } - i += count; + switch (types.length) { + case 1: + return "" + types[0].id; + case 2: + return types[0].id + "," + types[1].id; + default: + var result = ""; + for (var i = 0; i < types.length; i++) { + if (i > 0) { + result += ","; + } + result += types[i].id; + } + return result; } } - return result; + return ""; } function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; @@ -19046,29 +17738,20 @@ var ts; result |= type.flags; } } - return result & 234881024; + return result & 14680064; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); var type = target.instantiations[id]; if (!type) { var propagatedFlags = typeArguments ? getPropagatingFlagsOfTypes(typeArguments, 0) : 0; - var flags = 131072 | propagatedFlags; + var flags = 4096 | propagatedFlags; type = target.instantiations[id] = createObjectType(flags, target.symbol); type.target = target; type.typeArguments = typeArguments; } return type; } - function cloneTypeReference(source) { - var type = createObjectType(source.flags, source.symbol); - type.target = source.target; - type.typeArguments = source.typeArguments; - return type; - } - function getTypeReferenceArity(type) { - return type.target.typeParameters ? type.target.typeParameters.length : 0; - } function getTypeFromClassOrInterfaceReference(node, symbol) { var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); var typeParameters = type.localTypeParameters; @@ -19118,9 +17801,8 @@ var ts; case 267: return node.name; case 194: - var expr = node.expression; - if (ts.isEntityNameExpression(expr)) { - return expr; + if (ts.isSupportedExpressionWithTypeArguments(node)) { + return node.expression; } } return undefined; @@ -19129,7 +17811,7 @@ var ts; if (!typeReferenceName) { return unknownSymbol; } - return resolveEntityName(typeReferenceName, 793064) || unknownSymbol; + return resolveEntityName(typeReferenceName, 793056) || unknownSymbol; } function getTypeReferenceType(node, symbol) { if (symbol === unknownSymbol) { @@ -19155,14 +17837,14 @@ var ts; var typeReferenceName = getTypeReferenceName(node); symbol = resolveTypeReferenceName(node, typeReferenceName); type = getTypeReferenceType(node, symbol); + links.resolvedSymbol = symbol; + links.resolvedType = type; } else { - var typeNameOrExpression = node.kind === 155 - ? node.typeName - : ts.isEntityNameExpression(node.expression) - ? node.expression - : undefined; - symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793064) || unknownSymbol; + var typeNameOrExpression = node.kind === 155 ? node.typeName : + ts.isSupportedExpressionWithTypeArguments(node) ? node.expression : + undefined; + symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793056) || unknownSymbol; type = symbol === unknownSymbol ? unknownType : symbol.flags & (32 | 64) ? getTypeFromClassOrInterfaceReference(node, symbol) : symbol.flags & 524288 ? getTypeFromTypeAliasReference(node, symbol) : @@ -19197,7 +17879,7 @@ var ts; return arity ? emptyGenericType : emptyObjectType; } var type = getDeclaredTypeOfSymbol(symbol); - if (!(type.flags & 2588672)) { + if (!(type.flags & 80896)) { error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbol.name); return arity ? emptyGenericType : emptyObjectType; } @@ -19211,7 +17893,7 @@ var ts; return getGlobalSymbol(name, 107455, ts.Diagnostics.Cannot_find_global_value_0); } function getGlobalTypeSymbol(name) { - return getGlobalSymbol(name, 793064, ts.Diagnostics.Cannot_find_global_type_0); + return getGlobalSymbol(name, 793056, ts.Diagnostics.Cannot_find_global_type_0); } function getGlobalSymbol(name, meaning, diagnostic) { return resolveName(undefined, name, meaning, diagnostic, name); @@ -19221,8 +17903,8 @@ var ts; return getTypeOfGlobalSymbol(getGlobalTypeSymbol(name), arity); } function getExportedTypeFromNamespace(namespace, name) { - var namespaceSymbol = getGlobalSymbol(namespace, 1920, undefined); - var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793064); + var namespaceSymbol = getGlobalSymbol(namespace, 1536, undefined); + var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793056); return typeSymbol && getDeclaredTypeOfSymbol(typeSymbol); } function createTypedPropertyDescriptorType(propertyType) { @@ -19250,38 +17932,15 @@ var ts; } return links.resolvedType; } - function createTupleTypeOfArity(arity) { - var typeParameters = []; - var properties = []; - for (var i = 0; i < arity; i++) { - var typeParameter = createType(16384); - typeParameters.push(typeParameter); - var property = createSymbol(4 | 67108864, "" + i); - property.type = typeParameter; - properties.push(property); - } - var type = createObjectType(262144 | 131072); - type.typeParameters = typeParameters; - type.outerTypeParameters = undefined; - type.localTypeParameters = typeParameters; - type.instantiations = ts.createMap(); - type.instantiations[getTypeListId(type.typeParameters)] = type; - type.target = type; - type.typeArguments = type.typeParameters; - type.thisType = createType(16384 | 268435456); - type.thisType.constraint = type; - type.declaredProperties = properties; - type.declaredCallSignatures = emptyArray; - type.declaredConstructSignatures = emptyArray; - type.declaredStringIndexInfo = undefined; - type.declaredNumberIndexInfo = undefined; - return type; - } - function getTupleTypeOfArity(arity) { - return tupleTypes[arity] || (tupleTypes[arity] = createTupleTypeOfArity(arity)); - } function createTupleType(elementTypes) { - return createTypeReference(getTupleTypeOfArity(elementTypes.length), elementTypes); + var id = getTypeListId(elementTypes); + return tupleTypes[id] || (tupleTypes[id] = createNewTupleType(elementTypes)); + } + function createNewTupleType(elementTypes) { + var propagatedFlags = getPropagatingFlagsOfTypes(elementTypes, 0); + var type = createObjectType(8192 | propagatedFlags); + type.elementTypes = elementTypes; + return type; } function getTypeFromTupleTypeNode(node) { var links = getNodeLinks(node); @@ -19290,68 +17949,30 @@ var ts; } return links.resolvedType; } - function binarySearchTypes(types, type) { - var low = 0; - var high = types.length - 1; - var typeId = type.id; - while (low <= high) { - var middle = low + ((high - low) >> 1); - var id = types[middle].id; - if (id === typeId) { - return middle; - } - else if (id > typeId) { - high = middle - 1; - } - else { - low = middle + 1; - } + function addTypeToSet(typeSet, type, typeSetKind) { + if (type.flags & typeSetKind) { + addTypesToSet(typeSet, type.types, typeSetKind); } - return ~low; - } - function containsType(types, type) { - return binarySearchTypes(types, type) >= 0; - } - function addTypeToUnion(typeSet, type) { - if (type.flags & 524288) { - addTypesToUnion(typeSet, type.types); - } - else if (type.flags & 1) { - typeSet.containsAny = true; - } - else if (!strictNullChecks && type.flags & 6144) { - if (type.flags & 2048) + else if (type.flags & (1 | 32 | 64)) { + if (type.flags & 1) + typeSet.containsAny = true; + if (type.flags & 32) typeSet.containsUndefined = true; - if (type.flags & 4096) + if (type.flags & 64) typeSet.containsNull = true; - if (!(type.flags & 33554432)) + if (!(type.flags & 2097152)) typeSet.containsNonWideningType = true; } - else if (!(type.flags & 8192)) { - var len = typeSet.length; - var index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type); - if (index < 0) { - if (!(type.flags & 2097152 && type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); - } - } + else if (type !== neverType && !ts.contains(typeSet, type)) { + typeSet.push(type); } } - function addTypesToUnion(typeSet, types) { + function addTypesToSet(typeSet, types, typeSetKind) { for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { var type = types_4[_i]; - addTypeToUnion(typeSet, type); + addTypeToSet(typeSet, type, typeSetKind); } } - function containsIdenticalType(types, type) { - for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { - var t = types_5[_i]; - if (isTypeIdenticalTo(t, type)) { - return true; - } - } - return false; - } function isSubtypeOfAny(candidate, types) { for (var i = 0, len = types.length; i < len; i++) { if (candidate !== types[i] && isTypeSubtypeOf(candidate, types[i])) { @@ -19369,7 +17990,7 @@ var ts; } } } - function getUnionType(types, subtypeReduction, aliasSymbol, aliasTypeArguments) { + function getUnionType(types, noSubtypeReduction) { if (types.length === 0) { return neverType; } @@ -19377,11 +17998,17 @@ var ts; return types[0]; } var typeSet = []; - addTypesToUnion(typeSet, types); + addTypesToSet(typeSet, types, 16384); if (typeSet.containsAny) { return anyType; } - if (subtypeReduction) { + if (strictNullChecks) { + if (typeSet.containsNull) + typeSet.push(nullType); + if (typeSet.containsUndefined) + typeSet.push(undefinedType); + } + if (!noSubtypeReduction) { removeSubtypes(typeSet); } if (typeSet.length === 0) { @@ -19389,103 +18016,78 @@ var ts; typeSet.containsUndefined ? typeSet.containsNonWideningType ? undefinedType : undefinedWideningType : neverType; } - return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments); - } - function getUnionTypeFromSortedList(types, aliasSymbol, aliasTypeArguments) { - if (types.length === 0) { - return neverType; + else if (typeSet.length === 1) { + return typeSet[0]; } - if (types.length === 1) { - return types[0]; - } - var id = getTypeListId(types); + var id = getTypeListId(typeSet); var type = unionTypes[id]; if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(types, 6144); - type = unionTypes[id] = createObjectType(524288 | propagatedFlags); - type.types = types; - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = aliasTypeArguments; + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, 96); + type = unionTypes[id] = createObjectType(16384 | propagatedFlags); + type.types = typeSet; } return type; } - function getTypeFromUnionTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getTypeFromUnionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), false, aliasSymbol, aliasTypeArguments); + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), true); } return links.resolvedType; } - function addTypeToIntersection(typeSet, type) { - if (type.flags & 1048576) { - addTypesToIntersection(typeSet, type.types); - } - else if (type.flags & 1) { - typeSet.containsAny = true; - } - else if (!(type.flags & 8192) && (strictNullChecks || !(type.flags & 6144)) && !ts.contains(typeSet, type)) { - typeSet.push(type); - } - } - function addTypesToIntersection(typeSet, types) { - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type = types_6[_i]; - addTypeToIntersection(typeSet, type); - } - } - function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { + function getIntersectionType(types) { if (types.length === 0) { return emptyObjectType; } var typeSet = []; - addTypesToIntersection(typeSet, types); + addTypesToSet(typeSet, types, 32768); if (typeSet.containsAny) { return anyType; } + if (strictNullChecks) { + if (typeSet.containsNull) + typeSet.push(nullType); + if (typeSet.containsUndefined) + typeSet.push(undefinedType); + } if (typeSet.length === 1) { return typeSet[0]; } var id = getTypeListId(typeSet); var type = intersectionTypes[id]; if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, 6144); - type = intersectionTypes[id] = createObjectType(1048576 | propagatedFlags); + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, 96); + type = intersectionTypes[id] = createObjectType(32768 | propagatedFlags); type.types = typeSet; - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = aliasTypeArguments; } return type; } - function getTypeFromIntersectionTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getTypeFromIntersectionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, aliasTypeArguments); + links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode)); } return links.resolvedType; } - function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - var type = createObjectType(2097152, node.symbol); - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = aliasTypeArguments; - links.resolvedType = type; + links.resolvedType = createObjectType(65536, node.symbol); } return links.resolvedType; } - function createLiteralType(flags, text) { - var type = createType(flags); + function getStringLiteralTypeForText(text) { + if (ts.hasProperty(stringLiteralTypes, text)) { + return stringLiteralTypes[text]; + } + var type = stringLiteralTypes[text] = createType(256); type.text = text; return type; } - function getLiteralTypeForText(flags, text) { - var map = flags & 32 ? stringLiteralTypes : numericLiteralTypes; - return map[text] || (map[text] = createLiteralType(flags, text)); - } - function getTypeFromLiteralTypeNode(node) { + function getTypeFromStringLiteralTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = checkExpression(node.literal); + links.resolvedType = getStringLiteralTypeForText(ts.unescapeIdentifier(node.text)); } return links.resolvedType; } @@ -19524,7 +18126,7 @@ var ts; } return links.resolvedType; } - function getTypeFromTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getTypeFromTypeNode(node) { switch (node.kind) { case 117: case 258: @@ -19546,19 +18148,11 @@ var ts; return nullType; case 127: return neverType; - case 283: - return nullType; - case 284: - return undefinedType; - case 285: - return neverType; case 165: case 97: return getTypeFromThisTypeNode(node); case 166: - return getTypeFromLiteralTypeNode(node); - case 282: - return getTypeFromLiteralTypeNode(node.literal); + return getTypeFromStringLiteralTypeNode(node); case 155: case 267: return getTypeFromTypeReference(node); @@ -19575,9 +18169,9 @@ var ts; return getTypeFromTupleTypeNode(node); case 162: case 261: - return getTypeFromUnionTypeNode(node, aliasSymbol, aliasTypeArguments); + return getTypeFromUnionTypeNode(node); case 163: - return getTypeFromIntersectionTypeNode(node, aliasSymbol, aliasTypeArguments); + return getTypeFromIntersectionTypeNode(node); case 164: case 263: case 264: @@ -19591,7 +18185,7 @@ var ts; case 281: case 269: case 265: - return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node, aliasSymbol, aliasTypeArguments); + return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); case 69: case 139: var symbol = getSymbolAtLocation(node); @@ -19637,7 +18231,6 @@ var ts; count == 2 ? createBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : createArrayTypeMapper(sources, targets); mapper.mappedTypes = sources; - mapper.targetTypes = targets; return mapper; } function createTypeEraser(sources) { @@ -19670,7 +18263,7 @@ var ts; return mapper; } function cloneTypeParameter(typeParameter) { - var result = createType(16384); + var result = createType(512); result.symbol = typeParameter.symbol; result.target = typeParameter; return result; @@ -19705,7 +18298,7 @@ var ts; if (signature.typePredicate) { freshTypePredicate = cloneTypePredicate(signature.typePredicate, mapper); } - var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); + var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasStringLiterals); result.target = signature; result.mapper = mapper; return result; @@ -19736,11 +18329,9 @@ var ts; else { mapper.instantiations = []; } - var result = createObjectType(2097152 | 4194304, type.symbol); + var result = createObjectType(65536 | 131072, type.symbol); result.target = type; result.mapper = mapper; - result.aliasSymbol = type.aliasSymbol; - result.aliasTypeArguments = mapper.targetTypes; mapper.instantiations[type.id] = result; return result; } @@ -19792,23 +18383,26 @@ var ts; } function instantiateType(type, mapper) { if (type && mapper !== identityMapper) { - if (type.flags & 16384) { + if (type.flags & 512) { return mapper(type); } - if (type.flags & 2097152) { + if (type.flags & 65536) { return type.symbol && type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && - (type.flags & 4194304 || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? + (type.flags & 131072 || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? instantiateAnonymousType(type, mapper) : type; } - if (type.flags & 131072) { + if (type.flags & 4096) { return createTypeReference(type.target, instantiateList(type.typeArguments, mapper, instantiateType)); } - if (type.flags & 524288 && !(type.flags & 8190)) { - return getUnionType(instantiateList(type.types, mapper, instantiateType), false, type.aliasSymbol, mapper.targetTypes); + if (type.flags & 8192) { + return createTupleType(instantiateList(type.elementTypes, mapper, instantiateType)); } - if (type.flags & 1048576) { - return getIntersectionType(instantiateList(type.types, mapper, instantiateType), type.aliasSymbol, mapper.targetTypes); + if (type.flags & 16384) { + return getUnionType(instantiateList(type.types, mapper, instantiateType), true); + } + if (type.flags & 32768) { + return getIntersectionType(instantiateList(type.types, mapper, instantiateType)); } } return type; @@ -19851,10 +18445,10 @@ var ts; return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { - if (type.flags & 2588672) { + if (type.flags & 80896) { var resolved = resolveStructuredTypeMembers(type); if (resolved.constructSignatures.length) { - var result = createObjectType(2097152, type.symbol); + var result = createObjectType(65536, type.symbol); result.members = resolved.members; result.properties = resolved.properties; result.callSignatures = emptyArray; @@ -19865,25 +18459,22 @@ var ts; return type; } function isTypeIdenticalTo(source, target) { - return isTypeRelatedTo(source, target, identityRelation); + return checkTypeRelatedTo(source, target, identityRelation, undefined); } function compareTypesIdentical(source, target) { - return isTypeRelatedTo(source, target, identityRelation) ? -1 : 0; + return checkTypeRelatedTo(source, target, identityRelation, undefined) ? -1 : 0; } function compareTypesAssignable(source, target) { - return isTypeRelatedTo(source, target, assignableRelation) ? -1 : 0; + return checkTypeRelatedTo(source, target, assignableRelation, undefined) ? -1 : 0; } function isTypeSubtypeOf(source, target) { - return isTypeRelatedTo(source, target, subtypeRelation); + return checkTypeSubtypeOf(source, target, undefined); } function isTypeAssignableTo(source, target) { - return isTypeRelatedTo(source, target, assignableRelation); - } - function isTypeInstanceOf(source, target) { - return source === target || isTypeSubtypeOf(source, target) && !isTypeIdenticalTo(source, target); + return checkTypeAssignableTo(source, target, undefined); } function isTypeComparableTo(source, target) { - return isTypeRelatedTo(source, target, comparableRelation); + return checkTypeComparableTo(source, target, undefined); } function areTypesComparable(type1, type2) { return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); @@ -19996,8 +18587,8 @@ var ts; var sourceReturnType = getReturnTypeOfSignature(erasedSource); var targetReturnType = getReturnTypeOfSignature(erasedTarget); if (targetReturnType === voidType - || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation) - || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) { + || checkTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation, undefined) + || checkTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation, undefined)) { return isSignatureAssignableTo(erasedSource, erasedTarget, true); } return false; @@ -20023,88 +18614,6 @@ var ts; sourceNonRestParamCount; } } - function isEnumTypeRelatedTo(source, target, errorReporter) { - if (source === target) { - return true; - } - var id = source.id + "," + target.id; - if (enumRelation[id] !== undefined) { - return enumRelation[id]; - } - if (source.symbol.name !== target.symbol.name || - !(source.symbol.flags & 256) || !(target.symbol.flags & 256) || - (source.flags & 524288) !== (target.flags & 524288)) { - return enumRelation[id] = false; - } - var targetEnumType = getTypeOfSymbol(target.symbol); - for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { - var property = _a[_i]; - if (property.flags & 8) { - var targetProperty = getPropertyOfType(targetEnumType, property.name); - if (!targetProperty || !(targetProperty.flags & 8)) { - if (errorReporter) { - errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, undefined, 128)); - } - return enumRelation[id] = false; - } - } - } - return enumRelation[id] = true; - } - function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { - if (target.flags & 8192) - return false; - if (target.flags & 1 || source.flags & 8192) - return true; - if (source.flags & 34 && target.flags & 2) - return true; - if (source.flags & 340 && target.flags & 4) - return true; - if (source.flags & 136 && target.flags & 8) - return true; - if (source.flags & 256 && target.flags & 16 && source.baseType === target) - return true; - if (source.flags & 16 && target.flags & 16 && isEnumTypeRelatedTo(source, target, errorReporter)) - return true; - if (source.flags & 2048 && (!strictNullChecks || target.flags & (2048 | 1024))) - return true; - if (source.flags & 4096 && (!strictNullChecks || target.flags & 4096)) - return true; - if (relation === assignableRelation || relation === comparableRelation) { - if (source.flags & 1) - return true; - if ((source.flags & 4 | source.flags & 64) && target.flags & 272) - return true; - if (source.flags & 256 && - target.flags & 256 && - source.text === target.text && - isEnumTypeRelatedTo(source.baseType, target.baseType, errorReporter)) { - return true; - } - if (source.flags & 256 && - target.flags & 16 && - isEnumTypeRelatedTo(target, source.baseType, errorReporter)) { - return true; - } - } - return false; - } - function isTypeRelatedTo(source, target, relation) { - if (source === target || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { - return true; - } - if (source.flags & 2588672 && target.flags & 2588672) { - var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; - var related = relation[id]; - if (related !== undefined) { - return related === 1; - } - } - if (source.flags & 4177920 || target.flags & 4177920) { - return checkTypeRelatedTo(source, target, relation, undefined, undefined, undefined); - } - return false; - } function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain) { var errorInfo; var sourceStack; @@ -20143,16 +18652,6 @@ var ts; } reportError(message, sourceType, targetType); } - function tryElaborateErrorsForPrimitivesAndObjects(source, target) { - var sourceType = typeToString(source); - var targetType = typeToString(target); - if ((globalStringType === source && stringType === target) || - (globalNumberType === source && numberType === target) || - (globalBooleanType === source && booleanType === target) || - (getGlobalESSymbolType() === source && esSymbolType === target)) { - reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); - } - } function isRelatedTo(source, target, reportErrors, headMessage) { var result; if (source === target) @@ -20160,50 +18659,78 @@ var ts; if (relation === identityRelation) { return isIdenticalTo(source, target); } - if (isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) - return -1; - if (source.flags & 16777216) { + if (!(target.flags & 134217728)) { + if (target.flags & 1 || source.flags & 134217728) + return -1; + if (source.flags & 32) { + if (!strictNullChecks || target.flags & (32 | 16)) + return -1; + } + if (source.flags & 64) { + if (!strictNullChecks || target.flags & 64) + return -1; + } + if (source.flags & 128 && target === numberType) + return -1; + if (source.flags & 128 && target.flags & 128) { + if (result = enumRelatedTo(source, target, reportErrors)) { + return result; + } + } + if (source.flags & 256 && target === stringType) + return -1; + if (relation === assignableRelation || relation === comparableRelation) { + if (source.flags & 1) + return -1; + if (source === numberType && target.flags & 128) + return -1; + } + if (source.flags & 8 && target.flags & 8) { + return -1; + } + } + if (source.flags & 1048576) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { reportRelationError(headMessage, source, target); } return 0; } - if (target.flags & 1572864) { + if (target.flags & 49152) { source = getRegularTypeOfObjectLiteral(source); } } var saveErrorInfo = errorInfo; - if (source.flags & 524288) { + if (source.flags & 16384) { if (relation === comparableRelation) { - result = someTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190)); + result = someTypeRelatedToType(source, target, reportErrors); } else { - result = eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190)); + result = eachTypeRelatedToType(source, target, reportErrors); } if (result) { return result; } } - else if (target.flags & 1048576) { + else if (target.flags & 32768) { result = typeRelatedToEachType(source, target, reportErrors); if (result) { return result; } } else { - if (source.flags & 1048576) { + if (source.flags & 32768) { if (result = someTypeRelatedToType(source, target, false)) { return result; } } - if (target.flags & 524288) { - if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190) && !(target.flags & 8190))) { + if (target.flags & 16384) { + if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 16777726))) { return result; } } } - if (source.flags & 16384) { + if (source.flags & 512) { var constraint = getConstraintOfTypeParameter(source); if (!constraint || constraint.flags & 1) { constraint = emptyObjectType; @@ -20216,14 +18743,14 @@ var ts; } } else { - if (source.flags & 131072 && target.flags & 131072 && source.target === target.target) { + if (source.flags & 4096 && target.flags & 4096 && source.target === target.target) { if (result = typeArgumentsRelatedTo(source, target, reportErrors)) { return result; } } var apparentSource = getApparentType(source); - if (apparentSource.flags & (2588672 | 1048576) && target.flags & 2588672) { - var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !(source.flags & 8190); + if (apparentSource.flags & (80896 | 32768) && target.flags & 80896) { + var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !(source.flags & 16777726); if (result = objectTypeRelatedTo(apparentSource, source, target, reportStructuralErrors)) { errorInfo = saveErrorInfo; return result; @@ -20231,25 +18758,22 @@ var ts; } } if (reportErrors) { - if (source.flags & 2588672 && target.flags & 8190) { - tryElaborateErrorsForPrimitivesAndObjects(source, target); - } reportRelationError(headMessage, source, target); } return 0; } function isIdenticalTo(source, target) { var result; - if (source.flags & 2588672 && target.flags & 2588672) { - if (source.flags & 131072 && target.flags & 131072 && source.target === target.target) { + if (source.flags & 80896 && target.flags & 80896) { + if (source.flags & 4096 && target.flags & 4096 && source.target === target.target) { if (result = typeArgumentsRelatedTo(source, target, false)) { return result; } } return objectTypeRelatedTo(source, source, target, false); } - if (source.flags & 524288 && target.flags & 524288 || - source.flags & 1048576 && target.flags & 1048576) { + if (source.flags & 16384 && target.flags & 16384 || + source.flags & 32768 && target.flags & 32768) { if (result = eachTypeRelatedToSomeType(source, target, false)) { if (result &= eachTypeRelatedToSomeType(target, source, false)) { return result; @@ -20259,7 +18783,7 @@ var ts; return 0; } function isKnownProperty(type, name) { - if (type.flags & 2588672) { + if (type.flags & 80896) { var resolved = resolveStructuredTypeMembers(type); if ((relation === assignableRelation || relation === comparableRelation) && (type === globalObjectType || isEmptyObjectType(resolved)) || resolved.stringIndexInfo || @@ -20268,7 +18792,7 @@ var ts; return true; } } - else if (type.flags & 1572864) { + else if (type.flags & 49152) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; if (isKnownProperty(t, name)) { @@ -20286,7 +18810,7 @@ var ts; !t.numberIndexInfo; } function hasExcessProperties(source, target, reportErrors) { - if (!(target.flags & 536870912) && maybeTypeOfKind(target, 2588672)) { + if (!(target.flags & 67108864) && maybeTypeOfKind(target, 80896)) { for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; if (!isKnownProperty(target, prop.name)) { @@ -20316,10 +18840,14 @@ var ts; } function typeRelatedToSomeType(source, target, reportErrors) { var targetTypes = target.types; - if (target.flags & 524288 && containsType(targetTypes, source)) { - return -1; - } var len = targetTypes.length; + while (len >= 2 && targetTypes[len - 1].flags & 96) { + var related = isRelatedTo(source, targetTypes[len - 1], false); + if (related) { + return related; + } + len--; + } for (var i = 0; i < len; i++) { var related = isRelatedTo(source, targetTypes[i], reportErrors && i === len - 1); if (related) { @@ -20343,10 +18871,14 @@ var ts; } function someTypeRelatedToType(source, target, reportErrors) { var sourceTypes = source.types; - if (source.flags & 524288 && containsType(sourceTypes, target)) { - return -1; - } var len = sourceTypes.length; + while (len >= 2 && sourceTypes[len - 1].flags & 96) { + var related = isRelatedTo(sourceTypes[len - 1], target, false); + if (related) { + return related; + } + len--; + } for (var i = 0; i < len; i++) { var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); if (related) { @@ -20418,7 +18950,7 @@ var ts; } sourceStack[depth] = source; targetStack[depth] = target; - maybeStack[depth] = ts.createMap(); + maybeStack[depth] = {}; maybeStack[depth][id] = 1; depth++; var saveExpandingFlags = expandingFlags; @@ -20450,7 +18982,7 @@ var ts; if (result) { var maybeCache = maybeStack[depth]; var destinationCache = (result === -1 || depth === 0) ? relation : maybeStack[depth - 1]; - ts.copyProperties(maybeCache, destinationCache); + ts.copyMap(maybeCache, destinationCache); } else { relation[id] = reportErrors ? 3 : 2; @@ -20463,7 +18995,7 @@ var ts; } var result = -1; var properties = getPropertiesOfObjectType(target); - var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 8388608); + var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 524288); for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) { var targetProp = properties_1[_i]; var sourceProp = getPropertyOfType(source, targetProp.name); @@ -20529,7 +19061,7 @@ var ts; return result; } function propertiesIdenticalTo(source, target) { - if (!(source.flags & 2588672 && target.flags & 2588672)) { + if (!(source.flags & 80896 && target.flags & 80896)) { return 0; } var sourceProperties = getPropertiesOfObjectType(source); @@ -20642,7 +19174,7 @@ var ts; return indexTypesIdenticalTo(source, target, kind); } var targetInfo = getIndexInfoOfType(target, kind); - if (!targetInfo || ((targetInfo.type.flags & 1) && !(originalSource.flags & 8190))) { + if (!targetInfo || ((targetInfo.type.flags & 1) && !(originalSource.flags & 16777726))) { return -1; } var sourceInfo = getIndexInfoOfType(source, kind) || @@ -20679,6 +19211,27 @@ var ts; } return 0; } + function enumRelatedTo(source, target, reportErrors) { + if (source.symbol.name !== target.symbol.name || + source.symbol.flags & 128 || + target.symbol.flags & 128) { + return 0; + } + var targetEnumType = getTypeOfSymbol(target.symbol); + for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { + var property = _a[_i]; + if (property.flags & 8) { + var targetProperty = getPropertyOfType(targetEnumType, property.name); + if (!targetProperty || !(targetProperty.flags & 8)) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, undefined, 128)); + } + return 0; + } + } + } + return -1; + } function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) { if (!sourceSignature.declaration || !targetSignature.declaration) { return true; @@ -20701,7 +19254,7 @@ var ts; } } function isAbstractConstructorType(type) { - if (type.flags & 2097152) { + if (type.flags & 65536) { var symbol = type.symbol; if (symbol && symbol.flags & 32) { var declaration = getClassLikeDeclarationOfSymbol(symbol); @@ -20713,12 +19266,12 @@ var ts; return false; } function isDeeplyNestedGeneric(type, stack, depth) { - if (type.flags & (131072 | 4194304) && depth >= 5) { + if (type.flags & (4096 | 131072) && depth >= 5) { var symbol = type.symbol; var count = 0; for (var i = 0; i < depth; i++) { var t = stack[i]; - if (t.flags & (131072 | 4194304) && t.symbol === symbol) { + if (t.flags & (4096 | 131072) && t.symbol === symbol) { count++; if (count >= 5) return true; @@ -20760,10 +19313,8 @@ var ts; source.hasRestParameter === target.hasRestParameter) { return true; } - var sourceRestCount = source.hasRestParameter ? 1 : 0; - var targetRestCount = target.hasRestParameter ? 1 : 0; - if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (sourceRestCount > targetRestCount || - sourceRestCount === targetRestCount && source.parameters.length >= target.parameters.length)) { + if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (source.hasRestParameter && !target.hasRestParameter || + source.hasRestParameter === target.hasRestParameter && source.parameters.length >= target.parameters.length)) { return true; } return false; @@ -20813,23 +19364,31 @@ var ts; return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } function isSupertypeOfEach(candidate, types) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var t = types_5[_i]; if (candidate !== t && !isTypeSubtypeOf(t, candidate)) return false; } return true; } + function getCombinedFlagsOfTypes(types) { + var flags = 0; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var t = types_6[_i]; + flags |= t.flags; + } + return flags; + } function getCommonSupertype(types) { if (!strictNullChecks) { return ts.forEach(types, function (t) { return isSupertypeOfEach(t, types) ? t : undefined; }); } - var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 6144); }); + var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 96); }); if (!primaryTypes.length) { - return getUnionType(types, true); + return getUnionType(types); } var supertype = ts.forEach(primaryTypes, function (t) { return isSupertypeOfEach(t, primaryTypes) ? t : undefined; }); - return supertype && includeFalsyTypes(supertype, getFalsyFlagsOfTypes(types) & 6144); + return supertype && addTypeKind(supertype, getCombinedFlagsOfTypes(types) & 96); } function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { var bestSupertype; @@ -20859,72 +19418,44 @@ var ts; checkTypeSubtypeOf(bestSupertypeDownfallType, bestSupertype, errorLocation, ts.Diagnostics.Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0, errorMessageChainHead); } function isArrayType(type) { - return type.flags & 131072 && type.target === globalArrayType; + return type.flags & 4096 && type.target === globalArrayType; } function isArrayLikeType(type) { - return type.flags & 131072 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || - !(type.flags & 6144) && isTypeAssignableTo(type, anyReadonlyArrayType); + return type.flags & 4096 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || + !(type.flags & 96) && isTypeAssignableTo(type, anyReadonlyArrayType); } function isTupleLikeType(type) { return !!getPropertyOfType(type, "0"); } - function isUnitType(type) { - return (type.flags & (480 | 2048 | 4096)) !== 0; - } - function isUnitUnionType(type) { - return type.flags & 8 ? true : - type.flags & 524288 ? type.flags & 16 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : - isUnitType(type); - } - function getBaseTypeOfUnitType(type) { - return type.flags & 32 ? stringType : - type.flags & 64 ? numberType : - type.flags & 128 ? booleanType : - type.flags & 256 ? type.baseType : - type.flags & 524288 && !(type.flags & 16) ? getUnionType(ts.map(type.types, getBaseTypeOfUnitType)) : - type; + function isStringLiteralUnionType(type) { + return type.flags & 256 ? true : + type.flags & 16384 ? ts.forEach(type.types, isStringLiteralUnionType) : + false; } function isTupleType(type) { - return !!(type.flags & 131072 && type.target.flags & 262144); + return !!(type.flags & 8192); } - function getFalsyFlagsOfTypes(types) { - var result = 0; - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var t = types_8[_i]; - result |= getFalsyFlags(t); - } - return result; + function getCombinedTypeFlags(type) { + return type.flags & 16384 ? getCombinedFlagsOfTypes(type.types) : type.flags; } - function getFalsyFlags(type) { - return type.flags & 524288 ? getFalsyFlagsOfTypes(type.types) : - type.flags & 32 ? type === emptyStringType ? 32 : 0 : - type.flags & 64 ? type === zeroType ? 64 : 0 : - type.flags & 128 ? type === falseType ? 128 : 0 : - type.flags & 7406; - } - function includeFalsyTypes(type, flags) { - if ((getFalsyFlags(type) & flags) === flags) { + function addTypeKind(type, kind) { + if ((getCombinedTypeFlags(type) & kind) === kind) { return type; } var types = [type]; - if (flags & 34) - types.push(emptyStringType); - if (flags & 340) - types.push(zeroType); - if (flags & 136) - types.push(falseType); - if (flags & 1024) + if (kind & 2) + types.push(stringType); + if (kind & 4) + types.push(numberType); + if (kind & 8) + types.push(booleanType); + if (kind & 16) types.push(voidType); - if (flags & 2048) + if (kind & 32) types.push(undefinedType); - if (flags & 4096) + if (kind & 64) types.push(nullType); - return getUnionType(types, true); - } - function removeDefinitelyFalsyTypes(type) { - return getFalsyFlags(type) & 7392 ? - filterType(type, function (t) { return !(getFalsyFlags(t) & 7392); }) : - type; + return getUnionType(types); } function getNonNullableType(type) { return strictNullChecks ? getTypeWithFacts(type, 524288) : type; @@ -20946,7 +19477,7 @@ var ts; return symbol; } function transformTypeOfMembers(type, f) { - var members = ts.createMap(); + var members = {}; for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { var property = _a[_i]; var original = getTypeOfSymbol(property); @@ -20957,7 +19488,7 @@ var ts; return members; } function getRegularTypeOfObjectLiteral(type) { - if (!(type.flags & 16777216)) { + if (!(type.flags & 1048576)) { return type; } var regularType = type.regularType; @@ -20967,7 +19498,7 @@ var ts; var resolved = type; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); - regularNew.flags = resolved.flags & ~16777216; + regularNew.flags = resolved.flags & ~1048576; type.regularType = regularNew; return regularNew; } @@ -20981,28 +19512,31 @@ var ts; return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); } function getWidenedConstituentType(type) { - return type.flags & 6144 ? type : getWidenedType(type); + return type.flags & 96 ? type : getWidenedType(type); } function getWidenedType(type) { - if (type.flags & 100663296) { - if (type.flags & 6144) { + if (type.flags & 6291456) { + if (type.flags & 96) { return anyType; } - if (type.flags & 8388608) { + if (type.flags & 524288) { return getWidenedTypeOfObjectLiteral(type); } - if (type.flags & 524288) { - return getUnionType(ts.map(type.types, getWidenedConstituentType)); + if (type.flags & 16384) { + return getUnionType(ts.map(type.types, getWidenedConstituentType), true); } - if (isArrayType(type) || isTupleType(type)) { - return createTypeReference(type.target, ts.map(type.typeArguments, getWidenedType)); + if (isArrayType(type)) { + return createArrayType(getWidenedType(type.typeArguments[0])); + } + if (isTupleType(type)) { + return createTupleType(ts.map(type.elementTypes, getWidenedType)); } } return type; } function reportWideningErrorsInType(type) { var errorReported = false; - if (type.flags & 524288) { + if (type.flags & 16384) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; if (reportWideningErrorsInType(t)) { @@ -21010,19 +19544,22 @@ var ts; } } } - if (isArrayType(type) || isTupleType(type)) { - for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) { + if (isArrayType(type)) { + return reportWideningErrorsInType(type.typeArguments[0]); + } + if (isTupleType(type)) { + for (var _b = 0, _c = type.elementTypes; _b < _c.length; _b++) { var t = _c[_b]; if (reportWideningErrorsInType(t)) { errorReported = true; } } } - if (type.flags & 8388608) { + if (type.flags & 524288) { for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); - if (t.flags & 33554432) { + if (t.flags & 2097152) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, p.name, typeToString(getWidenedType(t))); } @@ -21067,7 +19604,7 @@ var ts; error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); } function reportErrorsFromWidening(declaration, type) { - if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 33554432) { + if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 2097152) { if (!reportWideningErrorsInType(type)) { reportImplicitAnyError(declaration, type); } @@ -21109,24 +19646,12 @@ var ts; isFixed: false }; } - function couldContainTypeParameters(type) { - return !!(type.flags & 16384 || - type.flags & 131072 && ts.forEach(type.typeArguments, couldContainTypeParameters) || - type.flags & 2097152 && type.symbol && type.symbol.flags & (8192 | 2048 | 32) || - type.flags & 1572864 && couldUnionOrIntersectionContainTypeParameters(type)); - } - function couldUnionOrIntersectionContainTypeParameters(type) { - if (type.couldContainTypeParameters === undefined) { - type.couldContainTypeParameters = ts.forEach(type.types, couldContainTypeParameters); - } - return type.couldContainTypeParameters; - } function inferTypes(context, source, target) { var sourceStack; var targetStack; var depth = 0; var inferiority = 0; - var visited = ts.createMap(); + var visited = {}; inferFromTypes(source, target); function isInProcess(source, target) { for (var i = 0; i < depth; i++) { @@ -21137,21 +19662,11 @@ var ts; return false; } function inferFromTypes(source, target) { - if (!couldContainTypeParameters(target)) { - return; - } - if (source.flags & 524288 && target.flags & 524288 && !(source.flags & 16 && target.flags & 16) || - source.flags & 1048576 && target.flags & 1048576) { - if (source === target) { - for (var _i = 0, _a = source.types; _i < _a.length; _i++) { - var t = _a[_i]; - inferFromTypes(t, t); - } - return; - } + if (source.flags & 16384 && target.flags & 16384 || + source.flags & 32768 && target.flags & 32768) { var matchingTypes = void 0; - for (var _b = 0, _c = target.types; _b < _c.length; _b++) { - var t = _c[_b]; + for (var _i = 0, _a = target.types; _i < _a.length; _i++) { + var t = _a[_i]; if (typeIdenticalToSomeType(t, source.types)) { (matchingTypes || (matchingTypes = [])).push(t); inferFromTypes(t, t); @@ -21162,8 +19677,8 @@ var ts; target = removeTypesFromUnionOrIntersection(target, matchingTypes); } } - if (target.flags & 16384) { - if (source.flags & 134217728) { + if (target.flags & 512) { + if (source.flags & 8388608) { return; } var typeParameters = context.typeParameters; @@ -21182,7 +19697,7 @@ var ts; } } } - else if (source.flags & 131072 && target.flags & 131072 && source.target === target.target) { + else if (source.flags & 4096 && target.flags & 4096 && source.target === target.target) { var sourceTypes = source.typeArguments || emptyArray; var targetTypes = target.typeArguments || emptyArray; var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; @@ -21190,13 +19705,20 @@ var ts; inferFromTypes(sourceTypes[i], targetTypes[i]); } } - else if (target.flags & 1572864) { + else if (source.flags & 8192 && target.flags & 8192 && source.elementTypes.length === target.elementTypes.length) { + var sourceTypes = source.elementTypes; + var targetTypes = target.elementTypes; + for (var i = 0; i < sourceTypes.length; i++) { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } + } + else if (target.flags & 49152) { var targetTypes = target.types; var typeParameterCount = 0; var typeParameter = void 0; - for (var _d = 0, targetTypes_2 = targetTypes; _d < targetTypes_2.length; _d++) { - var t = targetTypes_2[_d]; - if (t.flags & 16384 && ts.contains(context.typeParameters, t)) { + for (var _b = 0, targetTypes_2 = targetTypes; _b < targetTypes_2.length; _b++) { + var t = targetTypes_2[_b]; + if (t.flags & 512 && ts.contains(context.typeParameters, t)) { typeParameter = t; typeParameterCount++; } @@ -21210,16 +19732,18 @@ var ts; inferiority--; } } - else if (source.flags & 1572864) { + else if (source.flags & 49152) { var sourceTypes = source.types; - for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { - var sourceType = sourceTypes_3[_e]; + for (var _c = 0, sourceTypes_3 = sourceTypes; _c < sourceTypes_3.length; _c++) { + var sourceType = sourceTypes_3[_c]; inferFromTypes(sourceType, target); } } else { source = getApparentType(source); - if (source.flags & 2588672) { + if (source.flags & 80896 && (target.flags & 4096 && target.typeArguments || + target.flags & 8192 || + target.flags & 65536 && target.symbol && target.symbol.flags & (8192 | 2048 | 32))) { if (isInProcess(source, target)) { return; } @@ -21227,7 +19751,7 @@ var ts; return; } var key = source.id + "," + target.id; - if (visited[key]) { + if (ts.hasProperty(visited, key)) { return; } visited[key] = true; @@ -21296,8 +19820,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var t = types_7[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -21312,7 +19836,7 @@ var ts; reducedTypes.push(t); } } - return type.flags & 524288 ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); + return type.flags & 16384 ? getUnionType(reducedTypes, true) : getIntersectionType(reducedTypes); } function getInferenceCandidates(context, index) { var inferences = context.inferences[index]; @@ -21324,7 +19848,7 @@ var ts; if (!inferredType) { var inferences = getInferenceCandidates(context, index); if (inferences.length) { - var unionOrSuperType = context.inferUnionTypes ? getUnionType(inferences, true) : getCommonSupertype(inferences); + var unionOrSuperType = context.inferUnionTypes ? getUnionType(inferences) : getCommonSupertype(inferences); inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType; inferenceSucceeded = !!unionOrSuperType; } @@ -21390,6 +19914,10 @@ var ts; } return undefined; } + function isNullOrUndefinedLiteral(node) { + return node.kind === 93 || + node.kind === 69 && getResolvedSymbol(node) === undefinedSymbol; + } function getLeftmostIdentifierOrThis(node) { switch (node.kind) { case 69: @@ -21401,17 +19929,16 @@ var ts; return undefined; } function isMatchingReference(source, target) { - switch (source.kind) { - case 69: - return target.kind === 69 && getResolvedSymbol(source) === getResolvedSymbol(target) || - (target.kind === 218 || target.kind === 169) && - getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); - case 97: - return target.kind === 97; - case 172: - return target.kind === 172 && - source.name.text === target.name.text && - isMatchingReference(source.expression, target.expression); + if (source.kind === target.kind) { + switch (source.kind) { + case 69: + return getResolvedSymbol(source) === getResolvedSymbol(target); + case 97: + return true; + case 172: + return source.name.text === target.name.text && + isMatchingReference(source.expression, target.expression); + } } return false; } @@ -21424,40 +19951,6 @@ var ts; } return false; } - function containsMatchingReferenceDiscriminant(source, target) { - return target.kind === 172 && - containsMatchingReference(source, target.expression) && - isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.text); - } - function getDeclaredTypeOfReference(expr) { - if (expr.kind === 69) { - return getTypeOfSymbol(getResolvedSymbol(expr)); - } - if (expr.kind === 172) { - var type = getDeclaredTypeOfReference(expr.expression); - return type && getTypeOfPropertyOfType(type, expr.name.text); - } - return undefined; - } - function isDiscriminantProperty(type, name) { - if (type && type.flags & 524288) { - var prop = getPropertyOfType(type, name); - if (!prop) { - var filteredType = getTypeWithFacts(type, 4194304); - if (filteredType !== type && filteredType.flags & 524288) { - prop = getPropertyOfType(filteredType, name); - } - } - if (prop && prop.flags & 268435456) { - if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !prop.hasCommonType && - isUnitUnionType(getTypeOfSymbol(prop)); - } - return prop.isDiscriminantProperty; - } - } - return false; - } function isOrContainsMatchingReference(source, target) { return isMatchingReference(source, target) || containsMatchingReference(source, target); } @@ -21484,7 +19977,7 @@ var ts; return flow.id; } function typeMaybeAssignableTo(source, target) { - if (!(source.flags & 524288)) { + if (!(source.flags & 16384)) { return isTypeAssignableTo(source, target); } for (var _i = 0, _a = source.types; _i < _a.length; _i++) { @@ -21496,79 +19989,70 @@ var ts; return false; } function getAssignmentReducedType(declaredType, assignedType) { - if (declaredType !== assignedType) { - var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); - if (reducedType !== neverType) { - return reducedType; + if (declaredType !== assignedType && declaredType.flags & 16384) { + var reducedTypes = ts.filter(declaredType.types, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (reducedTypes.length) { + return reducedTypes.length === 1 ? reducedTypes[0] : getUnionType(reducedTypes); } } return declaredType; } - function getTypeFactsOfTypes(types) { - var result = 0; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; - result |= getTypeFacts(t); - } - return result; - } - function isFunctionObjectType(type) { - var resolved = resolveStructuredTypeMembers(type); - return !!(resolved.callSignatures.length || resolved.constructSignatures.length || - resolved.members["bind"] && isTypeSubtypeOf(type, globalFunctionType)); - } function getTypeFacts(type) { var flags = type.flags; - if (flags & 2) { + if (flags & 258) { return strictNullChecks ? 4079361 : 4194049; } - if (flags & 32) { - return strictNullChecks ? - type === emptyStringType ? 3030785 : 1982209 : - type === emptyStringType ? 3145473 : 4194049; - } - if (flags & (4 | 16)) { + if (flags & 132) { return strictNullChecks ? 4079234 : 4193922; } - if (flags & (64 | 256)) { - var isZero = type === zeroType || type.flags & 256 && type.text === "0"; - return strictNullChecks ? - isZero ? 3030658 : 1982082 : - isZero ? 3145346 : 4193922; - } if (flags & 8) { return strictNullChecks ? 4078980 : 4193668; } - if (flags & 136) { - return strictNullChecks ? - type === falseType ? 3030404 : 1981828 : - type === falseType ? 3145092 : 4193668; + if (flags & 80896) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length || resolved.constructSignatures.length || isTypeSubtypeOf(type, globalFunctionType) ? + strictNullChecks ? 1970144 : 4181984 : + strictNullChecks ? 1972176 : 4184016; } - if (flags & 2588672) { - return isFunctionObjectType(type) ? - strictNullChecks ? 6164448 : 8376288 : - strictNullChecks ? 6166480 : 8378320; - } - if (flags & (1024 | 2048)) { + if (flags & (16 | 32)) { return 2457472; } - if (flags & 4096) { + if (flags & 64) { return 2340752; } - if (flags & 512) { + if (flags & 16777216) { return strictNullChecks ? 1981320 : 4193160; } - if (flags & 16384) { + if (flags & 512) { var constraint = getConstraintOfTypeParameter(type); - return getTypeFacts(constraint || emptyObjectType); + return constraint ? getTypeFacts(constraint) : 4194303; } - if (flags & 1572864) { - return getTypeFactsOfTypes(type.types); + if (flags & 32768) { + return ts.reduceLeft(type.types, function (flags, type) { return flags |= getTypeFacts(type); }, 0); } - return 8388607; + return 4194303; } function getTypeWithFacts(type, include) { - return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); + if (!(type.flags & 16384)) { + return getTypeFacts(type) & include ? type : neverType; + } + var firstType; + var types; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (getTypeFacts(t) & include) { + if (!firstType) { + firstType = t; + } + else { + if (!types) { + types = [firstType]; + } + types.push(t); + } + } + } + return firstType ? types ? getUnionType(types, true) : firstType : neverType; } function getTypeWithDefault(type, defaultExpression) { if (defaultExpression) { @@ -21662,86 +20146,51 @@ var ts; getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } - function getInitialOrAssignedType(node) { - return node.kind === 218 || node.kind === 169 ? - getInitialType(node) : - getAssignedType(node); - } - function getReferenceCandidate(node) { + function getReferenceFromExpression(node) { switch (node.kind) { case 178: - return getReferenceCandidate(node.expression); + return getReferenceFromExpression(node.expression); case 187: switch (node.operatorToken.kind) { case 56: - return getReferenceCandidate(node.left); + return getReferenceFromExpression(node.left); case 24: - return getReferenceCandidate(node.right); + return getReferenceFromExpression(node.right); } } return node; } function getTypeOfSwitchClause(clause) { if (clause.kind === 249) { - var caseType = checkExpression(clause.expression); - return isUnitType(caseType) ? caseType : undefined; + var expr = clause.expression; + return expr.kind === 9 ? getStringLiteralTypeForText(expr.text) : checkExpression(expr); } - return neverType; + return undefined; } function getSwitchClauseTypes(switchStatement) { var links = getNodeLinks(switchStatement); if (!links.switchTypes) { var types = ts.map(switchStatement.caseBlock.clauses, getTypeOfSwitchClause); - links.switchTypes = !ts.contains(types, undefined) ? types : emptyArray; + links.switchTypes = ts.forEach(types, function (t) { return !t || t.flags & 256; }) ? types : emptyArray; } return links.switchTypes; } function eachTypeContainedIn(source, types) { - return source.flags & 524288 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); - } - function isTypeSubsetOf(source, target) { - return source === target || target.flags & 524288 && isTypeSubsetOfUnion(source, target); - } - function isTypeSubsetOfUnion(source, target) { - if (source.flags & 524288) { - for (var _i = 0, _a = source.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (!containsType(target.types, t)) { - return false; - } - } - return true; - } - if (source.flags & 256 && target.flags & 16 && source.baseType === target) { - return true; - } - return containsType(target.types, source); + return source.flags & 16384 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } function filterType(type, f) { - if (type.flags & 524288) { - var types = type.types; - var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered); - } - return f(type) ? type : neverType; + return type.flags & 16384 ? + getUnionType(ts.filter(type.types, f)) : + f(type) ? type : neverType; } - function isIncomplete(flowType) { - return flowType.flags === 0; - } - function getTypeFromFlowType(flowType) { - return flowType.flags === 0 ? flowType.type : flowType; - } - function createFlowType(type, incomplete) { - return incomplete ? { flags: 0, type: type } : type; - } - function getFlowTypeOfReference(reference, declaredType, assumeInitialized, flowContainer) { + function getFlowTypeOfReference(reference, declaredType, assumeInitialized, includeOuterFunctions) { var key; - if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 4178943)) { + if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 16908175)) { return declaredType; } - var initialType = assumeInitialized ? declaredType : includeFalsyTypes(declaredType, 2048); + var initialType = assumeInitialized ? declaredType : addTypeKind(declaredType, 32); var visitedFlowStart = visitedFlowCount; - var result = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); + var result = getTypeAtFlowNode(reference.flowNode); visitedFlowCount = visitedFlowStart; if (reference.parent.kind === 196 && getTypeWithFacts(result, 524288) === neverType) { return declaredType; @@ -21781,7 +20230,7 @@ var ts; } else if (flow.flags & 2) { var container = flow.container; - if (container && container !== flowContainer && reference.kind !== 172) { + if (container && includeOuterFunctions) { flow = container.flowNode; continue; } @@ -21800,9 +20249,16 @@ var ts; } function getTypeAtFlowAssignment(flow) { var node = flow.node; + if ((node.kind === 218 || node.kind === 169) && + reference.kind === 69 && + getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(reference)) === getSymbolOfNode(node)) { + return declaredType.flags & 16384 ? + getAssignmentReducedType(declaredType, getInitialType(node)) : + declaredType; + } if (isMatchingReference(reference, node)) { - return declaredType.flags & 524288 ? - getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : + return declaredType.flags & 16384 ? + getAssignmentReducedType(declaredType, getAssignedType(node)) : declaredType; } if (containsMatchingReference(reference, node)) { @@ -21811,55 +20267,37 @@ var ts; return undefined; } function getTypeAtFlowCondition(flow) { - var flowType = getTypeAtFlowNode(flow.antecedent); - var type = getTypeFromFlowType(flowType); + var type = getTypeAtFlowNode(flow.antecedent); if (type !== neverType) { var assumeTrue = (flow.flags & 32) !== 0; type = narrowType(type, flow.expression, assumeTrue); - if (type === neverType && isIncomplete(flowType)) { + if (type === neverType) { type = narrowType(declaredType, flow.expression, assumeTrue); } } - return createFlowType(type, isIncomplete(flowType)); + return type; } function getTypeAtSwitchClause(flow) { - var flowType = getTypeAtFlowNode(flow.antecedent); - var type = getTypeFromFlowType(flowType); - var expr = flow.switchStatement.expression; - if (isMatchingReference(reference, expr)) { - type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); - } - else if (isMatchingReferenceDiscriminant(expr)) { - type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); - } - return createFlowType(type, isIncomplete(flowType)); + var type = getTypeAtFlowNode(flow.antecedent); + return narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } function getTypeAtFlowBranchLabel(flow) { var antecedentTypes = []; - var subtypeReduction = false; - var seenIncomplete = false; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { var antecedent = _a[_i]; - var flowType = getTypeAtFlowNode(antecedent); - var type = getTypeFromFlowType(flowType); + var type = getTypeAtFlowNode(antecedent); if (type === declaredType && declaredType === initialType) { return type; } if (!ts.contains(antecedentTypes, type)) { antecedentTypes.push(type); } - if (!isTypeSubsetOf(type, declaredType)) { - subtypeReduction = true; - } - if (isIncomplete(flowType)) { - seenIncomplete = true; - } } - return createFlowType(getUnionType(antecedentTypes, subtypeReduction), seenIncomplete); + return getUnionType(antecedentTypes); } function getTypeAtFlowLoopLabel(flow) { var id = getFlowNodeId(flow); - var cache = flowLoopCaches[id] || (flowLoopCaches[id] = ts.createMap()); + var cache = flowLoopCaches[id] || (flowLoopCaches[id] = {}); if (!key) { key = getFlowCacheKey(reference); } @@ -21868,66 +20306,32 @@ var ts; } for (var i = flowLoopStart; i < flowLoopCount; i++) { if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key) { - return createFlowType(getUnionType(flowLoopTypes[i]), true); + return getUnionType(flowLoopTypes[i]); } } var antecedentTypes = []; - var subtypeReduction = false; - var firstAntecedentType; flowLoopNodes[flowLoopCount] = flow; flowLoopKeys[flowLoopCount] = key; flowLoopTypes[flowLoopCount] = antecedentTypes; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { var antecedent = _a[_i]; flowLoopCount++; - var flowType = getTypeAtFlowNode(antecedent); + var type = getTypeAtFlowNode(antecedent); flowLoopCount--; - if (!firstAntecedentType) { - firstAntecedentType = flowType; - } - var type = getTypeFromFlowType(flowType); if (cache[key]) { return cache[key]; } if (!ts.contains(antecedentTypes, type)) { antecedentTypes.push(type); } - if (!isTypeSubsetOf(type, declaredType)) { - subtypeReduction = true; - } if (type === declaredType) { break; } } - var result = getUnionType(antecedentTypes, subtypeReduction); - if (isIncomplete(firstAntecedentType)) { - return createFlowType(result, true); - } - return cache[key] = result; - } - function isMatchingReferenceDiscriminant(expr) { - return expr.kind === 172 && - declaredType.flags & 524288 && - isMatchingReference(reference, expr.expression) && - isDiscriminantProperty(declaredType, expr.name.text); - } - function narrowTypeByDiscriminant(type, propAccess, narrowType) { - var propName = propAccess.name.text; - var propType = getTypeOfPropertyOfType(type, propName); - var narrowedPropType = propType && narrowType(propType); - return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); + return cache[key] = getUnionType(antecedentTypes); } function narrowTypeByTruthiness(type, expr, assumeTrue) { - if (isMatchingReference(reference, expr)) { - return getTypeWithFacts(type, assumeTrue ? 1048576 : 2097152); - } - if (isMatchingReferenceDiscriminant(expr)) { - return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 1048576 : 2097152); }); - } - if (containsMatchingReferenceDiscriminant(reference, expr)) { - return declaredType; - } - return type; + return isMatchingReference(reference, expr) ? getTypeWithFacts(type, assumeTrue ? 1048576 : 2097152) : type; } function narrowTypeByBinaryExpression(type, expr, assumeTrue) { switch (expr.operatorToken.kind) { @@ -21937,29 +20341,26 @@ var ts; case 31: case 32: case 33: - var operator_1 = expr.operatorToken.kind; - var left_1 = getReferenceCandidate(expr.left); - var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 182 && right_1.kind === 9) { - return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); + var left = expr.left; + var operator = expr.operatorToken.kind; + var right = expr.right; + if (isNullOrUndefinedLiteral(right)) { + return narrowTypeByNullCheck(type, left, operator, right, assumeTrue); } - if (right_1.kind === 182 && left_1.kind === 9) { - return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); + if (isNullOrUndefinedLiteral(left)) { + return narrowTypeByNullCheck(type, right, operator, left, assumeTrue); } - if (isMatchingReference(reference, left_1)) { - return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); + if (left.kind === 182 && right.kind === 9) { + return narrowTypeByTypeof(type, left, operator, right, assumeTrue); } - if (isMatchingReference(reference, right_1)) { - return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); + if (right.kind === 182 && left.kind === 9) { + return narrowTypeByTypeof(type, right, operator, left, assumeTrue); } - if (isMatchingReferenceDiscriminant(left_1)) { - return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); + if (left.kind === 172) { + return narrowTypeByDiscriminant(type, left, operator, right, assumeTrue); } - if (isMatchingReferenceDiscriminant(right_1)) { - return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); - } - if (containsMatchingReferenceDiscriminant(reference, left_1) || containsMatchingReferenceDiscriminant(reference, right_1)) { - return declaredType; + if (right.kind === 172) { + return narrowTypeByDiscriminant(type, right, operator, left, assumeTrue); } break; case 91: @@ -21969,37 +20370,23 @@ var ts; } return type; } - function narrowTypeByEquality(type, operator, value, assumeTrue) { - if (type.flags & 1) { - return type; - } + function narrowTypeByNullCheck(type, target, operator, literal, assumeTrue) { if (operator === 31 || operator === 33) { assumeTrue = !assumeTrue; } - var valueType = checkExpression(value); - if (valueType.flags & 6144) { - if (!strictNullChecks) { - return type; - } - var doubleEquals = operator === 30 || operator === 31; - var facts = doubleEquals ? - assumeTrue ? 65536 : 524288 : - value.kind === 93 ? - assumeTrue ? 32768 : 262144 : - assumeTrue ? 16384 : 131072; - return getTypeWithFacts(type, facts); - } - if (type.flags & 2589191) { + if (!strictNullChecks || !isMatchingReference(reference, getReferenceFromExpression(target))) { return type; } - if (assumeTrue) { - var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType !== neverType ? narrowedType : type; - } - return isUnitType(valueType) ? filterType(type, function (t) { return t !== valueType; }) : type; + var doubleEquals = operator === 30 || operator === 31; + var facts = doubleEquals ? + assumeTrue ? 65536 : 524288 : + literal.kind === 93 ? + assumeTrue ? 32768 : 262144 : + assumeTrue ? 16384 : 131072; + return getTypeWithFacts(type, facts); } function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { - var target = getReferenceCandidate(typeOfExpr.expression); + var target = getReferenceFromExpression(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { if (containsMatchingReference(reference, target)) { return declaredType; @@ -22009,40 +20396,76 @@ var ts; if (operator === 31 || operator === 33) { assumeTrue = !assumeTrue; } - if (assumeTrue && !(type.flags & 524288)) { - var targetType = typeofTypesByName[literal.text]; + if (assumeTrue && !(type.flags & 16384)) { + var targetType = ts.getProperty(typeofTypesByName, literal.text); if (targetType && isTypeSubtypeOf(targetType, type)) { return targetType; } } var facts = assumeTrue ? - typeofEQFacts[literal.text] || 64 : - typeofNEFacts[literal.text] || 8192; + ts.getProperty(typeofEQFacts, literal.text) || 64 : + ts.getProperty(typeofNEFacts, literal.text) || 8192; return getTypeWithFacts(type, facts); } + function narrowTypeByDiscriminant(type, propAccess, operator, value, assumeTrue) { + if (!isMatchingReference(reference, propAccess.expression)) { + return type; + } + var propName = propAccess.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return type; + } + var discriminantType = value.kind === 9 ? getStringLiteralTypeForText(value.text) : checkExpression(value); + if (!isStringLiteralUnionType(discriminantType)) { + return type; + } + if (operator === 31 || operator === 33) { + assumeTrue = !assumeTrue; + } + if (assumeTrue) { + return filterType(type, function (t) { return areTypesComparable(getTypeOfPropertyOfType(t, propName), discriminantType); }); + } + if (discriminantType.flags & 256) { + return filterType(type, function (t) { return getTypeOfPropertyOfType(t, propName) !== discriminantType; }); + } + return type; + } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { + if (!isMatchingReference(reference, switchStatement.expression.expression)) { + return type; + } + var propName = switchStatement.expression.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return type; + } var switchTypes = getSwitchClauseTypes(switchStatement); if (!switchTypes.length) { return type; } var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); - var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); - var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType === neverType ? neverType : filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }); + var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, undefined); + var caseTypes = hasDefaultClause ? ts.filter(clauseTypes, function (t) { return !!t; }) : clauseTypes; + var discriminantType = caseTypes.length ? getUnionType(caseTypes) : undefined; + var caseType = discriminantType && filterType(type, function (t) { return isTypeComparableTo(discriminantType, getTypeOfPropertyOfType(t, propName)); }); if (!hasDefaultClause) { return caseType; } - var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, t)); }); - return caseType === neverType ? defaultType : getUnionType([caseType, defaultType]); + var defaultType = filterType(type, function (t) { return !eachTypeContainedIn(getTypeOfPropertyOfType(t, propName), switchTypes); }); + return caseType ? getUnionType([caseType, defaultType]) : defaultType; } function narrowTypeByInstanceof(type, expr, assumeTrue) { - var left = getReferenceCandidate(expr.left); + var left = getReferenceFromExpression(expr.left); if (!isMatchingReference(reference, left)) { if (containsMatchingReference(reference, left)) { return declaredType; } return type; } + if (isTypeAny(type)) { + return type; + } var rightType = checkExpression(expr.right); if (!isTypeSubtypeOf(rightType, globalFunctionType)) { return type; @@ -22055,15 +20478,12 @@ var ts; targetType = prototypePropertyType; } } - if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) { - return type; - } if (!targetType) { var constructSignatures = void 0; - if (rightType.flags & 65536) { + if (rightType.flags & 2048) { constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; } - else if (rightType.flags & 2097152) { + else if (rightType.flags & 65536) { constructSignatures = getSignaturesOfType(rightType, 1); } if (constructSignatures && constructSignatures.length) { @@ -22077,22 +20497,23 @@ var ts; } function getNarrowedType(type, candidate, assumeTrue) { if (!assumeTrue) { - return filterType(type, function (t) { return !isTypeInstanceOf(t, candidate); }); + return type.flags & 16384 ? + getUnionType(ts.filter(type.types, function (t) { return !isTypeSubtypeOf(t, candidate); })) : + type; } - if (type.flags & 524288) { - var assignableType = filterType(type, function (t) { return isTypeInstanceOf(t, candidate); }); - if (assignableType !== neverType) { - return assignableType; + if (type.flags & 16384) { + var assignableConstituents = ts.filter(type.types, function (t) { return isTypeAssignableTo(t, candidate); }); + if (assignableConstituents.length) { + return getUnionType(assignableConstituents); } } - var targetType = type.flags & 16384 ? getApparentType(type) : type; - return isTypeSubtypeOf(candidate, type) ? candidate : + var targetType = type.flags & 512 ? getApparentType(type) : type; + return isTypeAssignableTo(candidate, targetType) ? candidate : isTypeAssignableTo(type, candidate) ? type : - isTypeAssignableTo(candidate, targetType) ? candidate : - getIntersectionType([type, candidate]); + getIntersectionType([type, candidate]); } function narrowTypeByTypePredicate(type, callExpression, assumeTrue) { - if (!hasMatchingArgument(callExpression, reference)) { + if (type.flags & 1 || !hasMatchingArgument(callExpression, reference)) { return type; } var signature = getResolvedSignature(callExpression); @@ -22100,9 +20521,6 @@ var ts; if (!predicate) { return type; } - if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { - return type; - } if (ts.isIdentifierTypePredicate(predicate)) { var predicateArgument = callExpression.arguments[predicate.parameterIndex]; if (predicateArgument) { @@ -22173,48 +20591,20 @@ var ts; function getControlFlowContainer(node) { while (true) { node = node.parent; - if (ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || - node.kind === 226 || - node.kind === 256 || - node.kind === 145) { + if (ts.isFunctionLike(node) || node.kind === 226 || node.kind === 256 || node.kind === 145) { return node; } } } - function isParameterAssigned(symbol) { - var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; - var links = getNodeLinks(func); - if (!(links.flags & 4194304)) { - links.flags |= 4194304; - if (!hasParentWithAssignmentsMarked(func)) { - markParameterAssignments(func); - } - } - return symbol.isAssigned || false; - } - function hasParentWithAssignmentsMarked(node) { - while (true) { - node = node.parent; - if (!node) { - return false; - } - if (ts.isFunctionLike(node) && getNodeLinks(node).flags & 4194304) { - return true; - } - } - } - function markParameterAssignments(node) { - if (node.kind === 69) { - if (ts.isAssignmentTarget(node)) { - var symbol = getResolvedSymbol(node); - if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 142) { - symbol.isAssigned = true; - } - } - } - else { - ts.forEachChild(node, markParameterAssignments); + function isDeclarationIncludedInFlow(reference, declaration, includeOuterFunctions) { + var declarationContainer = getControlFlowContainer(declaration); + var container = getControlFlowContainer(reference); + while (container !== declarationContainer && + (container.kind === 179 || container.kind === 180) && + (includeOuterFunctions || ts.getImmediatelyInvokedFunctionExpression(container))) { + container = getControlFlowContainer(container); } + return container === declarationContainer; } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); @@ -22251,23 +20641,16 @@ var ts; checkCollisionWithCapturedThisVariable(node, node); checkNestedBlockScopedBinding(node, symbol); var type = getTypeOfSymbol(localOrExportSymbol); - var declaration = localOrExportSymbol.valueDeclaration; - if (!(localOrExportSymbol.flags & 3) || ts.isAssignmentTarget(node) || !declaration) { + if (!(localOrExportSymbol.flags & 3) || ts.isAssignmentTarget(node)) { return type; } - var isParameter = ts.getRootDeclaration(declaration).kind === 142; - var declarationContainer = getControlFlowContainer(declaration); - var flowContainer = getControlFlowContainer(node); - var isOuterVariable = flowContainer !== declarationContainer; - while (flowContainer !== declarationContainer && - (flowContainer.kind === 179 || flowContainer.kind === 180) && - (isReadonlySymbol(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { - flowContainer = getControlFlowContainer(flowContainer); - } - var assumeInitialized = !strictNullChecks || (type.flags & 1) !== 0 || isParameter || - isOuterVariable || ts.isInAmbientContext(declaration); - var flowType = getFlowTypeOfReference(node, type, assumeInitialized, flowContainer); - if (!assumeInitialized && !(getFalsyFlags(type) & 2048) && getFalsyFlags(flowType) & 2048) { + var declaration = localOrExportSymbol.valueDeclaration; + var includeOuterFunctions = isReadonlySymbol(localOrExportSymbol); + var assumeInitialized = !strictNullChecks || (type.flags & 1) !== 0 || !declaration || + ts.getRootDeclaration(declaration).kind === 142 || ts.isInAmbientContext(declaration) || + !isDeclarationIncludedInFlow(node, declaration, includeOuterFunctions); + var flowType = getFlowTypeOfReference(node, type, assumeInitialized, includeOuterFunctions); + if (!assumeInitialized && !(getCombinedTypeFlags(type) & 32) && getCombinedTypeFlags(flowType) & 32) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); return type; } @@ -22430,6 +20813,10 @@ var ts; return getInferredClassType(classSymbol); } } + var type = getContextuallyTypedThisType(container); + if (type) { + return type; + } var thisType = getThisTypeOfDeclaration(container); if (thisType) { return thisType; @@ -22438,7 +20825,7 @@ var ts; if (ts.isClassLike(container.parent)) { var symbol = getSymbolOfNode(container.parent); var type = container.flags & 32 ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; - return getFlowTypeOfReference(node, type, true, undefined); + return getFlowTypeOfReference(node, type, true, true); } if (ts.isInJavaScriptFile(node)) { var type = getTypeForThisExpressionFromJSDoc(container); @@ -22571,11 +20958,11 @@ var ts; return false; } } - function getContextualThisParameter(func) { + function getContextuallyTypedThisType(func) { if (isContextSensitiveFunctionOrObjectLiteralMethod(func) && func.kind !== 180) { var contextualSignature = getContextualSignature(func); if (contextualSignature) { - return contextualSignature.thisParameter; + return getThisTypeOfSignature(contextualSignature); } } return undefined; @@ -22632,15 +21019,15 @@ var ts; } } if (ts.isBindingPattern(declaration.name)) { - return getTypeFromBindingPattern(declaration.name, true, false); + return getTypeFromBindingPattern(declaration.name, true); } if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; - var name_15 = declaration.propertyName || declaration.name; + var name_13 = declaration.propertyName || declaration.name; if (ts.isVariableLike(parentDeclaration) && parentDeclaration.type && - !ts.isBindingPattern(name_15)) { - var text = getTextOfPropertyName(name_15); + !ts.isBindingPattern(name_13)) { + var text = getTextOfPropertyName(name_13); if (text) { return getTypeOfPropertyOfType(getTypeFromTypeNode(parentDeclaration.type), text); } @@ -22715,9 +21102,6 @@ var ts; var binaryExpression = node.parent; var operator = binaryExpression.operatorToken.kind; if (operator >= 56 && operator <= 68) { - if (ts.getSpecialPropertyAssignmentKind(binaryExpression) !== 0) { - return undefined; - } if (node === binaryExpression.right) { return checkExpression(binaryExpression.left); } @@ -22737,14 +21121,14 @@ var ts; return undefined; } function applyToContextualType(type, mapper) { - if (!(type.flags & 524288)) { + if (!(type.flags & 16384)) { return mapper(type); } var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var current = types_11[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var current = types_8[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -22762,7 +21146,7 @@ var ts; } function getTypeOfPropertyOfContextualType(type, name) { return applyToContextualType(type, function (t) { - var prop = t.flags & 4161536 ? getPropertyOfType(t, name) : undefined; + var prop = t.flags & 130048 ? getPropertyOfType(t, name) : undefined; return prop ? getTypeOfSymbol(prop) : undefined; }); } @@ -22770,7 +21154,7 @@ var ts; return applyToContextualType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); } function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 524288 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); + return !!(type.flags & 16384 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); } function getContextualTypeForObjectLiteralMethod(node) { ts.Debug.assert(ts.isObjectLiteralMethod(node)); @@ -22876,30 +21260,6 @@ var ts; } return undefined; } - function isLiteralTypeLocation(node) { - var parent = node.parent; - switch (parent.kind) { - case 187: - switch (parent.operatorToken.kind) { - case 32: - case 33: - case 30: - case 31: - return true; - } - break; - case 188: - return (node === parent.whenTrue || - node === parent.whenFalse) && - isLiteralTypeLocation(parent); - case 178: - return isLiteralTypeLocation(parent); - case 249: - case 166: - return true; - } - return false; - } function getNonGenericSignature(type) { var signatures = getSignaturesOfStructuredType(type, 0); if (signatures.length === 1) { @@ -22928,13 +21288,13 @@ var ts; if (!type) { return undefined; } - if (!(type.flags & 524288)) { + if (!(type.flags & 16384)) { return getNonGenericSignature(type); } var signatureList; var types = type.types; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var current = types_12[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var current = types_9[_i]; var signature = getNonGenericSignature(current); if (signature) { if (!signatureList) { @@ -22990,7 +21350,7 @@ var ts; } if (!hasSpreadElement) { if (inDestructuringPattern && elementTypes.length) { - var type = cloneTypeReference(createTupleType(elementTypes)); + var type = createNewTupleType(elementTypes); type.pattern = node; return type; } @@ -23002,7 +21362,7 @@ var ts; for (var i = elementTypes.length; i < patternElements.length; i++) { var patternElement = patternElements[i]; if (hasDefaultValue(patternElement)) { - elementTypes.push(contextualType.typeArguments[i]); + elementTypes.push(contextualType.elementTypes[i]); } else { if (patternElement.kind !== 193) { @@ -23017,15 +21377,13 @@ var ts; } } } - return createArrayType(elementTypes.length ? - getUnionType(elementTypes, true) : - strictNullChecks ? neverType : undefinedWideningType); + return createArrayType(elementTypes.length ? getUnionType(elementTypes) : strictNullChecks ? neverType : undefinedWideningType); } function isNumericName(name) { return name.kind === 140 ? isNumericComputedName(name) : isNumericLiteralName(name.text); } function isNumericComputedName(name) { - return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 340); + return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 132); } function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { return isTypeAny(type) || isTypeOfKind(type, kind); @@ -23037,7 +21395,7 @@ var ts; var links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); - if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 340 | 34 | 512)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 132 | 258 | 16777216)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -23053,13 +21411,13 @@ var ts; propTypes.push(getTypeOfSymbol(properties[i])); } } - var unionType = propTypes.length ? getUnionType(propTypes, true) : undefinedType; + var unionType = propTypes.length ? getUnionType(propTypes) : undefinedType; return createIndexInfo(unionType, false); } function checkObjectLiteral(node, contextualMapper) { var inDestructuringPattern = ts.isAssignmentTarget(node); checkGrammarObjectLiteralExpression(node, inDestructuringPattern); - var propertiesTable = ts.createMap(); + var propertiesTable = {}; var propertiesArray = []; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && @@ -23097,7 +21455,7 @@ var ts; patternWithComputedProperties = true; } } - else if (contextualTypeHasPattern && !(contextualType.flags & 536870912)) { + else if (contextualTypeHasPattern && !(contextualType.flags & 67108864)) { var impliedProp = getPropertyOfType(contextualType, member.name); if (impliedProp) { prop.flags |= impliedProp.flags & 536870912; @@ -23135,7 +21493,7 @@ var ts; if (contextualTypeHasPattern) { for (var _b = 0, _c = getPropertiesOfType(contextualType); _b < _c.length; _b++) { var prop = _c[_b]; - if (!propertiesTable[prop.name]) { + if (!ts.hasProperty(propertiesTable, prop.name)) { if (!(prop.flags & 536870912)) { error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } @@ -23147,8 +21505,8 @@ var ts; var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 0) : undefined; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 1) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16777216; - result.flags |= 8388608 | 67108864 | freshObjectLiteralFlag | (typeFlags & 234881024) | (patternWithComputedProperties ? 536870912 : 0); + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576; + result.flags |= 524288 | 4194304 | freshObjectLiteralFlag | (typeFlags & 14680064) | (patternWithComputedProperties ? 67108864 : 0); if (inDestructuringPattern) { result.pattern = node; } @@ -23202,9 +21560,9 @@ var ts; var correspondingPropSymbol = getPropertyOfType(elementAttributesType, node.name.text); correspondingPropType = correspondingPropSymbol && getTypeOfSymbol(correspondingPropSymbol); if (isUnhyphenatedJsxName(node.name.text)) { - var attributeType = getTypeOfPropertyOfType(elementAttributesType, getTextOfPropertyName(node.name)) || getIndexTypeOfType(elementAttributesType, 0); - if (attributeType) { - correspondingPropType = attributeType; + var indexerType = getIndexTypeOfType(elementAttributesType, 0); + if (indexerType) { + correspondingPropType = indexerType; } else { if (!correspondingPropType) { @@ -23277,7 +21635,7 @@ var ts; return links.resolvedSymbol; } function getJsxElementInstanceType(node, valueType) { - ts.Debug.assert(!(valueType.flags & 524288)); + ts.Debug.assert(!(valueType.flags & 16384)); if (isTypeAny(valueType)) { return anyType; } @@ -23289,11 +21647,11 @@ var ts; return unknownType; } } - return getUnionType(signatures.map(getReturnTypeOfSignature), true); + return getUnionType(signatures.map(getReturnTypeOfSignature)); } function getJsxElementPropertiesName() { - var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920, undefined); - var attribsPropTypeSym = jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.ElementAttributesPropertyNameContainer, 793064); + var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1536, undefined); + var attribsPropTypeSym = jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.ElementAttributesPropertyNameContainer, 793056); var attribPropType = attribsPropTypeSym && getDeclaredTypeOfSymbol(attribsPropTypeSym); var attribProperties = attribPropType && getPropertiesOfType(attribPropType); if (attribProperties) { @@ -23316,16 +21674,16 @@ var ts; if (!elemType) { elemType = checkExpression(node.tagName); } - if (elemType.flags & 524288) { + if (elemType.flags & 16384) { var types = elemType.types; return getUnionType(types.map(function (type) { return getResolvedJsxType(node, type, elemClassType); - }), true); + })); } if (elemType.flags & 2) { return anyType; } - else if (elemType.flags & 32) { + else if (elemType.flags & 256) { var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { var stringLiteralTypeName = elemType.text; @@ -23378,7 +21736,7 @@ var ts; else if (isTypeAny(attributesType) || (attributesType === unknownType)) { return attributesType; } - else if (attributesType.flags & 524288) { + else if (attributesType.flags & 16384) { error(node.tagName, ts.Diagnostics.JSX_element_attributes_type_0_may_not_be_a_union_type, typeToString(attributesType)); return anyType; } @@ -23461,7 +21819,7 @@ var ts; getSymbolLinks(reactSym).referenced = true; } var targetAttributesType = getJsxElementAttributesType(node); - var nameTable = ts.createMap(); + var nameTable = {}; var sawSpreadedAny = false; for (var i = node.attributes.length - 1; i >= 0; i--) { if (node.attributes[i].kind === 246) { @@ -23479,7 +21837,7 @@ var ts; var targetProperties = getPropertiesOfType(targetAttributesType); for (var i = 0; i < targetProperties.length; i++) { if (!(targetProperties[i].flags & 536870912) && - !nameTable[targetProperties[i].name]) { + nameTable[targetProperties[i].name] === undefined) { error(node, ts.Diagnostics.Property_0_is_missing_in_type_1, targetProperties[i].name, typeToString(targetAttributesType)); } } @@ -23540,10 +21898,10 @@ var ts; if (flags & 32) { return true; } - if (type.flags & 268435456) { + if (type.flags & 33554432) { type = getConstraintOfTypeParameter(type); } - if (!(getTargetType(type).flags & (32768 | 65536) && hasBaseType(type, enclosingClass))) { + if (!(getTargetType(type).flags & (1024 | 2048) && hasBaseType(type, enclosingClass))) { error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); return false; } @@ -23552,9 +21910,9 @@ var ts; function checkNonNullExpression(node) { var type = checkExpression(node); if (strictNullChecks) { - var kind = getFalsyFlags(type) & 6144; + var kind = getCombinedTypeFlags(type) & 96; if (kind) { - error(node, kind & 2048 ? kind & 4096 ? + error(node, kind & 32 ? kind & 64 ? ts.Diagnostics.Object_is_possibly_null_or_undefined : ts.Diagnostics.Object_is_possibly_undefined : ts.Diagnostics.Object_is_possibly_null); @@ -23575,13 +21933,13 @@ var ts; return type; } var apparentType = getApparentType(getWidenedType(type)); - if (apparentType === unknownType || (type.flags & 16384 && isTypeAny(apparentType))) { + if (apparentType === unknownType || (type.flags & 512 && isTypeAny(apparentType))) { return apparentType; } var prop = getPropertyOfType(apparentType, right.text); if (!prop) { if (right.text && !checkAndReportErrorForExtendingInterface(node)) { - error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type.flags & 268435456 ? apparentType : type)); + error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type.flags & 33554432 ? apparentType : type)); } return unknownType; } @@ -23600,15 +21958,12 @@ var ts; checkClassPropertyAccess(node, left, apparentType, prop); } var propType = getTypeOfSymbol(prop); - if (prop.flags & 8 && isLiteralContextForType(node, propType)) { - propType = getDeclaredTypeOfSymbol(prop); - } if (node.kind !== 172 || ts.isAssignmentTarget(node) || !(prop.flags & (3 | 4 | 98304)) && - !(prop.flags & 8192 && propType.flags & 524288)) { + !(prop.flags & 8192 && propType.flags & 16384)) { return propType; } - return getFlowTypeOfReference(node, propType, true, undefined); + return getFlowTypeOfReference(node, propType, true, false); } function isValidPropertyAccess(node, propertyName) { var left = node.kind === 172 @@ -23686,22 +22041,21 @@ var ts; return unknownType; } if (node.argumentExpression) { - var name_16 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); - if (name_16 !== undefined) { - var prop = getPropertyOfType(objectType, name_16); + var name_14 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); + if (name_14 !== undefined) { + var prop = getPropertyOfType(objectType, name_14); if (prop) { getNodeLinks(node).resolvedSymbol = prop; return getTypeOfSymbol(prop); } else if (isConstEnum) { - error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_16, symbolToString(objectType.symbol)); + error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_14, symbolToString(objectType.symbol)); return unknownType; } } } - var allowedNullableFlags = strictNullChecks ? 0 : 6144; - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 34 | 340 | 512 | allowedNullableFlags)) { - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 | allowedNullableFlags) || isForInVariableForNumericPropertyNames(node.argumentExpression)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 258 | 132 | 16777216)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 132) || isForInVariableForNumericPropertyNames(node.argumentExpression)) { var numberIndexInfo = getIndexInfoOfType(objectType, 1); if (numberIndexInfo) { getNodeLinks(node).resolvedIndexInfo = numberIndexInfo; @@ -23746,7 +22100,7 @@ var ts; if (!ts.isWellKnownSymbolSyntactically(expression)) { return false; } - if ((expressionType.flags & 512) === 0) { + if ((expressionType.flags & 16777216) === 0) { if (reportError) { error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); } @@ -23810,7 +22164,7 @@ var ts; lastParent = parent_9; } lastSymbol = symbol; - if (signature.hasLiteralTypes) { + if (signature.hasStringLiterals) { specializedIndex++; spliceIndex = specializedIndex; cutoffIndex++; @@ -23884,7 +22238,7 @@ var ts; return callIsIncomplete || hasEnoughArguments; } function getSingleCallSignature(type) { - if (type.flags & 2588672) { + if (type.flags & 80896) { var resolved = resolveStructuredTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -23984,7 +22338,9 @@ var ts; var paramType = getTypeAtPosition(signature, i); var argType = getEffectiveArgumentType(node, i, arg); if (argType === undefined) { - argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + argType = arg.kind === 9 && !reportErrors + ? getStringLiteralTypeForText(arg.text) + : checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); } var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; if (!checkTypeRelatedTo(argType, paramType, relation, errorNode, headMessage)) { @@ -24088,10 +22444,10 @@ var ts; case 69: case 8: case 9: - return getLiteralTypeForText(32, element.name.text); + return getStringLiteralTypeForText(element.name.text); case 140: var nameType = checkComputedPropertyName(element.name); - if (isTypeOfKind(nameType, 512)) { + if (isTypeOfKind(nameType, 16777216)) { return nameType; } else { @@ -24331,7 +22687,9 @@ var ts; } var callSignatures = getSignaturesOfType(apparentType, 0); var constructSignatures = getSignaturesOfType(apparentType, 1); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + if (isTypeAny(funcType) || + (isTypeAny(apparentType) && funcType.flags & 512) || + (!callSignatures.length && !constructSignatures.length && !(funcType.flags & 16384) && isTypeAssignableTo(funcType, globalFunctionType))) { if (funcType !== unknownType && node.typeArguments) { error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); } @@ -24348,21 +22706,6 @@ var ts; } return resolveCall(node, callSignatures, candidatesOutArray); } - function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { - if (isTypeAny(funcType)) { - return true; - } - if (isTypeAny(apparentFuncType) && funcType.flags & 16384) { - return true; - } - if (!numCallSignatures && !numConstructSignatures) { - if (funcType.flags & 524288) { - return false; - } - return isTypeAssignableTo(funcType, globalFunctionType); - } - return false; - } function resolveNewExpression(node, candidatesOutArray) { if (node.arguments && languageVersion < 1) { var spreadIndex = getSpreadArgumentIndex(node.arguments); @@ -24419,18 +22762,6 @@ var ts; var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); if (!isNodeWithinClass(node, declaringClassDeclaration)) { - var containingClass = ts.getContainingClass(node); - if (containingClass) { - var containingType = getTypeOfNode(containingClass); - var baseTypes = getBaseTypes(containingType); - if (baseTypes.length) { - var baseType = baseTypes[0]; - if (flags & 16 && - baseType.symbol === declaration.parent.symbol) { - return true; - } - } - } if (flags & 8) { error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); } @@ -24448,8 +22779,7 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0); - var constructSignatures = getSignaturesOfType(apparentType, 1); - if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { + if (isTypeAny(tagType) || (!callSignatures.length && !(tagType.flags & 16384) && isTypeAssignableTo(tagType, globalFunctionType))) { return resolveUntypedCall(node); } if (!callSignatures.length) { @@ -24480,8 +22810,7 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0); - var constructSignatures = getSignaturesOfType(apparentType, 1); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + if (funcType === anyType || (!callSignatures.length && !(funcType.flags & 16384) && isTypeAssignableTo(funcType, globalFunctionType))) { return resolveUntypedCall(node); } var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); @@ -24510,21 +22839,21 @@ var ts; function getResolvedSignature(node, candidatesOutArray) { var links = getNodeLinks(node); var cached = links.resolvedSignature; - if (cached && cached !== resolvingSignature && !candidatesOutArray) { + if (cached && cached !== anySignature && !candidatesOutArray) { return cached; } - links.resolvedSignature = resolvingSignature; + links.resolvedSignature = anySignature; var result = resolveSignature(node, candidatesOutArray); links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached; return result; } function getResolvedOrAnySignature(node) { - return getNodeLinks(node).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(node); + return getNodeLinks(node).resolvedSignature === anySignature ? anySignature : getResolvedSignature(node); } function getInferredClassType(symbol) { var links = getSymbolLinks(symbol); if (!links.inferredClassType) { - links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, undefined, undefined); + links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, undefined, undefined); } return links.inferredClassType; } @@ -24581,7 +22910,7 @@ var ts; if (strictNullChecks) { var declaration = symbol.valueDeclaration; if (declaration && declaration.initializer) { - return includeFalsyTypes(type, 2048); + return addTypeKind(type, 32); } } return type; @@ -24593,12 +22922,6 @@ var ts; } function assignContextualParameterTypes(signature, context, mapper) { var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); - if (context.thisParameter) { - if (!signature.thisParameter) { - signature.thisParameter = createTransientSymbol(context.thisParameter, undefined); - } - assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter), mapper); - } for (var i = 0; i < len; i++) { var parameter = signature.parameters[i]; var contextualParameterType = getTypeAtPosition(context, i); @@ -24696,7 +23019,7 @@ var ts; return isAsync ? createPromiseReturnType(func, voidType) : voidType; } } - type = contextualSignature ? getUnionType(types, true) : getCommonSupertype(types); + type = contextualSignature ? getUnionType(types) : getCommonSupertype(types); if (!type) { if (funcIsGenerator) { error(func, ts.Diagnostics.No_best_common_type_exists_among_yield_expressions); @@ -24704,7 +23027,7 @@ var ts; } else { error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); - return isAsync ? createPromiseReturnType(func, getUnionType(types, true)) : getUnionType(types, true); + return isAsync ? createPromiseReturnType(func, getUnionType(types)) : getUnionType(types); } } if (funcIsGenerator) { @@ -24734,18 +23057,24 @@ var ts; return aggregatedTypes; } function isExhaustiveSwitchStatement(node) { - if (!node.possiblyExhaustive) { + var expr = node.expression; + if (!node.possiblyExhaustive || expr.kind !== 172) { return false; } - var type = checkExpression(node.expression); - if (!isUnitUnionType(type)) { + var type = checkExpression(expr.expression); + if (!(type.flags & 16384)) { + return false; + } + var propName = expr.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { return false; } var switchTypes = getSwitchClauseTypes(node); if (!switchTypes.length) { return false; } - return eachTypeContainedIn(type, switchTypes); + return eachTypeContainedIn(propType, switchTypes); } function functionHasImplicitReturn(func) { if (!(func.flags & 32768)) { @@ -24795,7 +23124,7 @@ var ts; if (!produceDiagnostics) { return; } - if (returnType && maybeTypeOfKind(returnType, 1 | 1024)) { + if (returnType && maybeTypeOfKind(returnType, 1 | 16)) { return; } if (ts.nodeIsMissing(func.body) || func.body.kind !== 199 || !functionHasImplicitReturn(func)) { @@ -24897,7 +23226,7 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 340)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 132)) { error(operand, diagnostic); return false; } @@ -24991,22 +23320,16 @@ var ts; } function checkPrefixUnaryExpression(node) { var operandType = checkExpression(node.operand); - if (node.operator === 36 && node.operand.kind === 8 && isLiteralContextForType(node, numberType)) { - return getLiteralTypeForText(64, "" + -node.operand.text); - } switch (node.operator) { case 35: case 36: case 50: - if (maybeTypeOfKind(operandType, 512)) { + if (maybeTypeOfKind(operandType, 16777216)) { error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } return numberType; case 49: - var facts = getTypeFacts(operandType) & (1048576 | 2097152); - return facts === 1048576 ? falseType : - facts === 2097152 ? trueType : - booleanType; + return booleanType; case 41: case 42: var ok = checkArithmeticOperandType(node.operand, getNonNullableType(operandType), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); @@ -25029,10 +23352,10 @@ var ts; if (type.flags & kind) { return true; } - if (type.flags & 1572864) { + if (type.flags & 49152) { var types = type.types; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -25044,20 +23367,20 @@ var ts; if (type.flags & kind) { return true; } - if (type.flags & 524288) { + if (type.flags & 16384) { var types = type.types; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; if (!isTypeOfKind(t, kind)) { return false; } } return true; } - if (type.flags & 1048576) { + if (type.flags & 32768) { var types = type.types; - for (var _a = 0, types_15 = types; _a < types_15.length; _a++) { - var t = types_15[_a]; + for (var _a = 0, types_12 = types; _a < types_12.length; _a++) { + var t = types_12[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -25066,13 +23389,13 @@ var ts; return false; } function isConstEnumObjectType(type) { - return type.flags & (2588672 | 2097152) && type.symbol && isConstEnumSymbol(type.symbol); + return type.flags & (80896 | 65536) && type.symbol && isConstEnumSymbol(type.symbol); } function isConstEnumSymbol(symbol) { return (symbol.flags & 128) !== 0; } function checkInstanceOfExpression(left, right, leftType, rightType) { - if (isTypeOfKind(leftType, 8190)) { + if (isTypeOfKind(leftType, 16777726)) { error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } if (!(isTypeAny(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) { @@ -25081,10 +23404,10 @@ var ts; return booleanType; } function checkInExpression(left, right, leftType, rightType) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 34 | 340 | 512)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258 | 132 | 16777216)) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 2588672 | 16384)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 80896 | 512)) { error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; @@ -25099,14 +23422,14 @@ var ts; } function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, contextualMapper) { if (property.kind === 253 || property.kind === 254) { - var name_17 = property.name; - if (name_17.kind === 140) { - checkComputedPropertyName(name_17); + var name_15 = property.name; + if (name_15.kind === 140) { + checkComputedPropertyName(name_15); } - if (isComputedNonLiteralName(name_17)) { + if (isComputedNonLiteralName(name_15)) { return undefined; } - var text = getTextOfPropertyName(name_17); + var text = getTextOfPropertyName(name_15); var type = isTypeAny(objectLiteralType) ? objectLiteralType : getTypeOfPropertyOfType(objectLiteralType, text) || @@ -25121,7 +23444,7 @@ var ts; } } else { - error(name_17, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_17)); + error(name_15, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_15)); } } else { @@ -25151,9 +23474,8 @@ var ts; return checkDestructuringAssignment(element, type, contextualMapper); } else { - checkExpression(element); if (isTupleType(sourceType)) { - error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); + error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), sourceType.elementTypes.length, elements.length); } else { error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); @@ -25183,7 +23505,7 @@ var ts; var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { if (strictNullChecks && - !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 2048)) { + !(getCombinedTypeFlags(checkExpression(prop.objectAssignmentInitializer)) & 32)) { sourceType = getTypeWithFacts(sourceType, 131072); } checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, contextualMapper); @@ -25213,14 +23535,7 @@ var ts; return sourceType; } function isTypeEqualityComparableTo(source, target) { - return (target.flags & 6144) !== 0 || isTypeComparableTo(source, target); - } - function getBestChoiceType(type1, type2) { - var firstAssignableToSecond = isTypeAssignableTo(type1, type2); - var secondAssignableToFirst = isTypeAssignableTo(type2, type1); - return secondAssignableToFirst && !firstAssignableToSecond ? type1 : - firstAssignableToSecond && !secondAssignableToFirst ? type2 : - getUnionType([type1, type2], true); + return (target.flags & 96) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, contextualMapper) { return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, contextualMapper, node); @@ -25255,15 +23570,15 @@ var ts; case 68: case 46: case 66: - if (leftType.flags & 6144) + if (leftType.flags & 96) leftType = rightType; - if (rightType.flags & 6144) + if (rightType.flags & 96) rightType = leftType; leftType = getNonNullableType(leftType); rightType = getNonNullableType(rightType); var suggestedOperator = void 0; - if ((leftType.flags & 136) && - (rightType.flags & 136) && + if ((leftType.flags & 8) && + (rightType.flags & 8) && (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator)); } @@ -25277,18 +23592,18 @@ var ts; return numberType; case 35: case 57: - if (leftType.flags & 6144) + if (leftType.flags & 96) leftType = rightType; - if (rightType.flags & 6144) + if (rightType.flags & 96) rightType = leftType; leftType = getNonNullableType(leftType); rightType = getNonNullableType(rightType); var resultType = void 0; - if (isTypeOfKind(leftType, 340) && isTypeOfKind(rightType, 340)) { + if (isTypeOfKind(leftType, 132) && isTypeOfKind(rightType, 132)) { resultType = numberType; } else { - if (isTypeOfKind(leftType, 34) || isTypeOfKind(rightType, 34)) { + if (isTypeOfKind(leftType, 258) || isTypeOfKind(rightType, 258)) { resultType = stringType; } else if (isTypeAny(leftType) || isTypeAny(rightType)) { @@ -25320,12 +23635,6 @@ var ts; case 31: case 32: case 33: - var leftIsUnit = isUnitUnionType(leftType); - var rightIsUnit = isUnitUnionType(rightType); - if (!leftIsUnit || !rightIsUnit) { - leftType = leftIsUnit ? getBaseTypeOfUnitType(leftType) : leftType; - rightType = rightIsUnit ? getBaseTypeOfUnitType(rightType) : rightType; - } if (!isTypeEqualityComparableTo(leftType, rightType) && !isTypeEqualityComparableTo(rightType, leftType)) { reportOperatorError(); } @@ -25335,13 +23644,9 @@ var ts; case 90: return checkInExpression(left, right, leftType, rightType); case 51: - return getTypeFacts(leftType) & 1048576 ? - includeFalsyTypes(rightType, getFalsyFlags(strictNullChecks ? leftType : getBaseTypeOfUnitType(rightType))) : - leftType; + return strictNullChecks ? addTypeKind(rightType, getCombinedTypeFlags(leftType) & 112) : rightType; case 52: - return getTypeFacts(leftType) & 2097152 ? - getBestChoiceType(removeDefinitelyFalsyTypes(leftType), rightType) : - leftType; + return getUnionType([getNonNullableType(leftType), rightType]); case 56: checkAssignmentOperator(rightType); return getRegularTypeOfObjectLiteral(rightType); @@ -25349,8 +23654,8 @@ var ts; return rightType; } function checkForDisallowedESSymbolOperand(operator) { - var offendingSymbolOperand = maybeTypeOfKind(leftType, 512) ? left : - maybeTypeOfKind(rightType, 512) ? right : + var offendingSymbolOperand = maybeTypeOfKind(leftType, 16777216) ? left : + maybeTypeOfKind(rightType, 16777216) ? right : undefined; if (offendingSymbolOperand) { error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); @@ -25435,63 +23740,14 @@ var ts; checkExpression(node.condition); var type1 = checkExpression(node.whenTrue, contextualMapper); var type2 = checkExpression(node.whenFalse, contextualMapper); - return getBestChoiceType(type1, type2); + return getUnionType([type1, type2]); } - function typeContainsLiteralFromEnum(type, enumType) { - if (type.flags & 524288) { - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (t.flags & 256 && t.baseType === enumType) { - return true; - } - } - } - if (type.flags & 256) { - return type.baseType === enumType; - } - return false; - } - function isLiteralContextForType(node, type) { - if (isLiteralTypeLocation(node)) { - return true; - } + function checkStringLiteralExpression(node) { var contextualType = getContextualType(node); - if (contextualType) { - if (contextualType.flags & 16384) { - var apparentType = getApparentTypeOfTypeParameter(contextualType); - if (type === apparentType) { - return true; - } - contextualType = apparentType; - } - if (type.flags & 2) { - return maybeTypeOfKind(contextualType, 32); - } - if (type.flags & 4) { - return maybeTypeOfKind(contextualType, (64 | 256)); - } - if (type.flags & 8) { - return maybeTypeOfKind(contextualType, 128); - } - if (type.flags & 16) { - return typeContainsLiteralFromEnum(contextualType, type); - } - } - return false; - } - function checkLiteralExpression(node) { - if (node.kind === 8) { - checkGrammarNumericLiteral(node); - } - switch (node.kind) { - case 9: - return isLiteralContextForType(node, stringType) ? getLiteralTypeForText(32, node.text) : stringType; - case 8: - return isLiteralContextForType(node, numberType) ? getLiteralTypeForText(64, node.text) : numberType; - case 99: - case 84: - return isLiteralContextForType(node, booleanType) ? node.kind === 99 ? trueType : falseType : booleanType; + if (contextualType && isStringLiteralUnionType(contextualType)) { + return getStringLiteralTypeForText(node.text); } + return stringType; } function checkTemplateExpression(node) { ts.forEach(node.templateSpans, function (templateSpan) { @@ -25564,6 +23820,10 @@ var ts; } return type; } + function checkNumericLiteral(node) { + checkGrammarNumericLiteral(node); + return numberType; + } function checkExpressionWorker(node, contextualMapper) { switch (node.kind) { case 69: @@ -25574,13 +23834,15 @@ var ts; return checkSuperExpression(node); case 93: return nullWideningType; - case 9: - case 8: case 99: case 84: - return checkLiteralExpression(node); + return booleanType; + case 8: + return checkNumericLiteral(node); case 189: return checkTemplateExpression(node); + case 9: + return checkStringLiteralExpression(node); case 11: return stringType; case 10: @@ -25725,9 +23987,9 @@ var ts; else if (parameterName) { var hasReportedError = false; for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { - var name_18 = _a[_i].name; - if (ts.isBindingPattern(name_18) && - checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_18, parameterName, typePredicate.parameterName)) { + var name_16 = _a[_i].name; + if (ts.isBindingPattern(name_16) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_16, parameterName, typePredicate.parameterName)) { hasReportedError = true; break; } @@ -25755,15 +24017,15 @@ var ts; } function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) { for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { - var name_19 = _a[_i].name; - if (name_19.kind === 69 && - name_19.text === predicateVariableName) { + var name_17 = _a[_i].name; + if (name_17.kind === 69 && + name_17.text === predicateVariableName) { error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name_19.kind === 168 || - name_19.kind === 167) { - if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_19, predicateVariableNode, predicateVariableName)) { + else if (name_17.kind === 168 || + name_17.kind === 167) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_17, predicateVariableNode, predicateVariableName)) { return true; } } @@ -25811,21 +24073,22 @@ var ts; checkAsyncFunctionReturnType(node); } } - if (noUnusedIdentifiers && !node.body) { + if (!node.body) { checkUnusedTypeParameters(node); } } } function checkClassForDuplicateDeclarations(node) { - var instanceNames = ts.createMap(); - var staticNames = ts.createMap(); + var getter = 1, setter = 2, property = getter | setter; + var instanceNames = {}; + var staticNames = {}; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; if (member.kind === 148) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var param = _c[_b]; if (ts.isParameterPropertyDeclaration(param)) { - addName(instanceNames, param.name, param.name.text, 3); + addName(instanceNames, param.name, param.name.text, property); } } } @@ -25836,21 +24099,21 @@ var ts; if (memberName) { switch (member.kind) { case 149: - addName(names, member.name, memberName, 1); + addName(names, member.name, memberName, getter); break; case 150: - addName(names, member.name, memberName, 2); + addName(names, member.name, memberName, setter); break; case 145: - addName(names, member.name, memberName, 3); + addName(names, member.name, memberName, property); break; } } } } function addName(names, location, name, meaning) { - var prev = names[name]; - if (prev) { + if (ts.hasProperty(names, name)) { + var prev = names[name]; if (prev & meaning) { error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); } @@ -25864,7 +24127,7 @@ var ts; } } function checkObjectTypeForDuplicateDeclarations(node) { - var names = ts.createMap(); + var names = {}; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; if (member.kind == 144) { @@ -25878,7 +24141,7 @@ var ts; default: continue; } - if (names[memberName]) { + if (ts.hasProperty(names, memberName)) { error(member.symbol.valueDeclaration.name, ts.Diagnostics.Duplicate_identifier_0, memberName); error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); } @@ -26020,7 +24283,12 @@ var ts; checkSignatureDeclaration(node); if (node.kind === 149) { if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 32768)) { - if (!(node.flags & 65536)) { + if (node.flags & 65536) { + if (compilerOptions.noImplicitReturns) { + error(node.name, ts.Diagnostics.Not_all_code_paths_return_a_value); + } + } + else { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); } } @@ -26042,10 +24310,7 @@ var ts; checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type); } } - var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 149) { - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); - } + getTypeOfAccessors(getSymbolOfNode(node)); } if (node.parent.kind !== 171) { checkSourceElement(node.body); @@ -26098,9 +24363,6 @@ var ts; checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } - if (type.flags & 16 && !type.memberTypes && getNodeLinks(node).resolvedSymbol.flags & 8) { - error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); - } } } function checkTypeQuery(node) { @@ -26370,10 +24632,10 @@ var ts; case 224: return 2097152 | 1048576; case 229: - var result_2 = 0; + var result_1 = 0; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_2 |= getDeclarationSpaces(d); }); - return result_2; + ts.forEach(target.declarations, function (d) { result_1 |= getDeclarationSpaces(d); }); + return result_1; default: return 1048576; } @@ -26396,7 +24658,7 @@ var ts; if (isTypeAny(promise)) { return undefined; } - if (promise.flags & 131072) { + if (promise.flags & 4096) { if (promise.target === tryGetGlobalPromiseType() || promise.target === getGlobalPromiseLikeType()) { return promise.typeArguments[0]; @@ -26422,7 +24684,7 @@ var ts; if (onfulfilledParameterSignatures.length === 0) { return undefined; } - return getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), true); + return getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); } function getTypeOfFirstParameterOfSignature(signature) { return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType; @@ -26433,13 +24695,13 @@ var ts; function checkAwaitedType(type, location, message) { return checkAwaitedTypeWorker(type); function checkAwaitedTypeWorker(type) { - if (type.flags & 524288) { + if (type.flags & 16384) { var types = []; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var constituentType = _a[_i]; types.push(checkAwaitedTypeWorker(constituentType)); } - return getUnionType(types, true); + return getUnionType(types); } else { var promisedType = getPromisedType(type); @@ -26544,7 +24806,7 @@ var ts; function checkTypeNodeAsExpression(node) { if (node && node.kind === 155) { var root = getFirstIdentifier(node.typeName); - var meaning = root.parent.kind === 155 ? 793064 : 1920; + var meaning = root.parent.kind === 155 ? 793056 : 1536; var rootSymbol = resolveName(root, root.text, meaning | 8388608, undefined, undefined); if (rootSymbol && rootSymbol.flags & 8388608) { var aliasTarget = resolveAlias(rootSymbol); @@ -26700,19 +24962,20 @@ var ts; function checkUnusedLocalsAndParameters(node) { if (node.parent.kind !== 222 && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { var _loop_1 = function(key) { - var local = node.locals[key]; - if (!local.isReferenced) { - if (local.valueDeclaration && local.valueDeclaration.kind === 142) { - var parameter = local.valueDeclaration; - if (compilerOptions.noUnusedParameters && - !ts.isParameterPropertyDeclaration(parameter) && - !parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(parameter)) { - error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); + if (ts.hasProperty(node.locals, key)) { + var local_1 = node.locals[key]; + if (!local_1.isReferenced) { + if (local_1.valueDeclaration && local_1.valueDeclaration.kind === 142) { + var parameter = local_1.valueDeclaration; + if (compilerOptions.noUnusedParameters && + !ts.isParameterPropertyDeclaration(parameter) && + !parameterNameStartsWithUnderscore(parameter)) { + error(local_1.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local_1.name); + } + } + else if (compilerOptions.noUnusedLocals) { + ts.forEach(local_1.declarations, function (d) { return error(d.name || d, ts.Diagnostics._0_is_declared_but_never_used, local_1.name); }); } - } - else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return error(d.name || d, ts.Diagnostics._0_is_declared_but_never_used, local.name); }); } } }; @@ -26721,9 +24984,6 @@ var ts; } } } - function parameterIsThisKeyword(parameter) { - return parameter.name && parameter.name.originalKeywordKind === 97; - } function parameterNameStartsWithUnderscore(parameter) { return parameter.name && parameter.name.kind === 69 && parameter.name.text.charCodeAt(0) === 95; } @@ -26741,7 +25001,7 @@ var ts; for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; if (!parameter.symbol.isReferenced && parameter.flags & 8) { - error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_never_used, parameter.symbol.name); + error(parameter.name, ts.Diagnostics._0_is_declared_but_never_used, parameter.symbol.name); } } } @@ -26752,14 +25012,9 @@ var ts; function checkUnusedTypeParameters(node) { if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { if (node.typeParameters) { - var symbol = getSymbolOfNode(node); - var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations); - if (lastDeclaration !== node) { - return; - } for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { var typeParameter = _a[_i]; - if (!getMergedSymbol(typeParameter.symbol).isReferenced) { + if (!typeParameter.symbol.isReferenced) { error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name); } } @@ -26769,12 +25024,14 @@ var ts; function checkUnusedModuleMembers(node) { if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { for (var key in node.locals) { - var local = node.locals[key]; - if (!local.isReferenced && !local.exportSymbol) { - for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (!ts.isAmbientModule(declaration)) { - error(declaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); + if (ts.hasProperty(node.locals, key)) { + var local = node.locals[key]; + if (!local.isReferenced && !local.exportSymbol) { + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (!ts.isAmbientModule(declaration)) { + error(declaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); + } } } } @@ -26908,8 +25165,8 @@ var ts; container.kind === 225 || container.kind === 256); if (!namesShareScope) { - var name_20 = symbolToString(localDeclarationSymbol); - error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_20, name_20); + var name_18 = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_18, name_18); } } } @@ -26979,8 +25236,8 @@ var ts; } var parent_11 = node.parent.parent; var parentType = getTypeForBindingElementParent(parent_11); - var name_21 = node.propertyName || node.name; - var property = getPropertyOfType(parentType, getTextOfPropertyName(name_21)); + var name_19 = node.propertyName || node.name; + var property = getPropertyOfType(parentType, getTextOfPropertyName(name_19)); if (parent_11.initializer && property && getParentOfSymbol(property)) { checkClassPropertyAccess(parent_11, parent_11.initializer, parentType, property); } @@ -27156,7 +25413,7 @@ var ts; if (varExpr.kind === 170 || varExpr.kind === 171) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } - else if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 34)) { + else if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258)) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); } else { @@ -27164,7 +25421,7 @@ var ts; } } var rightType = checkNonNullExpression(node.expression); - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 2588672 | 16384)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 80896 | 512)) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); } checkSourceElement(node.statement); @@ -27217,7 +25474,7 @@ var ts; } var typeAsIterable = type; if (!typeAsIterable.iterableElementType) { - if ((type.flags & 131072) && type.target === getGlobalIterableType()) { + if ((type.flags & 4096) && type.target === getGlobalIterableType()) { typeAsIterable.iterableElementType = type.typeArguments[0]; } else { @@ -27232,7 +25489,7 @@ var ts; } return undefined; } - typeAsIterable.iterableElementType = getElementTypeOfIterator(getUnionType(ts.map(iteratorFunctionSignatures, getReturnTypeOfSignature), true), errorNode); + typeAsIterable.iterableElementType = getElementTypeOfIterator(getUnionType(ts.map(iteratorFunctionSignatures, getReturnTypeOfSignature)), errorNode); } } return typeAsIterable.iterableElementType; @@ -27243,7 +25500,7 @@ var ts; } var typeAsIterator = type; if (!typeAsIterator.iteratorElementType) { - if ((type.flags & 131072) && type.target === getGlobalIteratorType()) { + if ((type.flags & 4096) && type.target === getGlobalIteratorType()) { typeAsIterator.iteratorElementType = type.typeArguments[0]; } else { @@ -27258,7 +25515,7 @@ var ts; } return undefined; } - var iteratorNextResult = getUnionType(ts.map(iteratorNextFunctionSignatures, getReturnTypeOfSignature), true); + var iteratorNextResult = getUnionType(ts.map(iteratorNextFunctionSignatures, getReturnTypeOfSignature)); if (isTypeAny(iteratorNextResult)) { return undefined; } @@ -27278,7 +25535,7 @@ var ts; if (isTypeAny(type)) { return undefined; } - if ((type.flags & 131072) && type.target === getGlobalIterableIteratorType()) { + if ((type.flags & 4096) && type.target === getGlobalIterableIteratorType()) { return type.typeArguments[0]; } return getElementTypeOfIterable(type, undefined) || @@ -27287,10 +25544,10 @@ var ts; function checkElementTypeOfArrayOrString(arrayOrStringType, errorNode) { ts.Debug.assert(languageVersion < 2); var arrayType = arrayOrStringType; - if (arrayOrStringType.flags & 524288) { - arrayType = getUnionType(ts.filter(arrayOrStringType.types, function (t) { return !(t.flags & 34); }), true); + if (arrayOrStringType.flags & 16384) { + arrayType = getUnionType(ts.filter(arrayOrStringType.types, function (t) { return !(t.flags & 258); })); } - else if (arrayOrStringType.flags & 34) { + else if (arrayOrStringType.flags & 258) { arrayType = neverType; } var hasStringConstituent = arrayOrStringType !== arrayType; @@ -27315,10 +25572,10 @@ var ts; } var arrayElementType = getIndexTypeOfType(arrayType, 1) || unknownType; if (hasStringConstituent) { - if (arrayElementType.flags & 34) { + if (arrayElementType.flags & 258) { return stringType; } - return getUnionType([arrayElementType, stringType], true); + return getUnionType([arrayElementType, stringType]); } return arrayElementType; } @@ -27330,7 +25587,7 @@ var ts; } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { var unwrappedReturnType = ts.isAsyncFunctionLike(func) ? getPromisedType(returnType) : returnType; - return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 1024 | 1); + return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16 | 1); } function checkReturnStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { @@ -27461,7 +25718,7 @@ var ts; else { var identifierName = catchClause.variableDeclaration.name.text; var locals = catchClause.block.locals; - if (locals) { + if (locals && ts.hasProperty(locals, identifierName)) { var localSymbol = locals[identifierName]; if (localSymbol && (localSymbol.flags & 2) !== 0) { grammarErrorOnNode(localSymbol.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, identifierName); @@ -27486,7 +25743,7 @@ var ts; checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1); }); - if (type.flags & 32768 && ts.isClassLike(type.symbol.valueDeclaration)) { + if (type.flags & 1024 && ts.isClassLike(type.symbol.valueDeclaration)) { var classDeclaration = type.symbol.valueDeclaration; for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; @@ -27501,7 +25758,7 @@ var ts; var errorNode; if (stringIndexType && numberIndexType) { errorNode = declaredNumberIndexer || declaredStringIndexer; - if (!errorNode && (type.flags & 65536)) { + if (!errorNode && (type.flags & 2048)) { var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0) && getIndexTypeOfType(base, 1); }); errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; } @@ -27523,7 +25780,7 @@ var ts; else if (indexDeclaration) { errorNode = indexDeclaration; } - else if (containingType.flags & 65536) { + else if (containingType.flags & 2048) { var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.name) && getIndexTypeOfType(base, indexKind); }); errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; } @@ -27631,11 +25888,6 @@ var ts; } checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); - if (baseType_1.symbol.valueDeclaration && !ts.isInAmbientContext(baseType_1.symbol.valueDeclaration)) { - if (!isBlockScopedNameDeclaredBeforeUse(baseType_1.symbol.valueDeclaration, node)) { - error(baseTypeNode, ts.Diagnostics.A_class_must_be_declared_after_its_base_class); - } - } if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32)) { var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments); if (ts.forEach(constructors, function (sig) { return getReturnTypeOfSignature(sig) !== baseType_1; })) { @@ -27649,15 +25901,15 @@ var ts; if (implementedTypeNodes) { for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { var typeRefNode = implementedTypeNodes_1[_b]; - if (!ts.isEntityNameExpression(typeRefNode.expression)) { + if (!ts.isSupportedExpressionWithTypeArguments(typeRefNode)) { error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); } checkTypeReferenceNode(typeRefNode); if (produceDiagnostics) { var t = getTypeFromTypeNode(typeRefNode); if (t !== unknownType) { - var declaredType = (t.flags & 131072) ? t.target : t; - if (declaredType.flags & (32768 | 65536)) { + var declaredType = (t.flags & 4096) ? t.target : t; + if (declaredType.flags & (1024 | 2048)) { checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_implements_interface_1); } else { @@ -27781,7 +26033,7 @@ var ts; if (baseTypes.length < 2) { return true; } - var seen = ts.createMap(); + var seen = {}; ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen[p.name] = { prop: p, containingType: type }; }); var ok = true; for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { @@ -27789,11 +26041,11 @@ var ts; var properties = getPropertiesOfObjectType(getTypeWithThisArgument(base, type.thisType)); for (var _a = 0, properties_4 = properties; _a < properties_4.length; _a++) { var prop = properties_4[_a]; - var existing = seen[prop.name]; - if (!existing) { + if (!ts.hasProperty(seen, prop.name)) { seen[prop.name] = { prop: prop, containingType: base }; } else { + var existing = seen[prop.name]; var isInheritedProperty = existing.containingType !== type; if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) { ok = false; @@ -27831,7 +26083,7 @@ var ts; checkObjectTypeForDuplicateDeclarations(node); } ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) { - if (!ts.isEntityNameExpression(heritageElement.expression)) { + if (!ts.isSupportedExpressionWithTypeArguments(heritageElement)) { error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); } checkTypeReferenceNode(heritageElement); @@ -27839,7 +26091,7 @@ var ts; ts.forEach(node.members, checkSourceElement); if (produceDiagnostics) { checkTypeForDuplicateIndexSignatures(node); - registerForUnusedIdentifiersCheck(node); + checkUnusedTypeParameters(node); } } function checkTypeAliasDeclaration(node) { @@ -28154,6 +26406,9 @@ var ts; } } } + if (compilerOptions.noImplicitAny && !node.body) { + reportImplicitAnyError(node, anyType); + } if (node.body) { checkSourceElement(node.body); if (!ts.isGlobalScopeAugmentation(node)) { @@ -28179,9 +26434,9 @@ var ts; break; case 169: case 218: - var name_22 = node.name; - if (ts.isBindingPattern(name_22)) { - for (var _b = 0, _c = name_22.elements; _b < _c.length; _b++) { + var name_20 = node.name; + if (ts.isBindingPattern(name_20)) { + for (var _b = 0, _c = name_20.elements; _b < _c.length; _b++) { var el = _c[_b]; checkModuleAugmentationElement(el, isGlobalAugmentation); } @@ -28207,20 +26462,19 @@ var ts; } } function getFirstIdentifier(node) { - switch (node.kind) { - case 69: - return node; - case 139: - do { - node = node.left; - } while (node.kind !== 69); - return node; - case 172: - do { - node = node.expression; - } while (node.kind !== 69); - return node; + while (true) { + if (node.kind === 139) { + node = node.left; + } + else if (node.kind === 172) { + node = node.expression; + } + else { + break; + } } + ts.Debug.assert(node.kind === 69); + return node; } function checkExternalImportOrExportDeclaration(node) { var moduleName = ts.getExternalModuleName(node); @@ -28248,8 +26502,8 @@ var ts; var target = resolveAlias(symbol); if (target !== unknownSymbol) { var excludedMeanings = (symbol.flags & (107455 | 1048576) ? 107455 : 0) | - (symbol.flags & 793064 ? 793064 : 0) | - (symbol.flags & 1920 ? 1920 : 0); + (symbol.flags & 793056 ? 793056 : 0) | + (symbol.flags & 1536 ? 1536 : 0); if (target.flags & excludedMeanings) { var message = node.kind === 238 ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : @@ -28303,11 +26557,11 @@ var ts; if (target !== unknownSymbol) { if (target.flags & 107455) { var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 107455 | 1920).flags & 1920)) { + if (!(resolveEntityName(moduleName, 107455 | 1536).flags & 1536)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 793064) { + if (target.flags & 793056) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -28351,7 +26605,7 @@ var ts; checkAliasSymbol(node); if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; - var symbol = resolveName(exportedName, exportedName.text, 107455 | 793064 | 1920 | 8388608, undefined, undefined); + var symbol = resolveName(exportedName, exportedName.text, 107455 | 793056 | 1536 | 8388608, undefined, undefined); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, exportedName.text); } @@ -28407,13 +26661,13 @@ var ts; error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } - var exports_1 = getExportsOfModule(moduleSymbol); - for (var id in exports_1) { + var exports = getExportsOfModule(moduleSymbol); + for (var id in exports) { if (id === "__export") { continue; } - var _a = exports_1[id], declarations = _a.declarations, flags = _a.flags; - if (flags & (1920 | 64 | 384)) { + var _a = exports[id], declarations = _a.declarations, flags = _a.flags; + if (flags & (1536 | 64 | 384)) { continue; } var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverload); @@ -28583,10 +26837,9 @@ var ts; } } function checkSourceFile(node) { - ts.performance.mark("beforeCheck"); + var start = new Date().getTime(); checkSourceFileWorker(node); - ts.performance.mark("afterCheck"); - ts.performance.measure("Check", "beforeCheck", "afterCheck"); + ts.checkTime += new Date().getTime() - start; } function checkSourceFileWorker(node) { var links = getNodeLinks(node); @@ -28657,7 +26910,7 @@ var ts; return false; } function getSymbolsInScope(location, meaning) { - var symbols = ts.createMap(); + var symbols = {}; var memberFlags = 0; if (isInsideWithStatementBody(location)) { return []; @@ -28688,7 +26941,7 @@ var ts; case 221: case 222: if (!(memberFlags & 32)) { - copySymbols(getSymbolOfNode(location).members, meaning & 793064); + copySymbols(getSymbolOfNode(location).members, meaning & 793056); } break; case 179: @@ -28709,7 +26962,7 @@ var ts; function copySymbol(symbol, meaning) { if (symbol.flags & meaning) { var id = symbol.name; - if (!symbols[id]) { + if (!ts.hasProperty(symbols, id)) { symbols[id] = symbol; } } @@ -28797,13 +27050,15 @@ var ts; default: } } - if (entityName.parent.kind === 235 && ts.isEntityNameExpression(entityName)) { - return resolveEntityName(entityName, 107455 | 793064 | 1920 | 8388608); + if (entityName.parent.kind === 235) { + return resolveEntityName(entityName, 107455 | 793056 | 1536 | 8388608); } - if (entityName.kind !== 172 && isInRightSideOfImportOrExportAssignment(entityName)) { - var importEqualsDeclaration = ts.getAncestor(entityName, 229); - ts.Debug.assert(importEqualsDeclaration !== undefined); - return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importEqualsDeclaration, true); + if (entityName.kind !== 172) { + if (isInRightSideOfImportOrExportAssignment(entityName)) { + var importEqualsDeclaration = ts.getAncestor(entityName, 229); + ts.Debug.assert(importEqualsDeclaration !== undefined); + return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importEqualsDeclaration, true); + } } if (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; @@ -28811,13 +27066,13 @@ var ts; if (isHeritageClauseElementIdentifier(entityName)) { var meaning = 0; if (entityName.parent.kind === 194) { - meaning = 793064; + meaning = 793056; if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { meaning |= 107455; } } else { - meaning = 1920; + meaning = 1536; } meaning |= 8388608; return resolveEntityName(entityName, meaning); @@ -28848,7 +27103,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = (entityName.parent.kind === 155 || entityName.parent.kind === 267) ? 793064 : 1920; + var meaning = (entityName.parent.kind === 155 || entityName.parent.kind === 267) ? 793056 : 1536; return resolveEntityName(entityName, meaning, false, true); } else if (entityName.parent.kind === 246) { @@ -28940,7 +27195,7 @@ var ts; function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 107455 | 793064 | 1920 | 8388608); + resolveEntityName(node.propertyName || node.name, 107455 | 793056 | 1536 | 8388608); } function getTypeOfNode(node) { if (isInsideWithStatementBody(node)) { @@ -29021,7 +27276,7 @@ var ts; var propsByName = createSymbolTable(getPropertiesOfType(type)); if (getSignaturesOfType(type, 0).length || getSignaturesOfType(type, 1).length) { ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { - if (!propsByName[p.name]) { + if (!ts.hasProperty(propsByName, p.name)) { propsByName[p.name] = p; } }); @@ -29031,9 +27286,9 @@ var ts; function getRootSymbols(symbol) { if (symbol.flags & 268435456) { var symbols_3 = []; - var name_23 = symbol.name; + var name_21 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_23); + var symbol = getPropertyOfType(t, name_21); if (symbol) { symbols_3.push(symbol); } @@ -29057,7 +27312,7 @@ var ts; } function moduleExportsSomeValue(moduleReferenceExpression) { var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); - if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + if (!moduleSymbol) { return true; } var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol); @@ -29066,7 +27321,7 @@ var ts; if (symbolLinks.exportsSomeValue === undefined) { symbolLinks.exportsSomeValue = hasExportAssignment ? !!(moduleSymbol.flags & 107455) - : ts.forEachProperty(getExportsOfModule(moduleSymbol), isValue); + : ts.forEachValue(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { @@ -29210,7 +27465,7 @@ var ts; return undefined; } function isFunctionType(type) { - return type.flags & 2588672 && getSignaturesOfType(type, 0).length > 0; + return type.flags & 80896 && getSignaturesOfType(type, 0).length > 0; } function getTypeReferenceSerializationKind(typeName) { var valueSymbol = resolveEntityName(typeName, 107455, true); @@ -29218,7 +27473,7 @@ var ts; if (constructorType && isConstructorType(constructorType)) { return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue; } - var typeSymbol = resolveEntityName(typeName, 793064, true); + var typeSymbol = resolveEntityName(typeName, 793056, true); if (!typeSymbol) { return ts.TypeReferenceSerializationKind.ObjectType; } @@ -29229,22 +27484,22 @@ var ts; else if (type.flags & 1) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (isTypeOfKind(type, 1024)) { + else if (isTypeOfKind(type, 16)) { return ts.TypeReferenceSerializationKind.VoidType; } - else if (isTypeOfKind(type, 136)) { + else if (isTypeOfKind(type, 8)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeOfKind(type, 340)) { + else if (isTypeOfKind(type, 132)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (isTypeOfKind(type, 34)) { + else if (isTypeOfKind(type, 258)) { return ts.TypeReferenceSerializationKind.StringLikeType; } - else if (isTupleType(type)) { + else if (isTypeOfKind(type, 8192)) { return ts.TypeReferenceSerializationKind.ArrayLikeType; } - else if (isTypeOfKind(type, 512)) { + else if (isTypeOfKind(type, 16777216)) { return ts.TypeReferenceSerializationKind.ESSymbolType; } else if (isFunctionType(type)) { @@ -29279,7 +27534,7 @@ var ts; getSymbolDisplayBuilder().buildTypeDisplay(baseType, writer, enclosingDeclaration, flags); } function hasGlobalName(name) { - return !!globals[name]; + return ts.hasProperty(globals, name); } function getReferencedValueSymbol(reference) { return getNodeLinks(reference).resolvedSymbol || @@ -29296,14 +27551,14 @@ var ts; if (resolvedTypeReferenceDirectives) { fileToDirective = ts.createFileMap(); for (var key in resolvedTypeReferenceDirectives) { + if (!ts.hasProperty(resolvedTypeReferenceDirectives, key)) { + continue; + } var resolvedDirective = resolvedTypeReferenceDirectives[key]; if (!resolvedDirective) { continue; } var file = host.getSourceFile(resolvedDirective.resolvedFileName); - if (!file) { - continue; - } fileToDirective.set(file.path, key); } } @@ -29342,7 +27597,7 @@ var ts; } var meaning = (node.kind === 172) || (node.kind === 69 && isInTypeQuery(node)) ? 107455 | 1048576 - : 793064 | 1920; + : 793056 | 1536; var symbol = resolveEntityName(node, meaning, true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; } @@ -29417,12 +27672,7 @@ var ts; (augmentations || (augmentations = [])).push(file.moduleAugmentations); } if (file.symbol && file.symbol.globalExports) { - var source = file.symbol.globalExports; - for (var id in source) { - if (!(id in globals)) { - globals[id] = source[id]; - } - } + mergeSymbolTable(globals, file.symbol.globalExports); } }); if (augmentations) { @@ -29453,7 +27703,7 @@ var ts; getGlobalTypedPropertyDescriptorType = ts.memoize(function () { return getGlobalType("TypedPropertyDescriptor", 1); }); getGlobalESSymbolConstructorSymbol = ts.memoize(function () { return getGlobalValueSymbol("Symbol"); }); getGlobalPromiseType = ts.memoize(function () { return getGlobalType("Promise", 1); }); - tryGetGlobalPromiseType = ts.memoize(function () { return getGlobalSymbol("Promise", 793064, undefined) && getGlobalPromiseType(); }); + tryGetGlobalPromiseType = ts.memoize(function () { return getGlobalSymbol("Promise", 793056, undefined) && getGlobalPromiseType(); }); getGlobalPromiseLikeType = ts.memoize(function () { return getGlobalType("PromiseLike", 1); }); getInstantiatedGlobalPromiseLikeType = ts.memoize(createInstantiatedPromiseLikeType); getGlobalPromiseConstructorSymbol = ts.memoize(function () { return getGlobalValueSymbol("Promise"); }); @@ -29473,7 +27723,7 @@ var ts; getGlobalIterableIteratorType = ts.memoize(function () { return emptyGenericType; }); } anyArrayType = createArrayType(anyType); - var symbol = getGlobalSymbol("ReadonlyArray", 793064, undefined); + var symbol = getGlobalSymbol("ReadonlyArray", 793056, undefined); globalReadonlyArrayType = symbol && getTypeOfGlobalSymbol(symbol, 1); anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; } @@ -29487,7 +27737,7 @@ var ts; function createThenableType() { var thenPropertySymbol = createSymbol(67108864 | 4, "then"); getSymbolLinks(thenPropertySymbol).type = globalFunctionType; - var thenableType = createObjectType(2097152); + var thenableType = createObjectType(65536); thenableType.properties = [thenPropertySymbol]; thenableType.members = createSymbolTable(thenableType.properties); thenableType.callSignatures = []; @@ -29515,9 +27765,49 @@ var ts; return false; } function checkGrammarModifiers(node) { - var quickResult = reportObviousModifierErrors(node); - if (quickResult !== undefined) { - return quickResult; + switch (node.kind) { + case 149: + case 150: + case 148: + case 145: + case 144: + case 147: + case 146: + case 153: + case 225: + case 230: + case 229: + case 236: + case 235: + case 179: + case 180: + case 142: + break; + case 220: + if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 118) && + node.parent.kind !== 226 && node.parent.kind !== 256) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + break; + case 221: + case 222: + case 200: + case 223: + if (node.modifiers && node.parent.kind !== 226 && node.parent.kind !== 256) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + break; + case 224: + if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 74) && + node.parent.kind !== 226 && node.parent.kind !== 256) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + break; + default: + return false; + } + if (!node.modifiers) { + return; } var lastStatic, lastPrivate, lastProtected, lastDeclare, lastAsync, lastReadonly; var flags = 0; @@ -29710,56 +28000,6 @@ var ts; return checkGrammarAsyncModifier(node, lastAsync); } } - function reportObviousModifierErrors(node) { - return !node.modifiers - ? false - : shouldReportBadModifier(node) - ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here) - : undefined; - } - function shouldReportBadModifier(node) { - switch (node.kind) { - case 149: - case 150: - case 148: - case 145: - case 144: - case 147: - case 146: - case 153: - case 225: - case 230: - case 229: - case 236: - case 235: - case 179: - case 180: - case 142: - return false; - default: - if (node.parent.kind === 226 || node.parent.kind === 256) { - return false; - } - switch (node.kind) { - case 220: - return nodeHasAnyModifiersExcept(node, 118); - case 221: - return nodeHasAnyModifiersExcept(node, 115); - case 222: - case 200: - case 223: - return true; - case 224: - return nodeHasAnyModifiersExcept(node, 74); - default: - ts.Debug.fail(); - return false; - } - } - } - function nodeHasAnyModifiersExcept(node, allowedModifier) { - return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier; - } function checkGrammarAsyncModifier(node, asyncModifier) { if (languageVersion < 2) { return grammarErrorOnNode(asyncModifier, ts.Diagnostics.Async_functions_are_only_available_when_targeting_ECMAScript_2015_or_higher); @@ -29992,16 +28232,16 @@ var ts; } } function checkGrammarObjectLiteralExpression(node, inDestructuring) { - var seen = ts.createMap(); + var seen = {}; var Property = 1; var GetAccessor = 2; var SetAccessor = 4; var GetOrSetAccessor = GetAccessor | SetAccessor; var _loop_2 = function(prop) { - var name_24 = prop.name; + var name_22 = prop.name; if (prop.kind === 193 || - name_24.kind === 140) { - checkGrammarComputedPropertyName(name_24); + name_22.kind === 140) { + checkGrammarComputedPropertyName(name_22); } if (prop.kind === 254 && !inDestructuring && prop.objectAssignmentInitializer) { return { value: grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment) }; @@ -30014,8 +28254,8 @@ var ts; var currentKind = void 0; if (prop.kind === 253 || prop.kind === 254) { checkGrammarForInvalidQuestionMark(prop, prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name_24.kind === 8) { - checkGrammarNumericLiteral(name_24); + if (name_22.kind === 8) { + checkGrammarNumericLiteral(name_22); } currentKind = Property; } @@ -30031,28 +28271,28 @@ var ts; else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - var effectiveName = ts.getPropertyNameForPropertyNameNode(name_24); + var effectiveName = ts.getPropertyNameForPropertyNameNode(name_22); if (effectiveName === undefined) { return "continue"; } - if (!seen[effectiveName]) { + if (!ts.hasProperty(seen, effectiveName)) { seen[effectiveName] = currentKind; } else { var existingKind = seen[effectiveName]; if (currentKind === Property && existingKind === Property) { - grammarErrorOnNode(name_24, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_24)); + grammarErrorOnNode(name_22, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_22)); } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { seen[effectiveName] = currentKind | existingKind; } else { - return { value: grammarErrorOnNode(name_24, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name) }; + return { value: grammarErrorOnNode(name_22, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name) }; } } else { - return { value: grammarErrorOnNode(name_24, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name) }; + return { value: grammarErrorOnNode(name_22, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name) }; } } }; @@ -30063,19 +28303,19 @@ var ts; } } function checkGrammarJsxElement(node) { - var seen = ts.createMap(); + var seen = {}; for (var _i = 0, _a = node.attributes; _i < _a.length; _i++) { var attr = _a[_i]; if (attr.kind === 247) { continue; } var jsxAttr = attr; - var name_25 = jsxAttr.name; - if (!seen[name_25.text]) { - seen[name_25.text] = true; + var name_23 = jsxAttr.name; + if (!ts.hasProperty(seen, name_23.text)) { + seen[name_23.text] = true; } else { - return grammarErrorOnNode(name_25, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + return grammarErrorOnNode(name_23, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; if (initializer && initializer.kind === 248 && !initializer.expression) { @@ -30399,7 +28639,6 @@ var ts; node.kind === 229 || node.kind === 236 || node.kind === 235 || - node.kind === 228 || (node.flags & 2) || (node.flags & (1 | 512))) { return false; @@ -30451,15 +28690,7 @@ var ts; return true; } } - function getAmbientModules() { - var result = []; - for (var sym in globals) { - if (ambientModuleSymbolRegex.test(sym)) { - result.push(globals[sym]); - } - } - return result; - } + var _a; } ts.createTypeChecker = createTypeChecker; })(ts || (ts = {})); @@ -30493,7 +28724,6 @@ var ts; ts.getNullSourceMapWriter = getNullSourceMapWriter; function createSourceMapWriter(host, writer) { var compilerOptions = host.getCompilerOptions(); - var extendedDiagnostics = compilerOptions.extendedDiagnostics; var currentSourceFile; var sourceMapDir; var stopOverridingSpan = false; @@ -30622,9 +28852,6 @@ var ts; if (pos === -1) { return; } - if (extendedDiagnostics) { - ts.performance.mark("beforeSourcemap"); - } var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos); sourceLinePos.line++; sourceLinePos.character++; @@ -30652,10 +28879,6 @@ var ts; lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; } updateLastEncodedAndRecordedSpans(); - if (extendedDiagnostics) { - ts.performance.mark("afterSourcemap"); - ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); - } } function getStartPos(range) { var rangeHasDecorators = !!range.decorators; @@ -30743,11 +28966,11 @@ var ts; return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined); function getDeclarationDiagnosticsFromFile(_a, sources, isBundledEmit) { var declarationFilePath = _a.declarationFilePath; - emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit, false); + emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit); } } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles) { + function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit) { var newLine = host.getNewLine(); var compilerOptions = host.getCompilerOptions(); var write; @@ -30783,7 +29006,7 @@ var ts; ts.forEach(sourceFile.referencedFiles, function (fileReference) { var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); if (referencedFile && !ts.contains(emittedReferencedFiles, referencedFile)) { - if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference, emitOnlyDtsFiles)) { + if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference)) { addedGlobalFileReference = true; } emittedReferencedFiles.push(referencedFile); @@ -30833,7 +29056,9 @@ var ts; }); if (usedTypeDirectiveReferences) { for (var directive in usedTypeDirectiveReferences) { - referencesOutput += "/// " + newLine; + if (ts.hasProperty(usedTypeDirectiveReferences, directive)) { + referencesOutput += "/// " + newLine; + } } } return { @@ -30922,11 +29147,11 @@ var ts; return; } if (!usedTypeDirectiveReferences) { - usedTypeDirectiveReferences = ts.createMap(); + usedTypeDirectiveReferences = {}; } for (var _i = 0, typeReferenceDirectives_1 = typeReferenceDirectives; _i < typeReferenceDirectives_1.length; _i++) { var directive = typeReferenceDirectives_1[_i]; - if (!(directive in usedTypeDirectiveReferences)) { + if (!ts.hasProperty(usedTypeDirectiveReferences, directive)) { usedTypeDirectiveReferences[directive] = directive; } } @@ -30968,7 +29193,7 @@ var ts; } else { errorNameNode = declaration.name; - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 | 1024, writer); + resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2, writer); errorNameNode = undefined; } } @@ -30980,7 +29205,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 | 1024, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2, writer); errorNameNode = undefined; } } @@ -31078,7 +29303,7 @@ var ts; writeEntityName(entityName); } function emitExpressionWithTypeArguments(node) { - if (ts.isEntityNameExpression(node.expression)) { + if (ts.isSupportedExpressionWithTypeArguments(node)) { ts.Debug.assert(node.expression.kind === 69 || node.expression.kind === 172); emitEntityName(node.expression); if (node.typeArguments) { @@ -31147,15 +29372,15 @@ var ts; } function getExportDefaultTempVariableName() { var baseName = "_default"; - if (!(baseName in currentIdentifiers)) { + if (!ts.hasProperty(currentIdentifiers, baseName)) { return baseName; } var count = 0; while (true) { count++; - var name_26 = baseName + "_" + count; - if (!(name_26 in currentIdentifiers)) { - return name_26; + var name_24 = baseName + "_" + count; + if (!ts.hasProperty(currentIdentifiers, name_24)) { + return name_24; } } } @@ -31173,7 +29398,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 | 1024, writer); + resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2, writer); write(";"); writeLine(); write(node.isExportEquals ? "export = " : "export default "); @@ -31570,7 +29795,7 @@ var ts; emitCommaList(typeReferences, emitTypeOfTypeReference); } function emitTypeOfTypeReference(node) { - if (ts.isEntityNameExpression(node.expression)) { + if (ts.isSupportedExpressionWithTypeArguments(node)) { emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError); } else if (!isImplementsList && node.expression.kind === 93) { @@ -31578,7 +29803,7 @@ var ts; } else { writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 | 1024, writer); + resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2, writer); } function getHeritageClauseVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; @@ -31668,8 +29893,7 @@ var ts; } else { writeTextOfNode(currentText, node.name); - if ((node.kind === 145 || node.kind === 144 || - (node.kind === 142 && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { + if ((node.kind === 145 || node.kind === 144 || node.kind === 142) && ts.hasQuestionToken(node)) { write("?"); } if ((node.kind === 145 || node.kind === 144) && node.parent.kind === 159) { @@ -32142,14 +30366,14 @@ var ts; return emitSourceFile(node); } } - function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { + function writeReferencePath(referencedFile, addBundledFileReference) { var declFileName; var addedBundledEmitReference = false; if (ts.isDeclarationFile(referencedFile)) { declFileName = referencedFile.fileName; } else { - ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile, emitOnlyDtsFiles); + ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile); } if (declFileName) { declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, false); @@ -32166,8 +30390,8 @@ var ts; } } } - function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) { - var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles); + function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) { + var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit); var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; if (!emitSkipped) { var declarationOutput = emitDeclarationResult.referencesOutput @@ -32205,7 +30429,7 @@ var ts; return getResolvedExternalModuleName(host, file); } ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; - var entities = ts.createMap({ + var entities = { "quot": 0x0022, "amp": 0x0026, "apos": 0x0027, @@ -32459,8 +30683,8 @@ var ts; "clubs": 0x2663, "hearts": 0x2665, "diams": 0x2666 - }); - function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles) { + }; + function emitFiles(resolver, host, targetSourceFile) { var extendsHelper = "\nvar __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n};"; var assignHelper = "\nvar __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n};"; var decorateHelper = "\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};"; @@ -32476,7 +30700,7 @@ var ts; var emitSkipped = false; var newLine = host.getNewLine(); var emitJavaScript = createFileEmitter(); - ts.forEachExpectedEmitFile(host, emitFile, targetSourceFile, emitOnlyDtsFiles); + ts.forEachExpectedEmitFile(host, emitFile, targetSourceFile); return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -32485,7 +30709,7 @@ var ts; }; function isUniqueLocalName(name, container) { for (var node = container; ts.isNodeDescendentOf(node, container); node = node.nextContainer) { - if (node.locals && name in node.locals) { + if (node.locals && ts.hasProperty(node.locals, name)) { if (node.locals[name].flags & (107455 | 1048576 | 8388608)) { return false; } @@ -32496,13 +30720,13 @@ var ts; function setLabeledJump(state, isBreak, labelText, labelMarker) { if (isBreak) { if (!state.labeledNonLocalBreaks) { - state.labeledNonLocalBreaks = ts.createMap(); + state.labeledNonLocalBreaks = {}; } state.labeledNonLocalBreaks[labelText] = labelMarker; } else { if (!state.labeledNonLocalContinues) { - state.labeledNonLocalContinues = ts.createMap(); + state.labeledNonLocalContinues = {}; } state.labeledNonLocalContinues[labelText] = labelMarker; } @@ -32560,26 +30784,26 @@ var ts; var isOwnFileEmit; var emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos) { } : emitLeadingCommentsOfPositionWorker; var setSourceMapWriterEmit = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? changeSourceMapEmit : function (writer) { }; - var moduleEmitDelegates = ts.createMap((_a = {}, + var moduleEmitDelegates = (_a = {}, _a[ts.ModuleKind.ES6] = emitES6Module, _a[ts.ModuleKind.AMD] = emitAMDModule, _a[ts.ModuleKind.System] = emitSystemModule, _a[ts.ModuleKind.UMD] = emitUMDModule, _a[ts.ModuleKind.CommonJS] = emitCommonJSModule, _a - )); - var bundleEmitDelegates = ts.createMap((_b = {}, + ); + var bundleEmitDelegates = (_b = {}, _b[ts.ModuleKind.ES6] = function () { }, _b[ts.ModuleKind.AMD] = emitAMDModule, _b[ts.ModuleKind.System] = emitSystemModule, _b[ts.ModuleKind.UMD] = function () { }, _b[ts.ModuleKind.CommonJS] = function () { }, _b - )); + ); return doEmit; function doEmit(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit) { sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); - generatedNameSet = ts.createMap(); + generatedNameSet = {}; nodeToGeneratedName = []; decoratedClassAliases = []; isOwnFileEmit = !isBundledEmit; @@ -32590,7 +30814,7 @@ var ts; writeLine(); var sourceMappingURL = sourceMap.getSourceMappingURL(); if (sourceMappingURL) { - write("//# " + "sourceMappingURL" + "=" + sourceMappingURL); + write("//# sourceMappingURL=" + sourceMappingURL); } writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, compilerOptions.emitBOM, sourceFiles); sourceMap.reset(); @@ -32638,24 +30862,24 @@ var ts; } function isUniqueName(name) { return !resolver.hasGlobalName(name) && - !(name in currentFileIdentifiers) && - !(name in generatedNameSet); + !ts.hasProperty(currentFileIdentifiers, name) && + !ts.hasProperty(generatedNameSet, name); } function makeTempVariableName(flags) { if (flags && !(tempFlags & flags)) { - var name_27 = flags === 268435456 ? "_i" : "_n"; - if (isUniqueName(name_27)) { + var name_25 = flags === 268435456 ? "_i" : "_n"; + if (isUniqueName(name_25)) { tempFlags |= flags; - return name_27; + return name_25; } } while (true) { var count = tempFlags & 268435455; tempFlags++; if (count !== 8 && count !== 13) { - var name_28 = count < 26 ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); - if (isUniqueName(name_28)) { - return name_28; + var name_26 = count < 26 ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); + if (isUniqueName(name_26)) { + return name_26; } } } @@ -33353,8 +31577,8 @@ var ts; } else if (declaration.kind === 234) { write(getGeneratedNameForNode(declaration.parent.parent.parent)); - var name_29 = declaration.propertyName || declaration.name; - var identifier = ts.getTextOfNodeFromSourceText(currentText, name_29); + var name_27 = declaration.propertyName || declaration.name; + var identifier = ts.getTextOfNodeFromSourceText(currentText, name_27); if (languageVersion === 0 && identifier === "default") { write('["default"]'); } @@ -33421,8 +31645,8 @@ var ts; function emitIdentifier(node) { if (convertedLoopState) { if (node.text == "arguments" && resolver.isArgumentsLocalBinding(node)) { - var name_30 = convertedLoopState.argumentsName || (convertedLoopState.argumentsName = makeUniqueName("arguments")); - write(name_30); + var name_28 = convertedLoopState.argumentsName || (convertedLoopState.argumentsName = makeUniqueName("arguments")); + write(name_28); return; } } @@ -33536,10 +31760,6 @@ var ts; else if (node.parent.kind === 188 && node.parent.condition === node) { return true; } - else if (node.parent.kind === 185 || node.parent.kind === 181 || - node.parent.kind === 182 || node.parent.kind === 183) { - return true; - } return false; } function needsParenthesisForPropertyAccessOrInvocation(node) { @@ -33878,9 +32098,9 @@ var ts; if (languageVersion === 2 && node.expression.kind === 95 && isInAsyncMethodWithSuperInES6(node)) { - var name_31 = ts.createSynthesizedNode(9); - name_31.text = node.name.text; - emitSuperAccessInAsyncMethod(node.expression, name_31); + var name_29 = ts.createSynthesizedNode(9); + name_29.text = node.name.text; + emitSuperAccessInAsyncMethod(node.expression, name_29); return; } emit(node.expression); @@ -34126,7 +32346,6 @@ var ts; operand.kind !== 181 && operand.kind !== 186 && operand.kind !== 175 && - !(operand.kind === 187 && node.expression.kind === 195) && !(operand.kind === 174 && node.parent.kind === 175) && !(operand.kind === 179 && node.parent.kind === 174) && !(operand.kind === 8 && node.parent.kind === 172)) { @@ -34168,7 +32387,7 @@ var ts; if (modulekind === ts.ModuleKind.System || node.kind !== 69 || ts.nodeIsSynthesized(node)) { return false; } - return !exportEquals && exportSpecifiers && node.text in exportSpecifiers; + return !exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, node.text); } function emitPrefixUnaryExpression(node) { var isPlusPlusOrMinusMinus = (node.operator === 41 @@ -34629,12 +32848,12 @@ var ts; for (var _c = 0, _d = convertedLoopState.hoistedLocalVariables; _c < _d.length; _c++) { var id = _d[_c]; if (!seen) { - seen = ts.createMap(); + seen = {}; } else { write(", "); } - if (!(id.text in seen)) { + if (!ts.hasProperty(seen, id.text)) { emit(id); seen[id.text] = id.text; } @@ -35087,7 +33306,7 @@ var ts; } if (convertedLoopState) { if (!convertedLoopState.labels) { - convertedLoopState.labels = ts.createMap(); + convertedLoopState.labels = {}; } convertedLoopState.labels[node.label.text] = node.label.text; } @@ -35185,7 +33404,7 @@ var ts; if (modulekind === ts.ModuleKind.System) { return; } - if (!exportEquals && exportSpecifiers && name.text in exportSpecifiers) { + if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { for (var _a = 0, _b = exportSpecifiers[name.text]; _a < _b.length; _a++) { var specifier = _b[_a]; writeLine(); @@ -35554,12 +33773,12 @@ var ts; function emitParameter(node) { if (languageVersion < 2) { if (ts.isBindingPattern(node.name)) { - var name_32 = createTempVariable(0); + var name_30 = createTempVariable(0); if (!tempParameters) { tempParameters = []; } - tempParameters.push(name_32); - emit(name_32); + tempParameters.push(name_30); + emit(name_30); } else { emit(node.name); @@ -35618,12 +33837,11 @@ var ts; } function emitRestParameter(node) { if (languageVersion < 2 && ts.hasDeclaredRestParameter(node)) { - var restParam = node.parameters[node.parameters.length - 1]; + var restIndex = node.parameters.length - 1; + var restParam = node.parameters[restIndex]; if (ts.isBindingPattern(restParam.name)) { return; } - var skipThisCount = node.parameters.length && node.parameters[0].name.originalKeywordKind === 97 ? 1 : 0; - var restIndex = node.parameters.length - 1 - skipThisCount; var tempName = createTempVariable(268435456).text; writeLine(); emitLeadingComments(restParam); @@ -35736,7 +33954,7 @@ var ts; write("("); if (node) { var parameters = node.parameters; - var skipCount = node.parameters.length && node.parameters[0].name.originalKeywordKind === 97 ? 1 : 0; + var skipCount = node.parameters.length && node.parameters[0].name.text === "this" ? 1 : 0; var omitCount = languageVersion < 2 && ts.hasDeclaredRestParameter(node) ? 1 : 0; emitList(parameters, skipCount, parameters.length - omitCount - skipCount, false, false); } @@ -36153,7 +34371,12 @@ var ts; emitSignatureParameters(ctor); } else { - write("()"); + if (baseTypeElement) { + write("(...args)"); + } + else { + write("()"); + } } } var startIndex = 0; @@ -36185,7 +34408,7 @@ var ts; write("_super.apply(this, arguments);"); } else { - write("super(...arguments);"); + write("super(...args);"); } emitEnd(baseTypeElement); } @@ -36241,13 +34464,13 @@ var ts; if (isES6ExportedDeclaration(node) && !(node.flags & 512) && decoratedClassAlias === undefined) { write("export "); } + if (!isHoistedDeclarationInSystemModule) { + write("let "); + } if (decoratedClassAlias !== undefined) { - write("let " + decoratedClassAlias); + write("" + decoratedClassAlias); } else { - if (!isHoistedDeclarationInSystemModule) { - write("let "); - } emitDeclarationName(node); } write(" = "); @@ -36263,7 +34486,7 @@ var ts; var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 192; var generatedName; if (isClassExpressionWithStaticProperties) { - generatedName = node.name ? getGeneratedNameForNode(node.name) : makeUniqueName("classExpression"); + generatedName = getGeneratedNameForNode(node.name); var synthesizedNode = ts.createSynthesizedNode(69); synthesizedNode.text = generatedName; recordTempDeclaration(synthesizedNode); @@ -36713,11 +34936,10 @@ var ts; } if (valueDeclaration) { var parameters = valueDeclaration.parameters; - var skipThisCount = parameters.length && parameters[0].name.originalKeywordKind === 97 ? 1 : 0; var parameterCount = parameters.length; - if (parameterCount > skipThisCount) { - for (var i = skipThisCount; i < parameterCount; i++) { - if (i > skipThisCount) { + if (parameterCount > 0) { + for (var i = 0; i < parameterCount; i++) { + if (i > 0) { write(", "); } if (parameters[i].dotDotDotToken) { @@ -36972,7 +35194,7 @@ var ts; } } function tryRenameExternalModule(moduleName) { - if (renamedDependencies && moduleName.text in renamedDependencies) { + if (renamedDependencies && ts.hasProperty(renamedDependencies, moduleName.text)) { return "\"" + renamedDependencies[moduleName.text] + "\""; } return undefined; @@ -37073,7 +35295,7 @@ var ts; write(" = "); } else { - var isNakedImport = node.kind === 230 && !node.importClause; + var isNakedImport = 230 && !node.importClause; if (!isNakedImport) { write(varOrConst); write(getGeneratedNameForNode(node)); @@ -37272,7 +35494,7 @@ var ts; } function collectExternalModuleInfo(sourceFile) { externalImports = []; - exportSpecifiers = ts.createMap(); + exportSpecifiers = {}; exportEquals = undefined; hasExportStarsToExportValues = false; for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) { @@ -37304,8 +35526,8 @@ var ts; else { for (var _c = 0, _d = node.exportClause.elements; _c < _d.length; _c++) { var specifier = _d[_c]; - var name_33 = (specifier.propertyName || specifier.name).text; - (exportSpecifiers[name_33] || (exportSpecifiers[name_33] = [])).push(specifier); + var name_31 = (specifier.propertyName || specifier.name).text; + (exportSpecifiers[name_31] || (exportSpecifiers[name_31] = [])).push(specifier); } } break; @@ -37343,9 +35565,9 @@ var ts; } function getExternalModuleNameText(importNode, emitRelativePathAsModuleName) { if (emitRelativePathAsModuleName) { - var name_34 = getExternalModuleNameFromDeclaration(host, resolver, importNode); - if (name_34) { - return "\"" + name_34 + "\""; + var name_32 = getExternalModuleNameFromDeclaration(host, resolver, importNode); + if (name_32) { + return "\"" + name_32 + "\""; } } var moduleName = ts.getExternalModuleName(importNode); @@ -37384,7 +35606,7 @@ var ts; if (!hasExportStarsToExportValues) { return undefined; } - if (!exportedDeclarations && !ts.someProperties(exportSpecifiers)) { + if (!exportedDeclarations && ts.isEmpty(exportSpecifiers)) { var hasExportDeclarationWithExportClause = false; for (var _a = 0, externalImports_2 = externalImports; _a < externalImports_2.length; _a++) { var externalImport = externalImports_2[_a]; @@ -37488,15 +35710,15 @@ var ts; if (hoistedVars) { writeLine(); write("var "); - var seen = ts.createMap(); + var seen = {}; for (var i = 0; i < hoistedVars.length; i++) { var local = hoistedVars[i]; - var name_35 = local.kind === 69 + var name_33 = local.kind === 69 ? local : local.name; - if (name_35) { - var text = ts.unescapeIdentifier(name_35.text); - if (text in seen) { + if (name_33) { + var text = ts.unescapeIdentifier(name_33.text); + if (ts.hasProperty(seen, text)) { continue; } else { @@ -37574,15 +35796,15 @@ var ts; } if (node.kind === 218 || node.kind === 169) { if (shouldHoistVariable(node, false)) { - var name_36 = node.name; - if (name_36.kind === 69) { + var name_34 = node.name; + if (name_34.kind === 69) { if (!hoistedVars) { hoistedVars = []; } - hoistedVars.push(name_36); + hoistedVars.push(name_34); } else { - ts.forEachChild(name_36, visit); + ts.forEachChild(name_34, visit); } } return; @@ -37739,7 +35961,7 @@ var ts; write("System.register("); writeModuleName(node, emitRelativePathAsModuleName); write("["); - var groupIndices = ts.createMap(); + var groupIndices = {}; var dependencyGroups = []; for (var i = 0; i < externalImports.length; i++) { var text = getExternalModuleNameText(externalImports[i], emitRelativePathAsModuleName); @@ -37747,7 +35969,7 @@ var ts; continue; } var key = text.substr(1, text.length - 2); - if (key in groupIndices) { + if (ts.hasProperty(groupIndices, key)) { var groupIndex = groupIndices[key]; dependencyGroups[groupIndex].push(externalImports[i]); continue; @@ -38462,25 +36684,21 @@ var ts; } var _a, _b; } - function emitFile(_a, sourceFiles, isBundledEmit, emitOnlyDtsFiles) { + function emitFile(_a, sourceFiles, isBundledEmit) { var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath; - if (!emitOnlyDtsFiles) { - if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { - emitJavaScript(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); - } - else { - emitSkipped = true; - } + if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { + emitJavaScript(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + } + else { + emitSkipped = true; } if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; + emitSkipped = ts.writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; } if (!emitSkipped && emittedFilesList) { - if (!emitOnlyDtsFiles) { - emittedFilesList.push(jsFilePath); - if (sourceMapFilePath) { - emittedFilesList.push(sourceMapFilePath); - } + emittedFilesList.push(jsFilePath); + if (sourceMapFilePath) { + emittedFilesList.push(sourceMapFilePath); } if (declarationFilePath) { emittedFilesList.push(declarationFilePath); @@ -38492,12 +36710,16 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.version = "2.0.5"; + ts.programTime = 0; + ts.emitTime = 0; + ts.ioReadTime = 0; + ts.ioWriteTime = 0; + ts.version = "2.0.0"; var emptyArray = []; - function findConfigFile(searchPath, fileExists, configName) { - if (configName === void 0) { configName = "tsconfig.json"; } + var defaultTypeRoots = ["node_modules/@types"]; + function findConfigFile(searchPath, fileExists) { while (true) { - var fileName = ts.combinePaths(searchPath, configName); + var fileName = ts.combinePaths(searchPath, "tsconfig.json"); if (fileExists(fileName)) { return fileName; } @@ -38547,6 +36769,87 @@ var ts; return ts.getNormalizedPathFromPathComponents(commonPathComponents); } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; + function trace(host, message) { + host.trace(ts.formatMessage.apply(undefined, arguments)); + } + function isTraceEnabled(compilerOptions, host) { + return compilerOptions.traceResolution && host.trace !== undefined; + } + function hasZeroOrOneAsteriskCharacter(str) { + var seenAsterisk = false; + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) === 42) { + if (!seenAsterisk) { + seenAsterisk = true; + } + else { + return false; + } + } + } + return true; + } + ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; + function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { + return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; + } + function moduleHasNonRelativeName(moduleName) { + if (ts.isRootedDiskPath(moduleName)) { + return false; + } + var i = moduleName.lastIndexOf("./", 1); + var startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === 46); + return !startsWithDotSlashOrDotDotSlash; + } + function tryReadTypesSection(packageJsonPath, baseDirectory, state) { + var jsonContent; + try { + var jsonText = state.host.readFile(packageJsonPath); + jsonContent = jsonText ? JSON.parse(jsonText) : {}; + } + catch (e) { + jsonContent = {}; + } + var typesFile; + var fieldName; + if (jsonContent.typings) { + if (typeof jsonContent.typings === "string") { + fieldName = "typings"; + typesFile = jsonContent.typings; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, "typings", typeof jsonContent.typings); + } + } + } + if (!typesFile && jsonContent.types) { + if (typeof jsonContent.types === "string") { + fieldName = "types"; + typesFile = jsonContent.types; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, "types", typeof jsonContent.types); + } + } + } + if (typesFile) { + var typesFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath); + } + return typesFilePath; + } + if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); + } + var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); + return mainFilePath; + } + return undefined; + } var typeReferenceExtensions = [".d.ts"]; function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { @@ -38559,30 +36862,13 @@ var ts; else if (host.getCurrentDirectory) { currentDirectory = host.getCurrentDirectory(); } - return currentDirectory && getDefaultTypeRoots(currentDirectory, host); - } - ts.getEffectiveTypeRoots = getEffectiveTypeRoots; - function getDefaultTypeRoots(currentDirectory, host) { - if (!host.directoryExists) { - return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + if (!currentDirectory) { + return undefined; } - var typeRoots; - while (true) { - var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes); - if (host.directoryExists(atTypes)) { - (typeRoots || (typeRoots = [])).push(atTypes); - } - var parent_15 = ts.getDirectoryPath(currentDirectory); - if (parent_15 === currentDirectory) { - break; - } - currentDirectory = parent_15; - } - return typeRoots; + return ts.map(defaultTypeRoots, function (d) { return ts.combinePaths(currentDirectory, d); }); } - var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { - var traceEnabled = ts.isTraceEnabled(options, host); + var traceEnabled = isTraceEnabled(options, host); var moduleResolutionState = { compilerOptions: options, host: host, @@ -38593,35 +36879,35 @@ var ts; if (traceEnabled) { if (containingFile === undefined) { if (typeRoots === undefined) { - ts.trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); } else { - ts.trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); } } else { if (typeRoots === undefined) { - ts.trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); } else { - ts.trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); } } } var failedLookupLocations = []; if (typeRoots && typeRoots.length) { if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); } var primarySearchPaths = typeRoots; for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) { var typeRoot = primarySearchPaths_1[_i]; var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); - var resolvedFile_1 = ts.loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !ts.directoryProbablyExists(candidateDirectory, host), moduleResolutionState); + var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState); if (resolvedFile_1) { if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true); + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true); } return { resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 }, @@ -38632,7 +36918,7 @@ var ts; } else { if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); + trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); } } var resolvedFile; @@ -38642,21 +36928,21 @@ var ts; } if (initialLocationForSecondaryLookup !== undefined) { if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); + trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - resolvedFile = ts.loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, false); + resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState); if (traceEnabled) { if (resolvedFile) { - ts.trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); } else { - ts.trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); } } } else { if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); + trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); } } return { @@ -38667,8 +36953,398 @@ var ts; }; } ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; + function resolveModuleName(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + } + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + if (traceEnabled) { + trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + var result; + switch (moduleResolution) { + case ts.ModuleResolutionKind.NodeJs: + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); + break; + case ts.ModuleResolutionKind.Classic: + result = classicNameResolver(moduleName, containingFile, compilerOptions, host); + break; + } + if (traceEnabled) { + if (result.resolvedModule) { + trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); + } + else { + trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); + } + } + return result; + } + ts.resolveModuleName = resolveModuleName; + function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (moduleHasNonRelativeName(moduleName)) { + return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); + } + else { + return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); + } + } + function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.rootDirs) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var matchedRootDir; + var matchedNormalizedPrefix; + for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { + var rootDir = _a[_i]; + var normalizedRoot = ts.normalizePath(rootDir); + if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { + normalizedRoot += ts.directorySeparator; + } + var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && + (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); + } + if (isLongestMatchingPrefix) { + matchedNormalizedPrefix = normalizedRoot; + matchedRootDir = rootDir; + } + } + if (matchedNormalizedPrefix) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); + } + var suffix = candidate.substr(matchedNormalizedPrefix.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); + } + for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { + var rootDir = _c[_b]; + if (rootDir === matchedRootDir) { + continue; + } + var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); + } + var baseDirectory = ts.getDirectoryPath(candidate_1); + var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + if (resolvedFileName_1) { + return resolvedFileName_1; + } + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); + } + } + return undefined; + } + function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.baseUrl) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + } + var matchedPattern = undefined; + if (state.compilerOptions.paths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + matchedPattern = matchPatternOrExact(ts.getKeys(state.compilerOptions.paths), moduleName); + } + if (matchedPattern) { + var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName); + var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) { + var subst = _a[_i]; + var path = matchedStar ? subst.replace("*", matchedStar) : subst; + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + } + return undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); + } + return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + } + } + function matchPatternOrExact(patternStrings, candidate) { + var patterns = []; + for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { + var patternString = patternStrings_1[_i]; + var pattern = tryParsePattern(patternString); + if (pattern) { + patterns.push(pattern); + } + else if (patternString === candidate) { + return patternString; + } + } + return findBestPatternMatch(patterns, function (_) { return _; }, candidate); + } + function patternText(_a) { + var prefix = _a.prefix, suffix = _a.suffix; + return prefix + "*" + suffix; + } + function matchedText(pattern, candidate) { + ts.Debug.assert(isPatternMatch(pattern, candidate)); + return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); + } + function findBestPatternMatch(values, getPattern, candidate) { + var matchedValue = undefined; + var longestMatchPrefixLength = -1; + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var v = values_1[_i]; + var pattern = getPattern(v); + if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { + longestMatchPrefixLength = pattern.prefix.length; + matchedValue = v; + } + } + return matchedValue; + } + ts.findBestPatternMatch = findBestPatternMatch; + function isPatternMatch(_a, candidate) { + var prefix = _a.prefix, suffix = _a.suffix; + return candidate.length >= prefix.length + suffix.length && + ts.startsWith(candidate, prefix) && + ts.endsWith(candidate, suffix); + } + function tryParsePattern(pattern) { + ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); + var indexOfStar = pattern.indexOf("*"); + return indexOfStar === -1 ? undefined : { + prefix: pattern.substr(0, indexOfStar), + suffix: pattern.substr(indexOfStar + 1) + }; + } + ts.tryParsePattern = tryParsePattern; + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { + var containingDirectory = ts.getDirectoryPath(containingFile); + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var traceEnabled = isTraceEnabled(compilerOptions, host); + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); + var isExternalLibraryImport = false; + if (!resolvedFileName) { + if (moduleHasNonRelativeName(moduleName)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); + } + resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state); + isExternalLibraryImport = resolvedFileName !== undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, false, state); + } + } + if (resolvedFileName && host.realpath) { + var originalFileName = resolvedFileName; + resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName)); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); + } + } + return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; + function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); + } + var resolvedFileName = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); + return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); + } + function directoryProbablyExists(directoryName, host) { + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + var resolvedByAddingOrKeepingExtension = loadModuleFromFileWorker(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); + if (resolvedByAddingOrKeepingExtension) { + return resolvedByAddingOrKeepingExtension; + } + if (ts.hasJavaScriptFileExtension(candidate)) { + var extensionless = ts.removeFileExtension(candidate); + if (state.traceEnabled) { + var extension = candidate.substring(extensionless.length); + trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); + } + return loadModuleFromFileWorker(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); + } + } + function loadModuleFromFileWorker(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + var directory = ts.getDirectoryPath(candidate); + if (directory) { + onlyRecordFailures = !directoryProbablyExists(directory, state.host); + } + } + return ts.forEach(extensions, tryLoad); + function tryLoad(ext) { + if (state.skipTsx && ts.isJsxOrTsxExtension(ext)) { + return undefined; + } + var fileName = ts.fileExtensionIs(candidate, ext) ? candidate : candidate + ext; + if (!onlyRecordFailures && state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); + } + return fileName; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); + } + failedLookupLocation.push(fileName); + return undefined; + } + } + } + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { + var packageJsonPath = ts.combinePaths(candidate, "package.json"); + var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); + if (directoryExists && state.host.fileExists(packageJsonPath)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); + if (typesFile) { + var result = loadModuleFromFile(typesFile, extensions, failedLookupLocation, !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host), state); + if (result) { + return result; + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field); + } + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); + } + failedLookupLocation.push(packageJsonPath); + } + return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); + } + function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { + var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); + var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions); + var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); + if (result) { + return result; + } + result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); + if (result) { + return result; + } + } + function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state) { + directory = ts.normalizeSlashes(directory); + while (true) { + var baseName = ts.getBaseFileName(directory); + if (baseName !== "node_modules") { + var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); + if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { + return packageResult; + } + else { + var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); + if (typesResult || packageResult) { + return typesResult || packageResult; + } + } + } + var parentPath = ts.getDirectoryPath(directory); + if (parentPath === directory) { + break; + } + directory = parentPath; + } + return undefined; + } + function classicNameResolver(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; + var failedLookupLocations = []; + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var containingDirectory = ts.getDirectoryPath(containingFile); + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); + if (resolvedFileName) { + return createResolvedModule(resolvedFileName, false, failedLookupLocations); + } + var referencedSourceFile; + if (moduleHasNonRelativeName(moduleName)) { + while (true) { + var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state); + if (referencedSourceFile) { + break; + } + var parentPath = ts.getDirectoryPath(containingDirectory); + if (parentPath === containingDirectory) { + break; + } + containingDirectory = parentPath; + } + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, false, state); + } + return referencedSourceFile + ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } + : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; + } + ts.classicNameResolver = classicNameResolver; + ts.defaultInitCompilerOptions = { + module: ts.ModuleKind.CommonJS, + target: 1, + noImplicitAny: false, + sourceMap: false + }; function createCompilerHost(options, setParentNodes) { - var existingDirectories = ts.createMap(); + var existingDirectories = {}; function getCanonicalFileName(fileName) { return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } @@ -38676,10 +37352,9 @@ var ts; function getSourceFile(fileName, languageVersion, onError) { var text; try { - ts.performance.mark("beforeIORead"); + var start = new Date().getTime(); text = ts.sys.readFile(fileName, options.charset); - ts.performance.mark("afterIORead"); - ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); + ts.ioReadTime += new Date().getTime() - start; } catch (e) { if (onError) { @@ -38692,7 +37367,7 @@ var ts; return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined; } function directoryExists(directoryPath) { - if (directoryPath in existingDirectories) { + if (ts.hasProperty(existingDirectories, directoryPath)) { return true; } if (ts.sys.directoryExists(directoryPath)) { @@ -38711,11 +37386,11 @@ var ts; var outputFingerprints; function writeFileIfUpdated(fileName, data, writeByteOrderMark) { if (!outputFingerprints) { - outputFingerprints = ts.createMap(); + outputFingerprints = {}; } var hash = ts.sys.createHash(data); var mtimeBefore = ts.sys.getModifiedTime(fileName); - if (mtimeBefore && fileName in outputFingerprints) { + if (mtimeBefore && ts.hasProperty(outputFingerprints, fileName)) { var fingerprint = outputFingerprints[fileName]; if (fingerprint.byteOrderMark === writeByteOrderMark && fingerprint.hash === hash && @@ -38733,7 +37408,7 @@ var ts; } function writeFile(fileName, data, writeByteOrderMark, onError) { try { - ts.performance.mark("beforeIOWrite"); + var start = new Date().getTime(); ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { writeFileIfUpdated(fileName, data, writeByteOrderMark); @@ -38741,8 +37416,7 @@ var ts; else { ts.sys.writeFile(fileName, data, writeByteOrderMark); } - ts.performance.mark("afterIOWrite"); - ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + ts.ioWriteTime += new Date().getTime() - start; } catch (e) { if (onError) { @@ -38781,22 +37455,6 @@ var ts; return ts.sortAndDeduplicateDiagnostics(diagnostics); } ts.getPreEmitDiagnostics = getPreEmitDiagnostics; - function formatDiagnostics(diagnostics, host) { - var output = ""; - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; - if (diagnostic.file) { - var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; - var fileName = diagnostic.file.fileName; - var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }); - output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): "; - } - var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); - output += category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine(); - } - return output; - } - ts.formatDiagnostics = formatDiagnostics; function flattenDiagnosticMessageText(messageText, newLine) { if (typeof messageText === "string") { return messageText; @@ -38825,17 +37483,25 @@ var ts; return []; } var resolutions = []; - var cache = ts.createMap(); + var cache = {}; for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { - var name_37 = names_1[_i]; - var result = name_37 in cache - ? cache[name_37] - : cache[name_37] = loader(name_37, containingFile); + var name_35 = names_1[_i]; + var result = void 0; + if (ts.hasProperty(cache, name_35)) { + result = cache[name_35]; + } + else { + result = loader(name_35, containingFile); + cache[name_35] = result; + } resolutions.push(result); } return resolutions; } - function getAutomaticTypeDirectiveNames(options, host) { + function getInferredTypesRoot(options, rootFiles, host) { + return computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + function getAutomaticTypeDirectiveNames(options, rootFiles, host) { if (options.types) { return options.types; } @@ -38846,15 +37512,7 @@ var ts; for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { var root = typeRoots_1[_i]; if (host.directoryExists(root)) { - for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { - var typeDirectivePath = _b[_a]; - var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = ts.pathToPackageJson(ts.combinePaths(root, normalized)); - var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null; - if (!isNotNeededPackage) { - result.push(ts.getBaseFileName(normalized)); - } - } + result = result.concat(host.getDirectories(root)); } } } @@ -38869,13 +37527,13 @@ var ts; var diagnosticsProducingTypeChecker; var noDiagnosticsTypeChecker; var classifiableNames; - var resolvedTypeReferenceDirectives = ts.createMap(); + var resolvedTypeReferenceDirectives = {}; var fileProcessingDiagnostics = ts.createDiagnosticCollection(); - var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; - var currentNodeModulesDepth = 0; - var modulesWithElidedImports = ts.createMap(); - var sourceFilesFoundSearchingNodeModules = ts.createMap(); - ts.performance.mark("beforeProgram"); + var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 2; + var currentNodeModulesJsDepth = 0; + var modulesWithElidedImports = {}; + var sourceFilesFoundSearchingNodeModules = {}; + var start = new Date().getTime(); host = host || createCompilerHost(options); var skipDefaultLib = options.noLib; var programDiagnostics = ts.createDiagnosticCollection(); @@ -38887,7 +37545,7 @@ var ts; resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }; } else { - var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; + var loader_1 = function (moduleName, containingFile) { return resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(moduleNames, containingFile, loader_1); }; } var resolveTypeReferenceDirectiveNamesWorker; @@ -38902,9 +37560,10 @@ var ts; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; if (!tryReuseStructureFromOldProgram()) { ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); - var typeReferences = getAutomaticTypeDirectiveNames(options, host); + var typeReferences = getAutomaticTypeDirectiveNames(options, rootNames, host); if (typeReferences) { - var containingFilename = ts.combinePaths(host.getCurrentDirectory(), "__inferred type names__.ts"); + var inferredRoot = getInferredTypesRoot(options, rootNames, host); + var containingFilename = ts.combinePaths(inferredRoot, "__inferred type names__.ts"); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i]); @@ -38945,12 +37604,10 @@ var ts; getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, - getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, - dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker + getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; } }; verifyCompilerOptions(); - ts.performance.mark("afterProgram"); - ts.performance.measure("Program", "beforeProgram", "afterProgram"); + ts.programTime += new Date().getTime() - start; return program; function getCommonSourceDirectory() { if (typeof commonSourceDirectory === "undefined") { @@ -38969,10 +37626,10 @@ var ts; function getClassifiableNames() { if (!classifiableNames) { getTypeChecker(); - classifiableNames = ts.createMap(); + classifiableNames = {}; for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { var sourceFile = files_2[_i]; - ts.copyProperties(sourceFile.classifiableNames, classifiableNames); + ts.copyMap(sourceFile.classifiableNames, classifiableNames); } } return classifiableNames; @@ -38995,7 +37652,7 @@ var ts; (oldOptions.maxNodeModuleJsDepth !== options.maxNodeModuleJsDepth) || !ts.arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) || !ts.arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) || - !ts.equalOwnProperties(oldOptions.paths, options.paths)) { + !ts.mapIsEqualTo(oldOptions.paths, options.paths)) { return false; } ts.Debug.assert(!oldProgram.structureIsReused); @@ -39085,7 +37742,7 @@ var ts; getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, - isSourceFileFromExternalLibrary: function (file) { return !!sourceFilesFoundSearchingNodeModules[file.path]; }, + isSourceFileFromExternalLibrary: function (file) { return !!ts.lookUp(sourceFilesFoundSearchingNodeModules, file.path); }, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked }; @@ -39093,19 +37750,17 @@ var ts; function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, true)); } - function dropDiagnosticsProducingTypeChecker() { - diagnosticsProducingTypeChecker = undefined; - } function getTypeChecker() { return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, false)); } - function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { - return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles); }); + function emit(sourceFile, writeFileCallback, cancellationToken) { + var _this = this; + return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); }); } function isEmitBlocked(emitFileName) { return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); } - function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { + function emitWorker(program, sourceFile, writeFileCallback, cancellationToken) { var declarationDiagnostics = []; if (options.noEmit) { return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; @@ -39125,10 +37780,9 @@ var ts; } } var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); - ts.performance.mark("beforeEmit"); - var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles); - ts.performance.mark("afterEmit"); - ts.performance.measure("Emit", "beforeEmit", "afterEmit"); + var start = new Date().getTime(); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile); + ts.emitTime += new Date().getTime() - start; return emitResult; } function getSourceFile(fileName) { @@ -39267,16 +37921,16 @@ var ts; case 175: var expression = node; if (expression.typeArguments && expression.typeArguments.length > 0) { - var start = expression.typeArguments.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, expression.typeArguments.end - start, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); + var start_2 = expression.typeArguments.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start_2, expression.typeArguments.end - start_2, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); return true; } break; case 142: var parameter = node; if (parameter.modifiers) { - var start = parameter.modifiers.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, parameter.modifiers.end - start, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); + var start_3 = parameter.modifiers.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start_3, parameter.modifiers.end - start_3, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); return true; } if (parameter.questionToken) { @@ -39320,8 +37974,8 @@ var ts; } function checkTypeParameters(typeParameters) { if (typeParameters) { - var start = typeParameters.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, typeParameters.end - start, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); + var start_4 = typeParameters.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start_4, typeParameters.end - start_4, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); return true; } return false; @@ -39508,17 +38162,8 @@ var ts; if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); } - if (file_1 && sourceFilesFoundSearchingNodeModules[file_1.path] && currentNodeModulesDepth == 0) { - sourceFilesFoundSearchingNodeModules[file_1.path] = false; - if (!options.noResolve) { - processReferencedFiles(file_1, ts.getDirectoryPath(fileName), isDefaultLib); - processTypeReferenceDirectives(file_1); - } - modulesWithElidedImports[file_1.path] = false; - processImportedModules(file_1, ts.getDirectoryPath(fileName)); - } - else if (file_1 && modulesWithElidedImports[file_1.path]) { - if (currentNodeModulesDepth < maxNodeModulesJsDepth) { + if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) { + if (currentNodeModulesJsDepth < maxNodeModulesJsDepth) { modulesWithElidedImports[file_1.path] = false; processImportedModules(file_1, ts.getDirectoryPath(fileName)); } @@ -39535,7 +38180,6 @@ var ts; }); filesByName.set(path, file); if (file) { - sourceFilesFoundSearchingNodeModules[path] = (currentNodeModulesDepth > 0); file.path = path; if (host.useCaseSensitiveFileNames()) { var existingFile = filesByNameIgnoreCase.get(path); @@ -39569,14 +38213,13 @@ var ts; }); } function processTypeReferenceDirectives(file) { - var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); + var typeDirectives = ts.map(file.typeReferenceDirectives, function (l) { return l.fileName; }); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; var resolvedTypeReferenceDirective = resolutions[i]; - var fileName = ref.fileName.toLocaleLowerCase(); - ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective); - processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end); + ts.setResolvedTypeReferenceDirective(file, ref.fileName, resolvedTypeReferenceDirective); + processTypeReferenceDirective(ref.fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end); } } function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, refFile, refPos, refEnd) { @@ -39593,7 +38236,7 @@ var ts; if (previousResolution) { var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) { - fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_to_resolve_this_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); } saveResolution = false; } @@ -39627,7 +38270,7 @@ var ts; function processImportedModules(file, basePath) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { - file.resolvedModules = ts.createMap(); + file.resolvedModules = {}; var moduleNames = ts.map(ts.concatenate(file.imports, file.moduleAugmentations), getTextOfLiteral); var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory)); for (var i = 0; i < moduleNames.length; i++) { @@ -39637,9 +38280,12 @@ var ts; var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport; var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName); if (isFromNodeModulesSearch) { - currentNodeModulesDepth++; + sourceFilesFoundSearchingNodeModules[resolvedPath] = true; } - var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth; + if (isJsFileFromNodeModules) { + currentNodeModulesJsDepth++; + } + var elideImport = isJsFileFromNodeModules && currentNodeModulesJsDepth > maxNodeModulesJsDepth; var shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport; if (elideImport) { modulesWithElidedImports[file.path] = true; @@ -39647,8 +38293,8 @@ var ts; else if (shouldAddFile) { findSourceFile(resolution.resolvedFileName, resolvedPath, false, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); } - if (isFromNodeModulesSearch) { - currentNodeModulesDepth--; + if (isJsFileFromNodeModules) { + currentNodeModulesJsDepth--; } } } @@ -39715,18 +38361,15 @@ var ts; if (!ts.hasProperty(options.paths, key)) { continue; } - if (!ts.hasZeroOrOneAsteriskCharacter(key)) { + if (!hasZeroOrOneAsteriskCharacter(key)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); } if (ts.isArray(options.paths[key])) { - if (options.paths[key].length === 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key)); - } for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { var subst = _a[_i]; var typeOfSubst = typeof subst; if (typeOfSubst === "string") { - if (!ts.hasZeroOrOneAsteriskCharacter(subst)) { + if (!hasZeroOrOneAsteriskCharacter(subst)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key)); } } @@ -39767,7 +38410,7 @@ var ts; } var languageVersion = options.target || 0; var outFile = options.outFile || options.out; - var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); + var firstExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) ? f : undefined; }); if (options.isolatedModules) { if (options.module === ts.ModuleKind.None && languageVersion < 2) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); @@ -39778,17 +38421,17 @@ var ts; programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); } } - else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 && options.module === ts.ModuleKind.None) { - var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); + else if (firstExternalModuleSourceFile && languageVersion < 2 && options.module === ts.ModuleKind.None) { + var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } if (outFile) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); } - else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) { - var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); + else if (options.module === undefined && firstExternalModuleSourceFile) { + var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); } } if (options.outDir || @@ -40406,24 +39049,24 @@ var ts; switch (n.kind) { case 199: if (!ts.isFunctionBlock(n)) { - var parent_16 = n.parent; + var parent_15 = n.parent; var openBrace = ts.findChildOfKind(n, 15, sourceFile); var closeBrace = ts.findChildOfKind(n, 16, sourceFile); - if (parent_16.kind === 204 || - parent_16.kind === 207 || - parent_16.kind === 208 || - parent_16.kind === 206 || - parent_16.kind === 203 || - parent_16.kind === 205 || - parent_16.kind === 212 || - parent_16.kind === 252) { - addOutliningSpan(parent_16, openBrace, closeBrace, autoCollapse(n)); + if (parent_15.kind === 204 || + parent_15.kind === 207 || + parent_15.kind === 208 || + parent_15.kind === 206 || + parent_15.kind === 203 || + parent_15.kind === 205 || + parent_15.kind === 212 || + parent_15.kind === 252) { + addOutliningSpan(parent_15, openBrace, closeBrace, autoCollapse(n)); break; } - if (parent_16.kind === 216) { - var tryStatement = parent_16; + if (parent_15.kind === 216) { + var tryStatement = parent_15; if (tryStatement.tryBlock === n) { - addOutliningSpan(parent_16, openBrace, closeBrace, autoCollapse(n)); + addOutliningSpan(parent_15, openBrace, closeBrace, autoCollapse(n)); break; } else if (tryStatement.finallyBlock === n) { @@ -40479,17 +39122,17 @@ var ts; (function (ts) { var NavigateTo; (function (NavigateTo) { - function getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount, excludeDts) { + function getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; var baseSensitivity = { sensitivity: "base" }; ts.forEach(program.getSourceFiles(), function (sourceFile) { cancellationToken.throwIfCancellationRequested(); var nameToDeclarations = sourceFile.getNamedDeclarations(); - for (var name_38 in nameToDeclarations) { - var declarations = nameToDeclarations[name_38]; + for (var name_36 in nameToDeclarations) { + var declarations = ts.getProperty(nameToDeclarations, name_36); if (declarations) { - var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_38); + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_36); if (!matches) { continue; } @@ -40500,17 +39143,14 @@ var ts; if (!containers) { return undefined; } - matches = patternMatcher.getMatches(containers, name_38); + matches = patternMatcher.getMatches(containers, name_36); if (!matches) { continue; } } var fileName = sourceFile.fileName; var matchKind = bestMatchKind(matches); - if (excludeDts && ts.fileExtensionIs(declaration.getSourceFile().fileName, ".d.ts")) { - continue; - } - rawItems.push({ name: name_38, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); + rawItems.push({ name: name_36, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); } } } @@ -40756,9 +39396,9 @@ var ts; case 169: case 218: var decl = node; - var name_39 = decl.name; - if (ts.isBindingPattern(name_39)) { - addChildrenRecursively(name_39); + var name_37 = decl.name; + if (ts.isBindingPattern(name_37)) { + addChildrenRecursively(name_37); } else if (decl.initializer && isFunctionOrClassExpression(decl.initializer)) { addChildrenRecursively(decl.initializer); @@ -40819,14 +39459,14 @@ var ts; } } function mergeChildren(children) { - var nameToItems = ts.createMap(); + var nameToItems = {}; ts.filterMutate(children, function (child) { var decl = child.node; var name = decl.name && nodeText(decl.name); if (!name) { return true; } - var itemsWithSameName = nameToItems[name]; + var itemsWithSameName = ts.getProperty(nameToItems, name); if (!itemsWithSameName) { nameToItems[name] = child; return true; @@ -41054,7 +39694,7 @@ var ts; function convertToTopLevelItem(n) { return { text: getItemName(n.node), - kind: ts.getNodeKind(n.node), + kind: nodeKind(n.node), kindModifiers: ts.getNodeModifiers(n.node), spans: getSpans(n), childItems: ts.map(n.children, convertToChildItem) || emptyChildItemArray, @@ -41065,7 +39705,7 @@ var ts; function convertToChildItem(n) { return { text: getItemName(n.node), - kind: ts.getNodeKind(n.node), + kind: nodeKind(n.node), kindModifiers: ts.getNodeModifiers(n.node), spans: getSpans(n), childItems: emptyChildItemArray, @@ -41085,6 +39725,46 @@ var ts; return spans; } } + function nodeKind(node) { + switch (node.kind) { + case 256: + return ts.ScriptElementKind.moduleElement; + case 255: + return ts.ScriptElementKind.memberVariableElement; + case 218: + case 169: + var variableDeclarationNode = void 0; + var name_38; + if (node.kind === 169) { + name_38 = node.name; + variableDeclarationNode = node; + while (variableDeclarationNode && variableDeclarationNode.kind !== 218) { + variableDeclarationNode = variableDeclarationNode.parent; + } + ts.Debug.assert(!!variableDeclarationNode); + } + else { + ts.Debug.assert(!ts.isBindingPattern(node.name)); + variableDeclarationNode = node; + name_38 = node.name; + } + if (ts.isConst(variableDeclarationNode)) { + return ts.ScriptElementKind.constElement; + } + else if (ts.isLet(variableDeclarationNode)) { + return ts.ScriptElementKind.letElement; + } + else { + return ts.ScriptElementKind.variableElement; + } + case 180: + return ts.ScriptElementKind.functionElement; + case 279: + return ts.ScriptElementKind.typeElement; + default: + return ts.getNodeKind(node); + } + } function getModuleName(moduleDeclaration) { if (ts.isAmbientModule(moduleDeclaration)) { return ts.getTextOfNode(moduleDeclaration.name); @@ -41152,7 +39832,7 @@ var ts; }; } function createPatternMatcher(pattern) { - var stringToWordSpans = ts.createMap(); + var stringToWordSpans = {}; pattern = pattern.trim(); var dotSeparatedSegments = pattern.split(".").map(function (p) { return createSegment(p.trim()); }); var invalidPattern = dotSeparatedSegments.length === 0 || ts.forEach(dotSeparatedSegments, segmentIsInvalid); @@ -41195,7 +39875,7 @@ var ts; return totalMatch; } function getWordSpans(word) { - if (!(word in stringToWordSpans)) { + if (!ts.hasProperty(stringToWordSpans, word)) { stringToWordSpans[word] = breakIntoWordSpans(word); } return stringToWordSpans[word]; @@ -41207,7 +39887,7 @@ var ts; return createPatternMatch(PatternMatchKind.exact, punctuationStripped, candidate === chunk.text); } else { - return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, ts.startsWith(candidate, chunk.text)); + return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, startsWith(candidate, chunk.text)); } } var isLowercase = chunk.isLowerCase; @@ -41379,6 +40059,14 @@ var ts; var str = String.fromCharCode(ch); return str === str.toLowerCase(); } + function startsWith(string, search) { + for (var i = 0, n = search.length; i < n; i++) { + if (string.charCodeAt(i) !== search.charCodeAt(i)) { + return false; + } + } + return true; + } function indexOfIgnoringCase(string, value) { for (var i = 0, n = string.length - value.length; i <= n; i++) { if (startsWithIgnoringCase(string, value, i)) { @@ -41589,7 +40277,7 @@ var ts; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; var nameToDeclarations = sourceFile.getNamedDeclarations(); - var declarations = nameToDeclarations[name.text]; + var declarations = ts.getProperty(nameToDeclarations, name.text); if (declarations) { for (var _b = 0, declarations_8 = declarations; _b < declarations_8.length; _b++) { var declaration = declarations_8[_b]; @@ -41853,7 +40541,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var tripleSlashDirectivePrefixRegex = /^\/\/\/\s*= node.end) { + if (c.kind === 282 && c.pos <= node.pos && c.end >= node.end) { return c; } }); @@ -42186,7 +40873,8 @@ var ts; ts.findPrecedingToken = findPrecedingToken; function isInString(sourceFile, position) { var previousToken = findPrecedingToken(position, sourceFile); - if (previousToken && previousToken.kind === 9) { + if (previousToken && + (previousToken.kind === 9 || previousToken.kind === 166)) { var start = previousToken.getStart(); var end = previousToken.getEnd(); if (start < position && position < end) { @@ -42335,6 +41023,7 @@ var ts; ts.isComment = isComment; function isStringOrRegularExpressionOrTemplateLiteral(kind) { if (kind === 9 + || kind === 166 || kind === 10 || ts.isTemplateLiteralKind(kind)) { return true; @@ -42396,27 +41085,6 @@ var ts; return false; } ts.isArrayLiteralOrObjectLiteralDestructuringPattern = isArrayLiteralOrObjectLiteralDestructuringPattern; - function hasTrailingDirectorySeparator(path) { - var lastCharacter = path.charAt(path.length - 1); - return lastCharacter === "/" || lastCharacter === "\\"; - } - ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; - function isInReferenceComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, isReferenceComment); - function isReferenceComment(c) { - var commentText = sourceFile.text.substring(c.pos, c.end); - return tripleSlashDirectivePrefixRegex.test(commentText); - } - } - ts.isInReferenceComment = isInReferenceComment; - function isInNonReferenceComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, isNonReferenceComment); - function isNonReferenceComment(c) { - var commentText = sourceFile.text.substring(c.pos, c.end); - return !tripleSlashDirectivePrefixRegex.test(commentText); - } - } - ts.isInNonReferenceComment = isInNonReferenceComment; })(ts || (ts = {})); var ts; (function (ts) { @@ -42635,34 +41303,158 @@ var ts; if (host && host.getScriptKind) { scriptKind = host.getScriptKind(fileName); } - if (!scriptKind) { + if (!scriptKind || scriptKind === 0) { scriptKind = ts.getScriptKindFromFileName(fileName); } return ts.ensureScriptKind(fileName, scriptKind); } ts.getScriptKind = getScriptKind; - function sanitizeConfigFile(configFileName, content) { - var options = { - fileName: "config.js", - compilerOptions: { - target: 2, - removeComments: true - }, - reportDiagnostics: true - }; - var _a = ts.transpileModule("(" + content + ")", options), outputText = _a.outputText, diagnostics = _a.diagnostics; - var trimmedOutput = outputText.trim(); - for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { - var diagnostic = diagnostics_3[_i]; - diagnostic.start = diagnostic.start - 1; +})(ts || (ts = {})); +var ts; +(function (ts) { + var JsTyping; + (function (JsTyping) { + ; + ; + var safeList; + function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typingOptions, compilerOptions) { + var inferredTypings = {}; + if (!typingOptions || !typingOptions.enableAutoDiscovery) { + return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; + } + fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { return ts.scriptKindIs(f, undefined, 1, 2); }); + if (!safeList) { + var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); + if (result.config) { + safeList = result.config; + } + else { + safeList = {}; + } + ; + } + var filesToWatch = []; + var searchDirs = []; + var exclude = []; + mergeTypings(typingOptions.include); + exclude = typingOptions.exclude || []; + var possibleSearchDirs = ts.map(fileNames, ts.getDirectoryPath); + if (projectRootPath !== undefined) { + possibleSearchDirs.push(projectRootPath); + } + searchDirs = ts.deduplicate(possibleSearchDirs); + for (var _i = 0, searchDirs_1 = searchDirs; _i < searchDirs_1.length; _i++) { + var searchDir = searchDirs_1[_i]; + var packageJsonPath = ts.combinePaths(searchDir, "package.json"); + getTypingNamesFromJson(packageJsonPath, filesToWatch); + var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); + getTypingNamesFromJson(bowerJsonPath, filesToWatch); + var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); + getTypingNamesFromNodeModuleFolder(nodeModulesPath); + } + getTypingNamesFromSourceFileNames(fileNames); + for (var name_39 in packageNameToTypingLocation) { + if (ts.hasProperty(inferredTypings, name_39) && !inferredTypings[name_39]) { + inferredTypings[name_39] = packageNameToTypingLocation[name_39]; + } + } + for (var _a = 0, exclude_1 = exclude; _a < exclude_1.length; _a++) { + var excludeTypingName = exclude_1[_a]; + delete inferredTypings[excludeTypingName]; + } + var newTypingNames = []; + var cachedTypingPaths = []; + for (var typing in inferredTypings) { + if (inferredTypings[typing] !== undefined) { + cachedTypingPaths.push(inferredTypings[typing]); + } + else { + newTypingNames.push(typing); + } + } + return { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; + function mergeTypings(typingNames) { + if (!typingNames) { + return; + } + for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) { + var typing = typingNames_1[_i]; + if (!ts.hasProperty(inferredTypings, typing)) { + inferredTypings[typing] = undefined; + } + } + } + function getTypingNamesFromJson(jsonPath, filesToWatch) { + var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }); + if (result.config) { + var jsonConfig = result.config; + filesToWatch.push(jsonPath); + if (jsonConfig.dependencies) { + mergeTypings(ts.getKeys(jsonConfig.dependencies)); + } + if (jsonConfig.devDependencies) { + mergeTypings(ts.getKeys(jsonConfig.devDependencies)); + } + if (jsonConfig.optionalDependencies) { + mergeTypings(ts.getKeys(jsonConfig.optionalDependencies)); + } + if (jsonConfig.peerDependencies) { + mergeTypings(ts.getKeys(jsonConfig.peerDependencies)); + } + } + } + function getTypingNamesFromSourceFileNames(fileNames) { + var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension); + var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); }); + var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); }); + if (safeList === undefined) { + mergeTypings(cleanedTypingNames); + } + else { + mergeTypings(ts.filter(cleanedTypingNames, function (f) { return ts.hasProperty(safeList, f); })); + } + var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.scriptKindIs(f, undefined, 2); }); + if (hasJsxFile) { + mergeTypings(["react"]); + } + } + function getTypingNamesFromNodeModuleFolder(nodeModulesPath) { + if (!host.directoryExists(nodeModulesPath)) { + return; + } + var typingNames = []; + var fileNames = host.readDirectory(nodeModulesPath, ["*.json"], undefined, undefined, 2); + for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { + var fileName = fileNames_2[_i]; + var normalizedFileName = ts.normalizePath(fileName); + if (ts.getBaseFileName(normalizedFileName) !== "package.json") { + continue; + } + var result = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + if (!result.config) { + continue; + } + var packageJson = result.config; + if (packageJson._requiredBy && + ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { + continue; + } + if (!packageJson.name) { + continue; + } + if (packageJson.typings) { + var absolutePath = ts.getNormalizedAbsolutePath(packageJson.typings, ts.getDirectoryPath(normalizedFileName)); + inferredTypings[packageJson.name] = absolutePath; + } + else { + typingNames.push(packageJson.name); + } + } + mergeTypings(typingNames); + } } - var _b = ts.parseConfigFileTextToJson(configFileName, trimmedOutput.substring(1, trimmedOutput.length - 2), false), config = _b.config, error = _b.error; - return { - configJsonObject: config || {}, - diagnostics: error ? ts.concatenate(diagnostics, [error]) : diagnostics - }; - } - ts.sanitizeConfigFile = sanitizeConfigFile; + JsTyping.discoverTypings = discoverTypings; + })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); var ts; (function (ts) { @@ -42759,9 +41551,6 @@ var ts; } return false; } - function shouldRescanJsxText(node) { - return node && node.kind === 244; - } function shouldRescanSlashToken(container) { return container.kind === 10; } @@ -42789,9 +41578,7 @@ var ts; ? 3 : shouldRescanJsxIdentifier(n) ? 4 - : shouldRescanJsxText(n) - ? 5 - : 0; + : 0; if (lastTokenInfo && expectedScanAction === lastScanAction) { return fixTokenKind(lastTokenInfo, n); } @@ -42819,10 +41606,6 @@ var ts; currentToken = scanner.scanJsxIdentifier(); lastScanAction = 4; } - else if (expectedScanAction === 5) { - currentToken = scanner.reScanJsxToken(); - lastScanAction = 5; - } else { lastScanAction = 0; } @@ -43124,7 +41907,7 @@ var ts; this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 8)); this.SpaceAfterVoidOperator = new formatting.Rule(formatting.RuleDescriptor.create3(103, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsVoidOpContext), 2)); this.NoSpaceBetweenReturnAndSemicolon = new formatting.Rule(formatting.RuleDescriptor.create1(94, 23), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([18, 79, 80, 71]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNotForContext), 2)); + this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([18, 79, 80, 71]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isNonJsxElementContext, Rules.IsNotForContext), 2)); this.SpaceAfterTryFinally = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([100, 85]), 15), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([123, 131]), 69), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); this.SpaceBeforeBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryKeywordOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); @@ -43155,11 +41938,6 @@ var ts; this.SpaceBetweenAsyncAndOpenParen = new formatting.Rule(formatting.RuleDescriptor.create1(118, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsArrowFunctionContext, Rules.IsNonJsxSameLineTokenContext), 2)); this.SpaceBetweenAsyncAndFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(118, 87), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); this.NoSpaceBetweenTagAndTemplateString = new formatting.Rule(formatting.RuleDescriptor.create3(69, formatting.Shared.TokenRange.FromTokens([11, 12])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); - this.SpaceBeforeJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 69), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNextTokenParentJsxAttribute, Rules.IsNonJsxSameLineTokenContext), 2)); - this.SpaceBeforeSlashInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 39), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceBeforeGreaterThanTokenInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create1(39, 27), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceBeforeEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 56), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8)); - this.NoSpaceAfterEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create3(56, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8)); this.HighPriorityCommonRules = [ this.IgnoreBeforeComment, this.IgnoreAfterLineComment, this.NoSpaceBeforeColon, this.SpaceAfterColon, this.NoSpaceBeforeQuestionMark, this.SpaceAfterQuestionMarkInConditionalOperator, @@ -43186,8 +41964,6 @@ var ts; this.SpaceAfterVoidOperator, this.SpaceBetweenAsyncAndOpenParen, this.SpaceBetweenAsyncAndFunctionKeyword, this.NoSpaceBetweenTagAndTemplateString, - this.SpaceBeforeJsxAttribute, this.SpaceBeforeSlashInJsxOpeningElement, this.NoSpaceBeforeGreaterThanTokenInJsxOpeningElement, - this.NoSpaceBeforeEqualInJsxAttribute, this.NoSpaceAfterEqualInJsxAttribute, this.NoSpaceAfterConstructor, this.NoSpaceAfterModuleImport, this.SpaceAfterCertainTypeScriptKeywords, this.SpaceBeforeCertainTypeScriptKeywords, this.SpaceAfterModuleName, @@ -43215,8 +41991,8 @@ var ts; this.NoSpaceBeforeOpenParenInFuncDecl, this.SpaceBetweenStatements, this.SpaceAfterTryFinally ]; - this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2)); - this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext), 8)); + this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2)); + this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isNonJsxElementContext), 8)); this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); this.SpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); this.NoSpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); @@ -43242,10 +42018,10 @@ var ts; this.SpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([12, 13]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([13, 14])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); this.SpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([13, 14])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); - this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); - this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); - this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8)); - this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2)); + this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isJsxExpressionContext), 8)); + this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isJsxExpressionContext), 2)); + this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isJsxExpressionContext), 8)); + this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isJsxExpressionContext), 2)); this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(87, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(87, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 8)); } @@ -43420,21 +42196,12 @@ var ts; Rules.IsNonJsxSameLineTokenContext = function (context) { return context.TokensAreOnSameLine() && context.contextNode.kind !== 244; }; - Rules.IsNonJsxElementContext = function (context) { + Rules.isNonJsxElementContext = function (context) { return context.contextNode.kind !== 241; }; - Rules.IsJsxExpressionContext = function (context) { + Rules.isJsxExpressionContext = function (context) { return context.contextNode.kind === 248; }; - Rules.IsNextTokenParentJsxAttribute = function (context) { - return context.nextTokenParent.kind === 246; - }; - Rules.IsJsxAttributeContext = function (context) { - return context.contextNode.kind === 246; - }; - Rules.IsJsxSelfClosingElementContext = function (context) { - return context.contextNode.kind === 242; - }; Rules.IsNotBeforeBlockInFunctionDeclarationContext = function (context) { return !Rules.IsFunctionDeclContext(context) && !Rules.IsBeforeBlockContext(context); }; @@ -43784,25 +42551,25 @@ var ts; }; RulesProvider.prototype.createActiveRules = function (options) { var rules = this.globalRules.HighPriorityCommonRules.slice(0); - if (options.insertSpaceAfterCommaDelimiter) { + if (options.InsertSpaceAfterCommaDelimiter) { rules.push(this.globalRules.SpaceAfterComma); } else { rules.push(this.globalRules.NoSpaceAfterComma); } - if (options.insertSpaceAfterFunctionKeywordForAnonymousFunctions) { + if (options.InsertSpaceAfterFunctionKeywordForAnonymousFunctions) { rules.push(this.globalRules.SpaceAfterAnonymousFunctionKeyword); } else { rules.push(this.globalRules.NoSpaceAfterAnonymousFunctionKeyword); } - if (options.insertSpaceAfterKeywordsInControlFlowStatements) { + if (options.InsertSpaceAfterKeywordsInControlFlowStatements) { rules.push(this.globalRules.SpaceAfterKeywordInControl); } else { rules.push(this.globalRules.NoSpaceAfterKeywordInControl); } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { + if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { rules.push(this.globalRules.SpaceAfterOpenParen); rules.push(this.globalRules.SpaceBeforeCloseParen); rules.push(this.globalRules.NoSpaceBetweenParens); @@ -43812,7 +42579,7 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseParen); rules.push(this.globalRules.NoSpaceBetweenParens); } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { + if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { rules.push(this.globalRules.SpaceAfterOpenBracket); rules.push(this.globalRules.SpaceBeforeCloseBracket); rules.push(this.globalRules.NoSpaceBetweenBrackets); @@ -43822,7 +42589,7 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseBracket); rules.push(this.globalRules.NoSpaceBetweenBrackets); } - if (options.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { + if (options.InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle); rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail); } @@ -43830,7 +42597,7 @@ var ts; rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle); rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail); } - if (options.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) { + if (options.InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) { rules.push(this.globalRules.SpaceAfterOpenBraceInJsxExpression); rules.push(this.globalRules.SpaceBeforeCloseBraceInJsxExpression); } @@ -43838,13 +42605,13 @@ var ts; rules.push(this.globalRules.NoSpaceAfterOpenBraceInJsxExpression); rules.push(this.globalRules.NoSpaceBeforeCloseBraceInJsxExpression); } - if (options.insertSpaceAfterSemicolonInForStatements) { + if (options.InsertSpaceAfterSemicolonInForStatements) { rules.push(this.globalRules.SpaceAfterSemicolonInFor); } else { rules.push(this.globalRules.NoSpaceAfterSemicolonInFor); } - if (options.insertSpaceBeforeAndAfterBinaryOperators) { + if (options.InsertSpaceBeforeAndAfterBinaryOperators) { rules.push(this.globalRules.SpaceBeforeBinaryOperator); rules.push(this.globalRules.SpaceAfterBinaryOperator); } @@ -43852,10 +42619,10 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeBinaryOperator); rules.push(this.globalRules.NoSpaceAfterBinaryOperator); } - if (options.placeOpenBraceOnNewLineForControlBlocks) { + if (options.PlaceOpenBraceOnNewLineForControlBlocks) { rules.push(this.globalRules.NewLineBeforeOpenBraceInControl); } - if (options.placeOpenBraceOnNewLineForFunctions) { + if (options.PlaceOpenBraceOnNewLineForFunctions) { rules.push(this.globalRules.NewLineBeforeOpenBraceInFunction); rules.push(this.globalRules.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock); } @@ -44024,7 +42791,7 @@ var ts; break; } if (formatting.SmartIndenter.shouldIndentChildNode(n, child)) { - return options.indentSize; + return options.IndentSize; } previousLine = line; child = n; @@ -44084,12 +42851,12 @@ var ts; } function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) { var indentation = inheritedIndentation; - var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0; + var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.IndentSize : 0; if (effectiveParentStartLine === startLine) { indentation = startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(); - delta = Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta); + delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta(node) + delta); } else if (indentation === -1) { if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { @@ -44161,13 +42928,13 @@ var ts; recomputeIndentation: function (lineAdded) { if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent, node)) { if (lineAdded) { - indentation += options.indentSize; + indentation += options.IndentSize; } else { - indentation -= options.indentSize; + indentation -= options.IndentSize; } if (formatting.SmartIndenter.shouldIndentChildNode(node)) { - delta = options.indentSize; + delta = options.IndentSize; } else { delta = 0; @@ -44527,7 +43294,7 @@ var ts; } var lineDelta = currentStartLine - previousStartLine; if (lineDelta !== 1) { - recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.newLineCharacter); + recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.NewLineCharacter); } break; case 2: @@ -44586,14 +43353,14 @@ var ts; var internedTabsIndentation; var internedSpacesIndentation; function getIndentationString(indentation, options) { - var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.tabSize || internedSizes.indentSize !== options.indentSize); + var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.TabSize || internedSizes.indentSize !== options.IndentSize); if (resetInternedStrings) { - internedSizes = { tabSize: options.tabSize, indentSize: options.indentSize }; + internedSizes = { tabSize: options.TabSize, indentSize: options.IndentSize }; internedTabsIndentation = internedSpacesIndentation = undefined; } - if (!options.convertTabsToSpaces) { - var tabs = Math.floor(indentation / options.tabSize); - var spaces = indentation - tabs * options.tabSize; + if (!options.ConvertTabsToSpaces) { + var tabs = Math.floor(indentation / options.TabSize); + var spaces = indentation - tabs * options.TabSize; var tabString = void 0; if (!internedTabsIndentation) { internedTabsIndentation = []; @@ -44608,13 +43375,13 @@ var ts; } else { var spacesString = void 0; - var quotient = Math.floor(indentation / options.indentSize); - var remainder = indentation % options.indentSize; + var quotient = Math.floor(indentation / options.IndentSize); + var remainder = indentation % options.IndentSize; if (!internedSpacesIndentation) { internedSpacesIndentation = []; } if (internedSpacesIndentation[quotient] === undefined) { - spacesString = repeat(" ", options.indentSize * quotient); + spacesString = repeat(" ", options.IndentSize * quotient); internedSpacesIndentation[quotient] = spacesString; } else { @@ -44643,7 +43410,7 @@ var ts; if (position > sourceFile.text.length) { return getBaseIndentation(options); } - if (options.indentStyle === ts.IndentStyle.None) { + if (options.IndentStyle === ts.IndentStyle.None) { return 0; } var precedingToken = ts.findPrecedingToken(position, sourceFile); @@ -44655,7 +43422,7 @@ var ts; return 0; } var lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line; - if (options.indentStyle === ts.IndentStyle.Block) { + if (options.IndentStyle === ts.IndentStyle.Block) { var current_1 = position; while (current_1 > 0) { var char = sourceFile.text.charCodeAt(current_1); @@ -44684,7 +43451,7 @@ var ts; indentationDelta = 0; } else { - indentationDelta = lineAtPosition !== currentStart.line ? options.indentSize : 0; + indentationDelta = lineAtPosition !== currentStart.line ? options.IndentSize : 0; } break; } @@ -44694,7 +43461,7 @@ var ts; } actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); if (actualIndentation !== -1) { - return actualIndentation + options.indentSize; + return actualIndentation + options.IndentSize; } previous = current; current = current.parent; @@ -44705,15 +43472,15 @@ var ts; return getIndentationForNodeWorker(current, currentStart, undefined, indentationDelta, sourceFile, options); } SmartIndenter.getIndentation = getIndentation; + function getBaseIndentation(options) { + return options.BaseIndentSize || 0; + } + SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) { var start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, 0, sourceFile, options); } SmartIndenter.getIndentationForNode = getIndentationForNode; - function getBaseIndentation(options) { - return options.baseIndentSize || 0; - } - SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, options) { var parent = current.parent; var parentStart; @@ -44743,7 +43510,7 @@ var ts; } } if (shouldIndentChildNode(parent, current) && !parentAndChildShareLine) { - indentationDelta += options.indentSize; + indentationDelta += options.IndentSize; } current = parent; currentStart = parentStart; @@ -44921,7 +43688,7 @@ var ts; break; } if (ch === 9) { - column += options.tabSize + (column % options.tabSize); + column += options.TabSize + (column % options.TabSize); } else { column++; @@ -45043,20 +43810,6 @@ var ts; } ScriptSnapshot.fromString = fromString; })(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {})); - function realizeDiagnostics(diagnostics, newLine) { - return diagnostics.map(function (d) { return realizeDiagnostic(d, newLine); }); - } - ts.realizeDiagnostics = realizeDiagnostics; - function realizeDiagnostic(diagnostic, newLine) { - return { - message: ts.flattenDiagnosticMessageText(diagnostic.messageText, newLine), - start: diagnostic.start, - length: diagnostic.length, - category: ts.DiagnosticCategory[diagnostic.category].toLowerCase(), - code: diagnostic.code - }; - } - ts.realizeDiagnostic = realizeDiagnostic; var scanner = ts.createScanner(2, true); var emptyArray = []; var jsDocTagNames = [ @@ -45101,20 +43854,19 @@ var ts; "version" ]; var jsDocCompletionEntries; - function createNode(kind, pos, end, parent) { - var node = kind >= 139 ? new NodeObject(kind, pos, end) : - kind === 69 ? new IdentifierObject(kind, pos, end) : - new TokenObject(kind, pos, end); + function createNode(kind, pos, end, flags, parent) { + var node = new NodeObject(kind, pos, end); + node.flags = flags; node.parent = parent; return node; } var NodeObject = (function () { function NodeObject(kind, pos, end) { + this.kind = kind; this.pos = pos; this.end = end; this.flags = 0; this.parent = undefined; - this.kind = kind; } NodeObject.prototype.getSourceFile = function () { return ts.getSourceFileOfNode(this); @@ -45149,14 +43901,14 @@ var ts; var token = useJSDocScanner ? scanner.scanJSDocToken() : scanner.scan(); var textPos = scanner.getTextPos(); if (textPos <= end) { - nodes.push(createNode(token, pos, textPos, this)); + nodes.push(createNode(token, pos, textPos, 0, this)); } pos = textPos; } return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(286, nodes.pos, nodes.end, this); + var list = createNode(282, nodes.pos, nodes.end, 0, this); list._children = []; var pos = nodes.pos; for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { @@ -45179,16 +43931,13 @@ var ts; scanner.setText((sourceFile || this.getSourceFile()).text); children = []; var pos_3 = this.pos; - var useJSDocScanner_1 = this.kind >= 273 && this.kind <= 285; + var useJSDocScanner_1 = this.kind >= 273 && this.kind <= 281; var processNode = function (node) { - var isJSDocTagNode = ts.isJSDocTag(node); - if (!isJSDocTagNode && pos_3 < node.pos) { + if (pos_3 < node.pos) { pos_3 = _this.addSyntheticNodes(children, pos_3, node.pos, useJSDocScanner_1); } children.push(node); - if (!isJSDocTagNode) { - pos_3 = node.end; - } + pos_3 = node.end; }; var processNodes = function (nodes) { if (pos_3 < nodes.pos) { @@ -45244,73 +43993,6 @@ var ts; }; return NodeObject; }()); - var TokenOrIdentifierObject = (function () { - function TokenOrIdentifierObject(pos, end) { - this.pos = pos; - this.end = end; - this.flags = 0; - this.parent = undefined; - } - TokenOrIdentifierObject.prototype.getSourceFile = function () { - return ts.getSourceFileOfNode(this); - }; - TokenOrIdentifierObject.prototype.getStart = function (sourceFile, includeJsDocComment) { - return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment); - }; - TokenOrIdentifierObject.prototype.getFullStart = function () { - return this.pos; - }; - TokenOrIdentifierObject.prototype.getEnd = function () { - return this.end; - }; - TokenOrIdentifierObject.prototype.getWidth = function (sourceFile) { - return this.getEnd() - this.getStart(sourceFile); - }; - TokenOrIdentifierObject.prototype.getFullWidth = function () { - return this.end - this.pos; - }; - TokenOrIdentifierObject.prototype.getLeadingTriviaWidth = function (sourceFile) { - return this.getStart(sourceFile) - this.pos; - }; - TokenOrIdentifierObject.prototype.getFullText = function (sourceFile) { - return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end); - }; - TokenOrIdentifierObject.prototype.getText = function (sourceFile) { - return (sourceFile || this.getSourceFile()).text.substring(this.getStart(), this.getEnd()); - }; - TokenOrIdentifierObject.prototype.getChildCount = function (sourceFile) { - return 0; - }; - TokenOrIdentifierObject.prototype.getChildAt = function (index, sourceFile) { - return undefined; - }; - TokenOrIdentifierObject.prototype.getChildren = function (sourceFile) { - return emptyArray; - }; - TokenOrIdentifierObject.prototype.getFirstToken = function (sourceFile) { - return undefined; - }; - TokenOrIdentifierObject.prototype.getLastToken = function (sourceFile) { - return undefined; - }; - return TokenOrIdentifierObject; - }()); - var TokenObject = (function (_super) { - __extends(TokenObject, _super); - function TokenObject(kind, pos, end) { - _super.call(this, pos, end); - this.kind = kind; - } - return TokenObject; - }(TokenOrIdentifierObject)); - var IdentifierObject = (function (_super) { - __extends(IdentifierObject, _super); - function IdentifierObject(kind, pos, end) { - _super.call(this, pos, end); - } - return IdentifierObject; - }(TokenOrIdentifierObject)); - IdentifierObject.prototype.kind = 69; var SymbolObject = (function () { function SymbolObject(flags, name) { this.flags = flags; @@ -45613,7 +44295,7 @@ var ts; return this.checker.getIndexTypeOfType(this, 1); }; TypeObject.prototype.getBaseTypes = function () { - return this.flags & (32768 | 65536) + return this.flags & (1024 | 2048) ? this.checker.getBaseTypes(this) : undefined; }; @@ -45670,7 +44352,7 @@ var ts; return this.namedDeclarations; }; SourceFileObject.prototype.computeNamedDeclarations = function () { - var result = ts.createMap(); + var result = {}; ts.forEachChild(this, visit); return result; function addDeclaration(declaration) { @@ -45681,13 +44363,13 @@ var ts; } } function getDeclarations(name) { - return result[name] || (result[name] = []); + return ts.getProperty(result, name) || (result[name] = []); } function getDeclarationName(declaration) { if (declaration.name) { - var result_3 = getTextOfIdentifierOrLiteral(declaration.name); - if (result_3 !== undefined) { - return result_3; + var result_2 = getTextOfIdentifierOrLiteral(declaration.name); + if (result_2 !== undefined) { + return result_2; } if (declaration.name.kind === 140) { var expr = declaration.name.expression; @@ -45815,30 +44497,6 @@ var ts; IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; })(ts.IndentStyle || (ts.IndentStyle = {})); var IndentStyle = ts.IndentStyle; - function toEditorSettings(optionsAsMap) { - var allPropertiesAreCamelCased = true; - for (var key in optionsAsMap) { - if (ts.hasProperty(optionsAsMap, key) && !isCamelCase(key)) { - allPropertiesAreCamelCased = false; - break; - } - } - if (allPropertiesAreCamelCased) { - return optionsAsMap; - } - var settings = {}; - for (var key in optionsAsMap) { - if (ts.hasProperty(optionsAsMap, key)) { - var newKey = isCamelCase(key) ? key : key.charAt(0).toLowerCase() + key.substr(1); - settings[newKey] = optionsAsMap[key]; - } - } - return settings; - } - ts.toEditorSettings = toEditorSettings; - function isCamelCase(s) { - return !s.length || s.charAt(0) === s.charAt(0).toLowerCase(); - } (function (SymbolDisplayPartKind) { SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; SymbolDisplayPartKind[SymbolDisplayPartKind["className"] = 1] = "className"; @@ -45888,7 +44546,6 @@ var ts; ScriptElementKind.interfaceElement = "interface"; ScriptElementKind.typeElement = "type"; ScriptElementKind.enumElement = "enum"; - ScriptElementKind.enumMemberElement = "const"; ScriptElementKind.variableElement = "var"; ScriptElementKind.localVariableElement = "local var"; ScriptElementKind.functionElement = "function"; @@ -45908,8 +44565,6 @@ var ts; ScriptElementKind.alias = "alias"; ScriptElementKind.constElement = "const"; ScriptElementKind.letElement = "let"; - ScriptElementKind.directory = "directory"; - ScriptElementKind.externalModuleName = "external module name"; })(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {})); var ScriptElementKindModifier; (function (ScriptElementKindModifier) { @@ -45969,8 +44624,8 @@ var ts; if (declaration.kind !== 218 && declaration.kind !== 220) { return false; } - for (var parent_17 = declaration.parent; !ts.isFunctionBlock(parent_17); parent_17 = parent_17.parent) { - if (parent_17.kind === 256 || parent_17.kind === 226) { + for (var parent_16 = declaration.parent; !ts.isFunctionBlock(parent_16); parent_16 = parent_16.parent) { + if (parent_16.kind === 256 || parent_16.kind === 226) { return false; } } @@ -46048,16 +44703,43 @@ var ts; }; return HostCache; }()); + var SyntaxTreeCache = (function () { + function SyntaxTreeCache(host) { + this.host = host; + } + SyntaxTreeCache.prototype.getCurrentSourceFile = function (fileName) { + var scriptSnapshot = this.host.getScriptSnapshot(fileName); + if (!scriptSnapshot) { + throw new Error("Could not find file: '" + fileName + "'."); + } + var scriptKind = ts.getScriptKind(fileName, this.host); + var version = this.host.getScriptVersion(fileName); + var sourceFile; + if (this.currentFileName !== fileName) { + sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 2, version, true, scriptKind); + } + else if (this.currentFileVersion !== version) { + var editRange = scriptSnapshot.getChangeRange(this.currentFileScriptSnapshot); + sourceFile = updateLanguageServiceSourceFile(this.currentSourceFile, scriptSnapshot, version, editRange); + } + if (sourceFile) { + this.currentFileVersion = version; + this.currentFileName = fileName; + this.currentFileScriptSnapshot = scriptSnapshot; + this.currentSourceFile = sourceFile; + } + return this.currentSourceFile; + }; + return SyntaxTreeCache; + }()); function setSourceFileFields(sourceFile, scriptSnapshot, version) { sourceFile.version = version; sourceFile.scriptSnapshot = scriptSnapshot; } - var tripleSlashDirectiveFragmentRegex = /^(\/\/\/\s*= commentRange.pos && position <= commentRange.end && commentRange; }); - if (!range) { - return undefined; - } - var text = sourceFile.text.substr(range.pos, position - range.pos); - var match = tripleSlashDirectiveFragmentRegex.exec(text); - if (match) { - var prefix = match[1]; - var kind = match[2]; - var toComplete = match[3]; - var scriptPath = ts.getDirectoryPath(sourceFile.path); - var entries_3; - if (kind === "path") { - var span = getDirectoryFragmentTextSpan(toComplete, range.pos + prefix.length); - entries_3 = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(program.getCompilerOptions()), true, span, sourceFile.path); - } - else { - var span = { start: range.pos + prefix.length, length: match[0].length - prefix.length }; - entries_3 = getCompletionEntriesFromTypings(host, program.getCompilerOptions(), scriptPath, span); - } - return { - isMemberCompletion: false, - isNewIdentifierLocation: true, - entries: entries_3 - }; - } - return undefined; - } - function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { - if (result === void 0) { result = []; } - if (options.types) { - for (var _i = 0, _a = options.types; _i < _a.length; _i++) { - var moduleName = _a[_i]; - result.push(createCompletionEntryForModule(moduleName, ScriptElementKind.externalModuleName, span)); - } - } - else if (host.getDirectories) { - var typeRoots = ts.getEffectiveTypeRoots(options, host); - for (var _b = 0, typeRoots_2 = typeRoots; _b < typeRoots_2.length; _b++) { - var root = typeRoots_2[_b]; - getCompletionEntriesFromDirectories(host, options, root, span, result); - } - } - if (host.getDirectories) { - for (var _c = 0, _d = findPackageJsons(scriptPath); _c < _d.length; _c++) { - var package = _d[_c]; - var typesDir = ts.combinePaths(ts.getDirectoryPath(package), "node_modules/@types"); - getCompletionEntriesFromDirectories(host, options, typesDir, span, result); - } - } - return result; - } - function getCompletionEntriesFromDirectories(host, options, directory, span, result) { - if (host.getDirectories && tryDirectoryExists(host, directory)) { - var directories = tryGetDirectories(host, directory); - if (directories) { - for (var _i = 0, directories_3 = directories; _i < directories_3.length; _i++) { - var typeDirectory = directories_3[_i]; - typeDirectory = ts.normalizePath(typeDirectory); - result.push(createCompletionEntryForModule(ts.getBaseFileName(typeDirectory), ScriptElementKind.externalModuleName, span)); - } - } - } - } - function findPackageJsons(currentDir) { - var paths = []; - var currentConfigPath; - while (true) { - currentConfigPath = ts.findConfigFile(currentDir, function (f) { return tryFileExists(host, f); }, "package.json"); - if (currentConfigPath) { - paths.push(currentConfigPath); - currentDir = ts.getDirectoryPath(currentConfigPath); - var parent_21 = ts.getDirectoryPath(currentDir); - if (currentDir === parent_21) { - break; - } - currentDir = parent_21; - } - else { - break; - } - } - return paths; - } - function enumerateNodeModulesVisibleToScript(host, scriptPath) { - var result = []; - if (host.readFile && host.fileExists) { - for (var _i = 0, _a = findPackageJsons(scriptPath); _i < _a.length; _i++) { - var packageJson = _a[_i]; - var package = tryReadingPackageJson(packageJson); - if (!package) { - return; - } - var nodeModulesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules"); - var foundModuleNames = []; - for (var _b = 0, nodeModulesDependencyKeys_1 = nodeModulesDependencyKeys; _b < nodeModulesDependencyKeys_1.length; _b++) { - var key = nodeModulesDependencyKeys_1[_b]; - addPotentialPackageNames(package[key], foundModuleNames); - } - for (var _c = 0, foundModuleNames_1 = foundModuleNames; _c < foundModuleNames_1.length; _c++) { - var moduleName = foundModuleNames_1[_c]; - var moduleDir = ts.combinePaths(nodeModulesDir, moduleName); - result.push({ - moduleName: moduleName, - moduleDir: moduleDir - }); - } - } - } - return result; - function tryReadingPackageJson(filePath) { - try { - var fileText = tryReadFile(host, filePath); - return fileText ? JSON.parse(fileText) : undefined; - } - catch (e) { - return undefined; - } - } - function addPotentialPackageNames(dependencies, result) { - if (dependencies) { - for (var dep in dependencies) { - if (dependencies.hasOwnProperty(dep) && !ts.startsWith(dep, "@types/")) { - result.push(dep); - } - } - } - } - } - function createCompletionEntryForModule(name, kind, replacementSpan) { - return { name: name, kind: kind, kindModifiers: ScriptElementKindModifier.none, sortText: name, replacementSpan: replacementSpan }; - } - function getDirectoryFragmentTextSpan(text, textStart) { - var index = text.lastIndexOf(ts.directorySeparator); - var offset = index !== -1 ? index + 1 : 0; - return { start: textStart + offset, length: text.length - offset }; - } - function isPathRelativeToScript(path) { - if (path && path.length >= 2 && path.charCodeAt(0) === 46) { - var slashIndex = path.length >= 3 && path.charCodeAt(1) === 46 ? 2 : 1; - var slashCharCode = path.charCodeAt(slashIndex); - return slashCharCode === 47 || slashCharCode === 92; - } - return false; - } - function normalizeAndPreserveTrailingSlash(path) { - return ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(ts.normalizePath(path)) : ts.normalizePath(path); - } - function tryGetDirectories(host, directoryName) { - return tryIOAndConsumeErrors(host, host.getDirectories, directoryName); - } - function tryReadDirectory(host, path, extensions, exclude, include) { - return tryIOAndConsumeErrors(host, host.readDirectory, path, extensions, exclude, include); - } - function tryReadFile(host, path) { - return tryIOAndConsumeErrors(host, host.readFile, path); - } - function tryFileExists(host, path) { - return tryIOAndConsumeErrors(host, host.fileExists, path); - } - function tryDirectoryExists(host, path) { - try { - return ts.directoryProbablyExists(path, host); - } - catch (e) { } - return undefined; - } - function tryIOAndConsumeErrors(host, toApply) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - try { - return toApply && toApply.apply(host, args); - } - catch (e) { } - return undefined; - } } function getCompletionEntryDetails(fileName, position, entryName) { synchronizeHostData(); @@ -48434,7 +46629,7 @@ var ts; displayParts.push(ts.keywordPart(92)); displayParts.push(ts.spacePart()); } - if (!(type.flags & 2097152) && type.symbol) { + if (!(type.flags & 65536) && type.symbol) { ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, undefined, 1)); } addSignatureDisplayParts(signature, allSignatures, 8); @@ -48495,7 +46690,7 @@ var ts; displayParts.push(ts.spacePart()); displayParts.push(ts.operatorPart(56)); displayParts.push(ts.spacePart()); - ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 512)); + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration)); } if (symbolFlags & 384) { addNewLineIfDisplayPartsExist(); @@ -48569,14 +46764,7 @@ var ts; } if (symbolFlags & 8388608) { addNewLineIfDisplayPartsExist(); - if (symbol.declarations[0].kind === 228) { - displayParts.push(ts.keywordPart(82)); - displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(126)); - } - else { - displayParts.push(ts.keywordPart(89)); - } + displayParts.push(ts.keywordPart(89)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); ts.forEach(symbol.declarations, function (declaration) { @@ -48647,24 +46835,6 @@ var ts; } if (!documentation) { documentation = symbol.getDocumentationComment(); - if (documentation.length === 0 && symbol.flags & 4) { - if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 256; })) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (!declaration.parent || declaration.parent.kind !== 187) { - continue; - } - var rhsSymbol = program.getTypeChecker().getSymbolAtLocation(declaration.parent.right); - if (!rhsSymbol) { - continue; - } - documentation = rhsSymbol.getDocumentationComment(); - if (documentation.length > 0) { - break; - } - } - } - } } return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind }; function addNewLineIfDisplayPartsExist() { @@ -48861,7 +47031,7 @@ var ts; } var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); if (typeReferenceDirective) { - var referenceFile = program.getResolvedTypeReferenceDirectives()[typeReferenceDirective.fileName]; + var referenceFile = ts.lookUp(program.getResolvedTypeReferenceDirectives(), typeReferenceDirective.fileName); if (referenceFile && referenceFile.resolvedFileName) { return [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)]; } @@ -48918,14 +47088,14 @@ var ts; if (!type) { return undefined; } - if (type.flags & 524288 && !(type.flags & 16)) { - var result_4 = []; + if (type.flags & 16384) { + var result_3 = []; ts.forEach(type.types, function (t) { if (t.symbol) { - ts.addRange(result_4, getDefinitionFromSymbol(t.symbol, node)); + ts.addRange(result_3, getDefinitionFromSymbol(t.symbol, node)); } }); - return result_4; + return result_3; } if (!type.symbol) { return undefined; @@ -48973,14 +47143,14 @@ var ts; if (!referencedSymbols) { return undefined; } - var fileNameToDocumentHighlights = ts.createMap(); + var fileNameToDocumentHighlights = {}; var result = []; for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) { var referencedSymbol = referencedSymbols_1[_i]; for (var _a = 0, _b = referencedSymbol.references; _a < _b.length; _a++) { var referenceEntry = _b[_a]; var fileName_1 = referenceEntry.fileName; - var documentHighlights = fileNameToDocumentHighlights[fileName_1]; + var documentHighlights = ts.getProperty(fileNameToDocumentHighlights, fileName_1); if (!documentHighlights) { documentHighlights = { fileName: fileName_1, highlightSpans: [] }; fileNameToDocumentHighlights[fileName_1] = documentHighlights; @@ -49116,17 +47286,17 @@ var ts; function getThrowStatementOwner(throwStatement) { var child = throwStatement; while (child.parent) { - var parent_22 = child.parent; - if (ts.isFunctionBlock(parent_22) || parent_22.kind === 256) { - return parent_22; + var parent_20 = child.parent; + if (ts.isFunctionBlock(parent_20) || parent_20.kind === 256) { + return parent_20; } - if (parent_22.kind === 216) { - var tryStatement = parent_22; + if (parent_20.kind === 216) { + var tryStatement = parent_20; if (tryStatement.tryBlock === child && tryStatement.catchClause) { return child; } } - child = parent_22; + child = parent_20; } return undefined; } @@ -49549,7 +47719,7 @@ var ts; var sourceFile = sourceFiles_4[_i]; cancellationToken.throwIfCancellationRequested(); var nameTable = getNameTable(sourceFile); - if (nameTable[internedName] !== undefined) { + if (ts.lookUp(nameTable, internedName) !== undefined) { result = result || []; getReferencesInNode(sourceFile, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex); } @@ -49569,8 +47739,7 @@ var ts; name: name, kind: info.symbolKind, fileName: declarations[0].getSourceFile().fileName, - textSpan: ts.createTextSpan(declarations[0].getStart(), 0), - displayParts: info.displayParts + textSpan: ts.createTextSpan(declarations[0].getStart(), 0) }; } function getAliasSymbolForPropertyNameSymbol(symbol, location) { @@ -49701,8 +47870,7 @@ var ts; fileName: targetLabel.getSourceFile().fileName, kind: ScriptElementKind.label, name: labelName, - textSpan: ts.createTextSpanFromBounds(targetLabel.getStart(), targetLabel.getEnd()), - displayParts: [ts.displayPart(labelName, SymbolDisplayPartKind.text)] + textSpan: ts.createTextSpanFromBounds(targetLabel.getStart(), targetLabel.getEnd()) }; return [{ definition: definition, references: references }]; } @@ -49728,6 +47896,7 @@ var ts; } function getReferencesInNode(container, searchSymbol, searchText, searchLocation, searchMeaning, findInStrings, findInComments, result, symbolToIndex) { var sourceFile = container.getSourceFile(); + var tripleSlashDirectivePrefixRegex = /^\/\/\/\s*= 0 ? s : undefined; }); + var result_4 = []; + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result_4, {}); + return ts.forEach(result_4, function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); } return undefined; }); @@ -50075,20 +48247,20 @@ var ts; var contextualType = typeChecker.getContextualType(objectLiteral); var name = getNameFromObjectLiteralElement(node); if (name && contextualType) { - var result_6 = []; - var symbol_2 = contextualType.getProperty(name); - if (symbol_2) { - result_6.push(symbol_2); + var result_5 = []; + var symbol_1 = contextualType.getProperty(name); + if (symbol_1) { + result_5.push(symbol_1); } - if (contextualType.flags & 524288) { + if (contextualType.flags & 16384) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_6.push(symbol); + result_5.push(symbol); } }); } - return result_6; + return result_5; } return undefined; } @@ -50139,12 +48311,12 @@ var ts; } return false; } - function getNavigateToItems(searchValue, maxResultCount, excludeDts) { + function getNavigateToItems(searchValue, maxResultCount) { synchronizeHostData(); var checker = getProgram().getTypeChecker(); - return ts.NavigateTo.getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount, excludeDts); + return ts.NavigateTo.getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount); } - function getEmitOutput(fileName, emitDeclarationsOnly) { + function getEmitOutput(fileName) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var outputFiles = []; @@ -50155,7 +48327,7 @@ var ts; text: data }); } - var emitOutput = program.emit(sourceFile, writeFile, cancellationToken, emitDeclarationsOnly); + var emitOutput = program.emit(sourceFile, writeFile, cancellationToken); return { outputFiles: outputFiles, emitSkipped: emitOutput.emitSkipped @@ -50303,6 +48475,7 @@ var ts; case 172: case 139: case 9: + case 166: case 84: case 99: case 93: @@ -50603,9 +48776,6 @@ var ts; } } function tryClassifyNode(node) { - if (ts.isJSDocTag(node)) { - return true; - } if (ts.nodeIsMissing(node)) { return true; } @@ -50680,7 +48850,7 @@ var ts; else if (tokenKind === 8) { return 4; } - else if (tokenKind === 9) { + else if (tokenKind === 9 || tokenKind === 166) { return token.parent.kind === 246 ? 24 : 6; } else if (tokenKind === 10) { @@ -50791,37 +48961,33 @@ var ts; return undefined; } } - function getIndentationAtPosition(fileName, position, optionsOrSettings) { - var start = ts.timestamp(); - var settings = toEditorSettings(optionsOrSettings); + function getIndentationAtPosition(fileName, position, editorOptions) { + var start = new Date().getTime(); var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - log("getIndentationAtPosition: getCurrentSourceFile: " + (ts.timestamp() - start)); - start = ts.timestamp(); - var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, settings); - log("getIndentationAtPosition: computeIndentation : " + (ts.timestamp() - start)); + log("getIndentationAtPosition: getCurrentSourceFile: " + (new Date().getTime() - start)); + start = new Date().getTime(); + var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, editorOptions); + log("getIndentationAtPosition: computeIndentation : " + (new Date().getTime() - start)); return result; } - function getFormattingEditsForRange(fileName, start, end, optionsOrSettings) { - var settings = toEditorSettings(optionsOrSettings); + function getFormattingEditsForRange(fileName, start, end, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(settings), settings); + return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(options), options); } - function getFormattingEditsForDocument(fileName, optionsOrSettings) { - var settings = toEditorSettings(optionsOrSettings); + function getFormattingEditsForDocument(fileName, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.formatting.formatDocument(sourceFile, getRuleProvider(settings), settings); + return ts.formatting.formatDocument(sourceFile, getRuleProvider(options), options); } - function getFormattingEditsAfterKeystroke(fileName, position, key, optionsOrSettings) { - var settings = toEditorSettings(optionsOrSettings); + function getFormattingEditsAfterKeystroke(fileName, position, key, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); if (key === "}") { - return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(settings), settings); + return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(options), options); } else if (key === ";") { - return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(settings), settings); + return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(options), options); } else if (key === "\n") { - return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(settings), settings); + return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(options), options); } return []; } @@ -50987,7 +49153,7 @@ var ts; function getStringLiteralTypeForNode(node, typeChecker) { var searchNode = node.parent.kind === 166 ? node.parent : node; var type = typeChecker.getTypeAtLocation(searchNode); - if (type && type.flags & 32) { + if (type && type.flags & 256) { return type; } return undefined; @@ -51129,7 +49295,7 @@ var ts; } ts.getNameTable = getNameTable; function initializeNameTable(sourceFile) { - var nameTable = ts.createMap(); + var nameTable = {}; walk(sourceFile); sourceFile.nameTable = nameTable; function walk(node) { @@ -51197,7 +49363,7 @@ var ts; var lastEnd = 0; for (var i = 0, n = dense.length; i < n; i += 3) { var start = dense[i]; - var length_5 = dense[i + 1]; + var length_3 = dense[i + 1]; var type = dense[i + 2]; if (lastEnd >= 0) { var whitespaceLength_1 = start - lastEnd; @@ -51205,8 +49371,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: TokenClass.Whitespace }); } } - entries.push({ length: length_5, classification: convertClassification(type) }); - lastEnd = start + length_5; + entries.push({ length: length_3, classification: convertClassification(type) }); + lastEnd = start + length_3; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -51342,7 +49508,7 @@ var ts; var end = scanner.getTextPos(); addResult(start, end, classFromKind(token)); if (end >= text.length) { - if (token === 9) { + if (token === 9 || token === 166) { var tokenText = scanner.getTokenText(); if (scanner.isUnterminated()) { var lastCharIndex = tokenText.length - 1; @@ -51472,6 +49638,7 @@ var ts; case 8: return 4; case 9: + case 166: return 6; case 10: return 7; @@ -51506,8 +49673,6 @@ var ts; function initializeServices() { ts.objectAllocator = { getNodeConstructor: function () { return NodeObject; }, - getTokenConstructor: function () { return TokenObject; }, - getIdentifierConstructor: function () { return IdentifierObject; }, getSourceFileConstructor: function () { return SourceFileObject; }, getSymbolConstructor: function () { return SymbolObject; }, getTypeConstructor: function () { return TypeObject; }, @@ -51520,2279 +49685,43 @@ var ts; (function (ts) { var server; (function (server) { - var ScriptInfo = (function () { - function ScriptInfo(host, fileName, content, scriptKind, isOpen, hasMixedContent) { - if (isOpen === void 0) { isOpen = false; } - if (hasMixedContent === void 0) { hasMixedContent = false; } - this.host = host; - this.fileName = fileName; - this.scriptKind = scriptKind; - this.isOpen = isOpen; - this.hasMixedContent = hasMixedContent; - this.containingProjects = []; - this.path = ts.toPath(fileName, host.getCurrentDirectory(), ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames)); - this.svc = server.ScriptVersionCache.fromString(host, content); - this.scriptKind = scriptKind - ? scriptKind - : ts.getScriptKindFromFileName(fileName); - } - ScriptInfo.prototype.getFormatCodeSettings = function () { - return this.formatCodeSettings; - }; - ScriptInfo.prototype.attachToProject = function (project) { - var isNew = !this.isAttached(project); - if (isNew) { - this.containingProjects.push(project); - } - return isNew; - }; - ScriptInfo.prototype.isAttached = function (project) { - switch (this.containingProjects.length) { - case 0: return false; - case 1: return this.containingProjects[0] === project; - case 2: return this.containingProjects[0] === project || this.containingProjects[1] === project; - default: return ts.contains(this.containingProjects, project); - } - }; - ScriptInfo.prototype.detachFromProject = function (project) { - switch (this.containingProjects.length) { - case 0: - return; - case 1: - if (this.containingProjects[0] === project) { - this.containingProjects.pop(); - } - break; - case 2: - if (this.containingProjects[0] === project) { - this.containingProjects[0] = this.containingProjects.pop(); - } - else if (this.containingProjects[1] === project) { - this.containingProjects.pop(); - } - break; - default: - server.removeItemFromSet(this.containingProjects, project); - break; - } - }; - ScriptInfo.prototype.detachAllProjects = function () { - for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { - var p = _a[_i]; - p.removeFile(this, false); - } - this.containingProjects.length = 0; - }; - ScriptInfo.prototype.getDefaultProject = function () { - if (this.containingProjects.length === 0) { - return server.Errors.ThrowNoProject(); - } - ts.Debug.assert(this.containingProjects.length !== 0); - return this.containingProjects[0]; - }; - ScriptInfo.prototype.setFormatOptions = function (formatSettings) { - if (formatSettings) { - if (!this.formatCodeSettings) { - this.formatCodeSettings = server.getDefaultFormatCodeSettings(this.host); - } - server.mergeMaps(this.formatCodeSettings, formatSettings); - } - }; - ScriptInfo.prototype.setWatcher = function (watcher) { - this.stopWatcher(); - this.fileWatcher = watcher; - }; - ScriptInfo.prototype.stopWatcher = function () { - if (this.fileWatcher) { - this.fileWatcher.close(); - this.fileWatcher = undefined; - } - }; - ScriptInfo.prototype.getLatestVersion = function () { - return this.svc.latestVersion().toString(); - }; - ScriptInfo.prototype.reload = function (script) { - this.svc.reload(script); - this.markContainingProjectsAsDirty(); - }; - ScriptInfo.prototype.saveTo = function (fileName) { - var snap = this.snap(); - this.host.writeFile(fileName, snap.getText(0, snap.getLength())); - }; - ScriptInfo.prototype.reloadFromFile = function () { - if (this.hasMixedContent) { - this.reload(""); - } - else { - this.svc.reloadFromFile(this.fileName); - this.markContainingProjectsAsDirty(); - } - }; - ScriptInfo.prototype.snap = function () { - return this.svc.getSnapshot(); - }; - ScriptInfo.prototype.getLineInfo = function (line) { - var snap = this.snap(); - return snap.index.lineNumberToInfo(line); - }; - ScriptInfo.prototype.editContent = function (start, end, newText) { - this.svc.edit(start, end - start, newText); - this.markContainingProjectsAsDirty(); - }; - ScriptInfo.prototype.markContainingProjectsAsDirty = function () { - for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { - var p = _a[_i]; - p.markAsDirty(); - } - }; - ScriptInfo.prototype.lineToTextSpan = function (line) { - var index = this.snap().index; - var lineInfo = index.lineNumberToInfo(line + 1); - var len; - if (lineInfo.leaf) { - len = lineInfo.leaf.text.length; - } - else { - var nextLineInfo = index.lineNumberToInfo(line + 2); - len = nextLineInfo.offset - lineInfo.offset; - } - return ts.createTextSpan(lineInfo.offset, len); - }; - ScriptInfo.prototype.lineOffsetToPosition = function (line, offset) { - var index = this.snap().index; - var lineInfo = index.lineNumberToInfo(line); - return (lineInfo.offset + offset - 1); - }; - ScriptInfo.prototype.positionToLineOffset = function (position) { - var index = this.snap().index; - var lineOffset = index.charOffsetToLineNumberAndPos(position); - return { line: lineOffset.line, offset: lineOffset.offset + 1 }; - }; - return ScriptInfo; - }()); - server.ScriptInfo = ScriptInfo; - })(server = ts.server || (ts.server = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - var server; - (function (server) { - var LSHost = (function () { - function LSHost(host, project, cancellationToken) { - var _this = this; - this.host = host; - this.project = project; - this.cancellationToken = cancellationToken; - this.getCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); - this.resolvedModuleNames = ts.createFileMap(); - this.resolvedTypeReferenceDirectives = ts.createFileMap(); - if (host.trace) { - this.trace = function (s) { return host.trace(s); }; - } - this.resolveModuleName = function (moduleName, containingFile, compilerOptions, host) { - var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host); - if (primaryResult.resolvedModule) { - if (ts.fileExtensionIsAny(primaryResult.resolvedModule.resolvedFileName, ts.supportedTypeScriptExtensions)) { - return primaryResult; - } - } - var secondaryLookupFailedLookupLocations = []; - var globalCache = _this.project.projectService.typingsInstaller.globalTypingsCacheLocation; - if (_this.project.getTypingOptions().enableAutoDiscovery && globalCache) { - var traceEnabled = ts.isTraceEnabled(compilerOptions, host); - if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, _this.project.getProjectName(), moduleName, globalCache); - } - var state = { compilerOptions: compilerOptions, host: host, skipTsx: false, traceEnabled: traceEnabled }; - var resolvedName = ts.loadModuleFromNodeModules(moduleName, globalCache, secondaryLookupFailedLookupLocations, state, true); - if (resolvedName) { - return ts.createResolvedModule(resolvedName, true, primaryResult.failedLookupLocations.concat(secondaryLookupFailedLookupLocations)); - } - } - if (!primaryResult.resolvedModule && secondaryLookupFailedLookupLocations.length) { - primaryResult.failedLookupLocations = primaryResult.failedLookupLocations.concat(secondaryLookupFailedLookupLocations); - } - return primaryResult; - }; - } - LSHost.prototype.resolveNamesWithLocalCache = function (names, containingFile, cache, loader, getResult) { - var path = ts.toPath(containingFile, this.host.getCurrentDirectory(), this.getCanonicalFileName); - var currentResolutionsInFile = cache.get(path); - var newResolutions = ts.createMap(); - var resolvedModules = []; - var compilerOptions = this.getCompilationSettings(); - for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { - var name_43 = names_2[_i]; - var resolution = newResolutions[name_43]; - if (!resolution) { - var existingResolution = currentResolutionsInFile && currentResolutionsInFile[name_43]; - if (moduleResolutionIsValid(existingResolution)) { - resolution = existingResolution; - } - else { - newResolutions[name_43] = resolution = loader(name_43, containingFile, compilerOptions, this); - } - } - ts.Debug.assert(resolution !== undefined); - resolvedModules.push(getResult(resolution)); - } - cache.set(path, newResolutions); - return resolvedModules; - function moduleResolutionIsValid(resolution) { - if (!resolution) { - return false; - } - if (getResult(resolution)) { - return true; - } - return resolution.failedLookupLocations.length === 0; - } - }; - LSHost.prototype.getProjectVersion = function () { - return this.project.getProjectVersion(); - }; - LSHost.prototype.getCompilationSettings = function () { - return this.compilationSettings; - }; - LSHost.prototype.useCaseSensitiveFileNames = function () { - return this.host.useCaseSensitiveFileNames; - }; - LSHost.prototype.getCancellationToken = function () { - return this.cancellationToken; - }; - LSHost.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { - return this.resolveNamesWithLocalCache(typeDirectiveNames, containingFile, this.resolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, function (m) { return m.resolvedTypeReferenceDirective; }); - }; - LSHost.prototype.resolveModuleNames = function (moduleNames, containingFile) { - return this.resolveNamesWithLocalCache(moduleNames, containingFile, this.resolvedModuleNames, this.resolveModuleName, function (m) { return m.resolvedModule; }); - }; - LSHost.prototype.getDefaultLibFileName = function () { - var nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.host.getExecutingFilePath())); - return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilationSettings)); - }; - LSHost.prototype.getScriptSnapshot = function (filename) { - var scriptInfo = this.project.getScriptInfoLSHost(filename); - if (scriptInfo) { - return scriptInfo.snap(); - } - }; - LSHost.prototype.getScriptFileNames = function () { - return this.project.getRootFilesLSHost(); - }; - LSHost.prototype.getTypeRootsVersion = function () { - return this.project.typesVersion; - }; - LSHost.prototype.getScriptKind = function (fileName) { - var info = this.project.getScriptInfoLSHost(fileName); - return info && info.scriptKind; - }; - LSHost.prototype.getScriptVersion = function (filename) { - var info = this.project.getScriptInfoLSHost(filename); - return info && info.getLatestVersion(); - }; - LSHost.prototype.getCurrentDirectory = function () { - return this.host.getCurrentDirectory(); - }; - LSHost.prototype.resolvePath = function (path) { - return this.host.resolvePath(path); - }; - LSHost.prototype.fileExists = function (path) { - return this.host.fileExists(path); - }; - LSHost.prototype.directoryExists = function (path) { - return this.host.directoryExists(path); - }; - LSHost.prototype.readFile = function (fileName) { - return this.host.readFile(fileName); - }; - LSHost.prototype.getDirectories = function (path) { - return this.host.getDirectories(path); - }; - LSHost.prototype.notifyFileRemoved = function (info) { - this.resolvedModuleNames.remove(info.path); - this.resolvedTypeReferenceDirectives.remove(info.path); - }; - LSHost.prototype.setCompilationSettings = function (opt) { - this.compilationSettings = opt; - this.resolvedModuleNames.clear(); - this.resolvedTypeReferenceDirectives.clear(); - }; - return LSHost; - }()); - server.LSHost = LSHost; - })(server = ts.server || (ts.server = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - var server; - (function (server) { - server.nullTypingsInstaller = { - enqueueInstallTypingsRequest: function () { }, - attach: function (projectService) { }, - onProjectClosed: function (p) { }, - globalTypingsCacheLocation: undefined - }; - var TypingsCacheEntry = (function () { - function TypingsCacheEntry() { - } - return TypingsCacheEntry; - }()); - function setIsEqualTo(arr1, arr2) { - if (arr1 === arr2) { - return true; - } - if ((arr1 || server.emptyArray).length === 0 && (arr2 || server.emptyArray).length === 0) { - return true; - } - var set = ts.createMap(); - var unique = 0; - for (var _i = 0, arr1_1 = arr1; _i < arr1_1.length; _i++) { - var v = arr1_1[_i]; - if (set[v] !== true) { - set[v] = true; - unique++; - } - } - for (var _a = 0, arr2_1 = arr2; _a < arr2_1.length; _a++) { - var v = arr2_1[_a]; - if (!ts.hasProperty(set, v)) { - return false; - } - if (set[v] === true) { - set[v] = false; - unique--; - } - } - return unique === 0; - } - function typingOptionsChanged(opt1, opt2) { - return opt1.enableAutoDiscovery !== opt2.enableAutoDiscovery || - !setIsEqualTo(opt1.include, opt2.include) || - !setIsEqualTo(opt1.exclude, opt2.exclude); - } - function compilerOptionsChanged(opt1, opt2) { - return opt1.allowJs != opt2.allowJs; - } - function toTypingsArray(arr) { - arr.sort(); - return arr; - } - var TypingsCache = (function () { - function TypingsCache(installer) { - this.installer = installer; - this.perProjectCache = ts.createMap(); - } - TypingsCache.prototype.getTypingsForProject = function (project, forceRefresh) { - var typingOptions = project.getTypingOptions(); - if (!typingOptions || !typingOptions.enableAutoDiscovery) { - return server.emptyArray; - } - var entry = this.perProjectCache[project.getProjectName()]; - var result = entry ? entry.typings : server.emptyArray; - if (forceRefresh || !entry || typingOptionsChanged(typingOptions, entry.typingOptions) || compilerOptionsChanged(project.getCompilerOptions(), entry.compilerOptions)) { - this.perProjectCache[project.getProjectName()] = { - compilerOptions: project.getCompilerOptions(), - typingOptions: typingOptions, - typings: result, - poisoned: true - }; - this.installer.enqueueInstallTypingsRequest(project, typingOptions); - } - return result; - }; - TypingsCache.prototype.invalidateCachedTypingsForProject = function (project) { - var typingOptions = project.getTypingOptions(); - if (!typingOptions.enableAutoDiscovery) { - return; - } - this.installer.enqueueInstallTypingsRequest(project, typingOptions); - }; - TypingsCache.prototype.updateTypingsForProject = function (projectName, compilerOptions, typingOptions, newTypings) { - this.perProjectCache[projectName] = { - compilerOptions: compilerOptions, - typingOptions: typingOptions, - typings: toTypingsArray(newTypings), - poisoned: false - }; - }; - TypingsCache.prototype.onProjectClosed = function (project) { - delete this.perProjectCache[project.getProjectName()]; - this.installer.onProjectClosed(project); - }; - return TypingsCache; - }()); - server.TypingsCache = TypingsCache; - })(server = ts.server || (ts.server = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - var server; - (function (server) { - var crypto = require("crypto"); - function shouldEmitFile(scriptInfo) { - return !scriptInfo.hasMixedContent; - } - server.shouldEmitFile = shouldEmitFile; - var BuilderFileInfo = (function () { - function BuilderFileInfo(scriptInfo, project) { - this.scriptInfo = scriptInfo; - this.project = project; - } - BuilderFileInfo.prototype.isExternalModuleOrHasOnlyAmbientExternalModules = function () { - var sourceFile = this.getSourceFile(); - return ts.isExternalModule(sourceFile) || this.containsOnlyAmbientModules(sourceFile); - }; - BuilderFileInfo.prototype.containsOnlyAmbientModules = function (sourceFile) { - for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - if (statement.kind !== 225 || statement.name.kind !== 9) { - return false; - } - } - return true; - }; - BuilderFileInfo.prototype.computeHash = function (text) { - return crypto.createHash("md5") - .update(text) - .digest("base64"); - }; - BuilderFileInfo.prototype.getSourceFile = function () { - return this.project.getSourceFile(this.scriptInfo.path); - }; - BuilderFileInfo.prototype.updateShapeSignature = function () { - var sourceFile = this.getSourceFile(); - if (!sourceFile) { - return true; - } - var lastSignature = this.lastCheckedShapeSignature; - if (sourceFile.isDeclarationFile) { - this.lastCheckedShapeSignature = this.computeHash(sourceFile.text); - } - else { - var emitOutput = this.project.getFileEmitOutput(this.scriptInfo, true); - if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { - this.lastCheckedShapeSignature = this.computeHash(emitOutput.outputFiles[0].text); - } - } - return !lastSignature || this.lastCheckedShapeSignature !== lastSignature; - }; - return BuilderFileInfo; - }()); - server.BuilderFileInfo = BuilderFileInfo; - var AbstractBuilder = (function () { - function AbstractBuilder(project, ctor) { - this.project = project; - this.ctor = ctor; - this.fileInfos = ts.createFileMap(); - } - AbstractBuilder.prototype.getFileInfo = function (path) { - return this.fileInfos.get(path); - }; - AbstractBuilder.prototype.getOrCreateFileInfo = function (path) { - var fileInfo = this.getFileInfo(path); - if (!fileInfo) { - var scriptInfo = this.project.getScriptInfo(path); - fileInfo = new this.ctor(scriptInfo, this.project); - this.setFileInfo(path, fileInfo); - } - return fileInfo; - }; - AbstractBuilder.prototype.getFileInfoPaths = function () { - return this.fileInfos.getKeys(); - }; - AbstractBuilder.prototype.setFileInfo = function (path, info) { - this.fileInfos.set(path, info); - }; - AbstractBuilder.prototype.removeFileInfo = function (path) { - this.fileInfos.remove(path); - }; - AbstractBuilder.prototype.forEachFileInfo = function (action) { - this.fileInfos.forEachValue(function (path, value) { return action(value); }); - }; - AbstractBuilder.prototype.emitFile = function (scriptInfo, writeFile) { - var fileInfo = this.getFileInfo(scriptInfo.path); - if (!fileInfo) { - return false; - } - var _a = this.project.getFileEmitOutput(fileInfo.scriptInfo, false), emitSkipped = _a.emitSkipped, outputFiles = _a.outputFiles; - if (!emitSkipped) { - var projectRootPath = this.project.getProjectRootPath(); - for (var _i = 0, outputFiles_1 = outputFiles; _i < outputFiles_1.length; _i++) { - var outputFile = outputFiles_1[_i]; - var outputFileAbsoluteFileName = ts.getNormalizedAbsolutePath(outputFile.name, projectRootPath ? projectRootPath : ts.getDirectoryPath(scriptInfo.fileName)); - writeFile(outputFileAbsoluteFileName, outputFile.text, outputFile.writeByteOrderMark); - } - } - return !emitSkipped; - }; - return AbstractBuilder; - }()); - var NonModuleBuilder = (function (_super) { - __extends(NonModuleBuilder, _super); - function NonModuleBuilder(project) { - _super.call(this, project, BuilderFileInfo); - this.project = project; - } - NonModuleBuilder.prototype.onProjectUpdateGraph = function () { - }; - NonModuleBuilder.prototype.getFilesAffectedBy = function (scriptInfo) { - var info = this.getOrCreateFileInfo(scriptInfo.path); - var singleFileResult = scriptInfo.hasMixedContent ? [] : [scriptInfo.fileName]; - if (info.updateShapeSignature()) { - var options = this.project.getCompilerOptions(); - if (options && (options.out || options.outFile)) { - return singleFileResult; - } - return this.project.getAllEmittableFiles(); - } - return singleFileResult; - }; - return NonModuleBuilder; - }(AbstractBuilder)); - var ModuleBuilderFileInfo = (function (_super) { - __extends(ModuleBuilderFileInfo, _super); - function ModuleBuilderFileInfo() { - _super.apply(this, arguments); - this.references = []; - this.referencedBy = []; - } - ModuleBuilderFileInfo.compareFileInfos = function (lf, rf) { - var l = lf.scriptInfo.fileName; - var r = rf.scriptInfo.fileName; - return (l < r ? -1 : (l > r ? 1 : 0)); - }; - ; - ModuleBuilderFileInfo.addToReferenceList = function (array, fileInfo) { - if (array.length === 0) { - array.push(fileInfo); - return; - } - var insertIndex = ts.binarySearch(array, fileInfo, ModuleBuilderFileInfo.compareFileInfos); - if (insertIndex < 0) { - array.splice(~insertIndex, 0, fileInfo); - } - }; - ModuleBuilderFileInfo.removeFromReferenceList = function (array, fileInfo) { - if (!array || array.length === 0) { - return; - } - if (array[0] === fileInfo) { - array.splice(0, 1); - return; - } - var removeIndex = ts.binarySearch(array, fileInfo, ModuleBuilderFileInfo.compareFileInfos); - if (removeIndex >= 0) { - array.splice(removeIndex, 1); - } - }; - ModuleBuilderFileInfo.prototype.addReferencedBy = function (fileInfo) { - ModuleBuilderFileInfo.addToReferenceList(this.referencedBy, fileInfo); - }; - ModuleBuilderFileInfo.prototype.removeReferencedBy = function (fileInfo) { - ModuleBuilderFileInfo.removeFromReferenceList(this.referencedBy, fileInfo); - }; - ModuleBuilderFileInfo.prototype.removeFileReferences = function () { - for (var _i = 0, _a = this.references; _i < _a.length; _i++) { - var reference = _a[_i]; - reference.removeReferencedBy(this); - } - this.references = []; - }; - return ModuleBuilderFileInfo; - }(BuilderFileInfo)); - var ModuleBuilder = (function (_super) { - __extends(ModuleBuilder, _super); - function ModuleBuilder(project) { - _super.call(this, project, ModuleBuilderFileInfo); - this.project = project; - } - ModuleBuilder.prototype.getReferencedFileInfos = function (fileInfo) { - var _this = this; - if (!fileInfo.isExternalModuleOrHasOnlyAmbientExternalModules()) { - return []; - } - var referencedFilePaths = this.project.getReferencedFiles(fileInfo.scriptInfo.path); - if (referencedFilePaths.length > 0) { - return ts.map(referencedFilePaths, function (f) { return _this.getOrCreateFileInfo(f); }).sort(ModuleBuilderFileInfo.compareFileInfos); - } - return []; - }; - ModuleBuilder.prototype.onProjectUpdateGraph = function () { - this.ensureProjectDependencyGraphUpToDate(); - }; - ModuleBuilder.prototype.ensureProjectDependencyGraphUpToDate = function () { - var _this = this; - if (!this.projectVersionForDependencyGraph || this.project.getProjectVersion() !== this.projectVersionForDependencyGraph) { - var currentScriptInfos = this.project.getScriptInfos(); - for (var _i = 0, currentScriptInfos_1 = currentScriptInfos; _i < currentScriptInfos_1.length; _i++) { - var scriptInfo = currentScriptInfos_1[_i]; - var fileInfo = this.getOrCreateFileInfo(scriptInfo.path); - this.updateFileReferences(fileInfo); - } - this.forEachFileInfo(function (fileInfo) { - if (!_this.project.containsScriptInfo(fileInfo.scriptInfo)) { - fileInfo.removeFileReferences(); - _this.removeFileInfo(fileInfo.scriptInfo.path); - } - }); - this.projectVersionForDependencyGraph = this.project.getProjectVersion(); - } - }; - ModuleBuilder.prototype.updateFileReferences = function (fileInfo) { - if (fileInfo.scriptVersionForReferences === fileInfo.scriptInfo.getLatestVersion()) { - return; - } - var newReferences = this.getReferencedFileInfos(fileInfo); - var oldReferences = fileInfo.references; - var oldIndex = 0; - var newIndex = 0; - while (oldIndex < oldReferences.length && newIndex < newReferences.length) { - var oldReference = oldReferences[oldIndex]; - var newReference = newReferences[newIndex]; - var compare = ModuleBuilderFileInfo.compareFileInfos(oldReference, newReference); - if (compare < 0) { - oldReference.removeReferencedBy(fileInfo); - oldIndex++; - } - else if (compare > 0) { - newReference.addReferencedBy(fileInfo); - newIndex++; - } - else { - oldIndex++; - newIndex++; - } - } - for (var i = oldIndex; i < oldReferences.length; i++) { - oldReferences[i].removeReferencedBy(fileInfo); - } - for (var i = newIndex; i < newReferences.length; i++) { - newReferences[i].addReferencedBy(fileInfo); - } - fileInfo.references = newReferences; - fileInfo.scriptVersionForReferences = fileInfo.scriptInfo.getLatestVersion(); - }; - ModuleBuilder.prototype.getFilesAffectedBy = function (scriptInfo) { - this.ensureProjectDependencyGraphUpToDate(); - var singleFileResult = scriptInfo.hasMixedContent ? [] : [scriptInfo.fileName]; - var fileInfo = this.getFileInfo(scriptInfo.path); - if (!fileInfo || !fileInfo.updateShapeSignature()) { - return singleFileResult; - } - if (!fileInfo.isExternalModuleOrHasOnlyAmbientExternalModules()) { - return this.project.getAllEmittableFiles(); - } - var options = this.project.getCompilerOptions(); - if (options && (options.isolatedModules || options.out || options.outFile)) { - return singleFileResult; - } - var queue = fileInfo.referencedBy.slice(0); - var fileNameSet = ts.createMap(); - fileNameSet[scriptInfo.fileName] = scriptInfo; - while (queue.length > 0) { - var processingFileInfo = queue.pop(); - if (processingFileInfo.updateShapeSignature() && processingFileInfo.referencedBy.length > 0) { - for (var _i = 0, _a = processingFileInfo.referencedBy; _i < _a.length; _i++) { - var potentialFileInfo = _a[_i]; - if (!fileNameSet[potentialFileInfo.scriptInfo.fileName]) { - queue.push(potentialFileInfo); - } - } - } - fileNameSet[processingFileInfo.scriptInfo.fileName] = processingFileInfo.scriptInfo; - } - var result = []; - for (var fileName in fileNameSet) { - if (shouldEmitFile(fileNameSet[fileName])) { - result.push(fileName); - } - } - return result; - }; - return ModuleBuilder; - }(AbstractBuilder)); - function createBuilder(project) { - var moduleKind = project.getCompilerOptions().module; - switch (moduleKind) { - case ts.ModuleKind.None: - return new NonModuleBuilder(project); - default: - return new ModuleBuilder(project); - } - } - server.createBuilder = createBuilder; - })(server = ts.server || (ts.server = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - var server; - (function (server) { - (function (ProjectKind) { - ProjectKind[ProjectKind["Inferred"] = 0] = "Inferred"; - ProjectKind[ProjectKind["Configured"] = 1] = "Configured"; - ProjectKind[ProjectKind["External"] = 2] = "External"; - })(server.ProjectKind || (server.ProjectKind = {})); - var ProjectKind = server.ProjectKind; - function remove(items, item) { - var index = items.indexOf(item); - if (index >= 0) { - items.splice(index, 1); - } - } - function isJsOrDtsFile(info) { - return info.scriptKind === 1 || info.scriptKind == 2 || ts.fileExtensionIs(info.fileName, ".d.ts"); - } - function allRootFilesAreJsOrDts(project) { - return project.getRootScriptInfos().every(isJsOrDtsFile); - } - server.allRootFilesAreJsOrDts = allRootFilesAreJsOrDts; - function allFilesAreJsOrDts(project) { - return project.getScriptInfos().every(isJsOrDtsFile); - } - server.allFilesAreJsOrDts = allFilesAreJsOrDts; - var Project = (function () { - function Project(projectKind, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) { - this.projectKind = projectKind; - this.projectService = projectService; - this.documentRegistry = documentRegistry; - this.languageServiceEnabled = languageServiceEnabled; - this.compilerOptions = compilerOptions; - this.compileOnSaveEnabled = compileOnSaveEnabled; - this.rootFiles = []; - this.rootFilesMap = ts.createFileMap(); - this.lastReportedVersion = 0; - this.projectStructureVersion = 0; - this.projectStateVersion = 0; - this.typesVersion = 0; - if (!this.compilerOptions) { - this.compilerOptions = ts.getDefaultCompilerOptions(); - this.compilerOptions.allowNonTsExtensions = true; - this.compilerOptions.allowJs = true; - } - else if (hasExplicitListOfFiles) { - this.compilerOptions.allowNonTsExtensions = true; - } - if (languageServiceEnabled) { - this.enableLanguageService(); - } - else { - this.disableLanguageService(); - } - this.builder = server.createBuilder(this); - this.markAsDirty(); - } - Project.prototype.isJsOnlyProject = function () { - this.updateGraph(); - return allFilesAreJsOrDts(this); - }; - Project.prototype.getProjectErrors = function () { - return this.projectErrors; - }; - Project.prototype.getLanguageService = function (ensureSynchronized) { - if (ensureSynchronized === void 0) { ensureSynchronized = true; } - if (ensureSynchronized) { - this.updateGraph(); - } - return this.languageService; - }; - Project.prototype.getCompileOnSaveAffectedFileList = function (scriptInfo) { - if (!this.languageServiceEnabled) { - return []; - } - this.updateGraph(); - return this.builder.getFilesAffectedBy(scriptInfo); - }; - Project.prototype.getProjectVersion = function () { - return this.projectStateVersion.toString(); - }; - Project.prototype.enableLanguageService = function () { - var lsHost = new server.LSHost(this.projectService.host, this, this.projectService.cancellationToken); - lsHost.setCompilationSettings(this.compilerOptions); - this.languageService = ts.createLanguageService(lsHost, this.documentRegistry); - this.lsHost = lsHost; - this.languageServiceEnabled = true; - }; - Project.prototype.disableLanguageService = function () { - this.languageService = server.nullLanguageService; - this.lsHost = server.nullLanguageServiceHost; - this.languageServiceEnabled = false; - }; - Project.prototype.getSourceFile = function (path) { - if (!this.program) { - return undefined; - } - return this.program.getSourceFileByPath(path); - }; - Project.prototype.updateTypes = function () { - this.typesVersion++; - this.markAsDirty(); - this.updateGraph(); - }; - Project.prototype.close = function () { - if (this.program) { - for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) { - var f = _a[_i]; - var info = this.projectService.getScriptInfo(f.fileName); - info.detachFromProject(this); - } - } - else { - for (var _b = 0, _c = this.rootFiles; _b < _c.length; _b++) { - var root = _c[_b]; - root.detachFromProject(this); - } - } - this.rootFiles = undefined; - this.rootFilesMap = undefined; - this.program = undefined; - this.languageService.dispose(); - }; - Project.prototype.getCompilerOptions = function () { - return this.compilerOptions; - }; - Project.prototype.hasRoots = function () { - return this.rootFiles && this.rootFiles.length > 0; - }; - Project.prototype.getRootFiles = function () { - return this.rootFiles && this.rootFiles.map(function (info) { return info.fileName; }); - }; - Project.prototype.getRootFilesLSHost = function () { - var result = []; - if (this.rootFiles) { - for (var _i = 0, _a = this.rootFiles; _i < _a.length; _i++) { - var f = _a[_i]; - result.push(f.fileName); - } - if (this.typingFiles) { - for (var _b = 0, _c = this.typingFiles; _b < _c.length; _b++) { - var f = _c[_b]; - result.push(f); - } - } - } - return result; - }; - Project.prototype.getRootScriptInfos = function () { - return this.rootFiles; - }; - Project.prototype.getScriptInfos = function () { - var _this = this; - return ts.map(this.program.getSourceFiles(), function (sourceFile) { return _this.getScriptInfoLSHost(sourceFile.path); }); - }; - Project.prototype.getFileEmitOutput = function (info, emitOnlyDtsFiles) { - if (!this.languageServiceEnabled) { - return undefined; - } - return this.getLanguageService().getEmitOutput(info.fileName, emitOnlyDtsFiles); - }; - Project.prototype.getFileNames = function () { - if (!this.program) { - return []; - } - if (!this.languageServiceEnabled) { - var rootFiles = this.getRootFiles(); - if (this.compilerOptions) { - var defaultLibrary = ts.getDefaultLibFilePath(this.compilerOptions); - if (defaultLibrary) { - (rootFiles || (rootFiles = [])).push(server.asNormalizedPath(defaultLibrary)); - } - } - return rootFiles; - } - var sourceFiles = this.program.getSourceFiles(); - return sourceFiles.map(function (sourceFile) { return server.asNormalizedPath(sourceFile.fileName); }); - }; - Project.prototype.getAllEmittableFiles = function () { - if (!this.languageServiceEnabled) { - return []; - } - var defaultLibraryFileName = ts.getDefaultLibFileName(this.compilerOptions); - var infos = this.getScriptInfos(); - var result = []; - for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { - var info = infos_1[_i]; - if (ts.getBaseFileName(info.fileName) !== defaultLibraryFileName && server.shouldEmitFile(info)) { - result.push(info.fileName); - } - } - return result; - }; - Project.prototype.containsScriptInfo = function (info) { - return this.isRoot(info) || (this.program && this.program.getSourceFileByPath(info.path) !== undefined); - }; - Project.prototype.containsFile = function (filename, requireOpen) { - var info = this.projectService.getScriptInfoForNormalizedPath(filename); - if (info && (info.isOpen || !requireOpen)) { - return this.containsScriptInfo(info); - } - }; - Project.prototype.isRoot = function (info) { - return this.rootFilesMap && this.rootFilesMap.contains(info.path); - }; - Project.prototype.addRoot = function (info) { - if (!this.isRoot(info)) { - this.rootFiles.push(info); - this.rootFilesMap.set(info.path, info); - info.attachToProject(this); - this.markAsDirty(); - } - }; - Project.prototype.removeFile = function (info, detachFromProject) { - if (detachFromProject === void 0) { detachFromProject = true; } - this.removeRootFileIfNecessary(info); - this.lsHost.notifyFileRemoved(info); - if (detachFromProject) { - info.detachFromProject(this); - } - this.markAsDirty(); - }; - Project.prototype.markAsDirty = function () { - this.projectStateVersion++; - }; - Project.prototype.updateGraph = function () { - if (!this.languageServiceEnabled) { - return true; - } - var hasChanges = this.updateGraphWorker(); - var cachedTypings = this.projectService.typingsCache.getTypingsForProject(this, hasChanges); - if (this.setTypings(cachedTypings)) { - hasChanges = this.updateGraphWorker() || hasChanges; - } - if (hasChanges) { - this.projectStructureVersion++; - } - return !hasChanges; - }; - Project.prototype.setTypings = function (typings) { - if (ts.arrayIsEqualTo(this.typingFiles, typings)) { - return false; - } - this.typingFiles = typings; - this.markAsDirty(); - return true; - }; - Project.prototype.updateGraphWorker = function () { - var oldProgram = this.program; - this.program = this.languageService.getProgram(); - var hasChanges = false; - if (!oldProgram || (this.program !== oldProgram && !oldProgram.structureIsReused)) { - hasChanges = true; - if (oldProgram) { - for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { - var f = _a[_i]; - if (this.program.getSourceFileByPath(f.path)) { - continue; - } - var scriptInfoToDetach = this.projectService.getScriptInfo(f.fileName); - if (scriptInfoToDetach) { - scriptInfoToDetach.detachFromProject(this); - } - } - } - } - this.builder.onProjectUpdateGraph(); - return hasChanges; - }; - Project.prototype.getScriptInfoLSHost = function (fileName) { - var scriptInfo = this.projectService.getOrCreateScriptInfo(fileName, false); - if (scriptInfo) { - scriptInfo.attachToProject(this); - } - return scriptInfo; - }; - Project.prototype.getScriptInfoForNormalizedPath = function (fileName) { - var scriptInfo = this.projectService.getOrCreateScriptInfoForNormalizedPath(fileName, false); - if (scriptInfo && !scriptInfo.isAttached(this)) { - return server.Errors.ThrowProjectDoesNotContainDocument(fileName, this); - } - return scriptInfo; - }; - Project.prototype.getScriptInfo = function (uncheckedFileName) { - return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); - }; - Project.prototype.filesToString = function () { - if (!this.program) { - return ""; - } + var spaceCache = []; + function generateSpaces(n) { + if (!spaceCache[n]) { var strBuilder = ""; - for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) { - var file = _a[_i]; - strBuilder += file.fileName + "\n"; + for (var i = 0; i < n; i++) { + strBuilder += " "; } - return strBuilder; - }; - Project.prototype.setCompilerOptions = function (compilerOptions) { - if (compilerOptions) { - if (this.projectKind === ProjectKind.Inferred) { - compilerOptions.allowJs = true; - } - compilerOptions.allowNonTsExtensions = true; - this.compilerOptions = compilerOptions; - this.lsHost.setCompilationSettings(compilerOptions); - this.markAsDirty(); - } - }; - Project.prototype.reloadScript = function (filename) { - var script = this.projectService.getScriptInfoForNormalizedPath(filename); - if (script) { - ts.Debug.assert(script.isAttached(this)); - script.reloadFromFile(); - return true; - } - return false; - }; - Project.prototype.getChangesSinceVersion = function (lastKnownVersion) { - this.updateGraph(); - var info = { - projectName: this.getProjectName(), - version: this.projectStructureVersion, - isInferred: this.projectKind === ProjectKind.Inferred, - options: this.getCompilerOptions() - }; - if (this.lastReportedFileNames && lastKnownVersion === this.lastReportedVersion) { - if (this.projectStructureVersion == this.lastReportedVersion) { - return { info: info, projectErrors: this.projectErrors }; - } - var lastReportedFileNames = this.lastReportedFileNames; - var currentFiles = ts.arrayToMap(this.getFileNames(), function (x) { return x; }); - var added = []; - var removed = []; - for (var id in currentFiles) { - if (!ts.hasProperty(lastReportedFileNames, id)) { - added.push(id); - } - } - for (var id in lastReportedFileNames) { - if (!ts.hasProperty(currentFiles, id)) { - removed.push(id); - } - } - this.lastReportedFileNames = currentFiles; - this.lastReportedVersion = this.projectStructureVersion; - return { info: info, changes: { added: added, removed: removed }, projectErrors: this.projectErrors }; - } - else { - var projectFileNames = this.getFileNames(); - this.lastReportedFileNames = ts.arrayToMap(projectFileNames, function (x) { return x; }); - this.lastReportedVersion = this.projectStructureVersion; - return { info: info, files: projectFileNames, projectErrors: this.projectErrors }; - } - }; - Project.prototype.getReferencedFiles = function (path) { - var _this = this; - if (!this.languageServiceEnabled) { - return []; - } - var sourceFile = this.getSourceFile(path); - if (!sourceFile) { - return []; - } - var referencedFiles = ts.createMap(); - if (sourceFile.imports && sourceFile.imports.length > 0) { - var checker = this.program.getTypeChecker(); - for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var importName = _a[_i]; - var symbol = checker.getSymbolAtLocation(importName); - if (symbol && symbol.declarations && symbol.declarations[0]) { - var declarationSourceFile = symbol.declarations[0].getSourceFile(); - if (declarationSourceFile) { - referencedFiles[declarationSourceFile.path] = true; - } - } - } - } - var currentDirectory = ts.getDirectoryPath(path); - var getCanonicalFileName = ts.createGetCanonicalFileName(this.projectService.host.useCaseSensitiveFileNames); - if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { - for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { - var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, currentDirectory, getCanonicalFileName); - referencedFiles[referencedPath] = true; - } - } - if (sourceFile.resolvedTypeReferenceDirectiveNames) { - for (var typeName in sourceFile.resolvedTypeReferenceDirectiveNames) { - var resolvedTypeReferenceDirective = sourceFile.resolvedTypeReferenceDirectiveNames[typeName]; - if (!resolvedTypeReferenceDirective) { - continue; - } - var fileName = resolvedTypeReferenceDirective.resolvedFileName; - var typeFilePath = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - referencedFiles[typeFilePath] = true; - } - } - var allFileNames = ts.map(Object.keys(referencedFiles), function (key) { return key; }); - return ts.filter(allFileNames, function (file) { return _this.projectService.host.fileExists(file); }); - }; - Project.prototype.removeRootFileIfNecessary = function (info) { - if (this.isRoot(info)) { - remove(this.rootFiles, info); - this.rootFilesMap.remove(info.path); - } - }; - return Project; - }()); - server.Project = Project; - var InferredProject = (function (_super) { - __extends(InferredProject, _super); - function InferredProject(projectService, documentRegistry, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) { - _super.call(this, ProjectKind.Inferred, projectService, documentRegistry, undefined, languageServiceEnabled, compilerOptions, compileOnSaveEnabled); - this.compileOnSaveEnabled = compileOnSaveEnabled; - this.directoriesWatchedForTsconfig = []; - this.inferredProjectName = server.makeInferredProjectName(InferredProject.NextId); - InferredProject.NextId++; + spaceCache[n] = strBuilder; } - InferredProject.prototype.getProjectName = function () { - return this.inferredProjectName; - }; - InferredProject.prototype.getProjectRootPath = function () { - if (this.projectService.useSingleInferredProject) { - return undefined; - } - var rootFiles = this.getRootFiles(); - return ts.getDirectoryPath(rootFiles[0]); - }; - InferredProject.prototype.close = function () { - _super.prototype.close.call(this); - for (var _i = 0, _a = this.directoriesWatchedForTsconfig; _i < _a.length; _i++) { - var directory = _a[_i]; - this.projectService.stopWatchingDirectory(directory); - } - }; - InferredProject.prototype.getTypingOptions = function () { - return { - enableAutoDiscovery: allRootFilesAreJsOrDts(this), - include: [], - exclude: [] - }; - }; - InferredProject.NextId = 1; - return InferredProject; - }(Project)); - server.InferredProject = InferredProject; - var ConfiguredProject = (function (_super) { - __extends(ConfiguredProject, _super); - function ConfiguredProject(configFileName, projectService, documentRegistry, hasExplicitListOfFiles, compilerOptions, wildcardDirectories, languageServiceEnabled, compileOnSaveEnabled) { - _super.call(this, ProjectKind.Configured, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled); - this.configFileName = configFileName; - this.wildcardDirectories = wildcardDirectories; - this.compileOnSaveEnabled = compileOnSaveEnabled; - this.openRefCount = 0; - } - ConfiguredProject.prototype.getProjectRootPath = function () { - return ts.getDirectoryPath(this.configFileName); - }; - ConfiguredProject.prototype.setProjectErrors = function (projectErrors) { - this.projectErrors = projectErrors; - }; - ConfiguredProject.prototype.setTypingOptions = function (newTypingOptions) { - this.typingOptions = newTypingOptions; - }; - ConfiguredProject.prototype.getTypingOptions = function () { - return this.typingOptions; - }; - ConfiguredProject.prototype.getProjectName = function () { - return this.configFileName; - }; - ConfiguredProject.prototype.watchConfigFile = function (callback) { - var _this = this; - this.projectFileWatcher = this.projectService.host.watchFile(this.configFileName, function (_) { return callback(_this); }); - }; - ConfiguredProject.prototype.watchTypeRoots = function (callback) { - var _this = this; - var roots = this.getEffectiveTypeRoots(); - var watchers = []; - for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { - var root = roots_1[_i]; - this.projectService.logger.info("Add type root watcher for: " + root); - watchers.push(this.projectService.host.watchDirectory(root, function (path) { return callback(_this, path); }, false)); - } - this.typeRootsWatchers = watchers; - }; - ConfiguredProject.prototype.watchConfigDirectory = function (callback) { - var _this = this; - if (this.directoryWatcher) { - return; - } - var directoryToWatch = ts.getDirectoryPath(this.configFileName); - this.projectService.logger.info("Add recursive watcher for: " + directoryToWatch); - this.directoryWatcher = this.projectService.host.watchDirectory(directoryToWatch, function (path) { return callback(_this, path); }, true); - }; - ConfiguredProject.prototype.watchWildcards = function (callback) { - var _this = this; - if (!this.wildcardDirectories) { - return; - } - var configDirectoryPath = ts.getDirectoryPath(this.configFileName); - this.directoriesWatchedForWildcards = ts.reduceProperties(this.wildcardDirectories, function (watchers, flag, directory) { - if (ts.comparePaths(configDirectoryPath, directory, ".", !_this.projectService.host.useCaseSensitiveFileNames) !== 0) { - var recursive = (flag & 1) !== 0; - _this.projectService.logger.info("Add " + (recursive ? "recursive " : "") + "watcher for: " + directory); - watchers[directory] = _this.projectService.host.watchDirectory(directory, function (path) { return callback(_this, path); }, recursive); - } - return watchers; - }, {}); - }; - ConfiguredProject.prototype.stopWatchingDirectory = function () { - if (this.directoryWatcher) { - this.directoryWatcher.close(); - this.directoryWatcher = undefined; - } - }; - ConfiguredProject.prototype.close = function () { - _super.prototype.close.call(this); - if (this.projectFileWatcher) { - this.projectFileWatcher.close(); - } - if (this.typeRootsWatchers) { - for (var _i = 0, _a = this.typeRootsWatchers; _i < _a.length; _i++) { - var watcher = _a[_i]; - watcher.close(); - } - this.typeRootsWatchers = undefined; - } - for (var id in this.directoriesWatchedForWildcards) { - this.directoriesWatchedForWildcards[id].close(); - } - this.directoriesWatchedForWildcards = undefined; - this.stopWatchingDirectory(); - }; - ConfiguredProject.prototype.addOpenRef = function () { - this.openRefCount++; - }; - ConfiguredProject.prototype.deleteOpenRef = function () { - this.openRefCount--; - return this.openRefCount; - }; - ConfiguredProject.prototype.getEffectiveTypeRoots = function () { - return ts.getEffectiveTypeRoots(this.getCompilerOptions(), this.projectService.host) || []; - }; - return ConfiguredProject; - }(Project)); - server.ConfiguredProject = ConfiguredProject; - var ExternalProject = (function (_super) { - __extends(ExternalProject, _super); - function ExternalProject(externalProjectName, projectService, documentRegistry, compilerOptions, languageServiceEnabled, compileOnSaveEnabled, projectFilePath) { - _super.call(this, ProjectKind.External, projectService, documentRegistry, true, languageServiceEnabled, compilerOptions, compileOnSaveEnabled); - this.externalProjectName = externalProjectName; - this.compileOnSaveEnabled = compileOnSaveEnabled; - this.projectFilePath = projectFilePath; - } - ExternalProject.prototype.getProjectRootPath = function () { - if (this.projectFilePath) { - return ts.getDirectoryPath(this.projectFilePath); - } - return ts.getDirectoryPath(ts.normalizeSlashes(this.externalProjectName)); - }; - ExternalProject.prototype.getTypingOptions = function () { - return this.typingOptions; - }; - ExternalProject.prototype.setProjectErrors = function (projectErrors) { - this.projectErrors = projectErrors; - }; - ExternalProject.prototype.setTypingOptions = function (newTypingOptions) { - if (!newTypingOptions) { - newTypingOptions = { - enableAutoDiscovery: allRootFilesAreJsOrDts(this), - include: [], - exclude: [] - }; - } - else { - if (newTypingOptions.enableAutoDiscovery === undefined) { - newTypingOptions.enableAutoDiscovery = allRootFilesAreJsOrDts(this); - } - if (!newTypingOptions.include) { - newTypingOptions.include = []; - } - if (!newTypingOptions.exclude) { - newTypingOptions.exclude = []; - } - } - this.typingOptions = newTypingOptions; - }; - ExternalProject.prototype.getProjectName = function () { - return this.externalProjectName; - }; - return ExternalProject; - }(Project)); - server.ExternalProject = ExternalProject; - })(server = ts.server || (ts.server = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - var server; - (function (server) { - server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; - function combineProjectOutput(projects, action, comparer, areEqual) { - var result = projects.reduce(function (previous, current) { return ts.concatenate(previous, action(current)); }, []).sort(comparer); - return projects.length > 1 ? ts.deduplicate(result, areEqual) : result; + return spaceCache[n]; } - server.combineProjectOutput = combineProjectOutput; - var fileNamePropertyReader = { - getFileName: function (x) { return x; }, - getScriptKind: function (_) { return undefined; }, - hasMixedContent: function (_) { return false; } - }; - var externalFilePropertyReader = { - getFileName: function (x) { return x.fileName; }, - getScriptKind: function (x) { return x.scriptKind; }, - hasMixedContent: function (x) { return x.hasMixedContent; } - }; - function findProjectByName(projectName, projects) { - for (var _i = 0, projects_1 = projects; _i < projects_1.length; _i++) { - var proj = projects_1[_i]; - if (proj.getProjectName() === projectName) { - return proj; + server.generateSpaces = generateSpaces; + function generateIndentString(n, editorOptions) { + if (editorOptions.ConvertTabsToSpaces) { + return generateSpaces(n); + } + else { + var result = ""; + for (var i = 0; i < Math.floor(n / editorOptions.TabSize); i++) { + result += "\t"; } + for (var i = 0; i < n % editorOptions.TabSize; i++) { + result += " "; + } + return result; } } - function createFileNotFoundDiagnostic(fileName) { - return ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, fileName); - } - function isRootFileInInferredProject(info) { - if (info.containingProjects.length === 0) { - return false; - } - return info.containingProjects[0].projectKind === server.ProjectKind.Inferred && info.containingProjects[0].isRoot(info); - } - var DirectoryWatchers = (function () { - function DirectoryWatchers(projectService) { - this.projectService = projectService; - this.directoryWatchersForTsconfig = ts.createMap(); - this.directoryWatchersRefCount = ts.createMap(); - } - DirectoryWatchers.prototype.stopWatchingDirectory = function (directory) { - this.directoryWatchersRefCount[directory]--; - if (this.directoryWatchersRefCount[directory] === 0) { - this.projectService.logger.info("Close directory watcher for: " + directory); - this.directoryWatchersForTsconfig[directory].close(); - delete this.directoryWatchersForTsconfig[directory]; - } - }; - DirectoryWatchers.prototype.startWatchingContainingDirectoriesForFile = function (fileName, project, callback) { - var currentPath = ts.getDirectoryPath(fileName); - var parentPath = ts.getDirectoryPath(currentPath); - while (currentPath != parentPath) { - if (!this.directoryWatchersForTsconfig[currentPath]) { - this.projectService.logger.info("Add watcher for: " + currentPath); - this.directoryWatchersForTsconfig[currentPath] = this.projectService.host.watchDirectory(currentPath, callback); - this.directoryWatchersRefCount[currentPath] = 1; - } - else { - this.directoryWatchersRefCount[currentPath] += 1; - } - project.directoriesWatchedForTsconfig.push(currentPath); - currentPath = parentPath; - parentPath = ts.getDirectoryPath(parentPath); - } - }; - return DirectoryWatchers; - }()); - var ProjectService = (function () { - function ProjectService(host, logger, cancellationToken, useSingleInferredProject, typingsInstaller, eventHandler) { - if (typingsInstaller === void 0) { typingsInstaller = server.nullTypingsInstaller; } - this.host = host; - this.logger = logger; - this.cancellationToken = cancellationToken; - this.useSingleInferredProject = useSingleInferredProject; - this.typingsInstaller = typingsInstaller; - this.eventHandler = eventHandler; - this.filenameToScriptInfo = ts.createFileMap(); - this.externalProjectToConfiguredProjectMap = ts.createMap(); - this.externalProjects = []; - this.inferredProjects = []; - this.configuredProjects = []; - this.openFiles = []; - this.toCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - this.directoryWatchers = new DirectoryWatchers(this); - this.throttledOperations = new server.ThrottledOperations(host); - this.typingsInstaller.attach(this); - this.typingsCache = new server.TypingsCache(this.typingsInstaller); - this.hostConfiguration = { - formatCodeOptions: server.getDefaultFormatCodeSettings(this.host), - hostInfo: "Unknown host" - }; - this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames, host.getCurrentDirectory()); - } - ProjectService.prototype.getChangedFiles_TestOnly = function () { - return this.changedFiles; - }; - ProjectService.prototype.ensureInferredProjectsUpToDate_TestOnly = function () { - this.ensureInferredProjectsUpToDate(); - }; - ProjectService.prototype.updateTypingsForProject = function (response) { - var project = this.findProject(response.projectName); - if (!project) { - return; - } - switch (response.kind) { - case "set": - this.typingsCache.updateTypingsForProject(response.projectName, response.compilerOptions, response.typingOptions, response.typings); - project.updateGraph(); - break; - case "invalidate": - this.typingsCache.invalidateCachedTypingsForProject(project); - break; - } - }; - ProjectService.prototype.setCompilerOptionsForInferredProjects = function (projectCompilerOptions) { - this.compilerOptionsForInferredProjects = projectCompilerOptions; - this.compileOnSaveForInferredProjects = projectCompilerOptions.compileOnSave; - for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { - var proj = _a[_i]; - proj.setCompilerOptions(projectCompilerOptions); - proj.compileOnSaveEnabled = projectCompilerOptions.compileOnSave; - } - this.updateProjectGraphs(this.inferredProjects); - }; - ProjectService.prototype.stopWatchingDirectory = function (directory) { - this.directoryWatchers.stopWatchingDirectory(directory); - }; - ProjectService.prototype.findProject = function (projectName) { - if (projectName === undefined) { - return undefined; - } - if (server.isInferredProjectName(projectName)) { - this.ensureInferredProjectsUpToDate(); - return findProjectByName(projectName, this.inferredProjects); - } - return this.findExternalProjectByProjectName(projectName) || this.findConfiguredProjectByProjectName(server.toNormalizedPath(projectName)); - }; - ProjectService.prototype.getDefaultProjectForFile = function (fileName, refreshInferredProjects) { - if (refreshInferredProjects) { - this.ensureInferredProjectsUpToDate(); - } - var scriptInfo = this.getScriptInfoForNormalizedPath(fileName); - return scriptInfo && scriptInfo.getDefaultProject(); - }; - ProjectService.prototype.ensureInferredProjectsUpToDate = function () { - if (this.changedFiles) { - var projectsToUpdate = void 0; - if (this.changedFiles.length === 1) { - projectsToUpdate = this.changedFiles[0].containingProjects; - } - else { - projectsToUpdate = []; - for (var _i = 0, _a = this.changedFiles; _i < _a.length; _i++) { - var f = _a[_i]; - projectsToUpdate = projectsToUpdate.concat(f.containingProjects); - } - } - this.updateProjectGraphs(projectsToUpdate); - this.changedFiles = undefined; - } - }; - ProjectService.prototype.findContainingExternalProject = function (fileName) { - for (var _i = 0, _a = this.externalProjects; _i < _a.length; _i++) { - var proj = _a[_i]; - if (proj.containsFile(fileName)) { - return proj; - } - } - return undefined; - }; - ProjectService.prototype.getFormatCodeOptions = function (file) { - var formatCodeSettings; - if (file) { - var info = this.getScriptInfoForNormalizedPath(file); - if (info) { - formatCodeSettings = info.getFormatCodeSettings(); - } - } - return formatCodeSettings || this.hostConfiguration.formatCodeOptions; - }; - ProjectService.prototype.updateProjectGraphs = function (projects) { - var shouldRefreshInferredProjects = false; - for (var _i = 0, projects_2 = projects; _i < projects_2.length; _i++) { - var p = projects_2[_i]; - if (!p.updateGraph()) { - shouldRefreshInferredProjects = true; - } - } - if (shouldRefreshInferredProjects) { - this.refreshInferredProjects(); - } - }; - ProjectService.prototype.onSourceFileChanged = function (fileName) { - var info = this.getScriptInfoForNormalizedPath(fileName); - if (!info) { - this.logger.info("Error: got watch notification for unknown file: " + fileName); - return; - } - if (!this.host.fileExists(fileName)) { - this.handleDeletedFile(info); - } - else { - if (info && (!info.isOpen)) { - info.reloadFromFile(); - this.updateProjectGraphs(info.containingProjects); - } - } - }; - ProjectService.prototype.handleDeletedFile = function (info) { - this.logger.info(info.fileName + " deleted"); - info.stopWatcher(); - if (!info.isOpen) { - this.filenameToScriptInfo.remove(info.path); - var containingProjects = info.containingProjects.slice(); - info.detachAllProjects(); - this.updateProjectGraphs(containingProjects); - if (!this.eventHandler) { - return; - } - for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { - var openFile = _a[_i]; - this.eventHandler({ eventName: "context", data: { project: openFile.getDefaultProject(), fileName: openFile.fileName } }); - } - } - this.printProjects(); - }; - ProjectService.prototype.onTypeRootFileChanged = function (project, fileName) { - var _this = this; - this.logger.info("Type root file " + fileName + " changed"); - this.throttledOperations.schedule(project.configFileName + " * type root", 250, function () { - project.updateTypes(); - _this.updateConfiguredProject(project); - _this.refreshInferredProjects(); - }); - }; - ProjectService.prototype.onSourceFileInDirectoryChangedForConfiguredProject = function (project, fileName) { - var _this = this; - if (fileName && !ts.isSupportedSourceFileName(fileName, project.getCompilerOptions())) { - return; - } - this.logger.info("Detected source file changes: " + fileName); - this.throttledOperations.schedule(project.configFileName, 250, function () { return _this.handleChangeInSourceFileForConfiguredProject(project); }); - }; - ProjectService.prototype.handleChangeInSourceFileForConfiguredProject = function (project) { - var _this = this; - var _a = this.convertConfigFileContentToProjectOptions(project.configFileName), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors; - this.reportConfigFileDiagnostics(project.getProjectName(), configFileErrors); - var newRootFiles = projectOptions.files.map((function (f) { return _this.getCanonicalFileName(f); })); - var currentRootFiles = project.getRootFiles().map((function (f) { return _this.getCanonicalFileName(f); })); - if (!ts.arrayIsEqualTo(currentRootFiles.sort(), newRootFiles.sort())) { - this.logger.info("Updating configured project"); - this.updateConfiguredProject(project); - this.refreshInferredProjects(); - } - }; - ProjectService.prototype.onConfigChangedForConfiguredProject = function (project) { - this.logger.info("Config file changed: " + project.configFileName); - this.updateConfiguredProject(project); - this.refreshInferredProjects(); - }; - ProjectService.prototype.onConfigFileAddedForInferredProject = function (fileName) { - if (ts.getBaseFileName(fileName) != "tsconfig.json") { - this.logger.info(fileName + " is not tsconfig.json"); - return; - } - var configFileErrors = this.convertConfigFileContentToProjectOptions(fileName).configFileErrors; - this.reportConfigFileDiagnostics(fileName, configFileErrors); - this.logger.info("Detected newly added tsconfig file: " + fileName); - this.reloadProjects(); - }; - ProjectService.prototype.getCanonicalFileName = function (fileName) { - var name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); - return ts.normalizePath(name); - }; - ProjectService.prototype.removeProject = function (project) { - this.logger.info("remove project: " + project.getRootFiles().toString()); - project.close(); - switch (project.projectKind) { - case server.ProjectKind.External: - server.removeItemFromSet(this.externalProjects, project); - break; - case server.ProjectKind.Configured: - server.removeItemFromSet(this.configuredProjects, project); - break; - case server.ProjectKind.Inferred: - server.removeItemFromSet(this.inferredProjects, project); - break; - } - }; - ProjectService.prototype.assignScriptInfoToInferredProjectIfNecessary = function (info, addToListOfOpenFiles) { - var externalProject = this.findContainingExternalProject(info.fileName); - if (externalProject) { - if (addToListOfOpenFiles) { - this.openFiles.push(info); - } - return; - } - var foundConfiguredProject = false; - for (var _i = 0, _a = info.containingProjects; _i < _a.length; _i++) { - var p = _a[_i]; - if (p.projectKind === server.ProjectKind.Configured) { - foundConfiguredProject = true; - if (addToListOfOpenFiles) { - (p).addOpenRef(); - } - } - } - if (foundConfiguredProject) { - if (addToListOfOpenFiles) { - this.openFiles.push(info); - } - return; - } - if (info.containingProjects.length === 0) { - var inferredProject = this.createInferredProjectWithRootFileIfNecessary(info); - if (!this.useSingleInferredProject) { - for (var _b = 0, _c = this.openFiles; _b < _c.length; _b++) { - var f = _c[_b]; - if (f.containingProjects.length === 0) { - continue; - } - var defaultProject = f.getDefaultProject(); - if (isRootFileInInferredProject(info) && defaultProject !== inferredProject && inferredProject.containsScriptInfo(f)) { - this.removeProject(defaultProject); - f.attachToProject(inferredProject); - } - } - } - } - if (addToListOfOpenFiles) { - this.openFiles.push(info); - } - }; - ProjectService.prototype.closeOpenFile = function (info) { - info.reloadFromFile(); - server.removeItemFromSet(this.openFiles, info); - info.isOpen = false; - var projectsToRemove; - for (var _i = 0, _a = info.containingProjects; _i < _a.length; _i++) { - var p = _a[_i]; - if (p.projectKind === server.ProjectKind.Configured) { - if (p.deleteOpenRef() === 0) { - (projectsToRemove || (projectsToRemove = [])).push(p); - } - } - else if (p.projectKind === server.ProjectKind.Inferred && p.isRoot(info)) { - (projectsToRemove || (projectsToRemove = [])).push(p); - } - } - if (projectsToRemove) { - for (var _b = 0, projectsToRemove_1 = projectsToRemove; _b < projectsToRemove_1.length; _b++) { - var project = projectsToRemove_1[_b]; - this.removeProject(project); - } - var orphanFiles = void 0; - for (var _c = 0, _d = this.openFiles; _c < _d.length; _c++) { - var f = _d[_c]; - if (f.containingProjects.length === 0) { - (orphanFiles || (orphanFiles = [])).push(f); - } - } - if (orphanFiles) { - for (var _e = 0, orphanFiles_1 = orphanFiles; _e < orphanFiles_1.length; _e++) { - var f = orphanFiles_1[_e]; - this.assignScriptInfoToInferredProjectIfNecessary(f, false); - } - } - } - if (info.containingProjects.length === 0) { - this.filenameToScriptInfo.remove(info.path); - } - }; - ProjectService.prototype.openOrUpdateConfiguredProjectForFile = function (fileName) { - var searchPath = ts.getDirectoryPath(fileName); - this.logger.info("Search path: " + searchPath); - var configFileName = this.findConfigFile(server.asNormalizedPath(searchPath)); - if (!configFileName) { - this.logger.info("No config files found."); - return {}; - } - this.logger.info("Config file name: " + configFileName); - var project = this.findConfiguredProjectByProjectName(configFileName); - if (!project) { - var _a = this.openConfigFile(configFileName, fileName), success = _a.success, errors = _a.errors; - if (!success) { - return { configFileName: configFileName, configFileErrors: errors }; - } - this.logger.info("Opened configuration file " + configFileName); - if (errors && errors.length > 0) { - return { configFileName: configFileName, configFileErrors: errors }; - } - } - else { - this.updateConfiguredProject(project); - } - return { configFileName: configFileName }; - }; - ProjectService.prototype.findConfigFile = function (searchPath) { - while (true) { - var tsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "tsconfig.json")); - if (this.host.fileExists(tsconfigFileName)) { - return tsconfigFileName; - } - var jsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "jsconfig.json")); - if (this.host.fileExists(jsconfigFileName)) { - return jsconfigFileName; - } - var parentPath = server.asNormalizedPath(ts.getDirectoryPath(searchPath)); - if (parentPath === searchPath) { - break; - } - searchPath = parentPath; - } - return undefined; - }; - ProjectService.prototype.printProjects = function () { - if (!this.logger.hasLevel(server.LogLevel.verbose)) { - return; - } - this.logger.startGroup(); - var counter = 0; - counter = printProjects(this.logger, this.externalProjects, counter); - counter = printProjects(this.logger, this.configuredProjects, counter); - counter = printProjects(this.logger, this.inferredProjects, counter); - this.logger.info("Open files: "); - for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { - var rootFile = _a[_i]; - this.logger.info(rootFile.fileName); - } - this.logger.endGroup(); - function printProjects(logger, projects, counter) { - for (var _i = 0, projects_3 = projects; _i < projects_3.length; _i++) { - var project = projects_3[_i]; - project.updateGraph(); - logger.info("Project '" + project.getProjectName() + "' (" + server.ProjectKind[project.projectKind] + ") " + counter); - logger.info(project.filesToString()); - logger.info("-----------------------------------------------"); - counter++; - } - return counter; - } - }; - ProjectService.prototype.findConfiguredProjectByProjectName = function (configFileName) { - return findProjectByName(configFileName, this.configuredProjects); - }; - ProjectService.prototype.findExternalProjectByProjectName = function (projectFileName) { - return findProjectByName(projectFileName, this.externalProjects); - }; - ProjectService.prototype.convertConfigFileContentToProjectOptions = function (configFilename) { - configFilename = ts.normalizePath(configFilename); - var configFileContent = this.host.readFile(configFilename); - var errors; - var result = ts.parseConfigFileTextToJson(configFilename, configFileContent); - var config = result.config; - if (result.error) { - var _a = ts.sanitizeConfigFile(configFilename, configFileContent), sanitizedConfig = _a.configJsonObject, diagnostics = _a.diagnostics; - config = sanitizedConfig; - errors = diagnostics.length ? diagnostics : [result.error]; - } - var parsedCommandLine = ts.parseJsonConfigFileContent(config, this.host, ts.getDirectoryPath(configFilename), {}, configFilename); - if (parsedCommandLine.errors.length) { - errors = ts.concatenate(errors, parsedCommandLine.errors); - } - ts.Debug.assert(!!parsedCommandLine.fileNames); - if (parsedCommandLine.fileNames.length === 0) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename)); - return { success: false, configFileErrors: errors }; - } - var projectOptions = { - files: parsedCommandLine.fileNames, - compilerOptions: parsedCommandLine.options, - configHasFilesProperty: config["files"] !== undefined, - wildcardDirectories: ts.createMap(parsedCommandLine.wildcardDirectories), - typingOptions: parsedCommandLine.typingOptions, - compileOnSave: parsedCommandLine.compileOnSave - }; - return { success: true, projectOptions: projectOptions, configFileErrors: errors }; - }; - ProjectService.prototype.exceededTotalSizeLimitForNonTsFiles = function (options, fileNames, propertyReader) { - if (options && options.disableSizeLimit || !this.host.getFileSize) { - return false; - } - var totalNonTsFileSize = 0; - for (var _i = 0, fileNames_3 = fileNames; _i < fileNames_3.length; _i++) { - var f = fileNames_3[_i]; - var fileName = propertyReader.getFileName(f); - if (ts.hasTypeScriptFileExtension(fileName)) { - continue; - } - totalNonTsFileSize += this.host.getFileSize(fileName); - if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles) { - return true; - } - } - return false; - }; - ProjectService.prototype.createAndAddExternalProject = function (projectFileName, files, options, typingOptions) { - var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, options, !this.exceededTotalSizeLimitForNonTsFiles(options, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave); - this.addFilesToProjectAndUpdateGraph(project, files, externalFilePropertyReader, undefined, typingOptions, undefined); - this.externalProjects.push(project); - return project; - }; - ProjectService.prototype.reportConfigFileDiagnostics = function (configFileName, diagnostics, triggerFile) { - if (diagnostics && diagnostics.length > 0) { - this.eventHandler({ - eventName: "configFileDiag", - data: { configFileName: configFileName, diagnostics: diagnostics, triggerFile: triggerFile } - }); - } - }; - ProjectService.prototype.createAndAddConfiguredProject = function (configFileName, projectOptions, configFileErrors, clientFileName) { - var _this = this; - var sizeLimitExceeded = this.exceededTotalSizeLimitForNonTsFiles(projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); - var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, projectOptions.wildcardDirectories, !sizeLimitExceeded, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave); - this.addFilesToProjectAndUpdateGraph(project, projectOptions.files, fileNamePropertyReader, clientFileName, projectOptions.typingOptions, configFileErrors); - project.watchConfigFile(function (project) { return _this.onConfigChangedForConfiguredProject(project); }); - if (!sizeLimitExceeded) { - this.watchConfigDirectoryForProject(project, projectOptions); - } - project.watchWildcards(function (project, path) { return _this.onSourceFileInDirectoryChangedForConfiguredProject(project, path); }); - project.watchTypeRoots(function (project, path) { return _this.onTypeRootFileChanged(project, path); }); - this.configuredProjects.push(project); - return project; - }; - ProjectService.prototype.watchConfigDirectoryForProject = function (project, options) { - var _this = this; - if (!options.configHasFilesProperty) { - project.watchConfigDirectory(function (project, path) { return _this.onSourceFileInDirectoryChangedForConfiguredProject(project, path); }); - } - }; - ProjectService.prototype.addFilesToProjectAndUpdateGraph = function (project, files, propertyReader, clientFileName, typingOptions, configFileErrors) { - var errors; - for (var _i = 0, files_4 = files; _i < files_4.length; _i++) { - var f = files_4[_i]; - var rootFilename = propertyReader.getFileName(f); - var scriptKind = propertyReader.getScriptKind(f); - var hasMixedContent = propertyReader.hasMixedContent(f); - if (this.host.fileExists(rootFilename)) { - var info = this.getOrCreateScriptInfoForNormalizedPath(server.toNormalizedPath(rootFilename), clientFileName == rootFilename, undefined, scriptKind, hasMixedContent); - project.addRoot(info); - } - else { - (errors || (errors = [])).push(createFileNotFoundDiagnostic(rootFilename)); - } - } - project.setProjectErrors(ts.concatenate(configFileErrors, errors)); - project.setTypingOptions(typingOptions); - project.updateGraph(); - }; - ProjectService.prototype.openConfigFile = function (configFileName, clientFileName) { - var conversionResult = this.convertConfigFileContentToProjectOptions(configFileName); - var projectOptions = conversionResult.success - ? conversionResult.projectOptions - : { files: [], compilerOptions: {} }; - var project = this.createAndAddConfiguredProject(configFileName, projectOptions, conversionResult.configFileErrors, clientFileName); - return { - success: conversionResult.success, - project: project, - errors: project.getProjectErrors() - }; - }; - ProjectService.prototype.updateNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypingOptions, compileOnSave, configFileErrors) { - var oldRootScriptInfos = project.getRootScriptInfos(); - var newRootScriptInfos = []; - var newRootScriptInfoMap = server.createNormalizedPathMap(); - var projectErrors; - var rootFilesChanged = false; - for (var _i = 0, newUncheckedFiles_1 = newUncheckedFiles; _i < newUncheckedFiles_1.length; _i++) { - var f = newUncheckedFiles_1[_i]; - var newRootFile = propertyReader.getFileName(f); - if (!this.host.fileExists(newRootFile)) { - (projectErrors || (projectErrors = [])).push(createFileNotFoundDiagnostic(newRootFile)); - continue; - } - var normalizedPath = server.toNormalizedPath(newRootFile); - var scriptInfo = this.getScriptInfoForNormalizedPath(normalizedPath); - if (!scriptInfo || !project.isRoot(scriptInfo)) { - rootFilesChanged = true; - if (!scriptInfo) { - var scriptKind = propertyReader.getScriptKind(f); - var hasMixedContent = propertyReader.hasMixedContent(f); - scriptInfo = this.getOrCreateScriptInfoForNormalizedPath(normalizedPath, false, undefined, scriptKind, hasMixedContent); - } - } - newRootScriptInfos.push(scriptInfo); - newRootScriptInfoMap.set(scriptInfo.fileName, scriptInfo); - } - if (rootFilesChanged || newRootScriptInfos.length !== oldRootScriptInfos.length) { - var toAdd = void 0; - var toRemove = void 0; - for (var _a = 0, oldRootScriptInfos_1 = oldRootScriptInfos; _a < oldRootScriptInfos_1.length; _a++) { - var oldFile = oldRootScriptInfos_1[_a]; - if (!newRootScriptInfoMap.contains(oldFile.fileName)) { - (toRemove || (toRemove = [])).push(oldFile); - } - } - for (var _b = 0, newRootScriptInfos_1 = newRootScriptInfos; _b < newRootScriptInfos_1.length; _b++) { - var newFile = newRootScriptInfos_1[_b]; - if (!project.isRoot(newFile)) { - (toAdd || (toAdd = [])).push(newFile); - } - } - if (toRemove) { - for (var _c = 0, toRemove_1 = toRemove; _c < toRemove_1.length; _c++) { - var f = toRemove_1[_c]; - project.removeFile(f); - } - } - if (toAdd) { - for (var _d = 0, toAdd_1 = toAdd; _d < toAdd_1.length; _d++) { - var f = toAdd_1[_d]; - if (f.isOpen && isRootFileInInferredProject(f)) { - var inferredProject = f.containingProjects[0]; - inferredProject.removeFile(f); - if (!inferredProject.hasRoots()) { - this.removeProject(inferredProject); - } - } - project.addRoot(f); - } - } - } - project.setCompilerOptions(newOptions); - project.setTypingOptions(newTypingOptions); - if (compileOnSave !== undefined) { - project.compileOnSaveEnabled = compileOnSave; - } - project.setProjectErrors(ts.concatenate(configFileErrors, projectErrors)); - project.updateGraph(); - }; - ProjectService.prototype.updateConfiguredProject = function (project) { - if (!this.host.fileExists(project.configFileName)) { - this.logger.info("Config file deleted"); - this.removeProject(project); - return; - } - var _a = this.convertConfigFileContentToProjectOptions(project.configFileName), success = _a.success, projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors; - if (!success) { - this.updateNonInferredProject(project, [], fileNamePropertyReader, {}, {}, false, configFileErrors); - return configFileErrors; - } - if (this.exceededTotalSizeLimitForNonTsFiles(projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader)) { - project.setCompilerOptions(projectOptions.compilerOptions); - if (!project.languageServiceEnabled) { - return; - } - project.disableLanguageService(); - project.stopWatchingDirectory(); - } - else { - if (!project.languageServiceEnabled) { - project.enableLanguageService(); - } - this.watchConfigDirectoryForProject(project, projectOptions); - this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typingOptions, projectOptions.compileOnSave, configFileErrors); - } - }; - ProjectService.prototype.createInferredProjectWithRootFileIfNecessary = function (root) { - var _this = this; - var useExistingProject = this.useSingleInferredProject && this.inferredProjects.length; - var project = useExistingProject - ? this.inferredProjects[0] - : new server.InferredProject(this, this.documentRegistry, true, this.compilerOptionsForInferredProjects, this.compileOnSaveForInferredProjects); - project.addRoot(root); - this.directoryWatchers.startWatchingContainingDirectoriesForFile(root.fileName, project, function (fileName) { return _this.onConfigFileAddedForInferredProject(fileName); }); - project.updateGraph(); - if (!useExistingProject) { - this.inferredProjects.push(project); - } - return project; - }; - ProjectService.prototype.getOrCreateScriptInfo = function (uncheckedFileName, openedByClient, fileContent, scriptKind) { - return this.getOrCreateScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName), openedByClient, fileContent, scriptKind); - }; - ProjectService.prototype.getScriptInfo = function (uncheckedFileName) { - return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); - }; - ProjectService.prototype.getOrCreateScriptInfoForNormalizedPath = function (fileName, openedByClient, fileContent, scriptKind, hasMixedContent) { - var _this = this; - var info = this.getScriptInfoForNormalizedPath(fileName); - if (!info) { - var content = void 0; - if (this.host.fileExists(fileName)) { - content = fileContent || (hasMixedContent ? "" : this.host.readFile(fileName)); - } - if (!content) { - if (openedByClient) { - content = ""; - } - } - if (content !== undefined) { - info = new server.ScriptInfo(this.host, fileName, content, scriptKind, openedByClient, hasMixedContent); - this.filenameToScriptInfo.set(info.path, info); - if (!info.isOpen && !hasMixedContent) { - info.setWatcher(this.host.watchFile(fileName, function (_) { return _this.onSourceFileChanged(fileName); })); - } - } - } - if (info) { - if (fileContent) { - info.reload(fileContent); - } - if (openedByClient) { - info.isOpen = true; - } - } - return info; - }; - ProjectService.prototype.getScriptInfoForNormalizedPath = function (fileName) { - return this.filenameToScriptInfo.get(server.normalizedPathToPath(fileName, this.host.getCurrentDirectory(), this.toCanonicalFileName)); - }; - ProjectService.prototype.setHostConfiguration = function (args) { - if (args.file) { - var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(args.file)); - if (info) { - info.setFormatOptions(args.formatOptions); - this.logger.info("Host configuration update for file " + args.file); - } - } - else { - if (args.hostInfo !== undefined) { - this.hostConfiguration.hostInfo = args.hostInfo; - this.logger.info("Host information " + args.hostInfo); - } - if (args.formatOptions) { - server.mergeMaps(this.hostConfiguration.formatCodeOptions, args.formatOptions); - this.logger.info("Format host information updated"); - } - } - }; - ProjectService.prototype.closeLog = function () { - this.logger.close(); - }; - ProjectService.prototype.reloadProjects = function () { - this.logger.info("reload projects."); - for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { - var info = _a[_i]; - this.openOrUpdateConfiguredProjectForFile(info.fileName); - } - this.refreshInferredProjects(); - }; - ProjectService.prototype.refreshInferredProjects = function () { - this.logger.info("updating project structure from ..."); - this.printProjects(); - var orphantedFiles = []; - for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { - var info = _a[_i]; - if (info.containingProjects.length === 0) { - orphantedFiles.push(info); - } - else { - if (isRootFileInInferredProject(info) && info.containingProjects.length > 1) { - var inferredProject = info.containingProjects[0]; - ts.Debug.assert(inferredProject.projectKind === server.ProjectKind.Inferred); - inferredProject.removeFile(info); - if (!inferredProject.hasRoots()) { - this.removeProject(inferredProject); - } - } - } - } - for (var _b = 0, orphantedFiles_1 = orphantedFiles; _b < orphantedFiles_1.length; _b++) { - var f = orphantedFiles_1[_b]; - this.assignScriptInfoToInferredProjectIfNecessary(f, false); - } - for (var _c = 0, _d = this.inferredProjects; _c < _d.length; _c++) { - var p = _d[_c]; - p.updateGraph(); - } - this.printProjects(); - }; - ProjectService.prototype.openClientFile = function (fileName, fileContent, scriptKind) { - return this.openClientFileWithNormalizedPath(server.toNormalizedPath(fileName), fileContent, scriptKind); - }; - ProjectService.prototype.openClientFileWithNormalizedPath = function (fileName, fileContent, scriptKind, hasMixedContent) { - var _a = this.findContainingExternalProject(fileName) - ? {} - : this.openOrUpdateConfiguredProjectForFile(fileName), _b = _a.configFileName, configFileName = _b === void 0 ? undefined : _b, _c = _a.configFileErrors, configFileErrors = _c === void 0 ? undefined : _c; - var info = this.getOrCreateScriptInfoForNormalizedPath(fileName, true, fileContent, scriptKind, hasMixedContent); - this.assignScriptInfoToInferredProjectIfNecessary(info, true); - this.printProjects(); - return { configFileName: configFileName, configFileErrors: configFileErrors }; - }; - ProjectService.prototype.closeClientFile = function (uncheckedFileName) { - var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); - if (info) { - this.closeOpenFile(info); - info.isOpen = false; - } - this.printProjects(); - }; - ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) { - var _loop_4 = function(proj) { - var knownProject = ts.forEach(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName() && p; }); - result.push(proj.getChangesSinceVersion(knownProject && knownProject.version)); - }; - for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) { - var proj = currentProjects_1[_i]; - _loop_4(proj); - } - }; - ProjectService.prototype.synchronizeProjectList = function (knownProjects) { - var files = []; - this.collectChanges(knownProjects, this.externalProjects, files); - this.collectChanges(knownProjects, this.configuredProjects, files); - this.collectChanges(knownProjects, this.inferredProjects, files); - return files; - }; - ProjectService.prototype.applyChangesInOpenFiles = function (openFiles, changedFiles, closedFiles) { - var recordChangedFiles = changedFiles && !openFiles && !closedFiles; - if (openFiles) { - for (var _i = 0, openFiles_1 = openFiles; _i < openFiles_1.length; _i++) { - var file = openFiles_1[_i]; - var scriptInfo = this.getScriptInfo(file.fileName); - ts.Debug.assert(!scriptInfo || !scriptInfo.isOpen); - var normalizedPath = scriptInfo ? scriptInfo.fileName : server.toNormalizedPath(file.fileName); - this.openClientFileWithNormalizedPath(normalizedPath, file.content, file.scriptKind, file.hasMixedContent); - } - } - if (changedFiles) { - for (var _a = 0, changedFiles_1 = changedFiles; _a < changedFiles_1.length; _a++) { - var file = changedFiles_1[_a]; - var scriptInfo = this.getScriptInfo(file.fileName); - ts.Debug.assert(!!scriptInfo); - for (var i = file.changes.length - 1; i >= 0; i--) { - var change = file.changes[i]; - scriptInfo.editContent(change.span.start, change.span.start + change.span.length, change.newText); - } - if (recordChangedFiles) { - if (!this.changedFiles) { - this.changedFiles = [scriptInfo]; - } - else if (this.changedFiles.indexOf(scriptInfo) < 0) { - this.changedFiles.push(scriptInfo); - } - } - } - } - if (closedFiles) { - for (var _b = 0, closedFiles_1 = closedFiles; _b < closedFiles_1.length; _b++) { - var file = closedFiles_1[_b]; - this.closeClientFile(file); - } - } - if (openFiles || closedFiles) { - this.refreshInferredProjects(); - } - }; - ProjectService.prototype.closeConfiguredProject = function (configFile) { - var configuredProject = this.findConfiguredProjectByProjectName(configFile); - if (configuredProject && configuredProject.deleteOpenRef() === 0) { - this.removeProject(configuredProject); - } - }; - ProjectService.prototype.closeExternalProject = function (uncheckedFileName, suppressRefresh) { - if (suppressRefresh === void 0) { suppressRefresh = false; } - var fileName = server.toNormalizedPath(uncheckedFileName); - var configFiles = this.externalProjectToConfiguredProjectMap[fileName]; - if (configFiles) { - var shouldRefreshInferredProjects = false; - for (var _i = 0, configFiles_1 = configFiles; _i < configFiles_1.length; _i++) { - var configFile = configFiles_1[_i]; - if (this.closeConfiguredProject(configFile)) { - shouldRefreshInferredProjects = true; - } - } - delete this.externalProjectToConfiguredProjectMap[fileName]; - if (shouldRefreshInferredProjects && !suppressRefresh) { - this.refreshInferredProjects(); - } - } - else { - var externalProject = this.findExternalProjectByProjectName(uncheckedFileName); - if (externalProject) { - this.removeProject(externalProject); - if (!suppressRefresh) { - this.refreshInferredProjects(); - } - } - } - }; - ProjectService.prototype.openExternalProject = function (proj) { - var tsConfigFiles; - var rootFiles = []; - for (var _i = 0, _a = proj.rootFiles; _i < _a.length; _i++) { - var file = _a[_i]; - var normalized = server.toNormalizedPath(file.fileName); - if (ts.getBaseFileName(normalized) === "tsconfig.json") { - (tsConfigFiles || (tsConfigFiles = [])).push(normalized); - } - else { - rootFiles.push(file); - } - } - if (tsConfigFiles) { - tsConfigFiles.sort(); - } - var externalProject = this.findExternalProjectByProjectName(proj.projectFileName); - var exisingConfigFiles; - if (externalProject) { - if (!tsConfigFiles) { - this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, proj.options, proj.typingOptions, proj.options.compileOnSave, undefined); - return; - } - this.closeExternalProject(proj.projectFileName, true); - } - else if (this.externalProjectToConfiguredProjectMap[proj.projectFileName]) { - if (!tsConfigFiles) { - this.closeExternalProject(proj.projectFileName, true); - } - else { - var oldConfigFiles = this.externalProjectToConfiguredProjectMap[proj.projectFileName]; - var iNew = 0; - var iOld = 0; - while (iNew < tsConfigFiles.length && iOld < oldConfigFiles.length) { - var newConfig = tsConfigFiles[iNew]; - var oldConfig = oldConfigFiles[iOld]; - if (oldConfig < newConfig) { - this.closeConfiguredProject(oldConfig); - iOld++; - } - else if (oldConfig > newConfig) { - iNew++; - } - else { - (exisingConfigFiles || (exisingConfigFiles = [])).push(oldConfig); - iOld++; - iNew++; - } - } - for (var i = iOld; i < oldConfigFiles.length; i++) { - this.closeConfiguredProject(oldConfigFiles[i]); - } - } - } - if (tsConfigFiles) { - this.externalProjectToConfiguredProjectMap[proj.projectFileName] = tsConfigFiles; - for (var _b = 0, tsConfigFiles_1 = tsConfigFiles; _b < tsConfigFiles_1.length; _b++) { - var tsconfigFile = tsConfigFiles_1[_b]; - var project = this.findConfiguredProjectByProjectName(tsconfigFile); - if (!project) { - var result = this.openConfigFile(tsconfigFile); - project = result.success && result.project; - } - if (project && !ts.contains(exisingConfigFiles, tsconfigFile)) { - project.addOpenRef(); - } - } - } - else { - delete this.externalProjectToConfiguredProjectMap[proj.projectFileName]; - this.createAndAddExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typingOptions); - } - this.refreshInferredProjects(); - }; - return ProjectService; - }()); - server.ProjectService = ProjectService; - })(server = ts.server || (ts.server = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - var server; - (function (server) { - function hrTimeToMilliseconds(time) { - var seconds = time[0]; - var nanoseconds = time[1]; - return ((1e9 * seconds) + nanoseconds) / 1000000.0; - } + server.generateIndentString = generateIndentString; function compareNumber(a, b) { - return a - b; + if (a < b) { + return -1; + } + else if (a === b) { + return 0; + } + else + return 1; } function compareFileStart(a, b) { if (a.file < b.file) { @@ -53811,10 +49740,9 @@ var ts; } } function formatDiag(fileName, project, diag) { - var scriptInfo = project.getScriptInfoForNormalizedPath(fileName); return { - start: scriptInfo.positionToLineOffset(diag.start), - end: scriptInfo.positionToLineOffset(diag.start + diag.length), + start: project.compilerService.host.positionToLineOffset(fileName, diag.start), + end: project.compilerService.host.positionToLineOffset(fileName, diag.start + diag.length), text: ts.flattenDiagnosticMessageText(diag.messageText, "\n") }; } @@ -53826,9 +49754,8 @@ var ts; }; } function allEditsBeforePos(edits, pos) { - for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) { - var edit = edits_1[_i]; - if (ts.textSpanEnd(edit.span) >= pos) { + for (var i = 0, len = edits.length; i < len; i++) { + if (ts.textSpanEnd(edits[i].span) >= pos) { return false; } } @@ -53837,153 +49764,68 @@ var ts; var CommandNames; (function (CommandNames) { CommandNames.Brace = "brace"; - CommandNames.BraceFull = "brace-full"; - CommandNames.BraceCompletion = "braceCompletion"; CommandNames.Change = "change"; CommandNames.Close = "close"; CommandNames.Completions = "completions"; - CommandNames.CompletionsFull = "completions-full"; CommandNames.CompletionDetails = "completionEntryDetails"; - CommandNames.CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList"; - CommandNames.CompileOnSaveEmitFile = "compileOnSaveEmitFile"; CommandNames.Configure = "configure"; CommandNames.Definition = "definition"; - CommandNames.DefinitionFull = "definition-full"; CommandNames.Exit = "exit"; CommandNames.Format = "format"; CommandNames.Formatonkey = "formatonkey"; - CommandNames.FormatFull = "format-full"; - CommandNames.FormatonkeyFull = "formatonkey-full"; - CommandNames.FormatRangeFull = "formatRange-full"; CommandNames.Geterr = "geterr"; CommandNames.GeterrForProject = "geterrForProject"; CommandNames.SemanticDiagnosticsSync = "semanticDiagnosticsSync"; CommandNames.SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; CommandNames.NavBar = "navbar"; - CommandNames.NavBarFull = "navbar-full"; CommandNames.Navto = "navto"; - CommandNames.NavtoFull = "navto-full"; CommandNames.Occurrences = "occurrences"; CommandNames.DocumentHighlights = "documentHighlights"; - CommandNames.DocumentHighlightsFull = "documentHighlights-full"; CommandNames.Open = "open"; CommandNames.Quickinfo = "quickinfo"; - CommandNames.QuickinfoFull = "quickinfo-full"; CommandNames.References = "references"; - CommandNames.ReferencesFull = "references-full"; CommandNames.Reload = "reload"; CommandNames.Rename = "rename"; - CommandNames.RenameInfoFull = "rename-full"; - CommandNames.RenameLocationsFull = "renameLocations-full"; CommandNames.Saveto = "saveto"; CommandNames.SignatureHelp = "signatureHelp"; - CommandNames.SignatureHelpFull = "signatureHelp-full"; CommandNames.TypeDefinition = "typeDefinition"; CommandNames.ProjectInfo = "projectInfo"; CommandNames.ReloadProjects = "reloadProjects"; CommandNames.Unknown = "unknown"; - CommandNames.OpenExternalProject = "openExternalProject"; - CommandNames.OpenExternalProjects = "openExternalProjects"; - CommandNames.CloseExternalProject = "closeExternalProject"; - CommandNames.SynchronizeProjectList = "synchronizeProjectList"; - CommandNames.ApplyChangedToOpenFiles = "applyChangedToOpenFiles"; - CommandNames.EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full"; - CommandNames.Cleanup = "cleanup"; - CommandNames.OutliningSpans = "outliningSpans"; - CommandNames.TodoComments = "todoComments"; - CommandNames.Indentation = "indentation"; - CommandNames.DocCommentTemplate = "docCommentTemplate"; - CommandNames.CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full"; - CommandNames.NameOrDottedNameSpan = "nameOrDottedNameSpan"; - CommandNames.BreakpointStatement = "breakpointStatement"; - CommandNames.CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects"; })(CommandNames = server.CommandNames || (server.CommandNames = {})); - function formatMessage(msg, logger, byteLength, newLine) { - var verboseLogging = logger.hasLevel(server.LogLevel.verbose); - var json = JSON.stringify(msg); - if (verboseLogging) { - logger.info(msg.type + ": " + json); - } - var len = byteLength(json, "utf8"); - return "Content-Length: " + (1 + len) + "\r\n\r\n" + json + newLine; - } - server.formatMessage = formatMessage; + var Errors; + (function (Errors) { + Errors.NoProject = new Error("No Project."); + Errors.ProjectLanguageServiceDisabled = new Error("The project's language service is disabled."); + })(Errors || (Errors = {})); var Session = (function () { - function Session(host, cancellationToken, useSingleInferredProject, typingsInstaller, byteLength, hrtime, logger, canUseEvents) { + function Session(host, byteLength, hrtime, logger) { var _this = this; this.host = host; - this.typingsInstaller = typingsInstaller; this.byteLength = byteLength; this.hrtime = hrtime; this.logger = logger; - this.canUseEvents = canUseEvents; this.changeSeq = 0; - this.handlers = ts.createMap((_a = {}, - _a[CommandNames.OpenExternalProject] = function (request) { - _this.projectService.openExternalProject(request.arguments); - return _this.requiredResponse(true); - }, - _a[CommandNames.OpenExternalProjects] = function (request) { - for (var _i = 0, _a = request.arguments.projects; _i < _a.length; _i++) { - var proj = _a[_i]; - _this.projectService.openExternalProject(proj); - } - return _this.requiredResponse(true); - }, - _a[CommandNames.CloseExternalProject] = function (request) { - _this.projectService.closeExternalProject(request.arguments.projectFileName); - return _this.requiredResponse(true); - }, - _a[CommandNames.SynchronizeProjectList] = function (request) { - var result = _this.projectService.synchronizeProjectList(request.arguments.knownProjects); - if (!result.some(function (p) { return p.projectErrors && p.projectErrors.length !== 0; })) { - return _this.requiredResponse(result); - } - var converted = ts.map(result, function (p) { - if (!p.projectErrors || p.projectErrors.length === 0) { - return p; - } - return { - info: p.info, - changes: p.changes, - files: p.files, - projectErrors: _this.convertToDiagnosticsWithLinePosition(p.projectErrors, undefined) - }; - }); - return _this.requiredResponse(converted); - }, - _a[CommandNames.ApplyChangedToOpenFiles] = function (request) { - _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles, request.arguments.changedFiles, request.arguments.closedFiles); - _this.changeSeq++; - return _this.requiredResponse(true); - }, + this.handlers = (_a = {}, _a[CommandNames.Exit] = function () { _this.exit(); - return _this.notRequired(); + return { responseRequired: false }; }, _a[CommandNames.Definition] = function (request) { - return _this.requiredResponse(_this.getDefinition(request.arguments, true)); - }, - _a[CommandNames.DefinitionFull] = function (request) { - return _this.requiredResponse(_this.getDefinition(request.arguments, false)); + var defArgs = request.arguments; + return { response: _this.getDefinition(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true }; }, _a[CommandNames.TypeDefinition] = function (request) { - return _this.requiredResponse(_this.getTypeDefinition(request.arguments)); + var defArgs = request.arguments; + return { response: _this.getTypeDefinition(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true }; }, _a[CommandNames.References] = function (request) { - return _this.requiredResponse(_this.getReferences(request.arguments, true)); - }, - _a[CommandNames.ReferencesFull] = function (request) { - return _this.requiredResponse(_this.getReferences(request.arguments, false)); + var defArgs = request.arguments; + return { response: _this.getReferences(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true }; }, _a[CommandNames.Rename] = function (request) { - return _this.requiredResponse(_this.getRenameLocations(request.arguments, true)); - }, - _a[CommandNames.RenameLocationsFull] = function (request) { - return _this.requiredResponse(_this.getRenameLocations(request.arguments, false)); - }, - _a[CommandNames.RenameInfoFull] = function (request) { - return _this.requiredResponse(_this.getRenameInfo(request.arguments)); + var renameArgs = request.arguments; + return { response: _this.getRenameLocations(renameArgs.line, renameArgs.offset, renameArgs.file, renameArgs.findInComments, renameArgs.findInStrings), responseRequired: true }; }, _a[CommandNames.Open] = function (request) { var openArgs = request.arguments; @@ -54002,81 +49844,34 @@ var ts; scriptKind = 2; break; } - _this.openClientFile(server.toNormalizedPath(openArgs.file), openArgs.fileContent, scriptKind); - return _this.notRequired(); + _this.openClientFile(openArgs.file, openArgs.fileContent, scriptKind); + return { responseRequired: false }; }, _a[CommandNames.Quickinfo] = function (request) { - return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, true)); - }, - _a[CommandNames.QuickinfoFull] = function (request) { - return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, false)); - }, - _a[CommandNames.OutliningSpans] = function (request) { - return _this.requiredResponse(_this.getOutliningSpans(request.arguments)); - }, - _a[CommandNames.TodoComments] = function (request) { - return _this.requiredResponse(_this.getTodoComments(request.arguments)); - }, - _a[CommandNames.Indentation] = function (request) { - return _this.requiredResponse(_this.getIndentation(request.arguments)); - }, - _a[CommandNames.NameOrDottedNameSpan] = function (request) { - return _this.requiredResponse(_this.getNameOrDottedNameSpan(request.arguments)); - }, - _a[CommandNames.BreakpointStatement] = function (request) { - return _this.requiredResponse(_this.getBreakpointStatement(request.arguments)); - }, - _a[CommandNames.BraceCompletion] = function (request) { - return _this.requiredResponse(_this.isValidBraceCompletion(request.arguments)); - }, - _a[CommandNames.DocCommentTemplate] = function (request) { - return _this.requiredResponse(_this.getDocCommentTemplate(request.arguments)); + var quickinfoArgs = request.arguments; + return { response: _this.getQuickInfo(quickinfoArgs.line, quickinfoArgs.offset, quickinfoArgs.file), responseRequired: true }; }, _a[CommandNames.Format] = function (request) { - return _this.requiredResponse(_this.getFormattingEditsForRange(request.arguments)); + var formatArgs = request.arguments; + return { response: _this.getFormattingEditsForRange(formatArgs.line, formatArgs.offset, formatArgs.endLine, formatArgs.endOffset, formatArgs.file), responseRequired: true }; }, _a[CommandNames.Formatonkey] = function (request) { - return _this.requiredResponse(_this.getFormattingEditsAfterKeystroke(request.arguments)); - }, - _a[CommandNames.FormatFull] = function (request) { - return _this.requiredResponse(_this.getFormattingEditsForDocumentFull(request.arguments)); - }, - _a[CommandNames.FormatonkeyFull] = function (request) { - return _this.requiredResponse(_this.getFormattingEditsAfterKeystrokeFull(request.arguments)); - }, - _a[CommandNames.FormatRangeFull] = function (request) { - return _this.requiredResponse(_this.getFormattingEditsForRangeFull(request.arguments)); + var formatOnKeyArgs = request.arguments; + return { response: _this.getFormattingEditsAfterKeystroke(formatOnKeyArgs.line, formatOnKeyArgs.offset, formatOnKeyArgs.key, formatOnKeyArgs.file), responseRequired: true }; }, _a[CommandNames.Completions] = function (request) { - return _this.requiredResponse(_this.getCompletions(request.arguments, true)); - }, - _a[CommandNames.CompletionsFull] = function (request) { - return _this.requiredResponse(_this.getCompletions(request.arguments, false)); + var completionsArgs = request.arguments; + return { response: _this.getCompletions(completionsArgs.line, completionsArgs.offset, completionsArgs.prefix, completionsArgs.file), responseRequired: true }; }, _a[CommandNames.CompletionDetails] = function (request) { - return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments)); - }, - _a[CommandNames.CompileOnSaveAffectedFileList] = function (request) { - return _this.requiredResponse(_this.getCompileOnSaveAffectedFileList(request.arguments)); - }, - _a[CommandNames.CompileOnSaveEmitFile] = function (request) { - return _this.requiredResponse(_this.emitFile(request.arguments)); + var completionDetailsArgs = request.arguments; + return { + response: _this.getCompletionEntryDetails(completionDetailsArgs.line, completionDetailsArgs.offset, completionDetailsArgs.entryNames, completionDetailsArgs.file), responseRequired: true + }; }, _a[CommandNames.SignatureHelp] = function (request) { - return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, true)); - }, - _a[CommandNames.SignatureHelpFull] = function (request) { - return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, false)); - }, - _a[CommandNames.CompilerOptionsDiagnosticsFull] = function (request) { - return _this.requiredResponse(_this.getCompilerOptionsDiagnostics(request.arguments)); - }, - _a[CommandNames.EncodedSemanticClassificationsFull] = function (request) { - return _this.requiredResponse(_this.getEncodedSemanticClassifications(request.arguments)); - }, - _a[CommandNames.Cleanup] = function (request) { - _this.cleanup(); - return _this.requiredResponse(true); + var signatureHelpArgs = request.arguments; + return { response: _this.getSignatureHelpItems(signatureHelpArgs.line, signatureHelpArgs.offset, signatureHelpArgs.file), responseRequired: true }; }, _a[CommandNames.SemanticDiagnosticsSync] = function (request) { return _this.requiredResponse(_this.getSemanticDiagnosticsSync(request.arguments)); @@ -54093,105 +49888,95 @@ var ts; return { response: _this.getDiagnosticsForProject(delay, file), responseRequired: false }; }, _a[CommandNames.Change] = function (request) { - _this.change(request.arguments); - return _this.notRequired(); + var changeArgs = request.arguments; + _this.change(changeArgs.line, changeArgs.offset, changeArgs.endLine, changeArgs.endOffset, changeArgs.insertString, changeArgs.file); + return { responseRequired: false }; }, _a[CommandNames.Configure] = function (request) { - _this.projectService.setHostConfiguration(request.arguments); + var configureArgs = request.arguments; + _this.projectService.setHostConfiguration(configureArgs); _this.output(undefined, CommandNames.Configure, request.seq); - return _this.notRequired(); + return { responseRequired: false }; }, _a[CommandNames.Reload] = function (request) { - _this.reload(request.arguments, request.seq); - return _this.requiredResponse({ reloadFinished: true }); + var reloadArgs = request.arguments; + _this.reload(reloadArgs.file, reloadArgs.tmpfile, request.seq); + return { response: { reloadFinished: true }, responseRequired: true }; }, _a[CommandNames.Saveto] = function (request) { var savetoArgs = request.arguments; _this.saveToTmp(savetoArgs.file, savetoArgs.tmpfile); - return _this.notRequired(); + return { responseRequired: false }; }, _a[CommandNames.Close] = function (request) { var closeArgs = request.arguments; _this.closeClientFile(closeArgs.file); - return _this.notRequired(); + return { responseRequired: false }; }, _a[CommandNames.Navto] = function (request) { - return _this.requiredResponse(_this.getNavigateToItems(request.arguments, true)); - }, - _a[CommandNames.NavtoFull] = function (request) { - return _this.requiredResponse(_this.getNavigateToItems(request.arguments, false)); + var navtoArgs = request.arguments; + return { response: _this.getNavigateToItems(navtoArgs.searchValue, navtoArgs.file, navtoArgs.maxResultCount), responseRequired: true }; }, _a[CommandNames.Brace] = function (request) { - return _this.requiredResponse(_this.getBraceMatching(request.arguments, true)); - }, - _a[CommandNames.BraceFull] = function (request) { - return _this.requiredResponse(_this.getBraceMatching(request.arguments, false)); + var braceArguments = request.arguments; + return { response: _this.getBraceMatching(braceArguments.line, braceArguments.offset, braceArguments.file), responseRequired: true }; }, _a[CommandNames.NavBar] = function (request) { - return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, true)); - }, - _a[CommandNames.NavBarFull] = function (request) { - return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, false)); + var navBarArgs = request.arguments; + return { response: _this.getNavigationBarItems(navBarArgs.file), responseRequired: true }; }, _a[CommandNames.Occurrences] = function (request) { - return _this.requiredResponse(_this.getOccurrences(request.arguments)); + var _a = request.arguments, line = _a.line, offset = _a.offset, fileName = _a.file; + return { response: _this.getOccurrences(line, offset, fileName), responseRequired: true }; }, _a[CommandNames.DocumentHighlights] = function (request) { - return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, true)); - }, - _a[CommandNames.DocumentHighlightsFull] = function (request) { - return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, false)); - }, - _a[CommandNames.CompilerOptionsForInferredProjects] = function (request) { - return _this.requiredResponse(_this.setCompilerOptionsForInferredProjects(request.arguments)); + var _a = request.arguments, line = _a.line, offset = _a.offset, fileName = _a.file, filesToSearch = _a.filesToSearch; + return { response: _this.getDocumentHighlights(line, offset, fileName, filesToSearch), responseRequired: true }; }, _a[CommandNames.ProjectInfo] = function (request) { - return _this.requiredResponse(_this.getProjectInfo(request.arguments)); + var _a = request.arguments, file = _a.file, needFileNameList = _a.needFileNameList; + return { response: _this.getProjectInfo(file, needFileNameList), responseRequired: true }; }, _a[CommandNames.ReloadProjects] = function (request) { - _this.projectService.reloadProjects(); - return _this.notRequired(); + _this.reloadProjects(); + return { responseRequired: false }; }, _a - )); - var eventHandler = canUseEvents - ? function (event) { return _this.handleEvent(event); } - : undefined; - this.projectService = new server.ProjectService(host, logger, cancellationToken, useSingleInferredProject, typingsInstaller, eventHandler); - this.gcTimer = new server.GcTimer(host, 7000, logger); + ); + this.projectService = + new server.ProjectService(host, logger, function (eventName, project, fileName) { + _this.handleEvent(eventName, project, fileName); + }); var _a; } - Session.prototype.handleEvent = function (event) { + Session.prototype.handleEvent = function (eventName, project, fileName) { var _this = this; - switch (event.eventName) { - case "context": - var _a = event.data, project = _a.project, fileName = _a.fileName; - this.projectService.logger.info("got context event, updating diagnostics for " + fileName); - this.updateErrorCheck([{ fileName: fileName, project: project }], this.changeSeq, function (n) { return n === _this.changeSeq; }, 100); - break; - case "configFileDiag": - var _b = event.data, triggerFile = _b.triggerFile, configFileName = _b.configFileName, diagnostics = _b.diagnostics; - this.configFileDiagnosticEvent(triggerFile, configFileName, diagnostics); + if (eventName == "context") { + this.projectService.log("got context event, updating diagnostics for" + fileName, "Info"); + this.updateErrorCheck([{ fileName: fileName, project: project }], this.changeSeq, function (n) { return n === _this.changeSeq; }, 100); } }; Session.prototype.logError = function (err, cmd) { + var typedErr = err; var msg = "Exception on executing command " + cmd; - if (err.message) { - msg += ":\n" + err.message; - if (err.stack) { - msg += "\n" + err.stack; + if (typedErr.message) { + msg += ":\n" + typedErr.message; + if (typedErr.stack) { + msg += "\n" + typedErr.stack; } } - this.logger.msg(msg, server.Msg.Err); + this.projectService.log(msg); + }; + Session.prototype.sendLineToClient = function (line) { + this.host.write(line + this.host.newLine); }; Session.prototype.send = function (msg) { - if (msg.type === "event" && !this.canUseEvents) { - if (this.logger.hasLevel(server.LogLevel.verbose)) { - this.logger.info("Session does not support events: ignored event: " + JSON.stringify(msg)); - } - return; + var json = JSON.stringify(msg); + if (this.logger.isVerbose()) { + this.logger.info(msg.type + ": " + json); } - this.host.write(formatMessage(msg, this.logger, this.byteLength, this.host.newLine)); + this.sendLineToClient("Content-Length: " + (1 + this.byteLength(json, "utf8")) + + "\r\n\r\n" + json); }; Session.prototype.configFileDiagnosticEvent = function (triggerFile, configFile, diagnostics) { var bakedDiags = ts.map(diagnostics, formatConfigFileDiag); @@ -54216,7 +50001,7 @@ var ts; }; this.send(ev); }; - Session.prototype.output = function (info, cmdName, reqSeq, errorMsg) { + Session.prototype.response = function (info, cmdName, reqSeq, errorMsg) { if (reqSeq === void 0) { reqSeq = 0; } var res = { seq: 0, @@ -54233,9 +50018,13 @@ var ts; } this.send(res); }; + Session.prototype.output = function (body, commandName, requestSequence, errorMessage) { + if (requestSequence === void 0) { requestSequence = 0; } + this.response(body, commandName, requestSequence, errorMessage); + }; Session.prototype.semanticCheck = function (file, project) { try { - var diags = project.getLanguageService().getSemanticDiagnostics(file); + var diags = project.compilerService.languageService.getSemanticDiagnostics(file); if (diags) { var bakedDiags = diags.map(function (diag) { return formatDiag(file, project, diag); }); this.event({ file: file, diagnostics: bakedDiags }, "semanticDiag"); @@ -54247,7 +50036,7 @@ var ts; }; Session.prototype.syntacticCheck = function (file, project) { try { - var diags = project.getLanguageService().getSyntacticDiagnostics(file); + var diags = project.compilerService.languageService.getSyntacticDiagnostics(file); if (diags) { var bakedDiags = diags.map(function (diag) { return formatDiag(file, project, diag); }); this.event({ file: file, diagnostics: bakedDiags }, "syntaxDiag"); @@ -54257,12 +50046,15 @@ var ts; this.logError(err, "syntactic check"); } }; + Session.prototype.reloadProjects = function () { + this.projectService.reloadProjects(); + }; Session.prototype.updateProjectStructure = function (seq, matchSeq, ms) { var _this = this; if (ms === void 0) { ms = 1500; } - this.host.setTimeout(function () { + setTimeout(function () { if (matchSeq(seq)) { - _this.projectService.refreshInferredProjects(); + _this.projectService.updateProjectStructure(); } }, ms); }; @@ -54275,10 +50067,10 @@ var ts; followMs = ms; } if (this.errorTimer) { - this.host.clearTimeout(this.errorTimer); + clearTimeout(this.errorTimer); } if (this.immediateId) { - this.host.clearImmediate(this.immediateId); + clearImmediate(this.immediateId); this.immediateId = undefined; } var index = 0; @@ -54286,13 +50078,13 @@ var ts; if (matchSeq(seq)) { var checkSpec_1 = checkList[index]; index++; - if (checkSpec_1.project.containsFile(checkSpec_1.fileName, requireOpen)) { + if (checkSpec_1.project.getSourceFileFromName(checkSpec_1.fileName, requireOpen)) { _this.syntacticCheck(checkSpec_1.fileName, checkSpec_1.project); - _this.immediateId = _this.host.setImmediate(function () { + _this.immediateId = setImmediate(function () { _this.semanticCheck(checkSpec_1.fileName, checkSpec_1.project); _this.immediateId = undefined; if (checkList.length > index) { - _this.errorTimer = _this.host.setTimeout(checkOne, followMs); + _this.errorTimer = setTimeout(checkOne, followMs); } else { _this.errorTimer = undefined; @@ -54302,111 +50094,61 @@ var ts; } }; if ((checkList.length > index) && (matchSeq(seq))) { - this.errorTimer = this.host.setTimeout(checkOne, ms); + this.errorTimer = setTimeout(checkOne, ms); } }; - Session.prototype.cleanProjects = function (caption, projects) { - if (!projects) { - return; + Session.prototype.getDefinition = function (line, offset, fileName) { + var file = ts.normalizePath(fileName); + var project = this.projectService.getProjectForFile(file); + if (!project || project.languageServiceDiabled) { + throw Errors.NoProject; } - this.logger.info("cleaning " + caption); - for (var _i = 0, projects_4 = projects; _i < projects_4.length; _i++) { - var p = projects_4[_i]; - p.getLanguageService(false).cleanupSemanticCache(); - } - }; - Session.prototype.cleanup = function () { - this.cleanProjects("inferred projects", this.projectService.inferredProjects); - this.cleanProjects("configured projects", this.projectService.configuredProjects); - this.cleanProjects("external projects", this.projectService.externalProjects); - if (this.host.gc) { - this.logger.info("host.gc()"); - this.host.gc(); - } - }; - Session.prototype.getEncodedSemanticClassifications = function (args) { - var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - return project.getLanguageService().getEncodedSemanticClassifications(file, args); - }; - Session.prototype.getProject = function (projectFileName) { - return projectFileName && this.projectService.findProject(projectFileName); - }; - Session.prototype.getCompilerOptionsDiagnostics = function (args) { - var project = this.getProject(args.projectFileName); - return this.convertToDiagnosticsWithLinePosition(project.getLanguageService().getCompilerOptionsDiagnostics(), undefined); - }; - Session.prototype.convertToDiagnosticsWithLinePosition = function (diagnostics, scriptInfo) { - var _this = this; - return diagnostics.map(function (d) { return { - message: ts.flattenDiagnosticMessageText(d.messageText, _this.host.newLine), - start: d.start, - length: d.length, - category: ts.DiagnosticCategory[d.category].toLowerCase(), - code: d.code, - startLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start), - endLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start + d.length) - }; }); - }; - Session.prototype.getDiagnosticsWorker = function (args, selector, includeLinePosition) { - var _a = this.getFileAndProject(args), project = _a.project, file = _a.file; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var diagnostics = selector(project, file); - return includeLinePosition - ? this.convertToDiagnosticsWithLinePosition(diagnostics, scriptInfo) - : diagnostics.map(function (d) { return formatDiag(file, project, d); }); - }; - Session.prototype.getDefinition = function (args, simplifiedResult) { - var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, scriptInfo); - var definitions = project.getLanguageService().getDefinitionAtPosition(file, position); + var compilerService = project.compilerService; + var position = compilerService.host.lineOffsetToPosition(file, line, offset); + var definitions = compilerService.languageService.getDefinitionAtPosition(file, position); if (!definitions) { return undefined; } - if (simplifiedResult) { - return definitions.map(function (def) { - var defScriptInfo = project.getScriptInfo(def.fileName); - return { - file: def.fileName, - start: defScriptInfo.positionToLineOffset(def.textSpan.start), - end: defScriptInfo.positionToLineOffset(ts.textSpanEnd(def.textSpan)) - }; - }); - } - else { - return definitions; - } + return definitions.map(function (def) { return ({ + file: def.fileName, + start: compilerService.host.positionToLineOffset(def.fileName, def.textSpan.start), + end: compilerService.host.positionToLineOffset(def.fileName, ts.textSpanEnd(def.textSpan)) + }); }); }; - Session.prototype.getTypeDefinition = function (args) { - var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, scriptInfo); - var definitions = project.getLanguageService().getTypeDefinitionAtPosition(file, position); + Session.prototype.getTypeDefinition = function (line, offset, fileName) { + var file = ts.normalizePath(fileName); + var project = this.projectService.getProjectForFile(file); + if (!project || project.languageServiceDiabled) { + throw Errors.NoProject; + } + var compilerService = project.compilerService; + var position = compilerService.host.lineOffsetToPosition(file, line, offset); + var definitions = compilerService.languageService.getTypeDefinitionAtPosition(file, position); if (!definitions) { return undefined; } - return definitions.map(function (def) { - var defScriptInfo = project.getScriptInfo(def.fileName); - return { - file: def.fileName, - start: defScriptInfo.positionToLineOffset(def.textSpan.start), - end: defScriptInfo.positionToLineOffset(ts.textSpanEnd(def.textSpan)) - }; - }); + return definitions.map(function (def) { return ({ + file: def.fileName, + start: compilerService.host.positionToLineOffset(def.fileName, def.textSpan.start), + end: compilerService.host.positionToLineOffset(def.fileName, ts.textSpanEnd(def.textSpan)) + }); }); }; - Session.prototype.getOccurrences = function (args) { - var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, scriptInfo); - var occurrences = project.getLanguageService().getOccurrencesAtPosition(file, position); + Session.prototype.getOccurrences = function (line, offset, fileName) { + fileName = ts.normalizePath(fileName); + var project = this.projectService.getProjectForFile(fileName); + if (!project || project.languageServiceDiabled) { + throw Errors.NoProject; + } + var compilerService = project.compilerService; + var position = compilerService.host.lineOffsetToPosition(fileName, line, offset); + var occurrences = compilerService.languageService.getOccurrencesAtPosition(fileName, position); if (!occurrences) { return undefined; } return occurrences.map(function (occurrence) { var fileName = occurrence.fileName, isWriteAccess = occurrence.isWriteAccess, textSpan = occurrence.textSpan; - var scriptInfo = project.getScriptInfo(fileName); - var start = scriptInfo.positionToLineOffset(textSpan.start); - var end = scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan)); + var start = compilerService.host.positionToLineOffset(fileName, textSpan.start); + var end = compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(textSpan)); return { start: start, end: end, @@ -54415,142 +50157,115 @@ var ts; }; }); }; + Session.prototype.getDiagnosticsWorker = function (args, selector) { + var file = ts.normalizePath(args.file); + var project = this.projectService.getProjectForFile(file); + if (!project) { + throw Errors.NoProject; + } + if (project.languageServiceDiabled) { + throw Errors.ProjectLanguageServiceDisabled; + } + var diagnostics = selector(project, file); + return ts.map(diagnostics, function (originalDiagnostic) { return formatDiag(file, project, originalDiagnostic); }); + }; Session.prototype.getSyntacticDiagnosticsSync = function (args) { - return this.getDiagnosticsWorker(args, function (project, file) { return project.getLanguageService().getSyntacticDiagnostics(file); }, args.includeLinePosition); + return this.getDiagnosticsWorker(args, function (project, file) { return project.compilerService.languageService.getSyntacticDiagnostics(file); }); }; Session.prototype.getSemanticDiagnosticsSync = function (args) { - return this.getDiagnosticsWorker(args, function (project, file) { return project.getLanguageService().getSemanticDiagnostics(file); }, args.includeLinePosition); + return this.getDiagnosticsWorker(args, function (project, file) { return project.compilerService.languageService.getSemanticDiagnostics(file); }); }; - Session.prototype.getDocumentHighlights = function (args, simplifiedResult) { - var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, scriptInfo); - var documentHighlights = project.getLanguageService().getDocumentHighlights(file, position, args.filesToSearch); + Session.prototype.getDocumentHighlights = function (line, offset, fileName, filesToSearch) { + fileName = ts.normalizePath(fileName); + var project = this.projectService.getProjectForFile(fileName); + if (!project || project.languageServiceDiabled) { + throw Errors.NoProject; + } + var compilerService = project.compilerService; + var position = compilerService.host.lineOffsetToPosition(fileName, line, offset); + var documentHighlights = compilerService.languageService.getDocumentHighlights(fileName, position, filesToSearch); if (!documentHighlights) { return undefined; } - if (simplifiedResult) { - return documentHighlights.map(convertToDocumentHighlightsItem); - } - else { - return documentHighlights; - } + return documentHighlights.map(convertToDocumentHighlightsItem); function convertToDocumentHighlightsItem(documentHighlights) { var fileName = documentHighlights.fileName, highlightSpans = documentHighlights.highlightSpans; - var scriptInfo = project.getScriptInfo(fileName); return { file: fileName, highlightSpans: highlightSpans.map(convertHighlightSpan) }; function convertHighlightSpan(highlightSpan) { var textSpan = highlightSpan.textSpan, kind = highlightSpan.kind; - var start = scriptInfo.positionToLineOffset(textSpan.start); - var end = scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan)); + var start = compilerService.host.positionToLineOffset(fileName, textSpan.start); + var end = compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(textSpan)); return { start: start, end: end, kind: kind }; } } }; - Session.prototype.setCompilerOptionsForInferredProjects = function (args) { - this.projectService.setCompilerOptionsForInferredProjects(args.options); - }; - Session.prototype.getProjectInfo = function (args) { - return this.getProjectInfoWorker(args.file, args.projectFileName, args.needFileNameList); - }; - Session.prototype.getProjectInfoWorker = function (uncheckedFileName, projectFileName, needFileNameList) { - var project = this.getFileAndProjectWorker(uncheckedFileName, projectFileName, true, true).project; + Session.prototype.getProjectInfo = function (fileName, needFileNameList) { + fileName = ts.normalizePath(fileName); + var project = this.projectService.getProjectForFile(fileName); + if (!project) { + throw Errors.NoProject; + } var projectInfo = { - configFileName: project.getProjectName(), - languageServiceDisabled: !project.languageServiceEnabled, - fileNames: needFileNameList ? project.getFileNames() : undefined + configFileName: project.projectFilename, + languageServiceDisabled: project.languageServiceDiabled }; + if (needFileNameList) { + projectInfo.fileNames = project.getFileNames(); + } return projectInfo; }; - Session.prototype.getRenameInfo = function (args) { - var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, scriptInfo); - return project.getLanguageService().getRenameInfo(file, position); - }; - Session.prototype.getProjects = function (args) { - var projects; - if (args.projectFileName) { - var project = this.getProject(args.projectFileName); - if (project) { - projects = [project]; - } + Session.prototype.getRenameLocations = function (line, offset, fileName, findInComments, findInStrings) { + var file = ts.normalizePath(fileName); + var info = this.projectService.getScriptInfo(file); + var projects = this.projectService.findReferencingProjects(info); + var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; }); + if (projectsWithLanguageServiceEnabeld.length === 0) { + throw Errors.NoProject; } - else { - var scriptInfo = this.projectService.getScriptInfo(args.file); - projects = scriptInfo.containingProjects; + var defaultProject = projectsWithLanguageServiceEnabeld[0]; + var defaultProjectCompilerService = defaultProject.compilerService; + var position = defaultProjectCompilerService.host.lineOffsetToPosition(file, line, offset); + var renameInfo = defaultProjectCompilerService.languageService.getRenameInfo(file, position); + if (!renameInfo) { + return undefined; } - projects = ts.filter(projects, function (p) { return p.languageServiceEnabled; }); - if (!projects || !projects.length) { - return server.Errors.ThrowNoProject(); + if (!renameInfo.canRename) { + return { + info: renameInfo, + locs: [] + }; } - return projects; - }; - Session.prototype.getRenameLocations = function (args, simplifiedResult) { - var file = server.toNormalizedPath(args.file); - var info = this.projectService.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, info); - var projects = this.getProjects(args); - if (simplifiedResult) { - var defaultProject = projects[0]; - var renameInfo = defaultProject.getLanguageService().getRenameInfo(file, position); - if (!renameInfo) { - return undefined; + var fileSpans = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) { + var compilerService = project.compilerService; + var renameLocations = compilerService.languageService.findRenameLocations(file, position, findInStrings, findInComments); + if (!renameLocations) { + return []; } - if (!renameInfo.canRename) { - return { - info: renameInfo, - locs: [] - }; - } - var fileSpans = server.combineProjectOutput(projects, function (project) { - var renameLocations = project.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); - if (!renameLocations) { - return []; + return renameLocations.map(function (location) { return ({ + file: location.fileName, + start: compilerService.host.positionToLineOffset(location.fileName, location.textSpan.start), + end: compilerService.host.positionToLineOffset(location.fileName, ts.textSpanEnd(location.textSpan)) + }); }); + }, compareRenameLocation, function (a, b) { return a.file === b.file && a.start.line === b.start.line && a.start.offset === b.start.offset; }); + var locs = fileSpans.reduce(function (accum, cur) { + var curFileAccum; + if (accum.length > 0) { + curFileAccum = accum[accum.length - 1]; + if (curFileAccum.file !== cur.file) { + curFileAccum = undefined; } - return renameLocations.map(function (location) { - var locationScriptInfo = project.getScriptInfo(location.fileName); - return { - file: location.fileName, - start: locationScriptInfo.positionToLineOffset(location.textSpan.start), - end: locationScriptInfo.positionToLineOffset(ts.textSpanEnd(location.textSpan)) - }; - }); - }, compareRenameLocation, function (a, b) { return a.file === b.file && a.start.line === b.start.line && a.start.offset === b.start.offset; }); - var locs = fileSpans.reduce(function (accum, cur) { - var curFileAccum; - if (accum.length > 0) { - curFileAccum = accum[accum.length - 1]; - if (curFileAccum.file !== cur.file) { - curFileAccum = undefined; - } - } - if (!curFileAccum) { - curFileAccum = { file: cur.file, locs: [] }; - accum.push(curFileAccum); - } - curFileAccum.locs.push({ start: cur.start, end: cur.end }); - return accum; - }, []); - return { info: renameInfo, locs: locs }; - } - else { - return server.combineProjectOutput(projects, function (p) { return p.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); }, undefined, renameLocationIsEqualTo); - } - function renameLocationIsEqualTo(a, b) { - if (a === b) { - return true; } - if (!a || !b) { - return false; + if (!curFileAccum) { + curFileAccum = { file: cur.file, locs: [] }; + accum.push(curFileAccum); } - return a.fileName === b.fileName && - a.textSpan.start === b.textSpan.start && - a.textSpan.length === b.textSpan.length; - } + curFileAccum.locs.push({ start: cur.start, end: cur.end }); + return accum; + }, []); + return { info: renameInfo, locs: locs }; function compareRenameLocation(a, b) { if (a.file < b.file) { return -1; @@ -54571,51 +50286,51 @@ var ts; } } }; - Session.prototype.getReferences = function (args, simplifiedResult) { - var file = server.toNormalizedPath(args.file); - var projects = this.getProjects(args); - var defaultProject = projects[0]; - var scriptInfo = defaultProject.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, scriptInfo); - if (simplifiedResult) { - var nameInfo = defaultProject.getLanguageService().getQuickInfoAtPosition(file, position); - if (!nameInfo) { - return undefined; + Session.prototype.getReferences = function (line, offset, fileName) { + var file = ts.normalizePath(fileName); + var info = this.projectService.getScriptInfo(file); + var projects = this.projectService.findReferencingProjects(info); + var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; }); + if (projectsWithLanguageServiceEnabeld.length === 0) { + throw Errors.NoProject; + } + var defaultProject = projectsWithLanguageServiceEnabeld[0]; + var position = defaultProject.compilerService.host.lineOffsetToPosition(file, line, offset); + var nameInfo = defaultProject.compilerService.languageService.getQuickInfoAtPosition(file, position); + if (!nameInfo) { + return undefined; + } + var displayString = ts.displayPartsToString(nameInfo.displayParts); + var nameSpan = nameInfo.textSpan; + var nameColStart = defaultProject.compilerService.host.positionToLineOffset(file, nameSpan.start).offset; + var nameText = defaultProject.compilerService.host.getScriptSnapshot(file).getText(nameSpan.start, ts.textSpanEnd(nameSpan)); + var refs = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) { + var compilerService = project.compilerService; + var references = compilerService.languageService.getReferencesAtPosition(file, position); + if (!references) { + return []; } - var displayString = ts.displayPartsToString(nameInfo.displayParts); - var nameSpan = nameInfo.textSpan; - var nameColStart = scriptInfo.positionToLineOffset(nameSpan.start).offset; - var nameText = scriptInfo.snap().getText(nameSpan.start, ts.textSpanEnd(nameSpan)); - var refs = server.combineProjectOutput(projects, function (project) { - var references = project.getLanguageService().getReferencesAtPosition(file, position); - if (!references) { - return []; - } - return references.map(function (ref) { - var refScriptInfo = project.getScriptInfo(ref.fileName); - var start = refScriptInfo.positionToLineOffset(ref.textSpan.start); - var refLineSpan = refScriptInfo.lineToTextSpan(start.line - 1); - var lineText = refScriptInfo.snap().getText(refLineSpan.start, ts.textSpanEnd(refLineSpan)).replace(/\r|\n/g, ""); - return { - file: ref.fileName, - start: start, - lineText: lineText, - end: refScriptInfo.positionToLineOffset(ts.textSpanEnd(ref.textSpan)), - isWriteAccess: ref.isWriteAccess, - isDefinition: ref.isDefinition - }; - }); - }, compareFileStart, areReferencesResponseItemsForTheSameLocation); - return { - refs: refs, - symbolName: nameText, - symbolStartOffset: nameColStart, - symbolDisplayString: displayString - }; - } - else { - return server.combineProjectOutput(projects, function (project) { return project.getLanguageService().findReferences(file, position); }, undefined, undefined); - } + return references.map(function (ref) { + var start = compilerService.host.positionToLineOffset(ref.fileName, ref.textSpan.start); + var refLineSpan = compilerService.host.lineToTextSpan(ref.fileName, start.line - 1); + var snap = compilerService.host.getScriptSnapshot(ref.fileName); + var lineText = snap.getText(refLineSpan.start, ts.textSpanEnd(refLineSpan)).replace(/\r|\n/g, ""); + return { + file: ref.fileName, + start: start, + lineText: lineText, + end: compilerService.host.positionToLineOffset(ref.fileName, ts.textSpanEnd(ref.textSpan)), + isWriteAccess: ref.isWriteAccess, + isDefinition: ref.isDefinition + }; + }); + }, compareFileStart, areReferencesResponseItemsForTheSameLocation); + return { + refs: refs, + symbolName: nameText, + symbolStartOffset: nameColStart, + symbolDisplayString: displayString + }; function areReferencesResponseItemsForTheSameLocation(a, b) { if (a && b) { return a.file === b.file && @@ -54626,152 +50341,102 @@ var ts; } }; Session.prototype.openClientFile = function (fileName, fileContent, scriptKind) { - var _a = this.projectService.openClientFileWithNormalizedPath(fileName, fileContent, scriptKind), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors; + var file = ts.normalizePath(fileName); + var _a = this.projectService.openClientFile(file, fileContent, scriptKind), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors; if (configFileErrors) { this.configFileDiagnosticEvent(fileName, configFileName, configFileErrors); } }; - Session.prototype.getPosition = function (args, scriptInfo) { - return args.position !== undefined ? args.position : scriptInfo.lineOffsetToPosition(args.line, args.offset); - }; - Session.prototype.getFileAndProject = function (args, errorOnMissingProject) { - if (errorOnMissingProject === void 0) { errorOnMissingProject = true; } - return this.getFileAndProjectWorker(args.file, args.projectFileName, true, errorOnMissingProject); - }; - Session.prototype.getFileAndProjectWithoutRefreshingInferredProjects = function (args, errorOnMissingProject) { - if (errorOnMissingProject === void 0) { errorOnMissingProject = true; } - return this.getFileAndProjectWorker(args.file, args.projectFileName, false, errorOnMissingProject); - }; - Session.prototype.getFileAndProjectWorker = function (uncheckedFileName, projectFileName, refreshInferredProjects, errorOnMissingProject) { - var file = server.toNormalizedPath(uncheckedFileName); - var project = this.getProject(projectFileName) || this.projectService.getDefaultProjectForFile(file, refreshInferredProjects); - if (!project && errorOnMissingProject) { - return server.Errors.ThrowNoProject(); + Session.prototype.getQuickInfo = function (line, offset, fileName) { + var file = ts.normalizePath(fileName); + var project = this.projectService.getProjectForFile(file); + if (!project || project.languageServiceDiabled) { + throw Errors.NoProject; } - return { file: file, project: project }; - }; - Session.prototype.getOutliningSpans = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - return project.getLanguageService(false).getOutliningSpans(file); - }; - Session.prototype.getTodoComments = function (args) { - var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - return project.getLanguageService().getTodoComments(file, args.descriptors); - }; - Session.prototype.getDocCommentTemplate = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, scriptInfo); - return project.getLanguageService(false).getDocCommentTemplateAtPosition(file, position); - }; - Session.prototype.getIndentation = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); - var options = args.options || this.projectService.getFormatCodeOptions(file); - var indentation = project.getLanguageService(false).getIndentationAtPosition(file, position, options); - return { position: position, indentation: indentation }; - }; - Session.prototype.getBreakpointStatement = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); - return project.getLanguageService(false).getBreakpointStatementAtPosition(file, position); - }; - Session.prototype.getNameOrDottedNameSpan = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); - return project.getLanguageService(false).getNameOrDottedNameSpan(file, position, position); - }; - Session.prototype.isValidBraceCompletion = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); - return project.getLanguageService(false).isValidBraceCompletionAtPosition(file, position, args.openingBrace.charCodeAt(0)); - }; - Session.prototype.getQuickInfoWorker = function (args, simplifiedResult) { - var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var quickInfo = project.getLanguageService().getQuickInfoAtPosition(file, this.getPosition(args, scriptInfo)); + var compilerService = project.compilerService; + var position = compilerService.host.lineOffsetToPosition(file, line, offset); + var quickInfo = compilerService.languageService.getQuickInfoAtPosition(file, position); if (!quickInfo) { return undefined; } - if (simplifiedResult) { - var displayString = ts.displayPartsToString(quickInfo.displayParts); - var docString = ts.displayPartsToString(quickInfo.documentation); - return { - kind: quickInfo.kind, - kindModifiers: quickInfo.kindModifiers, - start: scriptInfo.positionToLineOffset(quickInfo.textSpan.start), - end: scriptInfo.positionToLineOffset(ts.textSpanEnd(quickInfo.textSpan)), - displayString: displayString, - documentation: docString - }; - } - else { - return quickInfo; - } + var displayString = ts.displayPartsToString(quickInfo.displayParts); + var docString = ts.displayPartsToString(quickInfo.documentation); + return { + kind: quickInfo.kind, + kindModifiers: quickInfo.kindModifiers, + start: compilerService.host.positionToLineOffset(file, quickInfo.textSpan.start), + end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(quickInfo.textSpan)), + displayString: displayString, + documentation: docString + }; }; - Session.prototype.getFormattingEditsForRange = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var startPosition = scriptInfo.lineOffsetToPosition(args.line, args.offset); - var endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); - var edits = project.getLanguageService(false).getFormattingEditsForRange(file, startPosition, endPosition, this.projectService.getFormatCodeOptions(file)); + Session.prototype.getFormattingEditsForRange = function (line, offset, endLine, endOffset, fileName) { + var file = ts.normalizePath(fileName); + var project = this.projectService.getProjectForFile(file); + if (!project || project.languageServiceDiabled) { + throw Errors.NoProject; + } + var compilerService = project.compilerService; + var startPosition = compilerService.host.lineOffsetToPosition(file, line, offset); + var endPosition = compilerService.host.lineOffsetToPosition(file, endLine, endOffset); + var edits = compilerService.languageService.getFormattingEditsForRange(file, startPosition, endPosition, this.projectService.getFormatCodeOptions(file)); if (!edits) { return undefined; } return edits.map(function (edit) { return { - start: scriptInfo.positionToLineOffset(edit.span.start), - end: scriptInfo.positionToLineOffset(ts.textSpanEnd(edit.span)), + start: compilerService.host.positionToLineOffset(file, edit.span.start), + end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(edit.span)), newText: edit.newText ? edit.newText : "" }; }); }; - Session.prototype.getFormattingEditsForRangeFull = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var options = args.options || this.projectService.getFormatCodeOptions(file); - return project.getLanguageService(false).getFormattingEditsForRange(file, args.position, args.endPosition, options); - }; - Session.prototype.getFormattingEditsForDocumentFull = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var options = args.options || this.projectService.getFormatCodeOptions(file); - return project.getLanguageService(false).getFormattingEditsForDocument(file, options); - }; - Session.prototype.getFormattingEditsAfterKeystrokeFull = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var options = args.options || this.projectService.getFormatCodeOptions(file); - return project.getLanguageService(false).getFormattingEditsAfterKeystroke(file, args.position, args.key, options); - }; - Session.prototype.getFormattingEditsAfterKeystroke = function (args) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var position = scriptInfo.lineOffsetToPosition(args.line, args.offset); + Session.prototype.getFormattingEditsAfterKeystroke = function (line, offset, key, fileName) { + var file = ts.normalizePath(fileName); + var project = this.projectService.getProjectForFile(file); + if (!project || project.languageServiceDiabled) { + throw Errors.NoProject; + } + var compilerService = project.compilerService; + var position = compilerService.host.lineOffsetToPosition(file, line, offset); var formatOptions = this.projectService.getFormatCodeOptions(file); - var edits = project.getLanguageService(false).getFormattingEditsAfterKeystroke(file, position, args.key, formatOptions); - if ((args.key == "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) { - var lineInfo = scriptInfo.getLineInfo(args.line); - if (lineInfo && (lineInfo.leaf) && (lineInfo.leaf.text)) { - var lineText = lineInfo.leaf.text; - if (lineText.search("\\S") < 0) { - var preferredIndent = project.getLanguageService(false).getIndentationAtPosition(file, position, formatOptions); - var hasIndent = 0; - var i = void 0, len = void 0; - for (i = 0, len = lineText.length; i < len; i++) { - if (lineText.charAt(i) == " ") { - hasIndent++; + var edits = compilerService.languageService.getFormattingEditsAfterKeystroke(file, position, key, formatOptions); + if ((key == "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) { + var scriptInfo = compilerService.host.getScriptInfo(file); + if (scriptInfo) { + var lineInfo = scriptInfo.getLineInfo(line); + if (lineInfo && (lineInfo.leaf) && (lineInfo.leaf.text)) { + var lineText = lineInfo.leaf.text; + if (lineText.search("\\S") < 0) { + var editorOptions = { + BaseIndentSize: formatOptions.BaseIndentSize, + IndentSize: formatOptions.IndentSize, + TabSize: formatOptions.TabSize, + NewLineCharacter: formatOptions.NewLineCharacter, + ConvertTabsToSpaces: formatOptions.ConvertTabsToSpaces, + IndentStyle: ts.IndentStyle.Smart + }; + var preferredIndent = compilerService.languageService.getIndentationAtPosition(file, position, editorOptions); + var hasIndent = 0; + var i = void 0, len = void 0; + for (i = 0, len = lineText.length; i < len; i++) { + if (lineText.charAt(i) == " ") { + hasIndent++; + } + else if (lineText.charAt(i) == "\t") { + hasIndent += editorOptions.TabSize; + } + else { + break; + } } - else if (lineText.charAt(i) == "\t") { - hasIndent += formatOptions.tabSize; + if (preferredIndent !== hasIndent) { + var firstNoWhiteSpacePosition = lineInfo.offset + i; + edits.push({ + span: ts.createTextSpanFromBounds(lineInfo.offset, firstNoWhiteSpacePosition), + newText: generateIndentString(preferredIndent, editorOptions) + }); } - else { - break; - } - } - if (preferredIndent !== hasIndent) { - var firstNoWhiteSpacePosition = lineInfo.offset + i; - edits.push({ - span: ts.createTextSpanFromBounds(lineInfo.offset, firstNoWhiteSpacePosition), - newText: ts.formatting.getIndentationString(preferredIndent, formatOptions) - }); } } } @@ -54781,111 +50446,81 @@ var ts; } return edits.map(function (edit) { return { - start: scriptInfo.positionToLineOffset(edit.span.start), - end: scriptInfo.positionToLineOffset(ts.textSpanEnd(edit.span)), + start: compilerService.host.positionToLineOffset(file, edit.span.start), + end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(edit.span)), newText: edit.newText ? edit.newText : "" }; }); }; - Session.prototype.getCompletions = function (args, simplifiedResult) { - var prefix = args.prefix || ""; - var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, scriptInfo); - var completions = project.getLanguageService().getCompletionsAtPosition(file, position); + Session.prototype.getCompletions = function (line, offset, prefix, fileName) { + if (!prefix) { + prefix = ""; + } + var file = ts.normalizePath(fileName); + var project = this.projectService.getProjectForFile(file); + if (!project || project.languageServiceDiabled) { + throw Errors.NoProject; + } + var compilerService = project.compilerService; + var position = compilerService.host.lineOffsetToPosition(file, line, offset); + var completions = compilerService.languageService.getCompletionsAtPosition(file, position); if (!completions) { return undefined; } - if (simplifiedResult) { - return completions.entries.reduce(function (result, entry) { - if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) { - var name_44 = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan; - var convertedSpan = undefined; - if (replacementSpan) { - convertedSpan = { - start: scriptInfo.positionToLineOffset(replacementSpan.start), - end: scriptInfo.positionToLineOffset(replacementSpan.start + replacementSpan.length) - }; - } - result.push({ name: name_44, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan }); - } - return result; - }, []).sort(function (a, b) { return a.name.localeCompare(b.name); }); - } - else { - return completions; - } + return completions.entries.reduce(function (result, entry) { + if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) { + result.push(entry); + } + return result; + }, []).sort(function (a, b) { return a.name.localeCompare(b.name); }); }; - Session.prototype.getCompletionEntryDetails = function (args) { - var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, scriptInfo); - return args.entryNames.reduce(function (accum, entryName) { - var details = project.getLanguageService().getCompletionEntryDetails(file, position, entryName); + Session.prototype.getCompletionEntryDetails = function (line, offset, entryNames, fileName) { + var file = ts.normalizePath(fileName); + var project = this.projectService.getProjectForFile(file); + if (!project || project.languageServiceDiabled) { + throw Errors.NoProject; + } + var compilerService = project.compilerService; + var position = compilerService.host.lineOffsetToPosition(file, line, offset); + return entryNames.reduce(function (accum, entryName) { + var details = compilerService.languageService.getCompletionEntryDetails(file, position, entryName); if (details) { accum.push(details); } return accum; }, []); }; - Session.prototype.getCompileOnSaveAffectedFileList = function (args) { - var info = this.projectService.getScriptInfo(args.file); - var result = []; - if (!info) { - return []; + Session.prototype.getSignatureHelpItems = function (line, offset, fileName) { + var file = ts.normalizePath(fileName); + var project = this.projectService.getProjectForFile(file); + if (!project || project.languageServiceDiabled) { + throw Errors.NoProject; } - var projectsToSearch = args.projectFileName ? [this.projectService.findProject(args.projectFileName)] : info.containingProjects; - for (var _i = 0, projectsToSearch_1 = projectsToSearch; _i < projectsToSearch_1.length; _i++) { - var project = projectsToSearch_1[_i]; - if (project.compileOnSaveEnabled && project.languageServiceEnabled) { - result.push({ - projectFileName: project.getProjectName(), - fileNames: project.getCompileOnSaveAffectedFileList(info) - }); - } - } - return result; - }; - Session.prototype.emitFile = function (args) { - var _this = this; - var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - if (!project) { - server.Errors.ThrowNoProject(); - } - var scriptInfo = project.getScriptInfo(file); - return project.builder.emitFile(scriptInfo, function (path, data, writeByteOrderMark) { return _this.host.writeFile(path, data, writeByteOrderMark); }); - }; - Session.prototype.getSignatureHelpItems = function (args, simplifiedResult) { - var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, scriptInfo); - var helpItems = project.getLanguageService().getSignatureHelpItems(file, position); + var compilerService = project.compilerService; + var position = compilerService.host.lineOffsetToPosition(file, line, offset); + var helpItems = compilerService.languageService.getSignatureHelpItems(file, position); if (!helpItems) { return undefined; } - if (simplifiedResult) { - var span = helpItems.applicableSpan; - return { - items: helpItems.items, - applicableSpan: { - start: scriptInfo.positionToLineOffset(span.start), - end: scriptInfo.positionToLineOffset(span.start + span.length) - }, - selectedItemIndex: helpItems.selectedItemIndex, - argumentIndex: helpItems.argumentIndex, - argumentCount: helpItems.argumentCount - }; - } - else { - return helpItems; - } + var span = helpItems.applicableSpan; + var result = { + items: helpItems.items, + applicableSpan: { + start: compilerService.host.positionToLineOffset(file, span.start), + end: compilerService.host.positionToLineOffset(file, span.start + span.length) + }, + selectedItemIndex: helpItems.selectedItemIndex, + argumentIndex: helpItems.argumentIndex, + argumentCount: helpItems.argumentCount + }; + return result; }; Session.prototype.getDiagnostics = function (delay, fileNames) { var _this = this; - var checkList = fileNames.reduce(function (accum, uncheckedFileName) { - var fileName = server.toNormalizedPath(uncheckedFileName); - var project = _this.projectService.getDefaultProjectForFile(fileName, true); - if (project) { + var checkList = fileNames.reduce(function (accum, fileName) { + fileName = ts.normalizePath(fileName); + var project = _this.projectService.getProjectForFile(fileName); + if (project && !project.languageServiceDiabled) { accum.push({ fileName: fileName, project: project }); } return accum; @@ -54894,34 +50529,40 @@ var ts; this.updateErrorCheck(checkList, this.changeSeq, function (n) { return n === _this.changeSeq; }, delay); } }; - Session.prototype.change = function (args) { + Session.prototype.change = function (line, offset, endLine, endOffset, insertString, fileName) { var _this = this; - var _a = this.getFileAndProject(args, false), file = _a.file, project = _a.project; - if (project) { - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var start = scriptInfo.lineOffsetToPosition(args.line, args.offset); - var end = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + var file = ts.normalizePath(fileName); + var project = this.projectService.getProjectForFile(file); + if (project && !project.languageServiceDiabled) { + var compilerService = project.compilerService; + var start = compilerService.host.lineOffsetToPosition(file, line, offset); + var end = compilerService.host.lineOffsetToPosition(file, endLine, endOffset); if (start >= 0) { - scriptInfo.editContent(start, end, args.insertString); + compilerService.host.editScript(file, start, end, insertString); this.changeSeq++; } this.updateProjectStructure(this.changeSeq, function (n) { return n === _this.changeSeq; }); } }; - Session.prototype.reload = function (args, reqSeq) { - var file = server.toNormalizedPath(args.file); - var project = this.projectService.getDefaultProjectForFile(file, true); - if (project) { + Session.prototype.reload = function (fileName, tempFileName, reqSeq) { + var _this = this; + if (reqSeq === void 0) { reqSeq = 0; } + var file = ts.normalizePath(fileName); + var tmpfile = ts.normalizePath(tempFileName); + var project = this.projectService.getProjectForFile(file); + if (project && !project.languageServiceDiabled) { this.changeSeq++; - if (project.reloadScript(file)) { - this.output(undefined, CommandNames.Reload, reqSeq); - } + project.compilerService.host.reloadScript(file, tmpfile, function () { + _this.output(undefined, CommandNames.Reload, reqSeq); + }); } }; Session.prototype.saveToTmp = function (fileName, tempFileName) { - var scriptInfo = this.projectService.getScriptInfo(fileName); - if (scriptInfo) { - scriptInfo.saveTo(tempFileName); + var file = ts.normalizePath(fileName); + var tmpfile = ts.normalizePath(tempFileName); + var project = this.projectService.getProjectForFile(file); + if (project && !project.languageServiceDiabled) { + project.compilerService.host.saveTo(file, tmpfile); } }; Session.prototype.closeClientFile = function (fileName) { @@ -54931,90 +50572,77 @@ var ts; var file = ts.normalizePath(fileName); this.projectService.closeClientFile(file); }; - Session.prototype.decorateNavigationBarItem = function (project, fileName, items) { + Session.prototype.decorateNavigationBarItem = function (project, fileName, items, lineIndex) { var _this = this; if (!items) { return undefined; } - var scriptInfo = project.getScriptInfoForNormalizedPath(fileName); + var compilerService = project.compilerService; return items.map(function (item) { return ({ text: item.text, kind: item.kind, kindModifiers: item.kindModifiers, spans: item.spans.map(function (span) { return ({ - start: scriptInfo.positionToLineOffset(span.start), - end: scriptInfo.positionToLineOffset(ts.textSpanEnd(span)) + start: compilerService.host.positionToLineOffset(fileName, span.start, lineIndex), + end: compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(span), lineIndex) }); }), - childItems: _this.decorateNavigationBarItem(project, fileName, item.childItems), + childItems: _this.decorateNavigationBarItem(project, fileName, item.childItems, lineIndex), indent: item.indent }); }); }; - Session.prototype.getNavigationBarItems = function (args, simplifiedResult) { - var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var items = project.getLanguageService().getNavigationBarItems(file); + Session.prototype.getNavigationBarItems = function (fileName) { + var file = ts.normalizePath(fileName); + var project = this.projectService.getProjectForFile(file); + if (!project || project.languageServiceDiabled) { + throw Errors.NoProject; + } + var compilerService = project.compilerService; + var items = compilerService.languageService.getNavigationBarItems(file); if (!items) { return undefined; } - return simplifiedResult - ? this.decorateNavigationBarItem(project, file, items) - : items; + return this.decorateNavigationBarItem(project, fileName, items, compilerService.host.getLineIndex(fileName)); }; - Session.prototype.getNavigateToItems = function (args, simplifiedResult) { - var projects = this.getProjects(args); - if (simplifiedResult) { - return server.combineProjectOutput(projects, function (project) { - var navItems = project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, project.isJsOnlyProject()); - if (!navItems) { - return []; + Session.prototype.getNavigateToItems = function (searchValue, fileName, maxResultCount) { + var file = ts.normalizePath(fileName); + var info = this.projectService.getScriptInfo(file); + var projects = this.projectService.findReferencingProjects(info); + var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; }); + if (projectsWithLanguageServiceEnabeld.length === 0) { + throw Errors.NoProject; + } + var allNavToItems = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) { + var compilerService = project.compilerService; + var navItems = compilerService.languageService.getNavigateToItems(searchValue, maxResultCount); + if (!navItems) { + return []; + } + return navItems.map(function (navItem) { + var start = compilerService.host.positionToLineOffset(navItem.fileName, navItem.textSpan.start); + var end = compilerService.host.positionToLineOffset(navItem.fileName, ts.textSpanEnd(navItem.textSpan)); + var bakedItem = { + name: navItem.name, + kind: navItem.kind, + file: navItem.fileName, + start: start, + end: end + }; + if (navItem.kindModifiers && (navItem.kindModifiers !== "")) { + bakedItem.kindModifiers = navItem.kindModifiers; } - return navItems.map(function (navItem) { - var scriptInfo = project.getScriptInfo(navItem.fileName); - var start = scriptInfo.positionToLineOffset(navItem.textSpan.start); - var end = scriptInfo.positionToLineOffset(ts.textSpanEnd(navItem.textSpan)); - var bakedItem = { - name: navItem.name, - kind: navItem.kind, - file: navItem.fileName, - start: start, - end: end - }; - if (navItem.kindModifiers && (navItem.kindModifiers !== "")) { - bakedItem.kindModifiers = navItem.kindModifiers; - } - if (navItem.matchKind !== "none") { - bakedItem.matchKind = navItem.matchKind; - } - if (navItem.containerName && (navItem.containerName.length > 0)) { - bakedItem.containerName = navItem.containerName; - } - if (navItem.containerKind && (navItem.containerKind.length > 0)) { - bakedItem.containerKind = navItem.containerKind; - } - return bakedItem; - }); - }, undefined, areNavToItemsForTheSameLocation); - } - else { - return server.combineProjectOutput(projects, function (project) { return project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, project.isJsOnlyProject()); }, undefined, navigateToItemIsEqualTo); - } - function navigateToItemIsEqualTo(a, b) { - if (a === b) { - return true; - } - if (!a || !b) { - return false; - } - return a.containerKind === b.containerKind && - a.containerName === b.containerName && - a.fileName === b.fileName && - a.isCaseSensitive === b.isCaseSensitive && - a.kind === b.kind && - a.kindModifiers === b.containerName && - a.matchKind === b.matchKind && - a.name === b.name && - a.textSpan.start === b.textSpan.start && - a.textSpan.length === b.textSpan.length; - } + if (navItem.matchKind !== "none") { + bakedItem.matchKind = navItem.matchKind; + } + if (navItem.containerName && (navItem.containerName.length > 0)) { + bakedItem.containerName = navItem.containerName; + } + if (navItem.containerKind && (navItem.containerKind.length > 0)) { + bakedItem.containerKind = navItem.containerKind; + } + return bakedItem; + }); + }, undefined, areNavToItemsForTheSameLocation); + return allNavToItems; function areNavToItemsForTheSameLocation(a, b) { if (a && b) { return a.file === b.file && @@ -55024,27 +50652,26 @@ var ts; return false; } }; - Session.prototype.getBraceMatching = function (args, simplifiedResult) { - var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, scriptInfo); - var spans = project.getLanguageService(false).getBraceMatchingAtPosition(file, position); + Session.prototype.getBraceMatching = function (line, offset, fileName) { + var file = ts.normalizePath(fileName); + var project = this.projectService.getProjectForFile(file); + if (!project || project.languageServiceDiabled) { + throw Errors.NoProject; + } + var compilerService = project.compilerService; + var position = compilerService.host.lineOffsetToPosition(file, line, offset); + var spans = compilerService.languageService.getBraceMatchingAtPosition(file, position); if (!spans) { return undefined; } - if (simplifiedResult) { - return spans.map(function (span) { return ({ - start: scriptInfo.positionToLineOffset(span.start), - end: scriptInfo.positionToLineOffset(span.start + span.length) - }); }); - } - else { - return spans; - } + return spans.map(function (span) { return ({ + start: compilerService.host.positionToLineOffset(file, span.start), + end: compilerService.host.positionToLineOffset(file, span.start + span.length) + }); }); }; Session.prototype.getDiagnosticsForProject = function (delay, fileName) { var _this = this; - var _a = this.getProjectInfoWorker(fileName, undefined, true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled; + var _a = this.getProjectInfo(fileName, true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled; if (languageServiceDisabled) { return; } @@ -55053,8 +50680,8 @@ var ts; var mediumPriorityFiles = []; var lowPriorityFiles = []; var veryLowPriorityFiles = []; - var normalizedFileName = server.toNormalizedPath(fileName); - var project = this.projectService.getDefaultProjectForFile(normalizedFileName, true); + var normalizedFileName = ts.normalizePath(fileName); + var project = this.projectService.getProjectForFile(normalizedFileName); for (var _i = 0, fileNamesInProject_1 = fileNamesInProject; _i < fileNamesInProject_1.length; _i++) { var fileNameInProject = fileNamesInProject_1[_i]; if (this.getCanonicalFileName(fileNameInProject) == this.getCanonicalFileName(fileName)) @@ -55073,7 +50700,10 @@ var ts; } fileNamesInProject = highPriorityFiles.concat(mediumPriorityFiles).concat(lowPriorityFiles).concat(veryLowPriorityFiles); if (fileNamesInProject.length > 0) { - var checkList = fileNamesInProject.map(function (fileName) { return ({ fileName: fileName, project: project }); }); + var checkList = fileNamesInProject.map(function (fileName) { + var normalizedFileName = ts.normalizePath(fileName); + return { fileName: normalizedFileName, project: project }; + }); this.updateErrorCheck(checkList, this.changeSeq, function (n) { return n == _this.changeSeq; }, delay, 200, false); } }; @@ -55083,14 +50713,11 @@ var ts; }; Session.prototype.exit = function () { }; - Session.prototype.notRequired = function () { - return { responseRequired: false }; - }; Session.prototype.requiredResponse = function (response) { return { response: response, responseRequired: true }; }; Session.prototype.addProtocolHandler = function (command, handler) { - if (command in this.handlers) { + if (this.handlers[command]) { throw new Error("Protocol handler already exists for command \"" + command + "\""); } this.handlers[command] = handler; @@ -55101,32 +50728,31 @@ var ts; return handler(request); } else { - this.logger.msg("Unrecognized JSON command: " + JSON.stringify(request), server.Msg.Err); + this.projectService.log("Unrecognized JSON command: " + JSON.stringify(request)); this.output(undefined, CommandNames.Unknown, request.seq, "Unrecognized JSON command: " + request.command); return { responseRequired: false }; } }; Session.prototype.onMessage = function (message) { - this.gcTimer.scheduleCollect(); var start; - if (this.logger.hasLevel(server.LogLevel.requestTime)) { + if (this.logger.isVerbose()) { + this.logger.info("request: " + message); start = this.hrtime(); - if (this.logger.hasLevel(server.LogLevel.verbose)) { - this.logger.info("request: " + message); - } } var request; try { request = JSON.parse(message); var _a = this.executeCommand(request), response = _a.response, responseRequired = _a.responseRequired; - if (this.logger.hasLevel(server.LogLevel.requestTime)) { - var elapsedTime = hrTimeToMilliseconds(this.hrtime(start)).toFixed(4); - if (responseRequired) { - this.logger.perftrc(request.seq + "::" + request.command + ": elapsed time (in milliseconds) " + elapsedTime); - } - else { - this.logger.perftrc(request.seq + "::" + request.command + ": async elapsed time (in milliseconds) " + elapsedTime); + if (this.logger.isVerbose()) { + var elapsed = this.hrtime(start); + var seconds = elapsed[0]; + var nanoseconds = elapsed[1]; + var elapsedMs = ((1e9 * seconds) + nanoseconds) / 1000000.0; + var leader = "Elapsed time (in milliseconds)"; + if (!responseRequired) { + leader = "Async elapsed time (in milliseconds)"; } + this.logger.msg(leader + ": " + elapsedMs.toFixed(4).toString(), "Perf"); } if (response) { this.output(response, request.command, request.seq); @@ -55137,8 +50763,6 @@ var ts; } catch (err) { if (err instanceof ts.OperationCanceledException) { - this.output({ canceled: true }, request.command, request.seq); - return; } this.logError(err, message); this.output(undefined, request ? request.command : CommandNames.Unknown, request ? request.seq : 0, "Error processing request. " + err.message + "\n" + err.stack); @@ -55154,6 +50778,1220 @@ var ts; var server; (function (server) { var lineCollectionCapacity = 4; + function mergeFormatOptions(formatCodeOptions, formatOptions) { + var hasOwnProperty = Object.prototype.hasOwnProperty; + Object.keys(formatOptions).forEach(function (key) { + var codeKey = key.charAt(0).toUpperCase() + key.substring(1); + if (hasOwnProperty.call(formatCodeOptions, codeKey)) { + formatCodeOptions[codeKey] = formatOptions[key]; + } + }); + } + server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; + var ScriptInfo = (function () { + function ScriptInfo(host, fileName, content, isOpen) { + if (isOpen === void 0) { isOpen = false; } + this.host = host; + this.fileName = fileName; + this.content = content; + this.isOpen = isOpen; + this.children = []; + this.formatCodeOptions = ts.clone(CompilerService.getDefaultFormatCodeOptions(this.host)); + this.path = ts.toPath(fileName, host.getCurrentDirectory(), ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames)); + this.svc = ScriptVersionCache.fromString(host, content); + } + ScriptInfo.prototype.setFormatOptions = function (formatOptions) { + if (formatOptions) { + mergeFormatOptions(this.formatCodeOptions, formatOptions); + } + }; + ScriptInfo.prototype.close = function () { + this.isOpen = false; + }; + ScriptInfo.prototype.addChild = function (childInfo) { + this.children.push(childInfo); + }; + ScriptInfo.prototype.snap = function () { + return this.svc.getSnapshot(); + }; + ScriptInfo.prototype.getText = function () { + var snap = this.snap(); + return snap.getText(0, snap.getLength()); + }; + ScriptInfo.prototype.getLineInfo = function (line) { + var snap = this.snap(); + return snap.index.lineNumberToInfo(line); + }; + ScriptInfo.prototype.editContent = function (start, end, newText) { + this.svc.edit(start, end - start, newText); + }; + ScriptInfo.prototype.getTextChangeRangeBetweenVersions = function (startVersion, endVersion) { + return this.svc.getTextChangesBetweenVersions(startVersion, endVersion); + }; + ScriptInfo.prototype.getChangeRange = function (oldSnapshot) { + return this.snap().getChangeRange(oldSnapshot); + }; + return ScriptInfo; + }()); + server.ScriptInfo = ScriptInfo; + var LSHost = (function () { + function LSHost(host, project) { + var _this = this; + this.host = host; + this.project = project; + this.roots = []; + this.getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + this.resolvedModuleNames = ts.createFileMap(); + this.resolvedTypeReferenceDirectives = ts.createFileMap(); + this.filenameToScript = ts.createFileMap(); + this.moduleResolutionHost = { + fileExists: function (fileName) { return _this.fileExists(fileName); }, + readFile: function (fileName) { return _this.host.readFile(fileName); }, + directoryExists: function (directoryName) { return _this.host.directoryExists(directoryName); } + }; + } + LSHost.prototype.resolveNamesWithLocalCache = function (names, containingFile, cache, loader, getResult) { + var path = ts.toPath(containingFile, this.host.getCurrentDirectory(), this.getCanonicalFileName); + var currentResolutionsInFile = cache.get(path); + var newResolutions = {}; + var resolvedModules = []; + var compilerOptions = this.getCompilationSettings(); + for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { + var name_43 = names_2[_i]; + var resolution = ts.lookUp(newResolutions, name_43); + if (!resolution) { + var existingResolution = currentResolutionsInFile && ts.lookUp(currentResolutionsInFile, name_43); + if (moduleResolutionIsValid(existingResolution)) { + resolution = existingResolution; + } + else { + resolution = loader(name_43, containingFile, compilerOptions, this.moduleResolutionHost); + resolution.lastCheckTime = Date.now(); + newResolutions[name_43] = resolution; + } + } + ts.Debug.assert(resolution !== undefined); + resolvedModules.push(getResult(resolution)); + } + cache.set(path, newResolutions); + return resolvedModules; + function moduleResolutionIsValid(resolution) { + if (!resolution) { + return false; + } + if (getResult(resolution)) { + return true; + } + return resolution.failedLookupLocations.length === 0; + } + }; + LSHost.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { + return this.resolveNamesWithLocalCache(typeDirectiveNames, containingFile, this.resolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, function (m) { return m.resolvedTypeReferenceDirective; }); + }; + LSHost.prototype.resolveModuleNames = function (moduleNames, containingFile) { + return this.resolveNamesWithLocalCache(moduleNames, containingFile, this.resolvedModuleNames, ts.resolveModuleName, function (m) { return m.resolvedModule; }); + }; + LSHost.prototype.getDefaultLibFileName = function () { + var nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.host.getExecutingFilePath())); + return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilationSettings)); + }; + LSHost.prototype.getScriptSnapshot = function (filename) { + var scriptInfo = this.getScriptInfo(filename); + if (scriptInfo) { + return scriptInfo.snap(); + } + }; + LSHost.prototype.setCompilationSettings = function (opt) { + this.compilationSettings = opt; + this.resolvedModuleNames.clear(); + this.resolvedTypeReferenceDirectives.clear(); + }; + LSHost.prototype.lineAffectsRefs = function (filename, line) { + var info = this.getScriptInfo(filename); + var lineInfo = info.getLineInfo(line); + if (lineInfo && lineInfo.text) { + var regex = /reference|import|\/\*|\*\//; + return regex.test(lineInfo.text); + } + }; + LSHost.prototype.getCompilationSettings = function () { + return this.compilationSettings; + }; + LSHost.prototype.getScriptFileNames = function () { + return this.roots.map(function (root) { return root.fileName; }); + }; + LSHost.prototype.getScriptKind = function (fileName) { + var info = this.getScriptInfo(fileName); + if (!info) { + return undefined; + } + if (!info.scriptKind) { + info.scriptKind = ts.getScriptKindFromFileName(fileName); + } + return info.scriptKind; + }; + LSHost.prototype.getScriptVersion = function (filename) { + return this.getScriptInfo(filename).svc.latestVersion().toString(); + }; + LSHost.prototype.getCurrentDirectory = function () { + return ""; + }; + LSHost.prototype.getScriptIsOpen = function (filename) { + return this.getScriptInfo(filename).isOpen; + }; + LSHost.prototype.removeReferencedFile = function (info) { + if (!info.isOpen) { + this.filenameToScript.remove(info.path); + this.resolvedModuleNames.remove(info.path); + this.resolvedTypeReferenceDirectives.remove(info.path); + } + }; + LSHost.prototype.getScriptInfo = function (filename) { + var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); + var scriptInfo = this.filenameToScript.get(path); + if (!scriptInfo) { + scriptInfo = this.project.openReferencedFile(filename); + if (scriptInfo) { + this.filenameToScript.set(path, scriptInfo); + } + } + return scriptInfo; + }; + LSHost.prototype.addRoot = function (info) { + if (!this.filenameToScript.contains(info.path)) { + this.filenameToScript.set(info.path, info); + this.roots.push(info); + } + }; + LSHost.prototype.removeRoot = function (info) { + if (this.filenameToScript.contains(info.path)) { + this.filenameToScript.remove(info.path); + this.roots = copyListRemovingItem(info, this.roots); + this.resolvedModuleNames.remove(info.path); + this.resolvedTypeReferenceDirectives.remove(info.path); + } + }; + LSHost.prototype.saveTo = function (filename, tmpfilename) { + var script = this.getScriptInfo(filename); + if (script) { + var snap = script.snap(); + this.host.writeFile(tmpfilename, snap.getText(0, snap.getLength())); + } + }; + LSHost.prototype.reloadScript = function (filename, tmpfilename, cb) { + var script = this.getScriptInfo(filename); + if (script) { + script.svc.reloadFromFile(tmpfilename, cb); + } + }; + LSHost.prototype.editScript = function (filename, start, end, newText) { + var script = this.getScriptInfo(filename); + if (script) { + script.editContent(start, end, newText); + return; + } + throw new Error("No script with name '" + filename + "'"); + }; + LSHost.prototype.resolvePath = function (path) { + var result = this.host.resolvePath(path); + return result; + }; + LSHost.prototype.fileExists = function (path) { + var result = this.host.fileExists(path); + return result; + }; + LSHost.prototype.directoryExists = function (path) { + return this.host.directoryExists(path); + }; + LSHost.prototype.getDirectories = function (path) { + return this.host.getDirectories(path); + }; + LSHost.prototype.lineToTextSpan = function (filename, line) { + var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); + var script = this.filenameToScript.get(path); + var index = script.snap().index; + var lineInfo = index.lineNumberToInfo(line + 1); + var len; + if (lineInfo.leaf) { + len = lineInfo.leaf.text.length; + } + else { + var nextLineInfo = index.lineNumberToInfo(line + 2); + len = nextLineInfo.offset - lineInfo.offset; + } + return ts.createTextSpan(lineInfo.offset, len); + }; + LSHost.prototype.lineOffsetToPosition = function (filename, line, offset) { + var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); + var script = this.filenameToScript.get(path); + var index = script.snap().index; + var lineInfo = index.lineNumberToInfo(line); + return (lineInfo.offset + offset - 1); + }; + LSHost.prototype.positionToLineOffset = function (filename, position, lineIndex) { + lineIndex = lineIndex || this.getLineIndex(filename); + var lineOffset = lineIndex.charOffsetToLineNumberAndPos(position); + return { line: lineOffset.line, offset: lineOffset.offset + 1 }; + }; + LSHost.prototype.getLineIndex = function (filename) { + var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); + var script = this.filenameToScript.get(path); + return script.snap().index; + }; + return LSHost; + }()); + server.LSHost = LSHost; + var Project = (function () { + function Project(projectService, projectOptions, languageServiceDiabled) { + if (languageServiceDiabled === void 0) { languageServiceDiabled = false; } + this.projectService = projectService; + this.projectOptions = projectOptions; + this.languageServiceDiabled = languageServiceDiabled; + this.directoriesWatchedForTsconfig = []; + this.filenameToSourceFile = {}; + this.updateGraphSeq = 0; + this.openRefCount = 0; + if (projectOptions && projectOptions.files) { + projectOptions.compilerOptions.allowNonTsExtensions = true; + } + if (!languageServiceDiabled) { + this.compilerService = new CompilerService(this, projectOptions && projectOptions.compilerOptions); + } + } + Project.prototype.enableLanguageService = function () { + if (this.languageServiceDiabled) { + this.compilerService = new CompilerService(this, this.projectOptions && this.projectOptions.compilerOptions); + } + this.languageServiceDiabled = false; + }; + Project.prototype.disableLanguageService = function () { + this.languageServiceDiabled = true; + }; + Project.prototype.addOpenRef = function () { + this.openRefCount++; + }; + Project.prototype.deleteOpenRef = function () { + this.openRefCount--; + return this.openRefCount; + }; + Project.prototype.openReferencedFile = function (filename) { + return this.projectService.openFile(filename, false); + }; + Project.prototype.getRootFiles = function () { + if (this.languageServiceDiabled) { + return this.projectOptions ? this.projectOptions.files : undefined; + } + return this.compilerService.host.roots.map(function (info) { return info.fileName; }); + }; + Project.prototype.getFileNames = function () { + if (this.languageServiceDiabled) { + if (!this.projectOptions) { + return undefined; + } + var fileNames = []; + if (this.projectOptions && this.projectOptions.compilerOptions) { + fileNames.push(ts.getDefaultLibFilePath(this.projectOptions.compilerOptions)); + } + ts.addRange(fileNames, this.projectOptions.files); + return fileNames; + } + var sourceFiles = this.program.getSourceFiles(); + return sourceFiles.map(function (sourceFile) { return sourceFile.fileName; }); + }; + Project.prototype.getSourceFile = function (info) { + if (this.languageServiceDiabled) { + return undefined; + } + return this.filenameToSourceFile[info.fileName]; + }; + Project.prototype.getSourceFileFromName = function (filename, requireOpen) { + if (this.languageServiceDiabled) { + return undefined; + } + var info = this.projectService.getScriptInfo(filename); + if (info) { + if ((!requireOpen) || info.isOpen) { + return this.getSourceFile(info); + } + } + }; + Project.prototype.isRoot = function (info) { + if (this.languageServiceDiabled) { + return undefined; + } + return this.compilerService.host.roots.some(function (root) { return root === info; }); + }; + Project.prototype.removeReferencedFile = function (info) { + if (this.languageServiceDiabled) { + return; + } + this.compilerService.host.removeReferencedFile(info); + this.updateGraph(); + }; + Project.prototype.updateFileMap = function () { + if (this.languageServiceDiabled) { + return; + } + this.filenameToSourceFile = {}; + var sourceFiles = this.program.getSourceFiles(); + for (var i = 0, len = sourceFiles.length; i < len; i++) { + var normFilename = ts.normalizePath(sourceFiles[i].fileName); + this.filenameToSourceFile[normFilename] = sourceFiles[i]; + } + }; + Project.prototype.finishGraph = function () { + if (this.languageServiceDiabled) { + return; + } + this.updateGraph(); + this.compilerService.languageService.getNavigateToItems(".*"); + }; + Project.prototype.updateGraph = function () { + if (this.languageServiceDiabled) { + return; + } + this.program = this.compilerService.languageService.getProgram(); + this.updateFileMap(); + }; + Project.prototype.isConfiguredProject = function () { + return this.projectFilename; + }; + Project.prototype.addRoot = function (info) { + if (this.languageServiceDiabled) { + return; + } + this.compilerService.host.addRoot(info); + }; + Project.prototype.removeRoot = function (info) { + if (this.languageServiceDiabled) { + return; + } + this.compilerService.host.removeRoot(info); + }; + Project.prototype.filesToString = function () { + if (this.languageServiceDiabled) { + if (this.projectOptions) { + var strBuilder_1 = ""; + ts.forEach(this.projectOptions.files, function (file) { strBuilder_1 += file + "\n"; }); + return strBuilder_1; + } + } + var strBuilder = ""; + ts.forEachValue(this.filenameToSourceFile, function (sourceFile) { strBuilder += sourceFile.fileName + "\n"; }); + return strBuilder; + }; + Project.prototype.setProjectOptions = function (projectOptions) { + this.projectOptions = projectOptions; + if (projectOptions.compilerOptions) { + projectOptions.compilerOptions.allowNonTsExtensions = true; + if (!this.languageServiceDiabled) { + this.compilerService.setCompilerOptions(projectOptions.compilerOptions); + } + } + }; + return Project; + }()); + server.Project = Project; + function copyListRemovingItem(item, list) { + var copiedList = []; + for (var i = 0, len = list.length; i < len; i++) { + if (list[i] != item) { + copiedList.push(list[i]); + } + } + return copiedList; + } + function combineProjectOutput(projects, action, comparer, areEqual) { + var result = projects.reduce(function (previous, current) { return ts.concatenate(previous, action(current)); }, []).sort(comparer); + return projects.length > 1 ? ts.deduplicate(result, areEqual) : result; + } + server.combineProjectOutput = combineProjectOutput; + var ProjectService = (function () { + function ProjectService(host, psLogger, eventHandler) { + this.host = host; + this.psLogger = psLogger; + this.eventHandler = eventHandler; + this.filenameToScriptInfo = {}; + this.openFileRoots = []; + this.inferredProjects = []; + this.configuredProjects = []; + this.openFilesReferenced = []; + this.openFileRootsConfigured = []; + this.directoryWatchersForTsconfig = {}; + this.directoryWatchersRefCount = {}; + this.timerForDetectingProjectFileListChanges = {}; + this.addDefaultHostConfiguration(); + } + ProjectService.prototype.addDefaultHostConfiguration = function () { + this.hostConfiguration = { + formatCodeOptions: ts.clone(CompilerService.getDefaultFormatCodeOptions(this.host)), + hostInfo: "Unknown host" + }; + }; + ProjectService.prototype.getFormatCodeOptions = function (file) { + if (file) { + var info = this.filenameToScriptInfo[file]; + if (info) { + return info.formatCodeOptions; + } + } + return this.hostConfiguration.formatCodeOptions; + }; + ProjectService.prototype.watchedFileChanged = function (fileName) { + var info = this.filenameToScriptInfo[fileName]; + if (!info) { + this.psLogger.info("Error: got watch notification for unknown file: " + fileName); + } + if (!this.host.fileExists(fileName)) { + this.fileDeletedInFilesystem(info); + } + else { + if (info && (!info.isOpen)) { + info.svc.reloadFromFile(info.fileName); + } + } + }; + ProjectService.prototype.directoryWatchedForSourceFilesChanged = function (project, fileName) { + if (fileName && !ts.isSupportedSourceFileName(fileName, project.projectOptions ? project.projectOptions.compilerOptions : undefined)) { + return; + } + this.log("Detected source file changes: " + fileName); + this.startTimerForDetectingProjectFileListChanges(project); + }; + ProjectService.prototype.startTimerForDetectingProjectFileListChanges = function (project) { + var _this = this; + if (this.timerForDetectingProjectFileListChanges[project.projectFilename]) { + this.host.clearTimeout(this.timerForDetectingProjectFileListChanges[project.projectFilename]); + } + this.timerForDetectingProjectFileListChanges[project.projectFilename] = this.host.setTimeout(function () { return _this.handleProjectFileListChanges(project); }, 250); + }; + ProjectService.prototype.handleProjectFileListChanges = function (project) { + var _this = this; + var projectOptions = this.configFileToProjectOptions(project.projectFilename).projectOptions; + var newRootFiles = projectOptions.files.map((function (f) { return _this.getCanonicalFileName(f); })); + var currentRootFiles = project.getRootFiles().map((function (f) { return _this.getCanonicalFileName(f); })); + if (!ts.arrayIsEqualTo(currentRootFiles && currentRootFiles.sort(), newRootFiles && newRootFiles.sort())) { + this.updateConfiguredProject(project); + this.updateProjectStructure(); + } + }; + ProjectService.prototype.directoryWatchedForTsconfigChanged = function (fileName) { + var _this = this; + if (ts.getBaseFileName(fileName) != "tsconfig.json") { + this.log(fileName + " is not tsconfig.json"); + return; + } + this.log("Detected newly added tsconfig file: " + fileName); + var projectOptions = this.configFileToProjectOptions(fileName).projectOptions; + var rootFilesInTsconfig = projectOptions.files.map(function (f) { return _this.getCanonicalFileName(f); }); + var openFileRoots = this.openFileRoots.map(function (s) { return _this.getCanonicalFileName(s.fileName); }); + for (var _i = 0, openFileRoots_1 = openFileRoots; _i < openFileRoots_1.length; _i++) { + var openFileRoot = openFileRoots_1[_i]; + if (rootFilesInTsconfig.indexOf(openFileRoot) >= 0) { + this.reloadProjects(); + return; + } + } + }; + ProjectService.prototype.getCanonicalFileName = function (fileName) { + var name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + return ts.normalizePath(name); + }; + ProjectService.prototype.watchedProjectConfigFileChanged = function (project) { + this.log("Config file changed: " + project.projectFilename); + this.updateConfiguredProject(project); + this.updateProjectStructure(); + }; + ProjectService.prototype.log = function (msg, type) { + if (type === void 0) { type = "Err"; } + this.psLogger.msg(msg, type); + }; + ProjectService.prototype.setHostConfiguration = function (args) { + if (args.file) { + var info = this.filenameToScriptInfo[args.file]; + if (info) { + info.setFormatOptions(args.formatOptions); + this.log("Host configuration update for file " + args.file, "Info"); + } + } + else { + if (args.hostInfo !== undefined) { + this.hostConfiguration.hostInfo = args.hostInfo; + this.log("Host information " + args.hostInfo, "Info"); + } + if (args.formatOptions) { + mergeFormatOptions(this.hostConfiguration.formatCodeOptions, args.formatOptions); + this.log("Format host information updated", "Info"); + } + } + }; + ProjectService.prototype.closeLog = function () { + this.psLogger.close(); + }; + ProjectService.prototype.createInferredProject = function (root) { + var _this = this; + var project = new Project(this); + project.addRoot(root); + var currentPath = ts.getDirectoryPath(root.fileName); + var parentPath = ts.getDirectoryPath(currentPath); + while (currentPath != parentPath) { + if (!project.projectService.directoryWatchersForTsconfig[currentPath]) { + this.log("Add watcher for: " + currentPath); + project.projectService.directoryWatchersForTsconfig[currentPath] = + this.host.watchDirectory(currentPath, function (fileName) { return _this.directoryWatchedForTsconfigChanged(fileName); }); + project.projectService.directoryWatchersRefCount[currentPath] = 1; + } + else { + project.projectService.directoryWatchersRefCount[currentPath] += 1; + } + project.directoriesWatchedForTsconfig.push(currentPath); + currentPath = parentPath; + parentPath = ts.getDirectoryPath(parentPath); + } + project.finishGraph(); + this.inferredProjects.push(project); + return project; + }; + ProjectService.prototype.fileDeletedInFilesystem = function (info) { + this.psLogger.info(info.fileName + " deleted"); + if (info.fileWatcher) { + info.fileWatcher.close(); + info.fileWatcher = undefined; + } + if (!info.isOpen) { + this.filenameToScriptInfo[info.fileName] = undefined; + var referencingProjects = this.findReferencingProjects(info); + if (info.defaultProject) { + info.defaultProject.removeRoot(info); + } + for (var i = 0, len = referencingProjects.length; i < len; i++) { + referencingProjects[i].removeReferencedFile(info); + } + for (var j = 0, flen = this.openFileRoots.length; j < flen; j++) { + var openFile = this.openFileRoots[j]; + if (this.eventHandler) { + this.eventHandler("context", openFile.defaultProject, openFile.fileName); + } + } + for (var j = 0, flen = this.openFilesReferenced.length; j < flen; j++) { + var openFile = this.openFilesReferenced[j]; + if (this.eventHandler) { + this.eventHandler("context", openFile.defaultProject, openFile.fileName); + } + } + } + this.printProjects(); + }; + ProjectService.prototype.updateConfiguredProjectList = function () { + var configuredProjects = []; + for (var i = 0, len = this.configuredProjects.length; i < len; i++) { + if (this.configuredProjects[i].openRefCount > 0) { + configuredProjects.push(this.configuredProjects[i]); + } + } + this.configuredProjects = configuredProjects; + }; + ProjectService.prototype.removeProject = function (project) { + this.log("remove project: " + project.getRootFiles().toString()); + if (project.isConfiguredProject()) { + project.projectFileWatcher.close(); + project.directoryWatcher.close(); + ts.forEachValue(project.directoriesWatchedForWildcards, function (watcher) { watcher.close(); }); + delete project.directoriesWatchedForWildcards; + this.configuredProjects = copyListRemovingItem(project, this.configuredProjects); + } + else { + for (var _i = 0, _a = project.directoriesWatchedForTsconfig; _i < _a.length; _i++) { + var directory = _a[_i]; + project.projectService.directoryWatchersRefCount[directory]--; + if (!project.projectService.directoryWatchersRefCount[directory]) { + this.log("Close directory watcher for: " + directory); + project.projectService.directoryWatchersForTsconfig[directory].close(); + delete project.projectService.directoryWatchersForTsconfig[directory]; + } + } + this.inferredProjects = copyListRemovingItem(project, this.inferredProjects); + } + var fileNames = project.getFileNames(); + for (var _b = 0, fileNames_3 = fileNames; _b < fileNames_3.length; _b++) { + var fileName = fileNames_3[_b]; + var info = this.getScriptInfo(fileName); + if (info.defaultProject == project) { + info.defaultProject = undefined; + } + } + }; + ProjectService.prototype.setConfiguredProjectRoot = function (info) { + for (var i = 0, len = this.configuredProjects.length; i < len; i++) { + var configuredProject = this.configuredProjects[i]; + if (configuredProject.isRoot(info)) { + info.defaultProject = configuredProject; + configuredProject.addOpenRef(); + return true; + } + } + return false; + }; + ProjectService.prototype.addOpenFile = function (info) { + if (this.setConfiguredProjectRoot(info)) { + this.openFileRootsConfigured.push(info); + } + else { + this.findReferencingProjects(info); + if (info.defaultProject) { + info.defaultProject.addOpenRef(); + this.openFilesReferenced.push(info); + } + else { + info.defaultProject = this.createInferredProject(info); + var openFileRoots = []; + for (var i = 0, len = this.openFileRoots.length; i < len; i++) { + var r = this.openFileRoots[i]; + if (info.defaultProject.getSourceFile(r)) { + this.removeProject(r.defaultProject); + this.openFilesReferenced.push(r); + r.defaultProject = info.defaultProject; + } + else { + openFileRoots.push(r); + } + } + this.openFileRoots = openFileRoots; + this.openFileRoots.push(info); + } + } + this.updateConfiguredProjectList(); + }; + ProjectService.prototype.closeOpenFile = function (info) { + info.svc.reloadFromFile(info.fileName); + var openFileRoots = []; + var removedProject; + for (var i = 0, len = this.openFileRoots.length; i < len; i++) { + if (info === this.openFileRoots[i]) { + removedProject = info.defaultProject; + } + else { + openFileRoots.push(this.openFileRoots[i]); + } + } + this.openFileRoots = openFileRoots; + if (!removedProject) { + var openFileRootsConfigured = []; + for (var i = 0, len = this.openFileRootsConfigured.length; i < len; i++) { + if (info === this.openFileRootsConfigured[i]) { + if (info.defaultProject.deleteOpenRef() === 0) { + removedProject = info.defaultProject; + } + } + else { + openFileRootsConfigured.push(this.openFileRootsConfigured[i]); + } + } + this.openFileRootsConfigured = openFileRootsConfigured; + } + if (removedProject) { + this.removeProject(removedProject); + var openFilesReferenced = []; + var orphanFiles = []; + for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) { + var f = this.openFilesReferenced[i]; + if (f.defaultProject === removedProject || !f.defaultProject) { + f.defaultProject = undefined; + orphanFiles.push(f); + } + else { + openFilesReferenced.push(f); + } + } + this.openFilesReferenced = openFilesReferenced; + for (var i = 0, len = orphanFiles.length; i < len; i++) { + this.addOpenFile(orphanFiles[i]); + } + } + else { + this.openFilesReferenced = copyListRemovingItem(info, this.openFilesReferenced); + } + info.close(); + }; + ProjectService.prototype.findReferencingProjects = function (info, excludedProject) { + var referencingProjects = []; + info.defaultProject = undefined; + for (var i = 0, len = this.inferredProjects.length; i < len; i++) { + var inferredProject = this.inferredProjects[i]; + inferredProject.updateGraph(); + if (inferredProject !== excludedProject) { + if (inferredProject.getSourceFile(info)) { + info.defaultProject = inferredProject; + referencingProjects.push(inferredProject); + } + } + } + for (var i = 0, len = this.configuredProjects.length; i < len; i++) { + var configuredProject = this.configuredProjects[i]; + configuredProject.updateGraph(); + if (configuredProject.getSourceFile(info)) { + info.defaultProject = configuredProject; + referencingProjects.push(configuredProject); + } + } + return referencingProjects; + }; + ProjectService.prototype.reloadProjects = function () { + this.log("reload projects."); + for (var _i = 0, _a = this.openFileRoots; _i < _a.length; _i++) { + var info = _a[_i]; + this.openOrUpdateConfiguredProjectForFile(info.fileName); + } + this.updateProjectStructure(); + }; + ProjectService.prototype.updateProjectStructure = function () { + this.log("updating project structure from ...", "Info"); + this.printProjects(); + var unattachedOpenFiles = []; + var openFileRootsConfigured = []; + for (var _i = 0, _a = this.openFileRootsConfigured; _i < _a.length; _i++) { + var info = _a[_i]; + var project = info.defaultProject; + if (!project || !(project.getSourceFile(info))) { + info.defaultProject = undefined; + unattachedOpenFiles.push(info); + } + else { + openFileRootsConfigured.push(info); + } + } + this.openFileRootsConfigured = openFileRootsConfigured; + var openFilesReferenced = []; + for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) { + var referencedFile = this.openFilesReferenced[i]; + referencedFile.defaultProject.updateGraph(); + var sourceFile = referencedFile.defaultProject.getSourceFile(referencedFile); + if (sourceFile) { + openFilesReferenced.push(referencedFile); + } + else { + unattachedOpenFiles.push(referencedFile); + } + } + this.openFilesReferenced = openFilesReferenced; + var openFileRoots = []; + for (var i = 0, len = this.openFileRoots.length; i < len; i++) { + var rootFile = this.openFileRoots[i]; + var rootedProject = rootFile.defaultProject; + var referencingProjects = this.findReferencingProjects(rootFile, rootedProject); + if (rootFile.defaultProject && rootFile.defaultProject.isConfiguredProject()) { + if (!rootedProject.isConfiguredProject()) { + this.removeProject(rootedProject); + } + this.openFileRootsConfigured.push(rootFile); + } + else { + if (referencingProjects.length === 0) { + rootFile.defaultProject = rootedProject; + openFileRoots.push(rootFile); + } + else { + this.removeProject(rootedProject); + this.openFilesReferenced.push(rootFile); + } + } + } + this.openFileRoots = openFileRoots; + for (var i = 0, len = unattachedOpenFiles.length; i < len; i++) { + this.addOpenFile(unattachedOpenFiles[i]); + } + this.printProjects(); + }; + ProjectService.prototype.getScriptInfo = function (filename) { + filename = ts.normalizePath(filename); + return ts.lookUp(this.filenameToScriptInfo, filename); + }; + ProjectService.prototype.openFile = function (fileName, openedByClient, fileContent, scriptKind) { + var _this = this; + fileName = ts.normalizePath(fileName); + var info = ts.lookUp(this.filenameToScriptInfo, fileName); + if (!info) { + var content = void 0; + if (this.host.fileExists(fileName)) { + content = fileContent || this.host.readFile(fileName); + } + if (!content) { + if (openedByClient) { + content = ""; + } + } + if (content !== undefined) { + info = new ScriptInfo(this.host, fileName, content, openedByClient); + info.scriptKind = scriptKind; + info.setFormatOptions(this.getFormatCodeOptions()); + this.filenameToScriptInfo[fileName] = info; + if (!info.isOpen) { + info.fileWatcher = this.host.watchFile(fileName, function (_) { _this.watchedFileChanged(fileName); }); + } + } + } + if (info) { + if (fileContent) { + info.svc.reload(fileContent); + } + if (openedByClient) { + info.isOpen = true; + } + } + return info; + }; + ProjectService.prototype.findConfigFile = function (searchPath) { + while (true) { + var tsconfigFileName = ts.combinePaths(searchPath, "tsconfig.json"); + if (this.host.fileExists(tsconfigFileName)) { + return tsconfigFileName; + } + var jsconfigFileName = ts.combinePaths(searchPath, "jsconfig.json"); + if (this.host.fileExists(jsconfigFileName)) { + return jsconfigFileName; + } + var parentPath = ts.getDirectoryPath(searchPath); + if (parentPath === searchPath) { + break; + } + searchPath = parentPath; + } + return undefined; + }; + ProjectService.prototype.openClientFile = function (fileName, fileContent, scriptKind) { + var _a = this.openOrUpdateConfiguredProjectForFile(fileName), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors; + var info = this.openFile(fileName, true, fileContent, scriptKind); + this.addOpenFile(info); + this.printProjects(); + return { configFileName: configFileName, configFileErrors: configFileErrors }; + }; + ProjectService.prototype.openOrUpdateConfiguredProjectForFile = function (fileName) { + var searchPath = ts.normalizePath(ts.getDirectoryPath(fileName)); + this.log("Search path: " + searchPath, "Info"); + var configFileName = this.findConfigFile(searchPath); + if (configFileName) { + this.log("Config file name: " + configFileName, "Info"); + var project = this.findConfiguredProjectByConfigFile(configFileName); + if (!project) { + var configResult = this.openConfigFile(configFileName, fileName); + if (!configResult.success) { + return { configFileName: configFileName, configFileErrors: configResult.errors }; + } + else { + this.log("Opened configuration file " + configFileName, "Info"); + this.configuredProjects.push(configResult.project); + if (configResult.errors && configResult.errors.length > 0) { + return { configFileName: configFileName, configFileErrors: configResult.errors }; + } + } + } + else { + this.updateConfiguredProject(project); + } + } + else { + this.log("No config files found."); + } + return configFileName ? { configFileName: configFileName } : {}; + }; + ProjectService.prototype.closeClientFile = function (filename) { + var info = ts.lookUp(this.filenameToScriptInfo, filename); + if (info) { + this.closeOpenFile(info); + info.isOpen = false; + } + this.printProjects(); + }; + ProjectService.prototype.getProjectForFile = function (filename) { + var scriptInfo = ts.lookUp(this.filenameToScriptInfo, filename); + if (scriptInfo) { + return scriptInfo.defaultProject; + } + }; + ProjectService.prototype.printProjectsForFile = function (filename) { + var scriptInfo = ts.lookUp(this.filenameToScriptInfo, filename); + if (scriptInfo) { + this.psLogger.startGroup(); + this.psLogger.info("Projects for " + filename); + var projects = this.findReferencingProjects(scriptInfo); + for (var i = 0, len = projects.length; i < len; i++) { + this.psLogger.info("Project " + i.toString()); + } + this.psLogger.endGroup(); + } + else { + this.psLogger.info(filename + " not in any project"); + } + }; + ProjectService.prototype.printProjects = function () { + if (!this.psLogger.isVerbose()) { + return; + } + this.psLogger.startGroup(); + for (var i = 0, len = this.inferredProjects.length; i < len; i++) { + var project = this.inferredProjects[i]; + project.updateGraph(); + this.psLogger.info("Project " + i.toString()); + this.psLogger.info(project.filesToString()); + this.psLogger.info("-----------------------------------------------"); + } + for (var i = 0, len = this.configuredProjects.length; i < len; i++) { + var project = this.configuredProjects[i]; + project.updateGraph(); + this.psLogger.info("Project (configured) " + (i + this.inferredProjects.length).toString()); + this.psLogger.info(project.filesToString()); + this.psLogger.info("-----------------------------------------------"); + } + this.psLogger.info("Open file roots of inferred projects: "); + for (var i = 0, len = this.openFileRoots.length; i < len; i++) { + this.psLogger.info(this.openFileRoots[i].fileName); + } + this.psLogger.info("Open files referenced by inferred or configured projects: "); + for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) { + var fileInfo = this.openFilesReferenced[i].fileName; + if (this.openFilesReferenced[i].defaultProject.isConfiguredProject()) { + fileInfo += " (configured)"; + } + this.psLogger.info(fileInfo); + } + this.psLogger.info("Open file roots of configured projects: "); + for (var i = 0, len = this.openFileRootsConfigured.length; i < len; i++) { + this.psLogger.info(this.openFileRootsConfigured[i].fileName); + } + this.psLogger.endGroup(); + }; + ProjectService.prototype.configProjectIsActive = function (fileName) { + return this.findConfiguredProjectByConfigFile(fileName) === undefined; + }; + ProjectService.prototype.findConfiguredProjectByConfigFile = function (configFileName) { + for (var i = 0, len = this.configuredProjects.length; i < len; i++) { + if (this.configuredProjects[i].projectFilename == configFileName) { + return this.configuredProjects[i]; + } + } + return undefined; + }; + ProjectService.prototype.configFileToProjectOptions = function (configFilename) { + configFilename = ts.normalizePath(configFilename); + var dirPath = ts.getDirectoryPath(configFilename); + var contents = this.host.readFile(configFilename); + var rawConfig = ts.parseConfigFileTextToJson(configFilename, contents); + if (rawConfig.error) { + return { succeeded: false, errors: [rawConfig.error] }; + } + else { + var parsedCommandLine = ts.parseJsonConfigFileContent(rawConfig.config, this.host, dirPath, {}, configFilename); + ts.Debug.assert(!!parsedCommandLine.fileNames); + if (parsedCommandLine.errors && (parsedCommandLine.errors.length > 0)) { + return { succeeded: false, errors: parsedCommandLine.errors }; + } + else if (parsedCommandLine.fileNames.length === 0) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename); + return { succeeded: false, errors: [error] }; + } + else { + var projectOptions = { + files: parsedCommandLine.fileNames, + wildcardDirectories: parsedCommandLine.wildcardDirectories, + compilerOptions: parsedCommandLine.options + }; + return { succeeded: true, projectOptions: projectOptions }; + } + } + }; + ProjectService.prototype.exceedTotalNonTsFileSizeLimit = function (fileNames) { + var totalNonTsFileSize = 0; + if (!this.host.getFileSize) { + return false; + } + for (var _i = 0, fileNames_4 = fileNames; _i < fileNames_4.length; _i++) { + var fileName = fileNames_4[_i]; + if (ts.hasTypeScriptFileExtension(fileName)) { + continue; + } + totalNonTsFileSize += this.host.getFileSize(fileName); + if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles) { + return true; + } + } + return false; + }; + ProjectService.prototype.openConfigFile = function (configFilename, clientFileName) { + var _this = this; + var _a = this.configFileToProjectOptions(configFilename), succeeded = _a.succeeded, projectOptions = _a.projectOptions, errors = _a.errors; + if (!succeeded) { + return { success: false, errors: errors }; + } + else { + if (!projectOptions.compilerOptions.disableSizeLimit && projectOptions.compilerOptions.allowJs) { + if (this.exceedTotalNonTsFileSizeLimit(projectOptions.files)) { + var project_1 = this.createProject(configFilename, projectOptions, true); + project_1.projectFileWatcher = this.host.watchFile(ts.toPath(configFilename, configFilename, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), function (_) { return _this.watchedProjectConfigFileChanged(project_1); }); + return { success: true, project: project_1 }; + } + } + var project_2 = this.createProject(configFilename, projectOptions); + var errors_1; + for (var _i = 0, _b = projectOptions.files; _i < _b.length; _i++) { + var rootFilename = _b[_i]; + if (this.host.fileExists(rootFilename)) { + var info = this.openFile(rootFilename, clientFileName == rootFilename); + project_2.addRoot(info); + } + else { + (errors_1 || (errors_1 = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, rootFilename)); + } + } + project_2.finishGraph(); + project_2.projectFileWatcher = this.host.watchFile(configFilename, function (_) { return _this.watchedProjectConfigFileChanged(project_2); }); + var configDirectoryPath_1 = ts.getDirectoryPath(configFilename); + this.log("Add recursive watcher for: " + configDirectoryPath_1); + project_2.directoryWatcher = this.host.watchDirectory(configDirectoryPath_1, function (path) { return _this.directoryWatchedForSourceFilesChanged(project_2, path); }, true); + project_2.directoriesWatchedForWildcards = ts.reduceProperties(projectOptions.wildcardDirectories, function (watchers, flag, directory) { + if (ts.comparePaths(configDirectoryPath_1, directory, ".", !_this.host.useCaseSensitiveFileNames) !== 0) { + var recursive = (flag & 1) !== 0; + _this.log("Add " + (recursive ? "recursive " : "") + "watcher for: " + directory); + watchers[directory] = _this.host.watchDirectory(directory, function (path) { return _this.directoryWatchedForSourceFilesChanged(project_2, path); }, recursive); + } + return watchers; + }, {}); + return { success: true, project: project_2, errors: errors_1 }; + } + }; + ProjectService.prototype.updateConfiguredProject = function (project) { + var _this = this; + if (!this.host.fileExists(project.projectFilename)) { + this.log("Config file deleted"); + this.removeProject(project); + } + else { + var _a = this.configFileToProjectOptions(project.projectFilename), succeeded = _a.succeeded, projectOptions = _a.projectOptions, errors = _a.errors; + if (!succeeded) { + return errors; + } + else { + if (projectOptions.compilerOptions && !projectOptions.compilerOptions.disableSizeLimit && this.exceedTotalNonTsFileSizeLimit(projectOptions.files)) { + project.setProjectOptions(projectOptions); + if (project.languageServiceDiabled) { + return; + } + project.disableLanguageService(); + if (project.directoryWatcher) { + project.directoryWatcher.close(); + project.directoryWatcher = undefined; + } + return; + } + if (project.languageServiceDiabled) { + project.setProjectOptions(projectOptions); + project.enableLanguageService(); + project.directoryWatcher = this.host.watchDirectory(ts.getDirectoryPath(project.projectFilename), function (path) { return _this.directoryWatchedForSourceFilesChanged(project, path); }, true); + for (var _i = 0, _b = projectOptions.files; _i < _b.length; _i++) { + var rootFilename = _b[_i]; + if (this.host.fileExists(rootFilename)) { + var info = this.openFile(rootFilename, false); + project.addRoot(info); + } + } + project.finishGraph(); + return; + } + var oldFileNames_1 = project.projectOptions ? project.projectOptions.files : project.compilerService.host.roots.map(function (info) { return info.fileName; }); + var newFileNames_1 = ts.filter(projectOptions.files, function (f) { return _this.host.fileExists(f); }); + var fileNamesToRemove = oldFileNames_1.filter(function (f) { return newFileNames_1.indexOf(f) < 0; }); + var fileNamesToAdd = newFileNames_1.filter(function (f) { return oldFileNames_1.indexOf(f) < 0; }); + for (var _c = 0, fileNamesToRemove_1 = fileNamesToRemove; _c < fileNamesToRemove_1.length; _c++) { + var fileName = fileNamesToRemove_1[_c]; + var info = this.getScriptInfo(fileName); + if (info) { + project.removeRoot(info); + } + } + for (var _d = 0, fileNamesToAdd_1 = fileNamesToAdd; _d < fileNamesToAdd_1.length; _d++) { + var fileName = fileNamesToAdd_1[_d]; + var info = this.getScriptInfo(fileName); + if (!info) { + info = this.openFile(fileName, false); + } + else { + if (info.isOpen) { + if (this.openFileRoots.indexOf(info) >= 0) { + this.openFileRoots = copyListRemovingItem(info, this.openFileRoots); + if (info.defaultProject && !info.defaultProject.isConfiguredProject()) { + this.removeProject(info.defaultProject); + } + } + if (this.openFilesReferenced.indexOf(info) >= 0) { + this.openFilesReferenced = copyListRemovingItem(info, this.openFilesReferenced); + } + this.openFileRootsConfigured.push(info); + info.defaultProject = project; + } + } + project.addRoot(info); + } + project.setProjectOptions(projectOptions); + project.finishGraph(); + } + } + }; + ProjectService.prototype.createProject = function (projectFilename, projectOptions, languageServiceDisabled) { + var project = new Project(this, projectOptions, languageServiceDisabled); + project.projectFilename = projectFilename; + return project; + }; + return ProjectService; + }()); + server.ProjectService = ProjectService; + var CompilerService = (function () { + function CompilerService(project, opt) { + this.project = project; + this.documentRegistry = ts.createDocumentRegistry(); + this.host = new LSHost(project.projectService.host, project); + if (opt) { + this.setCompilerOptions(opt); + } + else { + var defaultOpts = ts.getDefaultCompilerOptions(); + defaultOpts.allowNonTsExtensions = true; + defaultOpts.allowJs = true; + this.setCompilerOptions(defaultOpts); + } + this.languageService = ts.createLanguageService(this.host, this.documentRegistry); + this.classifier = ts.createClassifier(); + } + CompilerService.prototype.setCompilerOptions = function (opt) { + this.settings = opt; + this.host.setCompilationSettings(opt); + }; + CompilerService.prototype.isExternalModule = function (filename) { + var sourceFile = this.languageService.getNonBoundSourceFile(filename); + return ts.isExternalModule(sourceFile); + }; + CompilerService.getDefaultFormatCodeOptions = function (host) { + return ts.clone({ + BaseIndentSize: 0, + IndentSize: 4, + TabSize: 4, + NewLineCharacter: host.newLine || "\n", + ConvertTabsToSpaces: true, + IndentStyle: ts.IndentStyle.Smart, + InsertSpaceAfterCommaDelimiter: true, + InsertSpaceAfterSemicolonInForStatements: true, + InsertSpaceBeforeAndAfterBinaryOperators: true, + InsertSpaceAfterKeywordsInControlFlowStatements: true, + InsertSpaceAfterFunctionKeywordForAnonymousFunctions: false, + InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, + InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, + InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, + PlaceOpenBraceOnNewLineForFunctions: false, + PlaceOpenBraceOnNewLineForControlBlocks: false + }); + }; + return CompilerService; + }()); + server.CompilerService = CompilerService; (function (CharRangeSection) { CharRangeSection[CharRangeSection["PreStart"] = 0] = "PreStart"; CharRangeSection[CharRangeSection["Start"] = 1] = "Start"; @@ -55371,19 +52209,10 @@ var ts; var ScriptVersionCache = (function () { function ScriptVersionCache() { this.changes = []; - this.versions = new Array(ScriptVersionCache.maxVersions); + this.versions = []; this.minVersion = 0; this.currentVersion = 0; } - ScriptVersionCache.prototype.versionToIndex = function (version) { - if (version < this.minVersion || version > this.currentVersion) { - return undefined; - } - return version % ScriptVersionCache.maxVersions; - }; - ScriptVersionCache.prototype.currentVersionToIndex = function () { - return this.currentVersion % ScriptVersionCache.maxVersions; - }; ScriptVersionCache.prototype.edit = function (pos, deleteLen, insertedText) { this.changes[this.changes.length] = new TextChange(pos, deleteLen, insertedText); if ((this.changes.length > ScriptVersionCache.changeNumberThreshold) || @@ -55393,7 +52222,7 @@ var ts; } }; ScriptVersionCache.prototype.latest = function () { - return this.versions[this.currentVersionToIndex()]; + return this.versions[this.currentVersion]; }; ScriptVersionCache.prototype.latestVersion = function () { if (this.changes.length > 0) { @@ -55401,30 +52230,32 @@ var ts; } return this.currentVersion; }; - ScriptVersionCache.prototype.reloadFromFile = function (filename) { + ScriptVersionCache.prototype.reloadFromFile = function (filename, cb) { var content = this.host.readFile(filename); if (!content) { content = ""; } this.reload(content); + if (cb) + cb(); }; ScriptVersionCache.prototype.reload = function (script) { this.currentVersion++; this.changes = []; var snap = new LineIndexSnapshot(this.currentVersion, this); - for (var i = 0; i < this.versions.length; i++) { - this.versions[i] = undefined; - } - this.versions[this.currentVersionToIndex()] = snap; + this.versions[this.currentVersion] = snap; snap.index = new LineIndex(); var lm = LineIndex.linesFromText(script); snap.index.load(lm.lines); + for (var i = this.minVersion; i < this.currentVersion; i++) { + this.versions[i] = undefined; + } this.minVersion = this.currentVersion; }; ScriptVersionCache.prototype.getSnapshot = function () { - var snap = this.versions[this.currentVersionToIndex()]; + var snap = this.versions[this.currentVersion]; if (this.changes.length > 0) { - var snapIndex = snap.index; + var snapIndex = this.latest().index; for (var i = 0, len = this.changes.length; i < len; i++) { var change = this.changes[i]; snapIndex = snapIndex.edit(change.pos, change.deleteLen, change.insertedText); @@ -55433,10 +52264,14 @@ var ts; snap.index = snapIndex; snap.changesSincePreviousVersion = this.changes; this.currentVersion = snap.version; - this.versions[this.currentVersionToIndex()] = snap; + this.versions[snap.version] = snap; this.changes = []; if ((this.currentVersion - this.minVersion) >= ScriptVersionCache.maxVersions) { + var oldMin = this.minVersion; this.minVersion = (this.currentVersion - ScriptVersionCache.maxVersions) + 1; + for (var j = oldMin; j < this.minVersion; j++) { + this.versions[j] = undefined; + } } } return snap; @@ -55446,7 +52281,7 @@ var ts; if (oldVersion >= this.minVersion) { var textChangeRanges = []; for (var i = oldVersion + 1; i <= newVersion; i++) { - var snap = this.versions[this.versionToIndex(i)]; + var snap = this.versions[i]; for (var j = 0, len = snap.changesSincePreviousVersion.length; j < len; j++) { var textChange = snap.changesSincePreviousVersion[j]; textChangeRanges[textChangeRanges.length] = textChange.getTextChangeRange(); @@ -55597,7 +52432,7 @@ var ts; return source.substring(0, s) + nt + source.substring(s + dl, source.length); } if (this.root.charCount() === 0) { - if (newText !== undefined) { + if (newText) { this.load(LineIndex.linesFromText(newText).lines); return this; } @@ -55977,6 +52812,12 @@ var ts; function LineLeaf(text) { this.text = text; } + LineLeaf.prototype.setUdata = function (data) { + this.udata = data; + }; + LineLeaf.prototype.getUdata = function () { + return this.udata; + }; LineLeaf.prototype.isLeaf = function () { return true; }; @@ -55994,7 +52835,7 @@ var ts; server.LineLeaf = LineLeaf; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); -var debugObjectHost = new Function("return this")(); +var debugObjectHost = this; var ts; (function (ts) { function logInternalError(logger, err) { @@ -56038,7 +52879,7 @@ var ts; this.resolveModuleNames = function (moduleNames, containingFile) { var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile)); return ts.map(moduleNames, function (name) { - var result = ts.getProperty(resolutionsInFile, name); + var result = ts.lookUp(resolutionsInFile, name); return result ? { resolvedFileName: result } : undefined; }); }; @@ -56049,7 +52890,7 @@ var ts; if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) { this.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { var typeDirectivesForFile = JSON.parse(_this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile)); - return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); }); + return ts.map(typeDirectiveNames, function (name) { return ts.lookUp(typeDirectivesForFile, name); }); }; } } @@ -56072,12 +52913,6 @@ var ts; } return this.shimHost.getProjectVersion(); }; - LanguageServiceShimHostAdapter.prototype.getTypeRootsVersion = function () { - if (!this.shimHost.getTypeRootsVersion) { - return 0; - } - return this.shimHost.getTypeRootsVersion(); - }; LanguageServiceShimHostAdapter.prototype.useCaseSensitiveFileNames = function () { return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; }; @@ -56128,21 +52963,11 @@ var ts; return this.shimHost.getCurrentDirectory(); }; LanguageServiceShimHostAdapter.prototype.getDirectories = function (path) { - return JSON.parse(this.shimHost.getDirectories(path)); + return this.shimHost.getDirectories(path); }; LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) { return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); }; - LanguageServiceShimHostAdapter.prototype.readDirectory = function (path, extensions, exclude, include, depth) { - var pattern = ts.getFileMatcherPatterns(path, extensions, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); - return JSON.parse(this.shimHost.readDirectory(path, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); - }; - LanguageServiceShimHostAdapter.prototype.readFile = function (path, encoding) { - return this.shimHost.readFile(path, encoding); - }; - LanguageServiceShimHostAdapter.prototype.fileExists = function (path) { - return this.shimHost.fileExists(path); - }; return LanguageServiceShimHostAdapter; }()); ts.LanguageServiceShimHostAdapter = LanguageServiceShimHostAdapter; @@ -56152,7 +52977,7 @@ var ts; this.lastCancellationCheckTime = 0; } ThrottledCancellationToken.prototype.isCancellationRequested = function () { - var time = ts.timestamp(); + var time = Date.now(); var duration = Math.abs(time - this.lastCancellationCheckTime); if (duration > 10) { this.lastCancellationCheckTime = time; @@ -56202,9 +53027,6 @@ var ts; CoreServicesShimHostAdapter.prototype.readDirectoryFallback = function (rootDir, extension, exclude) { return JSON.parse(this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude))); }; - CoreServicesShimHostAdapter.prototype.getDirectories = function (path) { - return JSON.parse(this.shimHost.getDirectories(path)); - }; return CoreServicesShimHostAdapter; }()); ts.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter; @@ -56212,11 +53034,11 @@ var ts; var start; if (logPerformance) { logger.log(actionDescription); - start = ts.timestamp(); + start = Date.now(); } var result = action(); if (logPerformance) { - var end = ts.timestamp(); + var end = Date.now(); logger.log(actionDescription + " completed in " + (end - start) + " msec"); if (typeof result === "string") { var str = result; @@ -56255,6 +53077,19 @@ var ts; }; return ShimBase; }()); + function realizeDiagnostics(diagnostics, newLine) { + return diagnostics.map(function (d) { return realizeDiagnostic(d, newLine); }); + } + ts.realizeDiagnostics = realizeDiagnostics; + function realizeDiagnostic(diagnostic, newLine) { + return { + message: ts.flattenDiagnosticMessageText(diagnostic.messageText, newLine), + start: diagnostic.start, + length: diagnostic.length, + category: ts.DiagnosticCategory[diagnostic.category].toLowerCase(), + code: diagnostic.code + }; + } var LanguageServiceShimObject = (function (_super) { __extends(LanguageServiceShimObject, _super); function LanguageServiceShimObject(factory, host, languageService) { @@ -56530,13 +53365,6 @@ var ts; }; }); }; - CoreServicesShimObject.prototype.getAutomaticTypeDirectiveNames = function (compilerOptionsJson) { - var _this = this; - return this.forwardJSONCall("getAutomaticTypeDirectiveNames('" + compilerOptionsJson + "')", function () { - var compilerOptions = JSON.parse(compilerOptionsJson); - return ts.getAutomaticTypeDirectiveNames(compilerOptions, _this.host); - }); - }; CoreServicesShimObject.prototype.convertFileReferences = function (refs) { if (!refs) { return undefined; @@ -56563,7 +53391,7 @@ var ts; typingOptions: {}, files: [], raw: {}, - errors: [ts.realizeDiagnostic(result.error, "\r\n")] + errors: [realizeDiagnostic(result.error, "\r\n")] }; } var normalizedFileName = ts.normalizeSlashes(fileName); @@ -56573,7 +53401,7 @@ var ts; typingOptions: configFile.typingOptions, files: configFile.fileNames, raw: configFile.raw, - errors: ts.realizeDiagnostics(configFile.errors, "\r\n") + errors: realizeDiagnostics(configFile.errors, "\r\n") }; }); }; @@ -56660,4 +53488,4 @@ var TypeScript; Services.TypeScriptServicesFactory = ts.TypeScriptServicesFactory; })(Services = TypeScript.Services || (TypeScript.Services = {})); })(TypeScript || (TypeScript = {})); -var toolsVersion = "2.0"; +var toolsVersion = "1.9"; diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 712e95ce765..74e0e40530a 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -417,10 +417,7 @@ declare namespace ts { interface ModifiersArray extends NodeArray { flags: NodeFlags; } - interface Token extends Node { - __tokenTag: any; - } - interface Modifier extends Token { + interface Modifier extends Node { } interface Identifier extends PrimaryExpression { text: string; @@ -1738,6 +1735,7 @@ declare namespace ts { getCancellationToken?(): CancellationToken; getDefaultLibFileName(options: CompilerOptions): string; getDefaultLibLocation?(): string; + getDefaultTypeDirectiveNames?(rootPath: string): string[]; writeFile: WriteFileCallback; getCurrentDirectory(): string; getDirectories(path: string): string[]; @@ -1883,6 +1881,8 @@ declare namespace ts { function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange; function getTypeParameterOwner(d: Declaration): Declaration; function isParameterPropertyDeclaration(node: ParameterDeclaration): boolean; + function startsWith(str: string, prefix: string): boolean; + function endsWith(str: string, suffix: string): boolean; } declare namespace ts { function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; @@ -1909,12 +1909,6 @@ declare namespace ts { function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; - interface FormatDiagnosticsHost { - getCurrentDirectory(): string; - getCanonicalFileName(fileName: string): string; - getNewLine(): string; - } - function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; /** * Given a set of options, returns the set of type directive names diff --git a/lib/typescript.js b/lib/typescript.js index c131e3b758a..22cbe79129c 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -205,7 +205,7 @@ var ts; SyntaxKind[SyntaxKind["IntersectionType"] = 163] = "IntersectionType"; SyntaxKind[SyntaxKind["ParenthesizedType"] = 164] = "ParenthesizedType"; SyntaxKind[SyntaxKind["ThisType"] = 165] = "ThisType"; - SyntaxKind[SyntaxKind["LiteralType"] = 166] = "LiteralType"; + SyntaxKind[SyntaxKind["StringLiteralType"] = 166] = "StringLiteralType"; // Binding patterns SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 167] = "ObjectBindingPattern"; SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 168] = "ArrayBindingPattern"; @@ -334,14 +334,10 @@ var ts; SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 279] = "JSDocTypedefTag"; SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 280] = "JSDocPropertyTag"; SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 281] = "JSDocTypeLiteral"; - SyntaxKind[SyntaxKind["JSDocLiteralType"] = 282] = "JSDocLiteralType"; - SyntaxKind[SyntaxKind["JSDocNullKeyword"] = 283] = "JSDocNullKeyword"; - SyntaxKind[SyntaxKind["JSDocUndefinedKeyword"] = 284] = "JSDocUndefinedKeyword"; - SyntaxKind[SyntaxKind["JSDocNeverKeyword"] = 285] = "JSDocNeverKeyword"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 286] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 282] = "SyntaxList"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 287] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 283] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 56] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 68] = "LastAssignment"; @@ -367,9 +363,9 @@ var ts; SyntaxKind[SyntaxKind["LastBinaryOperator"] = 68] = "LastBinaryOperator"; SyntaxKind[SyntaxKind["FirstNode"] = 139] = "FirstNode"; SyntaxKind[SyntaxKind["FirstJSDocNode"] = 257] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 282] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 281] = "LastJSDocNode"; SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 273] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 285] = "LastJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 281] = "LastJSDocTagNode"; })(ts.SyntaxKind || (ts.SyntaxKind = {})); var SyntaxKind = ts.SyntaxKind; (function (NodeFlags) { @@ -479,8 +475,6 @@ var ts; TypeFormatFlags[TypeFormatFlags["InElementType"] = 64] = "InElementType"; TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 128] = "UseFullyQualifiedType"; TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 256] = "InFirstTypeArgument"; - TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 512] = "InTypeAlias"; - TypeFormatFlags[TypeFormatFlags["UseTypeAliasValue"] = 1024] = "UseTypeAliasValue"; })(ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var TypeFormatFlags = ts.TypeFormatFlags; (function (SymbolFormatFlags) { @@ -565,8 +559,8 @@ var ts; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; SymbolFlags[SymbolFlags["Value"] = 107455] = "Value"; - SymbolFlags[SymbolFlags["Type"] = 793064] = "Type"; - SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; + SymbolFlags[SymbolFlags["Type"] = 793056] = "Type"; + SymbolFlags[SymbolFlags["Namespace"] = 1536] = "Namespace"; SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; // Variables can be redeclared, but can not redeclare a block-scoped declaration with the @@ -577,10 +571,10 @@ var ts; SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 107455] = "BlockScopedVariableExcludes"; SymbolFlags[SymbolFlags["ParameterExcludes"] = 107455] = "ParameterExcludes"; SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; - SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 900095] = "EnumMemberExcludes"; + SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 107455] = "EnumMemberExcludes"; SymbolFlags[SymbolFlags["FunctionExcludes"] = 106927] = "FunctionExcludes"; SymbolFlags[SymbolFlags["ClassExcludes"] = 899519] = "ClassExcludes"; - SymbolFlags[SymbolFlags["InterfaceExcludes"] = 792968] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 792960] = "InterfaceExcludes"; SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 899327] = "RegularEnumExcludes"; SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 899967] = "ConstEnumExcludes"; SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 106639] = "ValueModuleExcludes"; @@ -588,8 +582,8 @@ var ts; SymbolFlags[SymbolFlags["MethodExcludes"] = 99263] = "MethodExcludes"; SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 41919] = "GetAccessorExcludes"; SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 74687] = "SetAccessorExcludes"; - SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 530920] = "TypeParameterExcludes"; - SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 793064] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 530912] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 793056] = "TypeAliasExcludes"; SymbolFlags[SymbolFlags["AliasExcludes"] = 8388608] = "AliasExcludes"; SymbolFlags[SymbolFlags["ModuleMember"] = 8914931] = "ModuleMember"; SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; @@ -624,7 +618,6 @@ var ts; NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding"; NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding"; NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter"; - NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 4194304] = "AssignmentsMarked"; })(ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); var NodeCheckFlags = ts.NodeCheckFlags; (function (TypeFlags) { @@ -632,63 +625,55 @@ var ts; TypeFlags[TypeFlags["String"] = 2] = "String"; TypeFlags[TypeFlags["Number"] = 4] = "Number"; TypeFlags[TypeFlags["Boolean"] = 8] = "Boolean"; - TypeFlags[TypeFlags["Enum"] = 16] = "Enum"; - TypeFlags[TypeFlags["StringLiteral"] = 32] = "StringLiteral"; - TypeFlags[TypeFlags["NumberLiteral"] = 64] = "NumberLiteral"; - TypeFlags[TypeFlags["BooleanLiteral"] = 128] = "BooleanLiteral"; - TypeFlags[TypeFlags["EnumLiteral"] = 256] = "EnumLiteral"; - TypeFlags[TypeFlags["ESSymbol"] = 512] = "ESSymbol"; - TypeFlags[TypeFlags["Void"] = 1024] = "Void"; - TypeFlags[TypeFlags["Undefined"] = 2048] = "Undefined"; - TypeFlags[TypeFlags["Null"] = 4096] = "Null"; - TypeFlags[TypeFlags["Never"] = 8192] = "Never"; - TypeFlags[TypeFlags["TypeParameter"] = 16384] = "TypeParameter"; - TypeFlags[TypeFlags["Class"] = 32768] = "Class"; - TypeFlags[TypeFlags["Interface"] = 65536] = "Interface"; - TypeFlags[TypeFlags["Reference"] = 131072] = "Reference"; - TypeFlags[TypeFlags["Tuple"] = 262144] = "Tuple"; - TypeFlags[TypeFlags["Union"] = 524288] = "Union"; - TypeFlags[TypeFlags["Intersection"] = 1048576] = "Intersection"; - TypeFlags[TypeFlags["Anonymous"] = 2097152] = "Anonymous"; - TypeFlags[TypeFlags["Instantiated"] = 4194304] = "Instantiated"; + TypeFlags[TypeFlags["Void"] = 16] = "Void"; + TypeFlags[TypeFlags["Undefined"] = 32] = "Undefined"; + TypeFlags[TypeFlags["Null"] = 64] = "Null"; + TypeFlags[TypeFlags["Enum"] = 128] = "Enum"; + TypeFlags[TypeFlags["StringLiteral"] = 256] = "StringLiteral"; + TypeFlags[TypeFlags["TypeParameter"] = 512] = "TypeParameter"; + TypeFlags[TypeFlags["Class"] = 1024] = "Class"; + TypeFlags[TypeFlags["Interface"] = 2048] = "Interface"; + TypeFlags[TypeFlags["Reference"] = 4096] = "Reference"; + TypeFlags[TypeFlags["Tuple"] = 8192] = "Tuple"; + TypeFlags[TypeFlags["Union"] = 16384] = "Union"; + TypeFlags[TypeFlags["Intersection"] = 32768] = "Intersection"; + TypeFlags[TypeFlags["Anonymous"] = 65536] = "Anonymous"; + TypeFlags[TypeFlags["Instantiated"] = 131072] = "Instantiated"; /* @internal */ - TypeFlags[TypeFlags["ObjectLiteral"] = 8388608] = "ObjectLiteral"; + TypeFlags[TypeFlags["FromSignature"] = 262144] = "FromSignature"; + TypeFlags[TypeFlags["ObjectLiteral"] = 524288] = "ObjectLiteral"; /* @internal */ - TypeFlags[TypeFlags["FreshObjectLiteral"] = 16777216] = "FreshObjectLiteral"; + TypeFlags[TypeFlags["FreshObjectLiteral"] = 1048576] = "FreshObjectLiteral"; /* @internal */ - TypeFlags[TypeFlags["ContainsWideningType"] = 33554432] = "ContainsWideningType"; + TypeFlags[TypeFlags["ContainsWideningType"] = 2097152] = "ContainsWideningType"; /* @internal */ - TypeFlags[TypeFlags["ContainsObjectLiteral"] = 67108864] = "ContainsObjectLiteral"; + TypeFlags[TypeFlags["ContainsObjectLiteral"] = 4194304] = "ContainsObjectLiteral"; /* @internal */ - TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 134217728] = "ContainsAnyFunctionType"; - TypeFlags[TypeFlags["ThisType"] = 268435456] = "ThisType"; - TypeFlags[TypeFlags["ObjectLiteralPatternWithComputedProperties"] = 536870912] = "ObjectLiteralPatternWithComputedProperties"; + TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 8388608] = "ContainsAnyFunctionType"; + TypeFlags[TypeFlags["ESSymbol"] = 16777216] = "ESSymbol"; + TypeFlags[TypeFlags["ThisType"] = 33554432] = "ThisType"; + TypeFlags[TypeFlags["ObjectLiteralPatternWithComputedProperties"] = 67108864] = "ObjectLiteralPatternWithComputedProperties"; + TypeFlags[TypeFlags["Never"] = 134217728] = "Never"; /* @internal */ - TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; - TypeFlags[TypeFlags["Literal"] = 480] = "Literal"; + TypeFlags[TypeFlags["Nullable"] = 96] = "Nullable"; /* @internal */ - TypeFlags[TypeFlags["DefinitelyFalsy"] = 7392] = "DefinitelyFalsy"; - TypeFlags[TypeFlags["PossiblyFalsy"] = 7406] = "PossiblyFalsy"; + TypeFlags[TypeFlags["Falsy"] = 112] = "Falsy"; /* @internal */ - TypeFlags[TypeFlags["Intrinsic"] = 16015] = "Intrinsic"; + TypeFlags[TypeFlags["Intrinsic"] = 150995071] = "Intrinsic"; /* @internal */ - TypeFlags[TypeFlags["Primitive"] = 8190] = "Primitive"; - TypeFlags[TypeFlags["StringLike"] = 34] = "StringLike"; - TypeFlags[TypeFlags["NumberLike"] = 340] = "NumberLike"; - TypeFlags[TypeFlags["BooleanLike"] = 136] = "BooleanLike"; - TypeFlags[TypeFlags["EnumLike"] = 272] = "EnumLike"; - TypeFlags[TypeFlags["ObjectType"] = 2588672] = "ObjectType"; - TypeFlags[TypeFlags["UnionOrIntersection"] = 1572864] = "UnionOrIntersection"; - TypeFlags[TypeFlags["StructuredType"] = 4161536] = "StructuredType"; - TypeFlags[TypeFlags["StructuredOrTypeParameter"] = 4177920] = "StructuredOrTypeParameter"; + TypeFlags[TypeFlags["Primitive"] = 16777726] = "Primitive"; + TypeFlags[TypeFlags["StringLike"] = 258] = "StringLike"; + TypeFlags[TypeFlags["NumberLike"] = 132] = "NumberLike"; + TypeFlags[TypeFlags["ObjectType"] = 80896] = "ObjectType"; + TypeFlags[TypeFlags["UnionOrIntersection"] = 49152] = "UnionOrIntersection"; + TypeFlags[TypeFlags["StructuredType"] = 130048] = "StructuredType"; // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never - TypeFlags[TypeFlags["Narrowable"] = 4178943] = "Narrowable"; - TypeFlags[TypeFlags["NotUnionOrUnit"] = 2589191] = "NotUnionOrUnit"; + TypeFlags[TypeFlags["Narrowable"] = 16908175] = "Narrowable"; /* @internal */ - TypeFlags[TypeFlags["RequiresWidening"] = 100663296] = "RequiresWidening"; + TypeFlags[TypeFlags["RequiresWidening"] = 6291456] = "RequiresWidening"; /* @internal */ - TypeFlags[TypeFlags["PropagatingFlags"] = 234881024] = "PropagatingFlags"; + TypeFlags[TypeFlags["PropagatingFlags"] = 14680064] = "PropagatingFlags"; })(ts.TypeFlags || (ts.TypeFlags = {})); var TypeFlags = ts.TypeFlags; (function (SignatureKind) { @@ -908,103 +893,7 @@ var ts; })(ts.CharacterCodes || (ts.CharacterCodes = {})); var CharacterCodes = ts.CharacterCodes; })(ts || (ts = {})); -/*@internal*/ -var ts; -(function (ts) { - /** Gets a timestamp with (at least) ms resolution */ - ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); }; -})(ts || (ts = {})); -/*@internal*/ -/** Performance measurements for the compiler. */ -var ts; -(function (ts) { - var performance; - (function (performance) { - var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true - ? onProfilerEvent - : function (markName) { }; - var enabled = false; - var profilerStart = 0; - var counts; - var marks; - var measures; - /** - * Marks a performance event. - * - * @param markName The name of the mark. - */ - function mark(markName) { - if (enabled) { - marks[markName] = ts.timestamp(); - counts[markName] = (counts[markName] || 0) + 1; - profilerEvent(markName); - } - } - performance.mark = mark; - /** - * Adds a performance measurement with the specified name. - * - * @param measureName The name of the performance measurement. - * @param startMarkName The name of the starting mark. If not supplied, the point at which the - * profiler was enabled is used. - * @param endMarkName The name of the ending mark. If not supplied, the current timestamp is - * used. - */ - function measure(measureName, startMarkName, endMarkName) { - if (enabled) { - var end = endMarkName && marks[endMarkName] || ts.timestamp(); - var start = startMarkName && marks[startMarkName] || profilerStart; - measures[measureName] = (measures[measureName] || 0) + (end - start); - } - } - performance.measure = measure; - /** - * Gets the number of times a marker was encountered. - * - * @param markName The name of the mark. - */ - function getCount(markName) { - return counts && counts[markName] || 0; - } - performance.getCount = getCount; - /** - * Gets the total duration of all measurements with the supplied name. - * - * @param measureName The name of the measure whose durations should be accumulated. - */ - function getDuration(measureName) { - return measures && measures[measureName] || 0; - } - performance.getDuration = getDuration; - /** - * Iterate over each measure, performing some action - * - * @param cb The action to perform for each measure - */ - function forEachMeasure(cb) { - for (var key in measures) { - cb(key, measures[key]); - } - } - performance.forEachMeasure = forEachMeasure; - /** Enables (and resets) performance measurements for the compiler. */ - function enable() { - counts = ts.createMap(); - marks = ts.createMap(); - measures = ts.createMap(); - enabled = true; - profilerStart = ts.timestamp(); - } - performance.enable = enable; - /** Disables performance measurements for the compiler. */ - function disable() { - enabled = false; - } - performance.disable = disable; - })(performance = ts.performance || (ts.performance = {})); -})(ts || (ts = {})); /// -/// /* @internal */ var ts; (function (ts) { @@ -1023,32 +912,14 @@ var ts; Ternary[Ternary["True"] = -1] = "True"; })(ts.Ternary || (ts.Ternary = {})); var Ternary = ts.Ternary; - var createObject = Object.create; - function createMap(template) { - var map = createObject(null); // tslint:disable-line:no-null-keyword - // Using 'delete' on an object causes V8 to put the object in dictionary mode. - // This disables creation of hidden classes, which are expensive when an object is - // constantly changing shape. - map["__"] = undefined; - delete map["__"]; - // Copies keys/values from template. Note that for..in will not throw if - // template is undefined, and instead will just exit the loop. - for (var key in template) - if (hasOwnProperty.call(template, key)) { - map[key] = template[key]; - } - return map; - } - ts.createMap = createMap; function createFileMap(keyMapper) { - var files = createMap(); + var files = {}; return { get: get, set: set, contains: contains, remove: remove, forEachValue: forEachValueInMap, - getKeys: getKeys, clear: clear }; function forEachValueInMap(f) { @@ -1056,13 +927,6 @@ var ts; f(key, files[key]); } } - function getKeys() { - var keys = []; - for (var key in files) { - keys.push(key); - } - return keys; - } // path should already be well-formed so it does not need to be normalized function get(path) { return files[toKey(path)]; @@ -1071,14 +935,14 @@ var ts; files[toKey(path)] = value; } function contains(path) { - return toKey(path) in files; + return hasProperty(files, toKey(path)); } function remove(path) { var key = toKey(path); delete files[key]; } function clear() { - files = createMap(); + files = {}; } function toKey(path) { return keyMapper ? keyMapper(path) : path; @@ -1115,36 +979,11 @@ var ts; return undefined; } ts.forEach = forEach; - /** Works like Array.prototype.find, returning `undefined` if no element satisfying the predicate is found. */ - function find(array, predicate) { - for (var i = 0, len = array.length; i < len; i++) { - var value = array[i]; - if (predicate(value, i)) { - return value; - } - } - return undefined; - } - ts.find = find; - /** - * Returns the first truthy result of `callback`, or else fails. - * This is like `forEach`, but never returns undefined. - */ - function findMap(array, callback) { - for (var i = 0, len = array.length; i < len; i++) { - var result = callback(array[i], i); - if (result) { - return result; - } - } - Debug.fail(); - } - ts.findMap = findMap; - function contains(array, value) { + function contains(array, value, areEqual) { if (array) { for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { var v = array_1[_i]; - if (v === value) { + if (areEqual ? areEqual(v, value) : v === value) { return true; } } @@ -1185,48 +1024,20 @@ var ts; return count; } ts.countWhere = countWhere; - /** - * Filters an array by a predicate function. Returns the same array instance if the predicate is - * true for all elements, otherwise returns a new array instance containing the filtered subset. - */ function filter(array, f) { + var result; if (array) { - var len = array.length; - var i = 0; - while (i < len && f(array[i])) - i++; - if (i < len) { - var result = array.slice(0, i); - i++; - while (i < len) { - var item = array[i]; - if (f(item)) { - result.push(item); - } - i++; + result = []; + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var item = array_3[_i]; + if (f(item)) { + result.push(item); } - return result; } } - return array; + return result; } ts.filter = filter; - function removeWhere(array, f) { - var outIndex = 0; - for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { - var item = array_3[_i]; - if (!f(item)) { - array[outIndex] = item; - outIndex++; - } - } - if (outIndex !== array.length) { - array.length = outIndex; - return true; - } - return false; - } - ts.removeWhere = removeWhere; function filterMutate(array, f) { var outIndex = 0; for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { @@ -1259,20 +1070,15 @@ var ts; return array1.concat(array2); } ts.concatenate = concatenate; - // TODO: fixme (N^2) - add optional comparer so collection can be sorted before deduplication. function deduplicate(array, areEqual) { var result; if (array) { result = []; - loop: for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { var item = array_6[_i]; - for (var _a = 0, result_1 = result; _a < result_1.length; _a++) { - var res = result_1[_a]; - if (areEqual ? areEqual(res, item) : res === item) { - continue loop; - } + if (!contains(result, item, areEqual)) { + result.push(item); } - result.push(item); } } return result; @@ -1323,22 +1129,16 @@ var ts; * @param array A sorted array whose first element must be no larger than number * @param number The value to be searched for in the array. */ - function binarySearch(array, value, comparer) { - if (!array || array.length === 0) { - return -1; - } + function binarySearch(array, value) { var low = 0; var high = array.length - 1; - comparer = comparer !== undefined - ? comparer - : function (v1, v2) { return (v1 < v2 ? -1 : (v1 > v2 ? 1 : 0)); }; while (low <= high) { var middle = low + ((high - low) >> 1); var midValue = array[middle]; - if (comparer(midValue, value) === 0) { + if (midValue === value) { return middle; } - else if (comparer(midValue, value) > 0) { + else if (midValue > value) { high = middle - 1; } else { @@ -1394,191 +1194,117 @@ var ts; } ts.reduceRight = reduceRight; var hasOwnProperty = Object.prototype.hasOwnProperty; - /** - * Indicates whether a map-like contains an own property with the specified key. - * - * NOTE: This is intended for use only with MapLike objects. For Map objects, use - * the 'in' operator. - * - * @param map A map-like. - * @param key A property key. - */ function hasProperty(map, key) { return hasOwnProperty.call(map, key); } ts.hasProperty = hasProperty; - /** - * Gets the value of an owned property in a map-like. - * - * NOTE: This is intended for use only with MapLike objects. For Map objects, use - * an indexer. - * - * @param map A map-like. - * @param key A property key. - */ + function getKeys(map) { + var keys = []; + for (var key in map) { + keys.push(key); + } + return keys; + } + ts.getKeys = getKeys; function getProperty(map, key) { return hasOwnProperty.call(map, key) ? map[key] : undefined; } ts.getProperty = getProperty; - /** - * Gets the owned, enumerable property keys of a map-like. - * - * NOTE: This is intended for use with MapLike objects. For Map objects, use - * Object.keys instead as it offers better performance. - * - * @param map A map-like. - */ - function getOwnKeys(map) { - var keys = []; - for (var key in map) - if (hasOwnProperty.call(map, key)) { - keys.push(key); + function isEmpty(map) { + for (var id in map) { + if (hasProperty(map, id)) { + return false; } - return keys; + } + return true; } - ts.getOwnKeys = getOwnKeys; - /** - * Enumerates the properties of a Map, invoking a callback and returning the first truthy result. - * - * @param map A map for which properties should be enumerated. - * @param callback A callback to invoke for each property. - */ - function forEachProperty(map, callback) { + ts.isEmpty = isEmpty; + function clone(object) { + var result = {}; + for (var id in object) { + result[id] = object[id]; + } + return result; + } + ts.clone = clone; + function extend(first, second) { + var result = {}; + for (var id in first) { + result[id] = first[id]; + } + for (var id in second) { + if (!hasProperty(result, id)) { + result[id] = second[id]; + } + } + return result; + } + ts.extend = extend; + function forEachValue(map, callback) { var result; - for (var key in map) { - if (result = callback(map[key], key)) + for (var id in map) { + if (result = callback(map[id])) break; } return result; } - ts.forEachProperty = forEachProperty; - /** - * Returns true if a Map has some matching property. - * - * @param map A map whose properties should be tested. - * @param predicate An optional callback used to test each property. - */ - function someProperties(map, predicate) { - for (var key in map) { - if (!predicate || predicate(map[key], key)) - return true; + ts.forEachValue = forEachValue; + function forEachKey(map, callback) { + var result; + for (var id in map) { + if (result = callback(id)) + break; } - return false; + return result; } - ts.someProperties = someProperties; - /** - * Performs a shallow copy of the properties from a source Map to a target MapLike - * - * @param source A map from which properties should be copied. - * @param target A map to which properties should be copied. - */ - function copyProperties(source, target) { - for (var key in source) { - target[key] = source[key]; + ts.forEachKey = forEachKey; + function lookUp(map, key) { + return hasProperty(map, key) ? map[key] : undefined; + } + ts.lookUp = lookUp; + function copyMap(source, target) { + for (var p in source) { + target[p] = source[p]; } } - ts.copyProperties = copyProperties; + ts.copyMap = copyMap; + /** + * Creates a map from the elements of an array. + * + * @param array the array of input elements. + * @param makeKey a function that produces a key for a given element. + * + * This function makes no effort to avoid collisions; if any two elements produce + * the same key with the given 'makeKey' function, then the element with the higher + * index in the array will be the one associated with the produced key. + */ + function arrayToMap(array, makeKey) { + var result = {}; + forEach(array, function (value) { + result[makeKey(value)] = value; + }); + return result; + } + ts.arrayToMap = arrayToMap; /** * Reduce the properties of a map. * - * NOTE: This is intended for use with Map objects. For MapLike objects, use - * reduceOwnProperties instead as it offers better runtime safety. - * * @param map The map to reduce * @param callback An aggregation function that is called for each entry in the map * @param initial The initial value for the reduction. */ function reduceProperties(map, callback, initial) { var result = initial; - for (var key in map) { - result = callback(result, map[key], String(key)); + if (map) { + for (var key in map) { + if (hasProperty(map, key)) { + result = callback(result, map[key], String(key)); + } + } } return result; } ts.reduceProperties = reduceProperties; - /** - * Reduce the properties defined on a map-like (but not from its prototype chain). - * - * NOTE: This is intended for use with MapLike objects. For Map objects, use - * reduceProperties instead as it offers better performance. - * - * @param map The map-like to reduce - * @param callback An aggregation function that is called for each entry in the map - * @param initial The initial value for the reduction. - */ - function reduceOwnProperties(map, callback, initial) { - var result = initial; - for (var key in map) - if (hasOwnProperty.call(map, key)) { - result = callback(result, map[key], String(key)); - } - return result; - } - ts.reduceOwnProperties = reduceOwnProperties; - /** - * Performs a shallow equality comparison of the contents of two map-likes. - * - * @param left A map-like whose properties should be compared. - * @param right A map-like whose properties should be compared. - */ - function equalOwnProperties(left, right, equalityComparer) { - if (left === right) - return true; - if (!left || !right) - return false; - for (var key in left) - if (hasOwnProperty.call(left, key)) { - if (!hasOwnProperty.call(right, key) === undefined) - return false; - if (equalityComparer ? !equalityComparer(left[key], right[key]) : left[key] !== right[key]) - return false; - } - for (var key in right) - if (hasOwnProperty.call(right, key)) { - if (!hasOwnProperty.call(left, key)) - return false; - } - return true; - } - ts.equalOwnProperties = equalOwnProperties; - function arrayToMap(array, makeKey, makeValue) { - var result = createMap(); - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var value = array_8[_i]; - result[makeKey(value)] = makeValue ? makeValue(value) : value; - } - return result; - } - ts.arrayToMap = arrayToMap; - function cloneMap(map) { - var clone = createMap(); - copyProperties(map, clone); - return clone; - } - ts.cloneMap = cloneMap; - function clone(object) { - var result = {}; - for (var id in object) { - if (hasOwnProperty.call(object, id)) { - result[id] = object[id]; - } - } - return result; - } - ts.clone = clone; - function extend(first, second) { - var result = {}; - for (var id in second) - if (hasOwnProperty.call(second, id)) { - result[id] = second[id]; - } - for (var id in first) - if (hasOwnProperty.call(first, id)) { - result[id] = first[id]; - } - return result; - } - ts.extend = extend; /** * Tests whether a value is an array. */ @@ -1603,7 +1329,9 @@ var ts; } ts.localizedDiagnosticMessages = undefined; function getLocaleSpecificMessage(message) { - return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message; + return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] + ? ts.localizedDiagnosticMessages[message.key] + : message.message; } ts.getLocaleSpecificMessage = getLocaleSpecificMessage; function createFileDiagnostic(file, start, length, message) { @@ -2028,19 +1756,10 @@ var ts; return true; } ts.containsPath = containsPath; - /* @internal */ - function startsWith(str, prefix) { - return str.lastIndexOf(prefix, 0) === 0; - } - ts.startsWith = startsWith; - /* @internal */ - function endsWith(str, suffix) { - var expectedPos = str.length - suffix.length; - return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; - } - ts.endsWith = endsWith; function fileExtensionIs(path, extension) { - return path.length > extension.length && endsWith(path, extension); + var pathLen = path.length; + var extLen = extension.length; + return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension; } ts.fileExtensionIs = fileExtensionIs; function fileExtensionIsAny(path, extensions) { @@ -2058,25 +1777,10 @@ var ts; // proof. var reservedCharacterPattern = /[^\w\s\/]/g; var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; - /** - * Matches any single directory segment unless it is the last segment and a .min.js file - * Breakdown: - * [^./] # matches everything up to the first . character (excluding directory seperators) - * (\\.(?!min\\.js$))? # matches . characters but not if they are part of the .min.js file extension - */ - var singleAsteriskRegexFragmentFiles = "([^./]|(\\.(?!min\\.js$))?)*"; - var singleAsteriskRegexFragmentOther = "[^/]*"; function getRegularExpressionForWildcard(specs, basePath, usage) { if (specs === undefined || specs.length === 0) { return undefined; } - var replaceWildcardCharacter = usage === "files" ? replaceWildCardCharacterFiles : replaceWildCardCharacterOther; - var singleAsteriskRegexFragment = usage === "files" ? singleAsteriskRegexFragmentFiles : singleAsteriskRegexFragmentOther; - /** - * Regex for the ** wildcard. Matches any number of subdirectories. When used for including - * files or directories, does not match subdirectories that start with a . character - */ - var doubleAsteriskRegexFragment = usage === "exclude" ? "(/.+?)?" : "(/[^/.][^/]*)*?"; var pattern = ""; var hasWrittenSubpattern = false; spec: for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { @@ -2101,7 +1805,7 @@ var ts; if (hasRecursiveDirectoryWildcard) { continue spec; } - subpattern += doubleAsteriskRegexFragment; + subpattern += "(/.+?)?"; hasRecursiveDirectoryWildcard = true; hasWrittenComponent = true; } @@ -2113,19 +1817,6 @@ var ts; if (hasWrittenComponent) { subpattern += ts.directorySeparator; } - if (usage !== "exclude") { - // The * and ? wildcards should not match directories or files that start with . if they - // appear first in a component. Dotted directories and files can be included explicitly - // like so: **/.*/.* - if (component.charCodeAt(0) === 42 /* asterisk */) { - subpattern += "([^./]" + singleAsteriskRegexFragment + ")?"; - component = component.substr(1); - } - else if (component.charCodeAt(0) === 63 /* question */) { - subpattern += "[^./]"; - component = component.substr(1); - } - } subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); hasWrittenComponent = true; } @@ -2146,14 +1837,8 @@ var ts; return "^(" + pattern + (usage === "exclude" ? ")($|/)" : ")$"); } ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; - function replaceWildCardCharacterFiles(match) { - return replaceWildcardCharacter(match, singleAsteriskRegexFragmentFiles); - } - function replaceWildCardCharacterOther(match) { - return replaceWildcardCharacter(match, singleAsteriskRegexFragmentOther); - } - function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { - return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; + function replaceWildcardCharacter(match) { + return match === "*" ? "[^/]*" : match === "?" ? "[^/]" : "\\" + match; } function getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { path = normalizePath(path); @@ -2272,22 +1957,12 @@ var ts; * List of supported extensions in order of file resolution precedence. */ ts.supportedTypeScriptExtensions = [".ts", ".tsx", ".d.ts"]; - /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ - ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"]; ts.supportedJavascriptExtensions = [".js", ".jsx"]; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); function getSupportedExtensions(options) { return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } ts.getSupportedExtensions = getSupportedExtensions; - function hasJavaScriptFileExtension(fileName) { - return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); - } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); - } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; function isSupportedSourceFileName(fileName, compilerOptions) { if (!fileName) { return false; @@ -2365,13 +2040,9 @@ var ts; } ts.removeFileExtension = removeFileExtension; function tryRemoveExtension(path, extension) { - return fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined; + return fileExtensionIs(path, extension) ? path.substring(0, path.length - extension.length) : undefined; } ts.tryRemoveExtension = tryRemoveExtension; - function removeExtension(path, extension) { - return path.substring(0, path.length - extension.length); - } - ts.removeExtension = removeExtension; function isJsxOrTsxExtension(ext) { return ext === ".jsx" || ext === ".tsx"; } @@ -2399,8 +2070,6 @@ var ts; } ts.objectAllocator = { getNodeConstructor: function () { return Node; }, - getTokenConstructor: function () { return Node; }, - getIdentifierConstructor: function () { return Node; }, getSourceFileConstructor: function () { return Node; }, getSymbolConstructor: function () { return Symbol; }, getTypeConstructor: function () { return Type; }, @@ -2453,68 +2122,6 @@ var ts; : (function (fileName) { return fileName.toLowerCase(); }); } ts.createGetCanonicalFileName = createGetCanonicalFileName; - function trace(host, message) { - host.trace(formatMessage.apply(undefined, arguments)); - } - ts.trace = trace; - /* @internal */ - function isTraceEnabled(compilerOptions, host) { - return compilerOptions.traceResolution && host.trace !== undefined; - } - ts.isTraceEnabled = isTraceEnabled; - /* @internal */ - function hasZeroOrOneAsteriskCharacter(str) { - var seenAsterisk = false; - for (var i = 0; i < str.length; i++) { - if (str.charCodeAt(i) === 42 /* asterisk */) { - if (!seenAsterisk) { - seenAsterisk = true; - } - else { - // have already seen asterisk - return false; - } - } - } - return true; - } - ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - /* @internal */ - function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; - } - ts.createResolvedModule = createResolvedModule; - /* @internal */ - function isExternalModuleNameRelative(moduleName) { - // TypeScript 1.0 spec (April 2014): 11.2.1 - // An external module name is "relative" if the first term is "." or "..". - return /^\.\.?($|[\\/])/.test(moduleName); - } - ts.isExternalModuleNameRelative = isExternalModuleNameRelative; - /* @internal */ - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - return jsonText ? JSON.parse(jsonText) : {}; - } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - return {}; - } - } - ts.readJson = readJson; - /* @internal */ - function getEmitModuleKind(compilerOptions) { - return typeof compilerOptions.module === "number" ? - compilerOptions.module : - getEmitScriptTarget(compilerOptions) === 2 /* ES6 */ ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; - } - ts.getEmitModuleKind = getEmitModuleKind; - /* @internal */ - function getEmitScriptTarget(compilerOptions) { - return compilerOptions.target || 0 /* ES3 */; - } - ts.getEmitScriptTarget = getEmitScriptTarget; })(ts || (ts = {})); /// var ts; @@ -2609,7 +2216,7 @@ var ts; function readDirectory(path, extensions, excludes, includes) { return ts.matchFiles(path, extensions, excludes, includes, /*useCaseSensitiveFileNames*/ false, shell.CurrentDirectory, getAccessibleFileSystemEntries); } - var wscriptSystem = { + return { args: args, newLine: "\r\n", useCaseSensitiveFileNames: false, @@ -2628,7 +2235,7 @@ var ts; return fso.FolderExists(path); }, createDirectory: function (directoryName) { - if (!wscriptSystem.directoryExists(directoryName)) { + if (!this.directoryExists(directoryName)) { fso.CreateFolder(directoryName); } }, @@ -2648,7 +2255,6 @@ var ts; } } }; - return wscriptSystem; } function getNodeSystem() { var _fs = require("fs"); @@ -2657,14 +2263,14 @@ var ts; var _crypto = require("crypto"); var useNonPollingWatchers = process.env["TSC_NONPOLLING_WATCHER"]; function createWatchedFileSet() { - var dirWatchers = ts.createMap(); + var dirWatchers = {}; // One file can have multiple watchers - var fileWatcherCallbacks = ts.createMap(); + var fileWatcherCallbacks = {}; return { addFile: addFile, removeFile: removeFile }; function reduceDirWatcherRefCountForFile(fileName) { var dirName = ts.getDirectoryPath(fileName); - var watcher = dirWatchers[dirName]; - if (watcher) { + if (ts.hasProperty(dirWatchers, dirName)) { + var watcher = dirWatchers[dirName]; watcher.referenceCount -= 1; if (watcher.referenceCount <= 0) { watcher.close(); @@ -2673,18 +2279,23 @@ var ts; } } function addDirWatcher(dirPath) { - var watcher = dirWatchers[dirPath]; - if (watcher) { - watcher.referenceCount += 1; + if (ts.hasProperty(dirWatchers, dirPath)) { + var watcher_1 = dirWatchers[dirPath]; + watcher_1.referenceCount += 1; return; } - watcher = _fs.watch(dirPath, { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); + var watcher = _fs.watch(dirPath, { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); watcher.referenceCount = 1; dirWatchers[dirPath] = watcher; return; } function addFileWatcherCallback(filePath, callback) { - (fileWatcherCallbacks[filePath] || (fileWatcherCallbacks[filePath] = [])).push(callback); + if (ts.hasProperty(fileWatcherCallbacks, filePath)) { + fileWatcherCallbacks[filePath].push(callback); + } + else { + fileWatcherCallbacks[filePath] = [callback]; + } } function addFile(fileName, callback) { addFileWatcherCallback(fileName, callback); @@ -2696,9 +2307,8 @@ var ts; reduceDirWatcherRefCountForFile(watchedFile.fileName); } function removeFileWatcherCallback(filePath, callback) { - var callbacks = fileWatcherCallbacks[filePath]; - if (callbacks) { - var newCallbacks = ts.copyListRemovingItem(callback, callbacks); + if (ts.hasProperty(fileWatcherCallbacks, filePath)) { + var newCallbacks = ts.copyListRemovingItem(callback, fileWatcherCallbacks[filePath]); if (newCallbacks.length === 0) { delete fileWatcherCallbacks[filePath]; } @@ -2713,7 +2323,7 @@ var ts; ? undefined : ts.getNormalizedAbsolutePath(relativeFileName, baseDirPath); // Some applications save a working file via rename operations - if ((eventName === "change" || eventName === "rename") && fileWatcherCallbacks[fileName]) { + if ((eventName === "change" || eventName === "rename") && ts.hasProperty(fileWatcherCallbacks, fileName)) { for (var _i = 0, _a = fileWatcherCallbacks[fileName]; _i < _a.length; _i++) { var fileCallback = _a[_i]; fileCallback(fileName); @@ -2834,7 +2444,7 @@ var ts; function getDirectories(path) { return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1 /* Directory */); }); } - var nodeSystem = { + return { args: process.argv.slice(2), newLine: _os.EOL, useCaseSensitiveFileNames: useCaseSensitiveFileNames, @@ -2890,7 +2500,7 @@ var ts; fileExists: fileExists, directoryExists: directoryExists, createDirectory: function (directoryName) { - if (!nodeSystem.directoryExists(directoryName)) { + if (!this.directoryExists(directoryName)) { _fs.mkdirSync(directoryName); } }, @@ -2938,7 +2548,6 @@ var ts; return _fs.realpathSync(path); } }; - return nodeSystem; } function getChakraSystem() { var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); }); @@ -2973,40 +2582,20 @@ var ts; realpath: realpath }; } - function recursiveCreateDirectory(directoryPath, sys) { - var basePath = ts.getDirectoryPath(directoryPath); - var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath); - if (shouldCreateParent) { - recursiveCreateDirectory(basePath, sys); - } - if (shouldCreateParent || !sys.directoryExists(directoryPath)) { - sys.createDirectory(directoryPath); - } - } - var sys; if (typeof ChakraHost !== "undefined") { - sys = getChakraSystem(); + return getChakraSystem(); } else if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { - sys = getWScriptSystem(); + return getWScriptSystem(); } else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") { // process and process.nextTick checks if current environment is node-like // process.browser check excludes webpack and browserify - sys = getNodeSystem(); + return getNodeSystem(); } - if (sys) { - // patch writefile to create folder before writing the file - var originalWriteFile_1 = sys.writeFile; - sys.writeFile = function (path, data, writeBom) { - var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path)); - if (directoryPath && !sys.directoryExists(directoryPath)) { - recursiveCreateDirectory(directoryPath, sys); - } - originalWriteFile_1.call(sys, path, data, writeBom); - }; + else { + return undefined; // Unsupported host } - return sys; })(); })(ts || (ts = {})); // @@ -3454,7 +3043,6 @@ var ts; Object_is_possibly_undefined: { code: 2532, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_undefined_2532", message: "Object is possibly 'undefined'." }, Object_is_possibly_null_or_undefined: { code: 2533, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_null_or_undefined_2533", message: "Object is possibly 'null' or 'undefined'." }, A_function_returning_never_cannot_have_a_reachable_end_point: { code: 2534, category: ts.DiagnosticCategory.Error, key: "A_function_returning_never_cannot_have_a_reachable_end_point_2534", message: "A function returning 'never' cannot have a reachable end point." }, - Enum_type_0_has_members_with_initializers_that_are_not_literals: { code: 2535, category: ts.DiagnosticCategory.Error, key: "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", message: "Enum type '{0}' has members with initializers that are not literals." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "The return type of a JSX element constructor must return an object type." }, JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -3502,9 +3090,6 @@ var ts; All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, - A_class_must_be_declared_after_its_base_class: { code: 2690, category: ts.DiagnosticCategory.Error, key: "A_class_must_be_declared_after_its_base_class_2690", message: "A class must be declared after its base class." }, - An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: { code: 2691, category: ts.DiagnosticCategory.Error, key: "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691", message: "An import path cannot end with a '{0}' extension. Consider importing '{1}' instead." }, - _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: { code: 2692, category: ts.DiagnosticCategory.Error, key: "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", message: "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible." }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -3575,7 +3160,7 @@ var ts; Parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4078, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", message: "Parameter '{0}' of exported function has or is using private name '{1}'." }, Exported_type_alias_0_has_or_is_using_private_name_1: { code: 4081, category: ts.DiagnosticCategory.Error, key: "Exported_type_alias_0_has_or_is_using_private_name_1_4081", message: "Exported type alias '{0}' has or is using private name '{1}'." }, Default_export_of_the_module_has_or_is_using_private_name_0: { code: 4082, category: ts.DiagnosticCategory.Error, key: "Default_export_of_the_module_has_or_is_using_private_name_0_4082", message: "Default export of the module has or is using private name '{0}'." }, - Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", message: "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict." }, + Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_to_resolve_this_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_t_4090", message: "Conflicting library definitions for '{0}' found at '{1}' and '{2}'. Copy the correct file to the 'typings' folder to resolve this conflict." }, The_current_host_does_not_support_the_0_option: { code: 5001, category: ts.DiagnosticCategory.Error, key: "The_current_host_does_not_support_the_0_option_5001", message: "The current host does not support the '{0}' option." }, Cannot_find_the_common_subdirectory_path_for_the_input_files: { code: 5009, category: ts.DiagnosticCategory.Error, key: "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", message: "Cannot find the common subdirectory path for the input files." }, File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5010, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", message: "File specification cannot end in a recursive directory wildcard ('**'): '{0}'." }, @@ -3603,7 +3188,6 @@ var ts; Substitutions_for_pattern_0_should_be_an_array: { code: 5063, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_should_be_an_array_5063", message: "Substitutions for pattern '{0}' should be an array." }, Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: { code: 5064, category: ts.DiagnosticCategory.Error, key: "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", message: "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'." }, File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5065, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", message: "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'." }, - Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: { code: 5066, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", message: "Substitutions for pattern '{0}' shouldn't be an empty array." }, Concatenate_and_emit_output_to_single_file: { code: 6001, category: ts.DiagnosticCategory.Message, key: "Concatenate_and_emit_output_to_single_file_6001", message: "Concatenate and emit output to single file." }, Generates_corresponding_d_ts_file: { code: 6002, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_d_ts_file_6002", message: "Generates corresponding '.d.ts' file." }, Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: ts.DiagnosticCategory.Message, key: "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", message: "Specify the location where debugger should locate map files instead of generated locations." }, @@ -3720,12 +3304,10 @@ var ts; Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." }, File_name_0_has_a_1_extension_stripping_it: { code: 6132, category: ts.DiagnosticCategory.Message, key: "File_name_0_has_a_1_extension_stripping_it_6132", message: "File name '{0}' has a '{1}' extension - stripping it" }, _0_is_declared_but_never_used: { code: 6133, category: ts.DiagnosticCategory.Error, key: "_0_is_declared_but_never_used_6133", message: "'{0}' is declared but never used." }, - Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, - Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, + Report_Errors_on_Unused_Locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Locals_6134", message: "Report Errors on Unused Locals." }, + Report_Errors_on_Unused_Parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Parameters_6135", message: "Report Errors on Unused Parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" }, No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" }, - Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, - Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6139, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6139", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -3734,6 +3316,7 @@ var ts; Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: { code: 7011, category: ts.DiagnosticCategory.Error, key: "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", message: "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type." }, Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7013, category: ts.DiagnosticCategory.Error, key: "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", message: "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type." }, Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: { code: 7015, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", message: "Element implicitly has an 'any' type because index expression is not of type 'number'." }, + Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation: { code: 7016, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation_7016", message: "Property '{0}' implicitly has type 'any', because its 'set' accessor lacks a type annotation." }, Index_signature_of_object_type_implicitly_has_an_any_type: { code: 7017, category: ts.DiagnosticCategory.Error, key: "Index_signature_of_object_type_implicitly_has_an_any_type_7017", message: "Index signature of object type implicitly has an 'any' type." }, Object_literal_s_property_0_implicitly_has_an_1_type: { code: 7018, category: ts.DiagnosticCategory.Error, key: "Object_literal_s_property_0_implicitly_has_an_1_type_7018", message: "Object literal's property '{0}' implicitly has an '{1}' type." }, Rest_parameter_0_implicitly_has_an_any_type: { code: 7019, category: ts.DiagnosticCategory.Error, key: "Rest_parameter_0_implicitly_has_an_any_type_7019", message: "Rest parameter '{0}' implicitly has an 'any[]' type." }, @@ -3748,8 +3331,6 @@ var ts; Fallthrough_case_in_switch: { code: 7029, category: ts.DiagnosticCategory.Error, key: "Fallthrough_case_in_switch_7029", message: "Fallthrough case in switch." }, Not_all_code_paths_return_a_value: { code: 7030, category: ts.DiagnosticCategory.Error, key: "Not_all_code_paths_return_a_value_7030", message: "Not all code paths return a value." }, Binding_element_0_implicitly_has_an_1_type: { code: 7031, category: ts.DiagnosticCategory.Error, key: "Binding_element_0_implicitly_has_an_1_type_7031", message: "Binding element '{0}' implicitly has an '{1}' type." }, - Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { code: 7032, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", message: "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation." }, - Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { code: 7033, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", message: "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation." }, You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, @@ -3789,7 +3370,7 @@ var ts; return token >= 69 /* Identifier */; } ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; - var textToToken = ts.createMap({ + var textToToken = { "abstract": 115 /* AbstractKeyword */, "any": 117 /* AnyKeyword */, "as": 116 /* AsKeyword */, @@ -3913,7 +3494,7 @@ var ts; "|=": 67 /* BarEqualsToken */, "^=": 68 /* CaretEqualsToken */, "@": 55 /* AtToken */ - }); + }; /* As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers IdentifierStart :: @@ -3999,7 +3580,9 @@ var ts; function makeReverseMap(source) { var result = []; for (var name_4 in source) { - result[source[name_4]] = name_4; + if (source.hasOwnProperty(name_4)) { + result[source[name_4]] = name_4; + } } return result; } @@ -5487,6 +5070,24 @@ var ts; return node.end - node.pos; } ts.getFullWidth = getFullWidth; + function mapIsEqualTo(map1, map2) { + if (!map1 || !map2) { + return map1 === map2; + } + return containsAll(map1, map2) && containsAll(map2, map1); + } + ts.mapIsEqualTo = mapIsEqualTo; + function containsAll(map, other) { + for (var key in map) { + if (!ts.hasProperty(map, key)) { + continue; + } + if (!ts.hasProperty(other, key) || map[key] !== other[key]) { + return false; + } + } + return true; + } function arrayIsEqualTo(array1, array2, equaler) { if (!array1 || !array2) { return array1 === array2; @@ -5504,7 +5105,7 @@ var ts; } ts.arrayIsEqualTo = arrayIsEqualTo; function hasResolvedModule(sourceFile, moduleNameText) { - return !!(sourceFile.resolvedModules && sourceFile.resolvedModules[moduleNameText]); + return sourceFile.resolvedModules && ts.hasProperty(sourceFile.resolvedModules, moduleNameText); } ts.hasResolvedModule = hasResolvedModule; function getResolvedModule(sourceFile, moduleNameText) { @@ -5513,14 +5114,14 @@ var ts; ts.getResolvedModule = getResolvedModule; function setResolvedModule(sourceFile, moduleNameText, resolvedModule) { if (!sourceFile.resolvedModules) { - sourceFile.resolvedModules = ts.createMap(); + sourceFile.resolvedModules = {}; } sourceFile.resolvedModules[moduleNameText] = resolvedModule; } ts.setResolvedModule = setResolvedModule; function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) { if (!sourceFile.resolvedTypeReferenceDirectiveNames) { - sourceFile.resolvedTypeReferenceDirectiveNames = ts.createMap(); + sourceFile.resolvedTypeReferenceDirectiveNames = {}; } sourceFile.resolvedTypeReferenceDirectiveNames[typeReferenceDirectiveName] = resolvedTypeReferenceDirective; } @@ -5542,7 +5143,7 @@ var ts; } for (var i = 0; i < names.length; i++) { var newResolution = newResolutions[i]; - var oldResolution = oldResolutions && oldResolutions[names[i]]; + var oldResolution = oldResolutions && ts.hasProperty(oldResolutions, names[i]) ? oldResolutions[names[i]] : undefined; var changed = oldResolution ? !newResolution || !comparer(oldResolution, newResolution) : newResolution; @@ -5676,20 +5277,16 @@ var ts; // the syntax list itself considers them as normal trivia. Therefore if we simply skip // trivia for the list, we may have skipped the JSDocComment as well. So we should process its // first child to determine the actual position of its first token. - if (node.kind === 286 /* SyntaxList */ && node._children.length > 0) { + if (node.kind === 282 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDocComment); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); } ts.getTokenPosOfNode = getTokenPosOfNode; function isJSDocNode(node) { - return node.kind >= 257 /* FirstJSDocNode */ && node.kind <= 282 /* LastJSDocNode */; + return node.kind >= 257 /* FirstJSDocNode */ && node.kind <= 281 /* LastJSDocNode */; } ts.isJSDocNode = isJSDocNode; - function isJSDocTag(node) { - return node.kind >= 273 /* FirstJSDocTagNode */ && node.kind <= 285 /* LastJSDocTagNode */; - } - ts.isJSDocTag = isJSDocTag; function getNonDecoratorTokenPosOfNode(node, sourceFile) { if (nodeIsMissing(node) || !node.decorators) { return getTokenPosOfNode(node, sourceFile); @@ -5744,14 +5341,11 @@ var ts; (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; - function isShorthandAmbientModuleSymbol(moduleSymbol) { - return isShorthandAmbientModule(moduleSymbol.valueDeclaration); - } - ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; function isShorthandAmbientModule(node) { // The only kind of module that can be missing a body is a shorthand ambient module. return node.kind === 225 /* ModuleDeclaration */ && (!node.body); } + ts.isShorthandAmbientModule = isShorthandAmbientModule; function isBlockScopedContainerTopLevel(node) { return node.kind === 256 /* SourceFile */ || node.kind === 225 /* ModuleDeclaration */ || @@ -6387,7 +5981,6 @@ var ts; case 155 /* TypeReference */: return node.typeName; case 194 /* ExpressionWithTypeArguments */: - ts.Debug.assert(isEntityNameExpression(node.expression)); return node.expression; case 69 /* Identifier */: case 139 /* QualifiedName */: @@ -6557,6 +6150,12 @@ var ts; return false; } ts.isExpression = isExpression; + function isExternalModuleNameRelative(moduleName) { + // TypeScript 1.0 spec (April 2014): 11.2.1 + // An external module name is "relative" if the first term is "." or "..". + return moduleName.substr(0, 2) === "./" || moduleName.substr(0, 3) === "../" || moduleName.substr(0, 2) === ".\\" || moduleName.substr(0, 3) === "..\\"; + } + ts.isExternalModuleNameRelative = isExternalModuleNameRelative; function isInstantiatedModule(node, preserveConstEnums) { var moduleState = ts.getModuleInstanceState(node); return moduleState === 1 /* Instantiated */ || @@ -6847,7 +6446,7 @@ var ts; continue; } return parent_5.kind === 187 /* BinaryExpression */ && - isAssignmentOperator(parent_5.operatorToken.kind) && + parent_5.operatorToken.kind === 56 /* EqualsToken */ && parent_5.left === node || (parent_5.kind === 207 /* ForInStatement */ || parent_5.kind === 208 /* ForOfStatement */) && parent_5.initializer === node; @@ -6894,7 +6493,6 @@ var ts; case 146 /* MethodSignature */: case 225 /* ModuleDeclaration */: case 232 /* NamespaceImport */: - case 228 /* NamespaceExportDeclaration */: case 142 /* Parameter */: case 253 /* PropertyAssignment */: case 145 /* PropertyDeclaration */: @@ -7016,8 +6614,8 @@ var ts; // import * as from ... // import { x as } from ... // export { x as } from ... - // export = - // export default + // export = ... + // export default ... function isAliasSymbolDeclaration(node) { return node.kind === 229 /* ImportEqualsDeclaration */ || node.kind === 228 /* NamespaceExportDeclaration */ || @@ -7025,13 +6623,9 @@ var ts; node.kind === 232 /* NamespaceImport */ || node.kind === 234 /* ImportSpecifier */ || node.kind === 238 /* ExportSpecifier */ || - node.kind === 235 /* ExportAssignment */ && exportAssignmentIsAlias(node); + node.kind === 235 /* ExportAssignment */ && node.expression.kind === 69 /* Identifier */; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; - function exportAssignmentIsAlias(node) { - return isEntityNameExpression(node.expression); - } - ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getClassExtendsHeritageClauseElement(node) { var heritageClause = getHeritageClause(node.heritageClauses, 83 /* ExtendsKeyword */); return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; @@ -7283,7 +6877,7 @@ var ts; ts.createSynthesizedNodeArray = createSynthesizedNodeArray; function createDiagnosticCollection() { var nonFileDiagnostics = []; - var fileDiagnostics = ts.createMap(); + var fileDiagnostics = {}; var diagnosticsModified = false; var modificationCount = 0; return { @@ -7297,12 +6891,12 @@ var ts; return modificationCount; } function reattachFileDiagnostics(newFile) { - var diagnostics = fileDiagnostics[newFile.fileName]; - if (diagnostics) { - for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { - var diagnostic = diagnostics_1[_i]; - diagnostic.file = newFile; - } + if (!ts.hasProperty(fileDiagnostics, newFile.fileName)) { + return; + } + for (var _i = 0, _a = fileDiagnostics[newFile.fileName]; _i < _a.length; _i++) { + var diagnostic = _a[_i]; + diagnostic.file = newFile; } } function add(diagnostic) { @@ -7336,7 +6930,9 @@ var ts; } ts.forEach(nonFileDiagnostics, pushDiagnostic); for (var key in fileDiagnostics) { - ts.forEach(fileDiagnostics[key], pushDiagnostic); + if (ts.hasProperty(fileDiagnostics, key)) { + ts.forEach(fileDiagnostics[key], pushDiagnostic); + } } return ts.sortAndDeduplicateDiagnostics(allDiagnostics); } @@ -7347,7 +6943,9 @@ var ts; diagnosticsModified = false; nonFileDiagnostics = ts.sortAndDeduplicateDiagnostics(nonFileDiagnostics); for (var key in fileDiagnostics) { - fileDiagnostics[key] = ts.sortAndDeduplicateDiagnostics(fileDiagnostics[key]); + if (ts.hasProperty(fileDiagnostics, key)) { + fileDiagnostics[key] = ts.sortAndDeduplicateDiagnostics(fileDiagnostics[key]); + } } } } @@ -7358,7 +6956,7 @@ var ts; // the map below must be updated. Note that this regexp *does not* include the 'delete' character. // There is no reason for this other than that JSON.stringify does not handle it either. var escapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; - var escapedCharsMap = ts.createMap({ + var escapedCharsMap = { "\0": "\\0", "\t": "\\t", "\v": "\\v", @@ -7371,7 +6969,7 @@ var ts; "\u2028": "\\u2028", "\u2029": "\\u2029", "\u0085": "\\u0085" // nextLine - }); + }; /** * Based heavily on the abstract 'Quote'/'QuoteJSONString' operation from ECMA-262 (24.3.2.2), * but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine) @@ -7511,13 +7109,25 @@ var ts; function getDeclarationEmitOutputFilePath(sourceFile, host) { var options = host.getCompilerOptions(); var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified - var path = outputDir - ? getSourceFilePathInNewDir(sourceFile, host, outputDir) - : sourceFile.fileName; - return ts.removeFileExtension(path) + ".d.ts"; + if (options.declaration) { + var path = outputDir + ? getSourceFilePathInNewDir(sourceFile, host, outputDir) + : sourceFile.fileName; + return ts.removeFileExtension(path) + ".d.ts"; + } } ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; - function forEachExpectedEmitFile(host, action, targetSourceFile, emitOnlyDtsFiles) { + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0 /* ES3 */; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return typeof compilerOptions.module === "number" ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) === 2 /* ES6 */ ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; + } + ts.getEmitModuleKind = getEmitModuleKind; + function forEachExpectedEmitFile(host, action, targetSourceFile) { var options = host.getCompilerOptions(); // Emit on each source file if (options.outFile || options.out) { @@ -7550,13 +7160,12 @@ var ts; } } var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); - var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; var emitFileNames = { jsFilePath: jsFilePath, sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), - declarationFilePath: declarationFilePath + declarationFilePath: !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined }; - action(emitFileNames, [sourceFile], /*isBundledEmit*/ false, emitOnlyDtsFiles); + action(emitFileNames, [sourceFile], /*isBundledEmit*/ false); } function onBundledEmit(host) { // Can emit only sources that are not declaration file and are either non module code or module with @@ -7564,7 +7173,7 @@ var ts; var bundledSources = ts.filter(host.getSourceFiles(), function (sourceFile) { return !isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile) && (!ts.isExternalModule(sourceFile) || - !!ts.getEmitModuleKind(options)); }); + !!getEmitModuleKind(options)); }); if (bundledSources.length) { var jsFilePath = options.outFile || options.out; var emitFileNames = { @@ -7572,7 +7181,7 @@ var ts; sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), declarationFilePath: options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined }; - action(emitFileNames, bundledSources, /*isBundledEmit*/ true, emitOnlyDtsFiles); + action(emitFileNames, bundledSources, /*isBundledEmit*/ true); } } function getSourceMapFilePath(jsFilePath, options) { @@ -7903,11 +7512,23 @@ var ts; isClassLike(node.parent.parent); } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; - function isEntityNameExpression(node) { - return node.kind === 69 /* Identifier */ || - node.kind === 172 /* PropertyAccessExpression */ && isEntityNameExpression(node.expression); + // Returns false if this heritage clause element's expression contains something unsupported + // (i.e. not a name or dotted name). + function isSupportedExpressionWithTypeArguments(node) { + return isSupportedExpressionWithTypeArgumentsRest(node.expression); + } + ts.isSupportedExpressionWithTypeArguments = isSupportedExpressionWithTypeArguments; + function isSupportedExpressionWithTypeArgumentsRest(node) { + if (node.kind === 69 /* Identifier */) { + return true; + } + else if (isPropertyAccessExpression(node)) { + return isSupportedExpressionWithTypeArgumentsRest(node.expression); + } + else { + return false; + } } - ts.isEntityNameExpression = isEntityNameExpression; function isRightSideOfQualifiedNameOrPropertyAccess(node) { return (node.parent.kind === 139 /* QualifiedName */ && node.parent.right === node) || (node.parent.kind === 172 /* PropertyAccessExpression */ && node.parent.name === node); @@ -7928,11 +7549,14 @@ var ts; return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & 512 /* Default */) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; - /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ - function tryExtractTypeScriptExtension(fileName) { - return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function hasJavaScriptFileExtension(fileName) { + return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; + ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; + function hasTypeScriptFileExtension(fileName) { + return ts.forEach(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; /** * Replace each instance of non-ascii characters by one, two, three, or four escape sequences * representing the UTF-8 encoding of the character, and return the expanded char code list. @@ -8002,7 +7626,7 @@ var ts; return (memo ? memo + "," : memo) + stringifyValue(value); } function stringifyObject(value) { - return "{" + ts.reduceOwnProperties(value, stringifyProperty, "") + "}"; + return "{" + ts.reduceProperties(value, stringifyProperty, "") + "}"; } function stringifyProperty(memo, value, key) { return value === undefined || typeof value === "function" || key === "__cycle" ? memo @@ -8292,25 +7916,27 @@ var ts; return node.flags & 92 /* ParameterPropertyModifier */ && node.parent.kind === 148 /* Constructor */ && ts.isClassLike(node.parent.parent); } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; + function startsWith(str, prefix) { + return str.lastIndexOf(prefix, 0) === 0; + } + ts.startsWith = startsWith; + function endsWith(str, suffix) { + var expectedPos = str.length - suffix.length; + return str.indexOf(suffix, expectedPos) === expectedPos; + } + ts.endsWith = endsWith; })(ts || (ts = {})); /// /// var ts; (function (ts) { + /* @internal */ ts.parseTime = 0; var NodeConstructor; - var TokenConstructor; - var IdentifierConstructor; var SourceFileConstructor; function createNode(kind, pos, end) { if (kind === 256 /* SourceFile */) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); } - else if (kind === 69 /* Identifier */) { - return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); - } - else if (kind < 139 /* FirstNode */) { - return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end); - } else { return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end); } @@ -8426,8 +8052,6 @@ var ts; return visitNodes(cbNodes, node.types); case 164 /* ParenthesizedType */: return visitNode(cbNode, node.type); - case 166 /* LiteralType */: - return visitNode(cbNode, node.literal); case 167 /* ObjectBindingPattern */: case 168 /* ArrayBindingPattern */: return visitNodes(cbNodes, node.elements); @@ -8706,17 +8330,14 @@ var ts; case 280 /* JSDocPropertyTag */: return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); - case 282 /* JSDocLiteralType */: - return visitNode(cbNode, node.literal); } } ts.forEachChild = forEachChild; function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { if (setParentNodes === void 0) { setParentNodes = false; } - ts.performance.mark("beforeParse"); + var start = new Date().getTime(); var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); - ts.performance.mark("afterParse"); - ts.performance.measure("Parse", "beforeParse", "afterParse"); + ts.parseTime += new Date().getTime() - start; return result; } ts.createSourceFile = createSourceFile; @@ -8743,7 +8364,7 @@ var ts; if (result && result.jsDocComment) { // because the jsDocComment was parsed out of the source file, it might // not be covered by the fixupParentReferences. - fixupParentReferences(result.jsDocComment); + Parser.fixupParentReferences(result.jsDocComment); } return result; } @@ -8754,37 +8375,6 @@ var ts; return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length); } ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; - /* @internal */ - function fixupParentReferences(rootNode) { - // normally parent references are set during binding. However, for clients that only need - // a syntax tree, and no semantic features, then the binding process is an unnecessary - // overhead. This functions allows us to set all the parents, without all the expense of - // binding. - var parent = rootNode; - forEachChild(rootNode, visitNode); - return; - function visitNode(n) { - // walk down setting parents that differ from the parent we think it should be. This - // allows us to quickly bail out of setting parents for subtrees during incremental - // parsing - if (n.parent !== parent) { - n.parent = parent; - var saveParent = parent; - parent = n; - forEachChild(n, visitNode); - if (n.jsDocComments) { - for (var _i = 0, _a = n.jsDocComments; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - jsDocComment.parent = n; - parent = jsDocComment; - forEachChild(jsDocComment, visitNode); - } - } - parent = saveParent; - } - } - } - ts.fixupParentReferences = fixupParentReferences; // Implement the parser as a singleton module. We do this for perf reasons because creating // parser instances can actually be expensive enough to impact us on projects with many source // files. @@ -8796,13 +8386,11 @@ var ts; var disallowInAndDecoratorContext = 4194304 /* DisallowInContext */ | 16777216 /* DecoratorContext */; // capture constructors in 'initializeState' to avoid null checks var NodeConstructor; - var TokenConstructor; - var IdentifierConstructor; var SourceFileConstructor; var sourceFile; var parseDiagnostics; var syntaxCursor; - var currentToken; + var token; var sourceText; var nodeCount; var identifiers; @@ -8897,14 +8485,12 @@ var ts; } function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind) { NodeConstructor = ts.objectAllocator.getNodeConstructor(); - TokenConstructor = ts.objectAllocator.getTokenConstructor(); - IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor(); SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor(); sourceText = _sourceText; syntaxCursor = _syntaxCursor; parseDiagnostics = []; parsingContext = 0; - identifiers = ts.createMap(); + identifiers = {}; identifierCount = 0; nodeCount = 0; contextFlags = scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */ ? 134217728 /* JavaScriptFile */ : 0 /* None */; @@ -8930,10 +8516,10 @@ var ts; sourceFile = createSourceFile(fileName, languageVersion, scriptKind); sourceFile.flags = contextFlags; // Prime the scanner. - nextToken(); + token = nextToken(); processReferenceComments(sourceFile); sourceFile.statements = parseList(0 /* SourceElements */, parseStatement); - ts.Debug.assert(token() === 1 /* EndOfFileToken */); + ts.Debug.assert(token === 1 /* EndOfFileToken */); sourceFile.endOfFileToken = parseTokenNode(); setExternalModuleIndicator(sourceFile); sourceFile.nodeCount = nodeCount; @@ -8964,6 +8550,36 @@ var ts; } return node; } + function fixupParentReferences(rootNode) { + // normally parent references are set during binding. However, for clients that only need + // a syntax tree, and no semantic features, then the binding process is an unnecessary + // overhead. This functions allows us to set all the parents, without all the expense of + // binding. + var parent = rootNode; + forEachChild(rootNode, visitNode); + return; + function visitNode(n) { + // walk down setting parents that differ from the parent we think it should be. This + // allows us to quickly bail out of setting parents for subtrees during incremental + // parsing + if (n.parent !== parent) { + n.parent = parent; + var saveParent = parent; + parent = n; + forEachChild(n, visitNode); + if (n.jsDocComments) { + for (var _i = 0, _a = n.jsDocComments; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + jsDocComment.parent = n; + parent = jsDocComment; + forEachChild(jsDocComment, visitNode); + } + } + parent = saveParent; + } + } + } + Parser.fixupParentReferences = fixupParentReferences; function createSourceFile(fileName, languageVersion, scriptKind) { // code from createNode is inlined here so createNode won't have to deal with special case of creating source files // this is quite rare comparing to other nodes and createNode should be as fast as possible @@ -9097,43 +8713,34 @@ var ts; function getNodeEnd() { return scanner.getStartPos(); } - // Use this function to access the current token instead of reading the currentToken - // variable. Since function results aren't narrowed in control flow analysis, this ensures - // that the type checker doesn't make wrong assumptions about the type of the current - // token (e.g. a call to nextToken() changes the current token but the checker doesn't - // reason about this side effect). Mainstream VMs inline simple functions like this, so - // there is no performance penalty. - function token() { - return currentToken; - } function nextToken() { - return currentToken = scanner.scan(); + return token = scanner.scan(); } function reScanGreaterToken() { - return currentToken = scanner.reScanGreaterToken(); + return token = scanner.reScanGreaterToken(); } function reScanSlashToken() { - return currentToken = scanner.reScanSlashToken(); + return token = scanner.reScanSlashToken(); } function reScanTemplateToken() { - return currentToken = scanner.reScanTemplateToken(); + return token = scanner.reScanTemplateToken(); } function scanJsxIdentifier() { - return currentToken = scanner.scanJsxIdentifier(); + return token = scanner.scanJsxIdentifier(); } function scanJsxText() { - return currentToken = scanner.scanJsxToken(); + return token = scanner.scanJsxToken(); } function speculationHelper(callback, isLookAhead) { // Keep track of the state we'll need to rollback to if lookahead fails (or if the // caller asked us to always reset our state). - var saveToken = currentToken; + var saveToken = token; var saveParseDiagnosticsLength = parseDiagnostics.length; var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; // Note: it is not actually necessary to save/restore the context flags here. That's // because the saving/restoring of these flags happens naturally through the recursive // descent nature of our parser. However, we still store this here just so we can - // assert that invariant holds. + // assert that that invariant holds. var saveContextFlags = contextFlags; // If we're only looking ahead, then tell the scanner to only lookahead as well. // Otherwise, if we're actually speculatively parsing, then tell the scanner to do the @@ -9145,7 +8752,7 @@ var ts; // If our callback returned something 'falsy' or we're just looking ahead, // then unconditionally restore us to where we were. if (!result || isLookAhead) { - currentToken = saveToken; + token = saveToken; parseDiagnostics.length = saveParseDiagnosticsLength; parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; } @@ -9168,24 +8775,24 @@ var ts; } // Ignore strict mode flag because we will report an error in type checker instead. function isIdentifier() { - if (token() === 69 /* Identifier */) { + if (token === 69 /* Identifier */) { return true; } // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is // considered a keyword and is not an identifier. - if (token() === 114 /* YieldKeyword */ && inYieldContext()) { + if (token === 114 /* YieldKeyword */ && inYieldContext()) { return false; } // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is // considered a keyword and is not an identifier. - if (token() === 119 /* AwaitKeyword */ && inAwaitContext()) { + if (token === 119 /* AwaitKeyword */ && inAwaitContext()) { return false; } - return token() > 105 /* LastReservedWord */; + return token > 105 /* LastReservedWord */; } function parseExpected(kind, diagnosticMessage, shouldAdvance) { if (shouldAdvance === void 0) { shouldAdvance = true; } - if (token() === kind) { + if (token === kind) { if (shouldAdvance) { nextToken(); } @@ -9201,14 +8808,14 @@ var ts; return false; } function parseOptional(t) { - if (token() === t) { + if (token === t) { nextToken(); return true; } return false; } function parseOptionalToken(t) { - if (token() === t) { + if (token === t) { return parseTokenNode(); } return undefined; @@ -9218,21 +8825,21 @@ var ts; createMissingNode(t, reportAtCurrentPosition, diagnosticMessage, arg0); } function parseTokenNode() { - var node = createNode(token()); + var node = createNode(token); nextToken(); return finishNode(node); } function canParseSemicolon() { // If there's a real semicolon, then we can always parse it out. - if (token() === 23 /* SemicolonToken */) { + if (token === 23 /* SemicolonToken */) { return true; } // We can parse out an optional semicolon in ASI cases in the following cases. - return token() === 16 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); + return token === 16 /* CloseBraceToken */ || token === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); } function parseSemicolon() { if (canParseSemicolon()) { - if (token() === 23 /* SemicolonToken */) { + if (token === 23 /* SemicolonToken */) { // consume the semicolon if it was explicitly provided. nextToken(); } @@ -9248,9 +8855,7 @@ var ts; if (!(pos >= 0)) { pos = scanner.getStartPos(); } - return kind >= 139 /* FirstNode */ ? new NodeConstructor(kind, pos, pos) : - kind === 69 /* Identifier */ ? new IdentifierConstructor(kind, pos, pos) : - new TokenConstructor(kind, pos, pos); + return new NodeConstructor(kind, pos, pos); } function finishNode(node, end) { node.end = end === undefined ? scanner.getStartPos() : end; @@ -9279,7 +8884,7 @@ var ts; } function internIdentifier(text) { text = ts.escapeIdentifier(text); - return identifiers[text] || (identifiers[text] = text); + return ts.hasProperty(identifiers, text) ? identifiers[text] : (identifiers[text] = text); } // An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for @@ -9289,8 +8894,8 @@ var ts; if (isIdentifier) { var node = createNode(69 /* Identifier */); // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker - if (token() !== 69 /* Identifier */) { - node.originalKeywordKind = token(); + if (token !== 69 /* Identifier */) { + node.originalKeywordKind = token; } node.text = internIdentifier(scanner.getTokenValue()); nextToken(); @@ -9302,18 +8907,18 @@ var ts; return createIdentifier(isIdentifier(), diagnosticMessage); } function parseIdentifierName() { - return createIdentifier(ts.tokenIsIdentifierOrKeyword(token())); + return createIdentifier(ts.tokenIsIdentifierOrKeyword(token)); } function isLiteralPropertyName() { - return ts.tokenIsIdentifierOrKeyword(token()) || - token() === 9 /* StringLiteral */ || - token() === 8 /* NumericLiteral */; + return ts.tokenIsIdentifierOrKeyword(token) || + token === 9 /* StringLiteral */ || + token === 8 /* NumericLiteral */; } function parsePropertyNameWorker(allowComputedPropertyNames) { - if (token() === 9 /* StringLiteral */ || token() === 8 /* NumericLiteral */) { + if (token === 9 /* StringLiteral */ || token === 8 /* NumericLiteral */) { return parseLiteralNode(/*internName*/ true); } - if (allowComputedPropertyNames && token() === 19 /* OpenBracketToken */) { + if (allowComputedPropertyNames && token === 19 /* OpenBracketToken */) { return parseComputedPropertyName(); } return parseIdentifierName(); @@ -9325,7 +8930,7 @@ var ts; return parsePropertyNameWorker(/*allowComputedPropertyNames*/ false); } function isSimplePropertyName() { - return token() === 9 /* StringLiteral */ || token() === 8 /* NumericLiteral */ || ts.tokenIsIdentifierOrKeyword(token()); + return token === 9 /* StringLiteral */ || token === 8 /* NumericLiteral */ || ts.tokenIsIdentifierOrKeyword(token); } function parseComputedPropertyName() { // PropertyName [Yield]: @@ -9341,7 +8946,7 @@ var ts; return finishNode(node); } function parseContextualModifier(t) { - return token() === t && tryParse(nextTokenCanFollowModifier); + return token === t && tryParse(nextTokenCanFollowModifier); } function nextTokenIsOnSameLineAndCanFollowModifier() { nextToken(); @@ -9351,40 +8956,40 @@ var ts; return canFollowModifier(); } function nextTokenCanFollowModifier() { - if (token() === 74 /* ConstKeyword */) { + if (token === 74 /* ConstKeyword */) { // 'const' is only a modifier if followed by 'enum'. return nextToken() === 81 /* EnumKeyword */; } - if (token() === 82 /* ExportKeyword */) { + if (token === 82 /* ExportKeyword */) { nextToken(); - if (token() === 77 /* DefaultKeyword */) { + if (token === 77 /* DefaultKeyword */) { return lookAhead(nextTokenIsClassOrFunctionOrAsync); } - return token() !== 37 /* AsteriskToken */ && token() !== 116 /* AsKeyword */ && token() !== 15 /* OpenBraceToken */ && canFollowModifier(); + return token !== 37 /* AsteriskToken */ && token !== 116 /* AsKeyword */ && token !== 15 /* OpenBraceToken */ && canFollowModifier(); } - if (token() === 77 /* DefaultKeyword */) { + if (token === 77 /* DefaultKeyword */) { return nextTokenIsClassOrFunctionOrAsync(); } - if (token() === 113 /* StaticKeyword */) { + if (token === 113 /* StaticKeyword */) { nextToken(); return canFollowModifier(); } return nextTokenIsOnSameLineAndCanFollowModifier(); } function parseAnyContextualModifier() { - return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); + return ts.isModifierKind(token) && tryParse(nextTokenCanFollowModifier); } function canFollowModifier() { - return token() === 19 /* OpenBracketToken */ - || token() === 15 /* OpenBraceToken */ - || token() === 37 /* AsteriskToken */ - || token() === 22 /* DotDotDotToken */ + return token === 19 /* OpenBracketToken */ + || token === 15 /* OpenBraceToken */ + || token === 37 /* AsteriskToken */ + || token === 22 /* DotDotDotToken */ || isLiteralPropertyName(); } function nextTokenIsClassOrFunctionOrAsync() { nextToken(); - return token() === 73 /* ClassKeyword */ || token() === 87 /* FunctionKeyword */ || - (token() === 118 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); + return token === 73 /* ClassKeyword */ || token === 87 /* FunctionKeyword */ || + (token === 118 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); } // True if positioned at the start of a list element function isListElement(parsingContext, inErrorRecovery) { @@ -9402,9 +9007,9 @@ var ts; // we're parsing. For example, if we have a semicolon in the middle of a class, then // we really don't want to assume the class is over and we're on a statement in the // outer module. We just want to consume and move on. - return !(token() === 23 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); + return !(token === 23 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); case 2 /* SwitchClauses */: - return token() === 71 /* CaseKeyword */ || token() === 77 /* DefaultKeyword */; + return token === 71 /* CaseKeyword */ || token === 77 /* DefaultKeyword */; case 4 /* TypeMembers */: return lookAhead(isTypeMemberStart); case 5 /* ClassMembers */: @@ -9412,19 +9017,19 @@ var ts; // not in error recovery. If we're in error recovery, we don't want an errant // semicolon to be treated as a class member (since they're almost always used // for statements. - return lookAhead(isClassMemberStart) || (token() === 23 /* SemicolonToken */ && !inErrorRecovery); + return lookAhead(isClassMemberStart) || (token === 23 /* SemicolonToken */ && !inErrorRecovery); case 6 /* EnumMembers */: // Include open bracket computed properties. This technically also lets in indexers, // which would be a candidate for improved error reporting. - return token() === 19 /* OpenBracketToken */ || isLiteralPropertyName(); + return token === 19 /* OpenBracketToken */ || isLiteralPropertyName(); case 12 /* ObjectLiteralMembers */: - return token() === 19 /* OpenBracketToken */ || token() === 37 /* AsteriskToken */ || isLiteralPropertyName(); + return token === 19 /* OpenBracketToken */ || token === 37 /* AsteriskToken */ || isLiteralPropertyName(); case 9 /* ObjectBindingElements */: - return token() === 19 /* OpenBracketToken */ || isLiteralPropertyName(); + return token === 19 /* OpenBracketToken */ || isLiteralPropertyName(); case 7 /* HeritageClauseElement */: // If we see { } then only consume it as an expression if it is followed by , or { // That way we won't consume the body of a class in its heritage clause. - if (token() === 15 /* OpenBraceToken */) { + if (token === 15 /* OpenBraceToken */) { return lookAhead(isValidHeritageClauseObjectLiteral); } if (!inErrorRecovery) { @@ -9439,23 +9044,23 @@ var ts; case 8 /* VariableDeclarations */: return isIdentifierOrPattern(); case 10 /* ArrayBindingElements */: - return token() === 24 /* CommaToken */ || token() === 22 /* DotDotDotToken */ || isIdentifierOrPattern(); + return token === 24 /* CommaToken */ || token === 22 /* DotDotDotToken */ || isIdentifierOrPattern(); case 17 /* TypeParameters */: return isIdentifier(); case 11 /* ArgumentExpressions */: case 15 /* ArrayLiteralMembers */: - return token() === 24 /* CommaToken */ || token() === 22 /* DotDotDotToken */ || isStartOfExpression(); + return token === 24 /* CommaToken */ || token === 22 /* DotDotDotToken */ || isStartOfExpression(); case 16 /* Parameters */: return isStartOfParameter(); case 18 /* TypeArguments */: case 19 /* TupleElementTypes */: - return token() === 24 /* CommaToken */ || isStartOfType(); + return token === 24 /* CommaToken */ || isStartOfType(); case 20 /* HeritageClauses */: return isHeritageClause(); case 21 /* ImportOrExportSpecifiers */: - return ts.tokenIsIdentifierOrKeyword(token()); + return ts.tokenIsIdentifierOrKeyword(token); case 13 /* JsxAttributes */: - return ts.tokenIsIdentifierOrKeyword(token()) || token() === 15 /* OpenBraceToken */; + return ts.tokenIsIdentifierOrKeyword(token) || token === 15 /* OpenBraceToken */; case 14 /* JsxChildren */: return true; case 22 /* JSDocFunctionParameters */: @@ -9468,7 +9073,7 @@ var ts; ts.Debug.fail("Non-exhaustive case in 'isListElement'."); } function isValidHeritageClauseObjectLiteral() { - ts.Debug.assert(token() === 15 /* OpenBraceToken */); + ts.Debug.assert(token === 15 /* OpenBraceToken */); if (nextToken() === 16 /* CloseBraceToken */) { // if we see "extends {}" then only treat the {} as what we're extending (and not // the class body) if we have: @@ -9488,11 +9093,11 @@ var ts; } function nextTokenIsIdentifierOrKeyword() { nextToken(); - return ts.tokenIsIdentifierOrKeyword(token()); + return ts.tokenIsIdentifierOrKeyword(token); } function isHeritageClauseExtendsOrImplementsKeyword() { - if (token() === 106 /* ImplementsKeyword */ || - token() === 83 /* ExtendsKeyword */) { + if (token === 106 /* ImplementsKeyword */ || + token === 83 /* ExtendsKeyword */) { return lookAhead(nextTokenIsStartOfExpression); } return false; @@ -9503,7 +9108,7 @@ var ts; } // True if positioned at a list terminator function isListTerminator(kind) { - if (token() === 1 /* EndOfFileToken */) { + if (token === 1 /* EndOfFileToken */) { // Being at the end of the file ends all lists. return true; } @@ -9516,43 +9121,43 @@ var ts; case 12 /* ObjectLiteralMembers */: case 9 /* ObjectBindingElements */: case 21 /* ImportOrExportSpecifiers */: - return token() === 16 /* CloseBraceToken */; + return token === 16 /* CloseBraceToken */; case 3 /* SwitchClauseStatements */: - return token() === 16 /* CloseBraceToken */ || token() === 71 /* CaseKeyword */ || token() === 77 /* DefaultKeyword */; + return token === 16 /* CloseBraceToken */ || token === 71 /* CaseKeyword */ || token === 77 /* DefaultKeyword */; case 7 /* HeritageClauseElement */: - return token() === 15 /* OpenBraceToken */ || token() === 83 /* ExtendsKeyword */ || token() === 106 /* ImplementsKeyword */; + return token === 15 /* OpenBraceToken */ || token === 83 /* ExtendsKeyword */ || token === 106 /* ImplementsKeyword */; case 8 /* VariableDeclarations */: return isVariableDeclaratorListTerminator(); case 17 /* TypeParameters */: // Tokens other than '>' are here for better error recovery - return token() === 27 /* GreaterThanToken */ || token() === 17 /* OpenParenToken */ || token() === 15 /* OpenBraceToken */ || token() === 83 /* ExtendsKeyword */ || token() === 106 /* ImplementsKeyword */; + return token === 27 /* GreaterThanToken */ || token === 17 /* OpenParenToken */ || token === 15 /* OpenBraceToken */ || token === 83 /* ExtendsKeyword */ || token === 106 /* ImplementsKeyword */; case 11 /* ArgumentExpressions */: // Tokens other than ')' are here for better error recovery - return token() === 18 /* CloseParenToken */ || token() === 23 /* SemicolonToken */; + return token === 18 /* CloseParenToken */ || token === 23 /* SemicolonToken */; case 15 /* ArrayLiteralMembers */: case 19 /* TupleElementTypes */: case 10 /* ArrayBindingElements */: - return token() === 20 /* CloseBracketToken */; + return token === 20 /* CloseBracketToken */; case 16 /* Parameters */: // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery - return token() === 18 /* CloseParenToken */ || token() === 20 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; + return token === 18 /* CloseParenToken */ || token === 20 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; case 18 /* TypeArguments */: // Tokens other than '>' are here for better error recovery - return token() === 27 /* GreaterThanToken */ || token() === 17 /* OpenParenToken */; + return token === 27 /* GreaterThanToken */ || token === 17 /* OpenParenToken */; case 20 /* HeritageClauses */: - return token() === 15 /* OpenBraceToken */ || token() === 16 /* CloseBraceToken */; + return token === 15 /* OpenBraceToken */ || token === 16 /* CloseBraceToken */; case 13 /* JsxAttributes */: - return token() === 27 /* GreaterThanToken */ || token() === 39 /* SlashToken */; + return token === 27 /* GreaterThanToken */ || token === 39 /* SlashToken */; case 14 /* JsxChildren */: - return token() === 25 /* LessThanToken */ && lookAhead(nextTokenIsSlash); + return token === 25 /* LessThanToken */ && lookAhead(nextTokenIsSlash); case 22 /* JSDocFunctionParameters */: - return token() === 18 /* CloseParenToken */ || token() === 54 /* ColonToken */ || token() === 16 /* CloseBraceToken */; + return token === 18 /* CloseParenToken */ || token === 54 /* ColonToken */ || token === 16 /* CloseBraceToken */; case 23 /* JSDocTypeArguments */: - return token() === 27 /* GreaterThanToken */ || token() === 16 /* CloseBraceToken */; + return token === 27 /* GreaterThanToken */ || token === 16 /* CloseBraceToken */; case 25 /* JSDocTupleTypes */: - return token() === 20 /* CloseBracketToken */ || token() === 16 /* CloseBraceToken */; + return token === 20 /* CloseBracketToken */ || token === 16 /* CloseBraceToken */; case 24 /* JSDocRecordMembers */: - return token() === 16 /* CloseBraceToken */; + return token === 16 /* CloseBraceToken */; } } function isVariableDeclaratorListTerminator() { @@ -9563,14 +9168,14 @@ var ts; } // in the case where we're parsing the variable declarator of a 'for-in' statement, we // are done if we see an 'in' keyword in front of us. Same with for-of - if (isInOrOfKeyword(token())) { + if (isInOrOfKeyword(token)) { return true; } // ERROR RECOVERY TWEAK: // For better error recovery, if we see an '=>' then we just stop immediately. We've got an // arrow function here and it's going to be very unlikely that we'll resynchronize and get // another variable declaration. - if (token() === 34 /* EqualsGreaterThanToken */) { + if (token === 34 /* EqualsGreaterThanToken */) { return true; } // Keep trying to parse out variable declarators. @@ -9911,7 +9516,7 @@ var ts; // parse errors. For example, this can happen when people do things like use // a semicolon to delimit object literal members. Note: we'll have already // reported an error when we called parseExpected above. - if (considerSemicolonAsDelimiter && token() === 23 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) { + if (considerSemicolonAsDelimiter && token === 23 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) { nextToken(); } continue; @@ -9982,7 +9587,7 @@ var ts; // the code would be implicitly: "name.identifierOrKeyword; identifierNameOrKeyword". // In the first case though, ASI will not take effect because there is not a // line terminator after the identifier or keyword. - if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) { + if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token)) { var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); if (matchesPattern) { // Report that we need an identifier. However, report it right after the dot, @@ -10010,7 +9615,7 @@ var ts; var span = createNode(197 /* TemplateSpan */); span.expression = allowInAnd(parseExpression); var literal; - if (token() === 16 /* CloseBraceToken */) { + if (token === 16 /* CloseBraceToken */) { reScanTemplateToken(); literal = parseTemplateLiteralFragment(); } @@ -10020,11 +9625,14 @@ var ts; span.literal = literal; return finishNode(span); } + function parseStringLiteralTypeNode() { + return parseLiteralLikeNode(166 /* StringLiteralType */, /*internName*/ true); + } function parseLiteralNode(internName) { - return parseLiteralLikeNode(token(), internName); + return parseLiteralLikeNode(token, internName); } function parseTemplateLiteralFragment() { - return parseLiteralLikeNode(token(), /*internName*/ false); + return parseLiteralLikeNode(token, /*internName*/ false); } function parseLiteralLikeNode(kind, internName) { var node = createNode(kind); @@ -10057,7 +9665,7 @@ var ts; var typeName = parseEntityName(/*allowReservedWords*/ false, ts.Diagnostics.Type_expected); var node = createNode(155 /* TypeReference */, typeName.pos); node.typeName = typeName; - if (!scanner.hasPrecedingLineBreak() && token() === 25 /* LessThanToken */) { + if (!scanner.hasPrecedingLineBreak() && token === 25 /* LessThanToken */) { node.typeArguments = parseBracketedList(18 /* TypeArguments */, parseType, 25 /* LessThanToken */, 27 /* GreaterThanToken */); } return finishNode(node); @@ -10105,7 +9713,7 @@ var ts; return finishNode(node); } function parseTypeParameters() { - if (token() === 25 /* LessThanToken */) { + if (token === 25 /* LessThanToken */) { return parseBracketedList(17 /* TypeParameters */, parseTypeParameter, 25 /* LessThanToken */, 27 /* GreaterThanToken */); } } @@ -10116,7 +9724,7 @@ var ts; return undefined; } function isStartOfParameter() { - return token() === 22 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 55 /* AtToken */ || token() === 97 /* ThisKeyword */; + return token === 22 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token) || token === 55 /* AtToken */ || token === 97 /* ThisKeyword */; } function setModifiers(node, modifiers) { if (modifiers) { @@ -10126,7 +9734,7 @@ var ts; } function parseParameter() { var node = createNode(142 /* Parameter */); - if (token() === 97 /* ThisKeyword */) { + if (token === 97 /* ThisKeyword */) { node.name = createIdentifier(/*isIdentifier*/ true, undefined); node.type = parseParameterType(); return finishNode(node); @@ -10137,7 +9745,7 @@ var ts; // FormalParameter [Yield,Await]: // BindingElement[?Yield,?Await] node.name = parseIdentifierOrPattern(); - if (ts.getFullWidth(node.name) === 0 && node.flags === 0 && ts.isModifierKind(token())) { + if (ts.getFullWidth(node.name) === 0 && node.flags === 0 && ts.isModifierKind(token)) { // in cases like // 'use strict' // function foo(static) @@ -10232,7 +9840,7 @@ var ts; return finishNode(node); } function isIndexSignature() { - if (token() !== 19 /* OpenBracketToken */) { + if (token !== 19 /* OpenBracketToken */) { return false; } return lookAhead(isUnambiguouslyIndexSignature); @@ -10255,10 +9863,10 @@ var ts; // [] // nextToken(); - if (token() === 22 /* DotDotDotToken */ || token() === 20 /* CloseBracketToken */) { + if (token === 22 /* DotDotDotToken */ || token === 20 /* CloseBracketToken */) { return true; } - if (ts.isModifierKind(token())) { + if (ts.isModifierKind(token)) { nextToken(); if (isIdentifier()) { return true; @@ -10274,18 +9882,18 @@ var ts; // A colon signifies a well formed indexer // A comma should be a badly formed indexer because comma expressions are not allowed // in computed properties. - if (token() === 54 /* ColonToken */ || token() === 24 /* CommaToken */) { + if (token === 54 /* ColonToken */ || token === 24 /* CommaToken */) { return true; } // Question mark could be an indexer with an optional property, // or it could be a conditional expression in a computed property. - if (token() !== 53 /* QuestionToken */) { + if (token !== 53 /* QuestionToken */) { return false; } // If any of the following tokens are after the question mark, it cannot // be a conditional expression, so treat it as an indexer. nextToken(); - return token() === 54 /* ColonToken */ || token() === 24 /* CommaToken */ || token() === 20 /* CloseBracketToken */; + return token === 54 /* ColonToken */ || token === 24 /* CommaToken */ || token === 20 /* CloseBracketToken */; } function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { var node = createNode(153 /* IndexSignature */, fullStart); @@ -10299,7 +9907,7 @@ var ts; function parsePropertyOrMethodSignature(fullStart, modifiers) { var name = parsePropertyName(); var questionToken = parseOptionalToken(53 /* QuestionToken */); - if (token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */) { + if (token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */) { var method = createNode(146 /* MethodSignature */, fullStart); setModifiers(method, modifiers); method.name = name; @@ -10316,7 +9924,7 @@ var ts; property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); - if (token() === 56 /* EqualsToken */) { + if (token === 56 /* EqualsToken */) { // Although type literal properties cannot not have initializers, we attempt // to parse an initializer so we can report in the checker that an interface // property or type literal property cannot have an initializer. @@ -10329,40 +9937,39 @@ var ts; function isTypeMemberStart() { var idToken; // Return true if we have the start of a signature member - if (token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */) { + if (token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */) { return true; } // Eat up all modifiers, but hold on to the last one in case it is actually an identifier - while (ts.isModifierKind(token())) { - idToken = token(); + while (ts.isModifierKind(token)) { + idToken = token; nextToken(); } // Index signatures and computed property names are type members - if (token() === 19 /* OpenBracketToken */) { + if (token === 19 /* OpenBracketToken */) { return true; } // Try to get the first property-like token following all modifiers if (isLiteralPropertyName()) { - idToken = token(); + idToken = token; nextToken(); } // If we were able to get any potential identifier, check that it is // the start of a member declaration if (idToken) { - return token() === 17 /* OpenParenToken */ || - token() === 25 /* LessThanToken */ || - token() === 53 /* QuestionToken */ || - token() === 54 /* ColonToken */ || - token() === 24 /* CommaToken */ || + return token === 17 /* OpenParenToken */ || + token === 25 /* LessThanToken */ || + token === 53 /* QuestionToken */ || + token === 54 /* ColonToken */ || canParseSemicolon(); } return false; } function parseTypeMember() { - if (token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */) { + if (token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */) { return parseSignatureMember(151 /* CallSignature */); } - if (token() === 92 /* NewKeyword */ && lookAhead(isStartOfConstructSignature)) { + if (token === 92 /* NewKeyword */ && lookAhead(isStartOfConstructSignature)) { return parseSignatureMember(152 /* ConstructSignature */); } var fullStart = getNodePos(); @@ -10374,7 +9981,7 @@ var ts; } function isStartOfConstructSignature() { nextToken(); - return token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */; + return token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */; } function parseTypeLiteral() { var node = createNode(159 /* TypeLiteral */); @@ -10414,19 +10021,10 @@ var ts; } function parseKeywordAndNoDot() { var node = parseTokenNode(); - return token() === 21 /* DotToken */ ? undefined : node; - } - function parseLiteralTypeNode() { - var node = createNode(166 /* LiteralType */); - node.literal = parseSimpleUnaryExpression(); - finishNode(node); - return node; - } - function nextTokenIsNumericLiteral() { - return nextToken() === 8 /* NumericLiteral */; + return token === 21 /* DotToken */ ? undefined : node; } function parseNonArrayType() { - switch (token()) { + switch (token) { case 117 /* AnyKeyword */: case 132 /* StringKeyword */: case 130 /* NumberKeyword */: @@ -10438,18 +10036,13 @@ var ts; var node = tryParse(parseKeywordAndNoDot); return node || parseTypeReference(); case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: - case 99 /* TrueKeyword */: - case 84 /* FalseKeyword */: - return parseLiteralTypeNode(); - case 36 /* MinusToken */: - return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode() : parseTypeReference(); + return parseStringLiteralTypeNode(); case 103 /* VoidKeyword */: case 93 /* NullKeyword */: return parseTokenNode(); case 97 /* ThisKeyword */: { var thisKeyword = parseThisTypeNode(); - if (token() === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + if (token === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { return parseThisTypePredicate(thisKeyword); } else { @@ -10469,7 +10062,7 @@ var ts; } } function isStartOfType() { - switch (token()) { + switch (token) { case 117 /* AnyKeyword */: case 132 /* StringKeyword */: case 130 /* NumberKeyword */: @@ -10486,12 +10079,7 @@ var ts; case 25 /* LessThanToken */: case 92 /* NewKeyword */: case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: - case 99 /* TrueKeyword */: - case 84 /* FalseKeyword */: return true; - case 36 /* MinusToken */: - return lookAhead(nextTokenIsNumericLiteral); case 17 /* OpenParenToken */: // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier, // or something that starts a type. We don't want to consider things like '(1)' a type. @@ -10502,7 +10090,7 @@ var ts; } function isStartOfParenthesizedOrFunctionType() { nextToken(); - return token() === 18 /* CloseParenToken */ || isStartOfParameter() || isStartOfType(); + return token === 18 /* CloseParenToken */ || isStartOfParameter() || isStartOfType(); } function parseArrayTypeOrHigher() { var type = parseNonArrayType(); @@ -10516,7 +10104,7 @@ var ts; } function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { var type = parseConstituentType(); - if (token() === operator) { + if (token === operator) { var types = [type]; types.pos = type.pos; while (parseOptional(operator)) { @@ -10536,21 +10124,21 @@ var ts; return parseUnionOrIntersectionType(162 /* UnionType */, parseIntersectionTypeOrHigher, 47 /* BarToken */); } function isStartOfFunctionType() { - if (token() === 25 /* LessThanToken */) { + if (token === 25 /* LessThanToken */) { return true; } - return token() === 17 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType); + return token === 17 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType); } function skipParameterStart() { - if (ts.isModifierKind(token())) { + if (ts.isModifierKind(token)) { // Skip modifiers parseModifiers(); } - if (isIdentifier() || token() === 97 /* ThisKeyword */) { + if (isIdentifier() || token === 97 /* ThisKeyword */) { nextToken(); return true; } - if (token() === 19 /* OpenBracketToken */ || token() === 15 /* OpenBraceToken */) { + if (token === 19 /* OpenBracketToken */ || token === 15 /* OpenBraceToken */) { // Return true if we can parse an array or object binding pattern with no errors var previousErrorCount = parseDiagnostics.length; parseIdentifierOrPattern(); @@ -10560,7 +10148,7 @@ var ts; } function isUnambiguouslyStartOfFunctionType() { nextToken(); - if (token() === 18 /* CloseParenToken */ || token() === 22 /* DotDotDotToken */) { + if (token === 18 /* CloseParenToken */ || token === 22 /* DotDotDotToken */) { // ( ) // ( ... return true; @@ -10568,17 +10156,17 @@ var ts; if (skipParameterStart()) { // We successfully skipped modifiers (if any) and an identifier or binding pattern, // now see if we have something that indicates a parameter declaration - if (token() === 54 /* ColonToken */ || token() === 24 /* CommaToken */ || - token() === 53 /* QuestionToken */ || token() === 56 /* EqualsToken */) { + if (token === 54 /* ColonToken */ || token === 24 /* CommaToken */ || + token === 53 /* QuestionToken */ || token === 56 /* EqualsToken */) { // ( xxx : // ( xxx , // ( xxx ? // ( xxx = return true; } - if (token() === 18 /* CloseParenToken */) { + if (token === 18 /* CloseParenToken */) { nextToken(); - if (token() === 34 /* EqualsGreaterThanToken */) { + if (token === 34 /* EqualsGreaterThanToken */) { // ( xxx ) => return true; } @@ -10601,7 +10189,7 @@ var ts; } function parseTypePredicatePrefix() { var id = parseIdentifier(); - if (token() === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + if (token === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { nextToken(); return id; } @@ -10615,7 +10203,7 @@ var ts; if (isStartOfFunctionType()) { return parseFunctionOrConstructorType(156 /* FunctionType */); } - if (token() === 92 /* NewKeyword */) { + if (token === 92 /* NewKeyword */) { return parseFunctionOrConstructorType(157 /* ConstructorType */); } return parseUnionTypeOrHigher(); @@ -10625,7 +10213,7 @@ var ts; } // EXPRESSIONS function isStartOfLeftHandSideExpression() { - switch (token()) { + switch (token) { case 97 /* ThisKeyword */: case 95 /* SuperKeyword */: case 93 /* NullKeyword */: @@ -10653,7 +10241,7 @@ var ts; if (isStartOfLeftHandSideExpression()) { return true; } - switch (token()) { + switch (token) { case 35 /* PlusToken */: case 36 /* MinusToken */: case 50 /* TildeToken */: @@ -10683,10 +10271,10 @@ var ts; } function isStartOfExpressionStatement() { // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement. - return token() !== 15 /* OpenBraceToken */ && - token() !== 87 /* FunctionKeyword */ && - token() !== 73 /* ClassKeyword */ && - token() !== 55 /* AtToken */ && + return token !== 15 /* OpenBraceToken */ && + token !== 87 /* FunctionKeyword */ && + token !== 73 /* ClassKeyword */ && + token !== 55 /* AtToken */ && isStartOfExpression(); } function parseExpression() { @@ -10709,7 +10297,7 @@ var ts; return expr; } function parseInitializer(inParameter) { - if (token() !== 56 /* EqualsToken */) { + if (token !== 56 /* EqualsToken */) { // It's not uncommon during typing for the user to miss writing the '=' token. Check if // there is no newline after the last token and if we're on an expression. If so, parse // this as an equals-value clause with a missing equals. @@ -10718,7 +10306,7 @@ var ts; // it's more likely that a { would be a allowed (as an object literal). While this // is also allowed for parameters, the risk is that we consume the { as an object // literal when it really will be for the block following the parameter. - if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 15 /* OpenBraceToken */) || !isStartOfExpression()) { + if (scanner.hasPrecedingLineBreak() || (inParameter && token === 15 /* OpenBraceToken */) || !isStartOfExpression()) { // preceding line break, open brace in a parameter (likely a function body) or current token is not an expression - // do not try to parse initializer return undefined; @@ -10740,7 +10328,7 @@ var ts; // // Note: for ease of implementation we treat productions '2' and '3' as the same thing. // (i.e. they're both BinaryExpressions with an assignment operator in it). - // First, do the simple check if we have a YieldExpression (production '6'). + // First, do the simple check if we have a YieldExpression (production '5'). if (isYieldExpression()) { return parseYieldExpression(); } @@ -10772,7 +10360,7 @@ var ts; // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single // identifier and the current token is an arrow. - if (expr.kind === 69 /* Identifier */ && token() === 34 /* EqualsGreaterThanToken */) { + if (expr.kind === 69 /* Identifier */ && token === 34 /* EqualsGreaterThanToken */) { return parseSimpleArrowFunctionExpression(expr); } // Now see if we might be in cases '2' or '3'. @@ -10788,7 +10376,7 @@ var ts; return parseConditionalExpressionRest(expr); } function isYieldExpression() { - if (token() === 114 /* YieldKeyword */) { + if (token === 114 /* YieldKeyword */) { // If we have a 'yield' keyword, and this is a context where yield expressions are // allowed, then definitely parse out a yield expression. if (inYieldContext()) { @@ -10824,7 +10412,7 @@ var ts; // yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] nextToken(); if (!scanner.hasPrecedingLineBreak() && - (token() === 37 /* AsteriskToken */ || isStartOfExpression())) { + (token === 37 /* AsteriskToken */ || isStartOfExpression())) { node.asteriskToken = parseOptionalToken(37 /* AsteriskToken */); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); @@ -10836,7 +10424,7 @@ var ts; } } function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { - ts.Debug.assert(token() === 34 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + ts.Debug.assert(token === 34 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); var node; if (asyncModifier) { node = createNode(180 /* ArrowFunction */, asyncModifier.pos); @@ -10875,7 +10463,7 @@ var ts; var isAsync = !!(arrowFunction.flags & 256 /* Async */); // If we have an arrow, then try to parse the body. Even if not, try to parse if we // have an opening brace, just in case we're in an error state. - var lastToken = token(); + var lastToken = token; arrowFunction.equalsGreaterThanToken = parseExpectedToken(34 /* EqualsGreaterThanToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, "=>"); arrowFunction.body = (lastToken === 34 /* EqualsGreaterThanToken */ || lastToken === 15 /* OpenBraceToken */) ? parseArrowFunctionExpressionBody(isAsync) @@ -10887,10 +10475,10 @@ var ts; // Unknown -> There *might* be a parenthesized arrow function here. // Speculatively look ahead to be sure, and rollback if not. function isParenthesizedArrowFunctionExpression() { - if (token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */ || token() === 118 /* AsyncKeyword */) { + if (token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */ || token === 118 /* AsyncKeyword */) { return lookAhead(isParenthesizedArrowFunctionExpressionWorker); } - if (token() === 34 /* EqualsGreaterThanToken */) { + if (token === 34 /* EqualsGreaterThanToken */) { // ERROR RECOVERY TWEAK: // If we see a standalone => try to parse it as an arrow function expression as that's // likely what the user intended to write. @@ -10900,16 +10488,16 @@ var ts; return 0 /* False */; } function isParenthesizedArrowFunctionExpressionWorker() { - if (token() === 118 /* AsyncKeyword */) { + if (token === 118 /* AsyncKeyword */) { nextToken(); if (scanner.hasPrecedingLineBreak()) { return 0 /* False */; } - if (token() !== 17 /* OpenParenToken */ && token() !== 25 /* LessThanToken */) { + if (token !== 17 /* OpenParenToken */ && token !== 25 /* LessThanToken */) { return 0 /* False */; } } - var first = token(); + var first = token; var second = nextToken(); if (first === 17 /* OpenParenToken */) { if (second === 18 /* CloseParenToken */) { @@ -10998,7 +10586,7 @@ var ts; } function tryParseAsyncSimpleArrowFunctionExpression() { // We do a check here so that we won't be doing unnecessarily call to "lookAhead" - if (token() === 118 /* AsyncKeyword */) { + if (token === 118 /* AsyncKeyword */) { var isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker); if (isUnParenthesizedAsyncArrowFunction === 1 /* True */) { var asyncModifier = parseModifiersForArrowFunction(); @@ -11012,16 +10600,16 @@ var ts; // AsyncArrowFunctionExpression: // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In] // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] - if (token() === 118 /* AsyncKeyword */) { + if (token === 118 /* AsyncKeyword */) { nextToken(); // If the "async" is followed by "=>" token then it is not a begining of an async arrow-function // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher" - if (scanner.hasPrecedingLineBreak() || token() === 34 /* EqualsGreaterThanToken */) { + if (scanner.hasPrecedingLineBreak() || token === 34 /* EqualsGreaterThanToken */) { return 0 /* False */; } // Check for un-parenthesized AsyncArrowFunction var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); - if (!scanner.hasPrecedingLineBreak() && expr.kind === 69 /* Identifier */ && token() === 34 /* EqualsGreaterThanToken */) { + if (!scanner.hasPrecedingLineBreak() && expr.kind === 69 /* Identifier */ && token === 34 /* EqualsGreaterThanToken */) { return 1 /* True */; } } @@ -11051,19 +10639,19 @@ var ts; // - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation. // // So we need just a bit of lookahead to ensure that it can only be a signature. - if (!allowAmbiguity && token() !== 34 /* EqualsGreaterThanToken */ && token() !== 15 /* OpenBraceToken */) { + if (!allowAmbiguity && token !== 34 /* EqualsGreaterThanToken */ && token !== 15 /* OpenBraceToken */) { // Returning undefined here will cause our caller to rewind to where we started from. return undefined; } return node; } function parseArrowFunctionExpressionBody(isAsync) { - if (token() === 15 /* OpenBraceToken */) { + if (token === 15 /* OpenBraceToken */) { return parseFunctionBlock(/*allowYield*/ false, /*allowAwait*/ isAsync, /*ignoreMissingOpenBrace*/ false); } - if (token() !== 23 /* SemicolonToken */ && - token() !== 87 /* FunctionKeyword */ && - token() !== 73 /* ClassKeyword */ && + if (token !== 23 /* SemicolonToken */ && + token !== 87 /* FunctionKeyword */ && + token !== 73 /* ClassKeyword */ && isStartOfStatement() && !isStartOfExpressionStatement()) { // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations) @@ -11136,16 +10724,16 @@ var ts; // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand // a ** b - c // ^token; leftOperand = b. Return b to the caller as a rightOperand - var consumeCurrentOperator = token() === 38 /* AsteriskAsteriskToken */ ? + var consumeCurrentOperator = token === 38 /* AsteriskAsteriskToken */ ? newPrecedence >= precedence : newPrecedence > precedence; if (!consumeCurrentOperator) { break; } - if (token() === 90 /* InKeyword */ && inDisallowInContext()) { + if (token === 90 /* InKeyword */ && inDisallowInContext()) { break; } - if (token() === 116 /* AsKeyword */) { + if (token === 116 /* AsKeyword */) { // Make sure we *do* perform ASI for constructs like this: // var x = foo // as (Bar) @@ -11166,13 +10754,13 @@ var ts; return leftOperand; } function isBinaryOperator() { - if (inDisallowInContext() && token() === 90 /* InKeyword */) { + if (inDisallowInContext() && token === 90 /* InKeyword */) { return false; } return getBinaryOperatorPrecedence() > 0; } function getBinaryOperatorPrecedence() { - switch (token()) { + switch (token) { case 52 /* BarBarToken */: return 1; case 51 /* AmpersandAmpersandToken */: @@ -11229,7 +10817,7 @@ var ts; } function parsePrefixUnaryExpression() { var node = createNode(185 /* PrefixUnaryExpression */); - node.operator = token(); + node.operator = token; nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); @@ -11253,7 +10841,7 @@ var ts; return finishNode(node); } function isAwaitExpression() { - if (token() === 119 /* AwaitKeyword */) { + if (token === 119 /* AwaitKeyword */) { if (inAwaitContext()) { return true; } @@ -11269,42 +10857,25 @@ var ts; return finishNode(node); } /** - * Parse ES7 exponential expression and await expression - * - * ES7 ExponentiationExpression: - * 1) UnaryExpression[?Yield] - * 2) UpdateExpression[?Yield] ** ExponentiationExpression[?Yield] + * Parse ES7 unary expression and await expression * + * ES7 UnaryExpression: + * 1) SimpleUnaryExpression[?yield] + * 2) IncrementExpression[?yield] ** UnaryExpression[?yield] */ function parseUnaryExpressionOrHigher() { - /** - * ES7 UpdateExpression: - * 1) LeftHandSideExpression[?Yield] - * 2) LeftHandSideExpression[?Yield][no LineTerminator here]++ - * 3) LeftHandSideExpression[?Yield][no LineTerminator here]-- - * 4) ++UnaryExpression[?Yield] - * 5) --UnaryExpression[?Yield] - */ - if (isUpdateExpression()) { + if (isAwaitExpression()) { + return parseAwaitExpression(); + } + if (isIncrementExpression()) { var incrementExpression = parseIncrementExpression(); - return token() === 38 /* AsteriskAsteriskToken */ ? + return token === 38 /* AsteriskAsteriskToken */ ? parseBinaryExpressionRest(getBinaryOperatorPrecedence(), incrementExpression) : incrementExpression; } - /** - * ES7 UnaryExpression: - * 1) UpdateExpression[?yield] - * 2) delete UpdateExpression[?yield] - * 3) void UpdateExpression[?yield] - * 4) typeof UpdateExpression[?yield] - * 5) + UpdateExpression[?yield] - * 6) - UpdateExpression[?yield] - * 7) ~ UpdateExpression[?yield] - * 8) ! UpdateExpression[?yield] - */ - var unaryOperator = token(); + var unaryOperator = token; var simpleUnaryExpression = parseSimpleUnaryExpression(); - if (token() === 38 /* AsteriskAsteriskToken */) { + if (token === 38 /* AsteriskAsteriskToken */) { var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); if (simpleUnaryExpression.kind === 177 /* TypeAssertionExpression */) { parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); @@ -11318,8 +10889,8 @@ var ts; /** * Parse ES7 simple-unary expression or higher: * - * ES7 UnaryExpression: - * 1) UpdateExpression[?yield] + * ES7 SimpleUnaryExpression: + * 1) IncrementExpression[?yield] * 2) delete UnaryExpression[?yield] * 3) void UnaryExpression[?yield] * 4) typeof UnaryExpression[?yield] @@ -11327,10 +10898,9 @@ var ts; * 6) - UnaryExpression[?yield] * 7) ~ UnaryExpression[?yield] * 8) ! UnaryExpression[?yield] - * 9) [+Await] await UnaryExpression[?yield] */ function parseSimpleUnaryExpression() { - switch (token()) { + switch (token) { case 35 /* PlusToken */: case 36 /* MinusToken */: case 50 /* TildeToken */: @@ -11347,10 +10917,6 @@ var ts; // UnaryExpression (modified): // < type > UnaryExpression return parseTypeAssertion(); - case 119 /* AwaitKeyword */: - if (isAwaitExpression()) { - return parseAwaitExpression(); - } default: return parseIncrementExpression(); } @@ -11358,17 +10924,17 @@ var ts; /** * Check if the current token can possibly be an ES7 increment expression. * - * ES7 UpdateExpression: + * ES7 IncrementExpression: * LeftHandSideExpression[?Yield] * LeftHandSideExpression[?Yield][no LineTerminator here]++ * LeftHandSideExpression[?Yield][no LineTerminator here]-- * ++LeftHandSideExpression[?Yield] * --LeftHandSideExpression[?Yield] */ - function isUpdateExpression() { + function isIncrementExpression() { // This function is called inside parseUnaryExpression to decide // whether to call parseSimpleUnaryExpression or call parseIncrementExpression directly - switch (token()) { + switch (token) { case 35 /* PlusToken */: case 36 /* MinusToken */: case 50 /* TildeToken */: @@ -11376,7 +10942,6 @@ var ts; case 78 /* DeleteKeyword */: case 101 /* TypeOfKeyword */: case 103 /* VoidKeyword */: - case 119 /* AwaitKeyword */: return false; case 25 /* LessThanToken */: // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression @@ -11401,23 +10966,23 @@ var ts; * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression */ function parseIncrementExpression() { - if (token() === 41 /* PlusPlusToken */ || token() === 42 /* MinusMinusToken */) { + if (token === 41 /* PlusPlusToken */ || token === 42 /* MinusMinusToken */) { var node = createNode(185 /* PrefixUnaryExpression */); - node.operator = token(); + node.operator = token; nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); return finishNode(node); } - else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 25 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeyword)) { + else if (sourceFile.languageVariant === 1 /* JSX */ && token === 25 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeyword)) { // JSXElement is part of primaryExpression return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); } var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); - if ((token() === 41 /* PlusPlusToken */ || token() === 42 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { + if ((token === 41 /* PlusPlusToken */ || token === 42 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { var node = createNode(186 /* PostfixUnaryExpression */, expression.pos); node.operand = expression; - node.operator = token(); + node.operator = token; nextToken(); return finishNode(node); } @@ -11454,7 +11019,7 @@ var ts; // the last two CallExpression productions. Or we have a MemberExpression which either // completes the LeftHandSideExpression, or starts the beginning of the first four // CallExpression productions. - var expression = token() === 95 /* SuperKeyword */ + var expression = token === 95 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher(); // Now, we *may* be complete. However, we might have consumed the start of a @@ -11514,7 +11079,7 @@ var ts; } function parseSuperExpression() { var expression = parseTokenNode(); - if (token() === 17 /* OpenParenToken */ || token() === 21 /* DotToken */ || token() === 19 /* OpenBracketToken */) { + if (token === 17 /* OpenParenToken */ || token === 21 /* DotToken */ || token === 19 /* OpenBracketToken */) { return expression; } // If we have seen "super" it must be followed by '(' or '.'. @@ -11566,7 +11131,7 @@ var ts; // does less damage and we can report a better error. // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios // of one sort or another. - if (inExpressionContext && token() === 25 /* LessThanToken */) { + if (inExpressionContext && token === 25 /* LessThanToken */) { var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); @@ -11583,11 +11148,11 @@ var ts; } function parseJsxText() { var node = createNode(244 /* JsxText */, scanner.getStartPos()); - currentToken = scanner.scanJsxToken(); + token = scanner.scanJsxToken(); return finishNode(node); } function parseJsxChild() { - switch (token()) { + switch (token) { case 244 /* JsxText */: return parseJsxText(); case 15 /* OpenBraceToken */: @@ -11595,7 +11160,7 @@ var ts; case 25 /* LessThanToken */: return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ false); } - ts.Debug.fail("Unknown JSX child kind " + token()); + ts.Debug.fail("Unknown JSX child kind " + token); } function parseJsxChildren(openingTagName) { var result = []; @@ -11603,12 +11168,12 @@ var ts; var saveParsingContext = parsingContext; parsingContext |= 1 << 14 /* JsxChildren */; while (true) { - currentToken = scanner.reScanJsxToken(); - if (token() === 26 /* LessThanSlashToken */) { + token = scanner.reScanJsxToken(); + if (token === 26 /* LessThanSlashToken */) { // Closing tag break; } - else if (token() === 1 /* EndOfFileToken */) { + else if (token === 1 /* EndOfFileToken */) { // If we hit EOF, issue the error at the tag that lacks the closing element // rather than at the end of the file (which is useless) parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); @@ -11626,7 +11191,7 @@ var ts; var tagName = parseJsxElementName(); var attributes = parseList(13 /* JsxAttributes */, parseJsxAttribute); var node; - if (token() === 27 /* GreaterThanToken */) { + if (token === 27 /* GreaterThanToken */) { // Closing tag, so scan the immediately-following text with the JSX scanning instead // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate // scanning errors @@ -11655,7 +11220,7 @@ var ts; // primaryExpression in the form of an identifier and "this" keyword // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword // We only want to consider "this" as a primaryExpression - var expression = token() === 97 /* ThisKeyword */ ? + var expression = token === 97 /* ThisKeyword */ ? parseTokenNode() : parseIdentifierName(); while (parseOptional(21 /* DotToken */)) { var propertyAccess = createNode(172 /* PropertyAccessExpression */, expression.pos); @@ -11668,7 +11233,7 @@ var ts; function parseJsxExpression(inExpressionContext) { var node = createNode(248 /* JsxExpression */); parseExpected(15 /* OpenBraceToken */); - if (token() !== 16 /* CloseBraceToken */) { + if (token !== 16 /* CloseBraceToken */) { node.expression = parseAssignmentExpressionOrHigher(); } if (inExpressionContext) { @@ -11681,14 +11246,14 @@ var ts; return finishNode(node); } function parseJsxAttribute() { - if (token() === 15 /* OpenBraceToken */) { + if (token === 15 /* OpenBraceToken */) { return parseJsxSpreadAttribute(); } scanJsxIdentifier(); var node = createNode(246 /* JsxAttribute */); node.name = parseIdentifierName(); if (parseOptional(56 /* EqualsToken */)) { - switch (token()) { + switch (token) { case 9 /* StringLiteral */: node.initializer = parseLiteralNode(); break; @@ -11738,7 +11303,7 @@ var ts; expression = finishNode(propertyAccess); continue; } - if (token() === 49 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + if (token === 49 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { nextToken(); var nonNullExpression = createNode(196 /* NonNullExpression */, expression.pos); nonNullExpression.expression = expression; @@ -11751,7 +11316,7 @@ var ts; indexedAccess.expression = expression; // It's not uncommon for a user to write: "new Type[]". // Check for that common pattern and report a better error message. - if (token() !== 20 /* CloseBracketToken */) { + if (token !== 20 /* CloseBracketToken */) { indexedAccess.argumentExpression = allowInAnd(parseExpression); if (indexedAccess.argumentExpression.kind === 9 /* StringLiteral */ || indexedAccess.argumentExpression.kind === 8 /* NumericLiteral */) { var literal = indexedAccess.argumentExpression; @@ -11762,10 +11327,10 @@ var ts; expression = finishNode(indexedAccess); continue; } - if (token() === 11 /* NoSubstitutionTemplateLiteral */ || token() === 12 /* TemplateHead */) { + if (token === 11 /* NoSubstitutionTemplateLiteral */ || token === 12 /* TemplateHead */) { var tagExpression = createNode(176 /* TaggedTemplateExpression */, expression.pos); tagExpression.tag = expression; - tagExpression.template = token() === 11 /* NoSubstitutionTemplateLiteral */ + tagExpression.template = token === 11 /* NoSubstitutionTemplateLiteral */ ? parseLiteralNode() : parseTemplateExpression(); expression = finishNode(tagExpression); @@ -11777,7 +11342,7 @@ var ts; function parseCallExpressionRest(expression) { while (true) { expression = parseMemberExpressionRest(expression); - if (token() === 25 /* LessThanToken */) { + if (token === 25 /* LessThanToken */) { // See if this is the start of a generic invocation. If so, consume it and // keep checking for postfix expressions. Otherwise, it's just a '<' that's // part of an arithmetic expression. Break out so we consume it higher in the @@ -11793,7 +11358,7 @@ var ts; expression = finishNode(callExpr); continue; } - else if (token() === 17 /* OpenParenToken */) { + else if (token === 17 /* OpenParenToken */) { var callExpr = createNode(174 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); @@ -11825,7 +11390,7 @@ var ts; : undefined; } function canFollowTypeArgumentsInExpression() { - switch (token()) { + switch (token) { case 17 /* OpenParenToken */: // foo( // this case are the only case where this token can legally follow a type argument // list. So we definitely want to treat this as a type arg list. @@ -11861,7 +11426,7 @@ var ts; } } function parsePrimaryExpression() { - switch (token()) { + switch (token) { case 8 /* NumericLiteral */: case 9 /* StringLiteral */: case 11 /* NoSubstitutionTemplateLiteral */: @@ -11917,8 +11482,8 @@ var ts; return finishNode(node); } function parseArgumentOrArrayLiteralElement() { - return token() === 22 /* DotDotDotToken */ ? parseSpreadElement() : - token() === 24 /* CommaToken */ ? createNode(193 /* OmittedExpression */) : + return token === 22 /* DotDotDotToken */ ? parseSpreadElement() : + token === 24 /* CommaToken */ ? createNode(193 /* OmittedExpression */) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { @@ -11956,7 +11521,7 @@ var ts; var propertyName = parsePropertyName(); // Disallowing of optional property assignments happens in the grammar checker. var questionToken = parseOptionalToken(53 /* QuestionToken */); - if (asteriskToken || token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */) { + if (asteriskToken || token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */) { return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); } // check if it is short-hand property assignment or normal property assignment @@ -11964,7 +11529,7 @@ var ts; // CoverInitializedName[Yield] : // IdentifierReference[?Yield] Initializer[In, ?Yield] // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern - var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 24 /* CommaToken */ || token() === 16 /* CloseBraceToken */ || token() === 56 /* EqualsToken */); + var isShorthandPropertyAssignment = tokenIsIdentifier && (token === 24 /* CommaToken */ || token === 16 /* CloseBraceToken */ || token === 56 /* EqualsToken */); if (isShorthandPropertyAssignment) { var shorthandDeclaration = createNode(254 /* ShorthandPropertyAssignment */, fullStart); shorthandDeclaration.name = propertyName; @@ -12032,7 +11597,7 @@ var ts; parseExpected(92 /* NewKeyword */); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); - if (node.typeArguments || token() === 17 /* OpenParenToken */) { + if (node.typeArguments || token === 17 /* OpenParenToken */) { node.arguments = parseArgumentList(); } return finishNode(node); @@ -12112,8 +11677,8 @@ var ts; parseExpected(86 /* ForKeyword */); parseExpected(17 /* OpenParenToken */); var initializer = undefined; - if (token() !== 23 /* SemicolonToken */) { - if (token() === 102 /* VarKeyword */ || token() === 108 /* LetKeyword */ || token() === 74 /* ConstKeyword */) { + if (token !== 23 /* SemicolonToken */) { + if (token === 102 /* VarKeyword */ || token === 108 /* LetKeyword */ || token === 74 /* ConstKeyword */) { initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true); } else { @@ -12139,11 +11704,11 @@ var ts; var forStatement = createNode(206 /* ForStatement */, pos); forStatement.initializer = initializer; parseExpected(23 /* SemicolonToken */); - if (token() !== 23 /* SemicolonToken */ && token() !== 18 /* CloseParenToken */) { + if (token !== 23 /* SemicolonToken */ && token !== 18 /* CloseParenToken */) { forStatement.condition = allowInAnd(parseExpression); } parseExpected(23 /* SemicolonToken */); - if (token() !== 18 /* CloseParenToken */) { + if (token !== 18 /* CloseParenToken */) { forStatement.incrementor = allowInAnd(parseExpression); } parseExpected(18 /* CloseParenToken */); @@ -12195,7 +11760,7 @@ var ts; return finishNode(node); } function parseCaseOrDefaultClause() { - return token() === 71 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); + return token === 71 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { var node = createNode(213 /* SwitchStatement */); @@ -12229,10 +11794,10 @@ var ts; var node = createNode(216 /* TryStatement */); parseExpected(100 /* TryKeyword */); node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); - node.catchClause = token() === 72 /* CatchKeyword */ ? parseCatchClause() : undefined; + node.catchClause = token === 72 /* CatchKeyword */ ? parseCatchClause() : undefined; // If we don't have a catch clause, then we must have a finally clause. Try to parse // one out no matter what. - if (!node.catchClause || token() === 85 /* FinallyKeyword */) { + if (!node.catchClause || token === 85 /* FinallyKeyword */) { parseExpected(85 /* FinallyKeyword */); node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); } @@ -12275,19 +11840,19 @@ var ts; } function nextTokenIsIdentifierOrKeywordOnSameLine() { nextToken(); - return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak(); + return ts.tokenIsIdentifierOrKeyword(token) && !scanner.hasPrecedingLineBreak(); } function nextTokenIsFunctionKeywordOnSameLine() { nextToken(); - return token() === 87 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak(); + return token === 87 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak(); } function nextTokenIsIdentifierOrKeywordOrNumberOnSameLine() { nextToken(); - return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */) && !scanner.hasPrecedingLineBreak(); + return (ts.tokenIsIdentifierOrKeyword(token) || token === 8 /* NumericLiteral */) && !scanner.hasPrecedingLineBreak(); } function isDeclaration() { while (true) { - switch (token()) { + switch (token) { case 102 /* VarKeyword */: case 108 /* LetKeyword */: case 74 /* ConstKeyword */: @@ -12337,16 +11902,16 @@ var ts; continue; case 137 /* GlobalKeyword */: nextToken(); - return token() === 15 /* OpenBraceToken */ || token() === 69 /* Identifier */ || token() === 82 /* ExportKeyword */; + return token === 15 /* OpenBraceToken */ || token === 69 /* Identifier */ || token === 82 /* ExportKeyword */; case 89 /* ImportKeyword */: nextToken(); - return token() === 9 /* StringLiteral */ || token() === 37 /* AsteriskToken */ || - token() === 15 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token()); + return token === 9 /* StringLiteral */ || token === 37 /* AsteriskToken */ || + token === 15 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token); case 82 /* ExportKeyword */: nextToken(); - if (token() === 56 /* EqualsToken */ || token() === 37 /* AsteriskToken */ || - token() === 15 /* OpenBraceToken */ || token() === 77 /* DefaultKeyword */ || - token() === 116 /* AsKeyword */) { + if (token === 56 /* EqualsToken */ || token === 37 /* AsteriskToken */ || + token === 15 /* OpenBraceToken */ || token === 77 /* DefaultKeyword */ || + token === 116 /* AsKeyword */) { return true; } continue; @@ -12362,7 +11927,7 @@ var ts; return lookAhead(isDeclaration); } function isStartOfStatement() { - switch (token()) { + switch (token) { case 55 /* AtToken */: case 23 /* SemicolonToken */: case 15 /* OpenBraceToken */: @@ -12415,7 +11980,7 @@ var ts; } function nextTokenIsIdentifierOrStartOfDestructuring() { nextToken(); - return isIdentifier() || token() === 15 /* OpenBraceToken */ || token() === 19 /* OpenBracketToken */; + return isIdentifier() || token === 15 /* OpenBraceToken */ || token === 19 /* OpenBracketToken */; } function isLetDeclaration() { // In ES6 'let' always starts a lexical declaration if followed by an identifier or { @@ -12423,7 +11988,7 @@ var ts; return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); } function parseStatement() { - switch (token()) { + switch (token) { case 23 /* SemicolonToken */: return parseEmptyStatement(); case 15 /* OpenBraceToken */: @@ -12496,7 +12061,7 @@ var ts; var fullStart = getNodePos(); var decorators = parseDecorators(); var modifiers = parseModifiers(); - switch (token()) { + switch (token) { case 102 /* VarKeyword */: case 108 /* LetKeyword */: case 74 /* ConstKeyword */: @@ -12519,7 +12084,7 @@ var ts; return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); case 82 /* ExportKeyword */: nextToken(); - switch (token()) { + switch (token) { case 77 /* DefaultKeyword */: case 56 /* EqualsToken */: return parseExportAssignment(fullStart, decorators, modifiers); @@ -12542,10 +12107,10 @@ var ts; } function nextTokenIsIdentifierOrStringLiteralOnSameLine() { nextToken(); - return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9 /* StringLiteral */); + return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token === 9 /* StringLiteral */); } function parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage) { - if (token() !== 15 /* OpenBraceToken */ && canParseSemicolon()) { + if (token !== 15 /* OpenBraceToken */ && canParseSemicolon()) { parseSemicolon(); return; } @@ -12553,7 +12118,7 @@ var ts; } // DECLARATIONS function parseArrayBindingElement() { - if (token() === 24 /* CommaToken */) { + if (token === 24 /* CommaToken */) { return createNode(193 /* OmittedExpression */); } var node = createNode(169 /* BindingElement */); @@ -12566,7 +12131,7 @@ var ts; var node = createNode(169 /* BindingElement */); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); - if (tokenIsIdentifier && token() !== 54 /* ColonToken */) { + if (tokenIsIdentifier && token !== 54 /* ColonToken */) { node.name = propertyName; } else { @@ -12592,13 +12157,13 @@ var ts; return finishNode(node); } function isIdentifierOrPattern() { - return token() === 15 /* OpenBraceToken */ || token() === 19 /* OpenBracketToken */ || isIdentifier(); + return token === 15 /* OpenBraceToken */ || token === 19 /* OpenBracketToken */ || isIdentifier(); } function parseIdentifierOrPattern() { - if (token() === 19 /* OpenBracketToken */) { + if (token === 19 /* OpenBracketToken */) { return parseArrayBindingPattern(); } - if (token() === 15 /* OpenBraceToken */) { + if (token === 15 /* OpenBraceToken */) { return parseObjectBindingPattern(); } return parseIdentifier(); @@ -12607,14 +12172,14 @@ var ts; var node = createNode(218 /* VariableDeclaration */); node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); - if (!isInOrOfKeyword(token())) { + if (!isInOrOfKeyword(token)) { node.initializer = parseInitializer(/*inParameter*/ false); } return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { var node = createNode(219 /* VariableDeclarationList */); - switch (token()) { + switch (token) { case 102 /* VarKeyword */: break; case 108 /* LetKeyword */: @@ -12636,7 +12201,7 @@ var ts; // So we need to look ahead to determine if 'of' should be treated as a keyword in // this context. // The checker will then give an error that there is an empty declaration list. - if (token() === 138 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { + if (token === 138 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { @@ -12721,7 +12286,7 @@ var ts; // Note: this is not legal as per the grammar. But we allow it in the parser and // report an error in the grammar checker. var questionToken = parseOptionalToken(53 /* QuestionToken */); - if (asteriskToken || token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */) { + if (asteriskToken || token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */) { return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, ts.Diagnostics.or_expected); } else { @@ -12754,12 +12319,12 @@ var ts; } function isClassMemberStart() { var idToken; - if (token() === 55 /* AtToken */) { + if (token === 55 /* AtToken */) { return true; } // Eat up all modifiers, but hold on to the last one in case it is actually an identifier. - while (ts.isModifierKind(token())) { - idToken = token(); + while (ts.isModifierKind(token)) { + idToken = token; // If the idToken is a class modifier (protected, private, public, and static), it is // certain that we are starting to parse class member. This allows better error recovery // Example: @@ -12771,17 +12336,17 @@ var ts; } nextToken(); } - if (token() === 37 /* AsteriskToken */) { + if (token === 37 /* AsteriskToken */) { return true; } // Try to get the first property-like token following all modifiers. // This can either be an identifier or the 'get' or 'set' keywords. if (isLiteralPropertyName()) { - idToken = token(); + idToken = token; nextToken(); } // Index signatures and computed properties are class members; we can parse. - if (token() === 19 /* OpenBracketToken */) { + if (token === 19 /* OpenBracketToken */) { return true; } // If we were able to get any potential identifier... @@ -12792,7 +12357,7 @@ var ts; } // If it *is* a keyword, but not an accessor, check a little farther along // to see if it should actually be parsed as a class member. - switch (token()) { + switch (token) { case 17 /* OpenParenToken */: // Method declaration case 25 /* LessThanToken */: // Generic Method declaration case 54 /* ColonToken */: // Type Annotation for declaration @@ -12842,8 +12407,8 @@ var ts; var modifiers; while (true) { var modifierStart = scanner.getStartPos(); - var modifierKind = token(); - if (token() === 74 /* ConstKeyword */ && permitInvalidConstAsModifier) { + var modifierKind = token; + if (token === 74 /* ConstKeyword */ && permitInvalidConstAsModifier) { // We need to ensure that any subsequent modifiers appear on the same line // so that when 'const' is a standalone declaration, we don't issue an error. if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { @@ -12871,9 +12436,9 @@ var ts; function parseModifiersForArrowFunction() { var flags = 0; var modifiers; - if (token() === 118 /* AsyncKeyword */) { + if (token === 118 /* AsyncKeyword */) { var modifierStart = scanner.getStartPos(); - var modifierKind = token(); + var modifierKind = token; nextToken(); modifiers = []; modifiers.pos = modifierStart; @@ -12885,7 +12450,7 @@ var ts; return modifiers; } function parseClassElement() { - if (token() === 23 /* SemicolonToken */) { + if (token === 23 /* SemicolonToken */) { var result = createNode(198 /* SemicolonClassElement */); nextToken(); return finishNode(result); @@ -12897,7 +12462,7 @@ var ts; if (accessor) { return accessor; } - if (token() === 121 /* ConstructorKeyword */) { + if (token === 121 /* ConstructorKeyword */) { return parseConstructorDeclaration(fullStart, decorators, modifiers); } if (isIndexSignature()) { @@ -12905,11 +12470,11 @@ var ts; } // It is very important that we check this *after* checking indexers because // the [ token can start an index signature or a computed property name - if (ts.tokenIsIdentifierOrKeyword(token()) || - token() === 9 /* StringLiteral */ || - token() === 8 /* NumericLiteral */ || - token() === 37 /* AsteriskToken */ || - token() === 19 /* OpenBracketToken */) { + if (ts.tokenIsIdentifierOrKeyword(token) || + token === 9 /* StringLiteral */ || + token === 8 /* NumericLiteral */ || + token === 37 /* AsteriskToken */ || + token === 19 /* OpenBracketToken */) { return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); } if (decorators || modifiers) { @@ -12959,7 +12524,7 @@ var ts; : undefined; } function isImplementsClause() { - return token() === 106 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword); + return token === 106 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword); } function parseHeritageClauses(isClassHeritageClause) { // ClassTail[Yield,Await] : (Modified) See 14.5 @@ -12970,9 +12535,9 @@ var ts; return undefined; } function parseHeritageClause() { - if (token() === 83 /* ExtendsKeyword */ || token() === 106 /* ImplementsKeyword */) { + if (token === 83 /* ExtendsKeyword */ || token === 106 /* ImplementsKeyword */) { var node = createNode(251 /* HeritageClause */); - node.token = token(); + node.token = token; nextToken(); node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); return finishNode(node); @@ -12982,13 +12547,13 @@ var ts; function parseExpressionWithTypeArguments() { var node = createNode(194 /* ExpressionWithTypeArguments */); node.expression = parseLeftHandSideExpressionOrHigher(); - if (token() === 25 /* LessThanToken */) { + if (token === 25 /* LessThanToken */) { node.typeArguments = parseBracketedList(18 /* TypeArguments */, parseType, 25 /* LessThanToken */, 27 /* GreaterThanToken */); } return finishNode(node); } function isHeritageClause() { - return token() === 83 /* ExtendsKeyword */ || token() === 106 /* ImplementsKeyword */; + return token === 83 /* ExtendsKeyword */ || token === 106 /* ImplementsKeyword */; } function parseClassMembers() { return parseList(5 /* ClassMembers */, parseClassElement); @@ -13070,7 +12635,7 @@ var ts; var node = createNode(225 /* ModuleDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); - if (token() === 137 /* GlobalKeyword */) { + if (token === 137 /* GlobalKeyword */) { // parse 'global' as name of global scope augmentation node.name = parseIdentifier(); node.flags |= 131072 /* GlobalAugmentation */; @@ -13078,7 +12643,7 @@ var ts; else { node.name = parseLiteralNode(/*internName*/ true); } - if (token() === 15 /* OpenBraceToken */) { + if (token === 15 /* OpenBraceToken */) { node.body = parseModuleBlock(); } else { @@ -13088,7 +12653,7 @@ var ts; } function parseModuleDeclaration(fullStart, decorators, modifiers) { var flags = modifiers ? modifiers.flags : 0; - if (token() === 137 /* GlobalKeyword */) { + if (token === 137 /* GlobalKeyword */) { // global augmentation return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } @@ -13097,14 +12662,14 @@ var ts; } else { parseExpected(125 /* ModuleKeyword */); - if (token() === 9 /* StringLiteral */) { + if (token === 9 /* StringLiteral */) { return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } } return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); } function isExternalModuleReference() { - return token() === 129 /* RequireKeyword */ && + return token === 129 /* RequireKeyword */ && lookAhead(nextTokenIsOpenParen); } function nextTokenIsOpenParen() { @@ -13129,7 +12694,7 @@ var ts; var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token() !== 24 /* CommaToken */ && token() !== 136 /* FromKeyword */) { + if (token !== 24 /* CommaToken */ && token !== 136 /* FromKeyword */) { // ImportEquals declaration of type: // import x = require("mod"); or // import x = M.x; @@ -13151,8 +12716,8 @@ var ts; // import ImportClause from ModuleSpecifier ; // import ModuleSpecifier; if (identifier || - token() === 37 /* AsteriskToken */ || - token() === 15 /* OpenBraceToken */) { + token === 37 /* AsteriskToken */ || + token === 15 /* OpenBraceToken */) { importDeclaration.importClause = parseImportClause(identifier, afterImportPos); parseExpected(136 /* FromKeyword */); } @@ -13177,7 +12742,7 @@ var ts; // parse namespace or named imports if (!importClause.name || parseOptional(24 /* CommaToken */)) { - importClause.namedBindings = token() === 37 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(233 /* NamedImports */); + importClause.namedBindings = token === 37 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(233 /* NamedImports */); } return finishNode(importClause); } @@ -13195,7 +12760,7 @@ var ts; return finishNode(node); } function parseModuleSpecifier() { - if (token() === 9 /* StringLiteral */) { + if (token === 9 /* StringLiteral */) { var result = parseLiteralNode(); internIdentifier(result.text); return result; @@ -13242,14 +12807,14 @@ var ts; // ExportSpecifier: // IdentifierName // IdentifierName as IdentifierName - var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); + var checkIdentifierIsKeyword = ts.isKeyword(token) && !isIdentifier(); var checkIdentifierStart = scanner.getTokenPos(); var checkIdentifierEnd = scanner.getTextPos(); var identifierName = parseIdentifierName(); - if (token() === 116 /* AsKeyword */) { + if (token === 116 /* AsKeyword */) { node.propertyName = identifierName; parseExpected(116 /* AsKeyword */); - checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); + checkIdentifierIsKeyword = ts.isKeyword(token) && !isIdentifier(); checkIdentifierStart = scanner.getTokenPos(); checkIdentifierEnd = scanner.getTextPos(); node.name = parseIdentifierName(); @@ -13276,7 +12841,7 @@ var ts; // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios, // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`) // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect. - if (token() === 136 /* FromKeyword */ || (token() === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { + if (token === 136 /* FromKeyword */ || (token === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { parseExpected(136 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } @@ -13414,7 +12979,7 @@ var ts; var JSDocParser; (function (JSDocParser) { function isJSDocType() { - switch (token()) { + switch (token) { case 37 /* AsteriskToken */: case 53 /* QuestionToken */: case 17 /* OpenParenToken */: @@ -13427,13 +12992,13 @@ var ts; case 97 /* ThisKeyword */: return true; } - return ts.tokenIsIdentifierOrKeyword(token()); + return ts.tokenIsIdentifierOrKeyword(token); } JSDocParser.isJSDocType = isJSDocType; function parseJSDocTypeExpressionForTests(content, start, length) { initializeState("file.js", content, 2 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); scanner.setText(content, start, length); - currentToken = scanner.scan(); + token = scanner.scan(); var jsDocTypeExpression = parseJSDocTypeExpression(); var diagnostics = parseDiagnostics; clearState(); @@ -13453,12 +13018,12 @@ var ts; JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression; function parseJSDocTopLevelType() { var type = parseJSDocType(); - if (token() === 47 /* BarToken */) { + if (token === 47 /* BarToken */) { var unionType = createNode(261 /* JSDocUnionType */, type.pos); unionType.types = parseJSDocTypeList(type); type = finishNode(unionType); } - if (token() === 56 /* EqualsToken */) { + if (token === 56 /* EqualsToken */) { var optionalType = createNode(268 /* JSDocOptionalType */, type.pos); nextToken(); optionalType.type = type; @@ -13469,20 +13034,20 @@ var ts; function parseJSDocType() { var type = parseBasicTypeExpression(); while (true) { - if (token() === 19 /* OpenBracketToken */) { + if (token === 19 /* OpenBracketToken */) { var arrayType = createNode(260 /* JSDocArrayType */, type.pos); arrayType.elementType = type; nextToken(); parseExpected(20 /* CloseBracketToken */); type = finishNode(arrayType); } - else if (token() === 53 /* QuestionToken */) { + else if (token === 53 /* QuestionToken */) { var nullableType = createNode(263 /* JSDocNullableType */, type.pos); nullableType.type = type; nextToken(); type = finishNode(nullableType); } - else if (token() === 49 /* ExclamationToken */) { + else if (token === 49 /* ExclamationToken */) { var nonNullableType = createNode(264 /* JSDocNonNullableType */, type.pos); nonNullableType.type = type; nextToken(); @@ -13495,7 +13060,7 @@ var ts; return type; } function parseBasicTypeExpression() { - switch (token()) { + switch (token) { case 37 /* AsteriskToken */: return parseJSDocAllType(); case 53 /* QuestionToken */: @@ -13522,16 +13087,9 @@ var ts; case 120 /* BooleanKeyword */: case 133 /* SymbolKeyword */: case 103 /* VoidKeyword */: - case 93 /* NullKeyword */: - case 135 /* UndefinedKeyword */: - case 127 /* NeverKeyword */: return parseTokenNode(); - case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: - case 99 /* TrueKeyword */: - case 84 /* FalseKeyword */: - return parseJSDocLiteralType(); } + // TODO (drosen): Parse string literal types in JSDoc as well. return parseJSDocTypeReference(); } function parseJSDocThisType() { @@ -13561,7 +13119,7 @@ var ts; result.parameters = parseDelimitedList(22 /* JSDocFunctionParameters */, parseJSDocParameter); checkForTrailingComma(result.parameters); parseExpected(18 /* CloseParenToken */); - if (token() === 54 /* ColonToken */) { + if (token === 54 /* ColonToken */) { nextToken(); result.type = parseJSDocType(); } @@ -13578,12 +13136,12 @@ var ts; function parseJSDocTypeReference() { var result = createNode(267 /* JSDocTypeReference */); result.name = parseSimplePropertyName(); - if (token() === 25 /* LessThanToken */) { + if (token === 25 /* LessThanToken */) { result.typeArguments = parseTypeArguments(); } else { while (parseOptional(21 /* DotToken */)) { - if (token() === 25 /* LessThanToken */) { + if (token === 25 /* LessThanToken */) { result.typeArguments = parseTypeArguments(); break; } @@ -13627,7 +13185,7 @@ var ts; function parseJSDocRecordMember() { var result = createNode(266 /* JSDocRecordMember */); result.name = parseSimplePropertyName(); - if (token() === 54 /* ColonToken */) { + if (token === 54 /* ColonToken */) { nextToken(); result.type = parseJSDocType(); } @@ -13676,11 +13234,6 @@ var ts; nextToken(); return finishNode(result); } - function parseJSDocLiteralType() { - var result = createNode(282 /* JSDocLiteralType */); - result.literal = parseLiteralTypeNode(); - return finishNode(result); - } function parseJSDocUnknownOrNullableType() { var pos = scanner.getStartPos(); // skip the ? @@ -13694,12 +13247,12 @@ var ts; // Foo // Foo(?= // (?| - if (token() === 24 /* CommaToken */ || - token() === 16 /* CloseBraceToken */ || - token() === 18 /* CloseParenToken */ || - token() === 27 /* GreaterThanToken */ || - token() === 56 /* EqualsToken */ || - token() === 47 /* BarToken */) { + if (token === 24 /* CommaToken */ || + token === 16 /* CloseBraceToken */ || + token === 18 /* CloseParenToken */ || + token === 27 /* GreaterThanToken */ || + token === 56 /* EqualsToken */ || + token === 47 /* BarToken */) { var result = createNode(259 /* JSDocUnknownType */, pos); return finishNode(result); } @@ -13719,14 +13272,14 @@ var ts; } JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; function parseJSDocComment(parent, start, length) { - var saveToken = currentToken; + var saveToken = token; var saveParseDiagnosticsLength = parseDiagnostics.length; var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; var comment = parseJSDocCommentWorker(start, length); if (comment) { comment.parent = parent; } - currentToken = saveToken; + token = saveToken; parseDiagnostics.length = saveParseDiagnosticsLength; parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; return comment; @@ -13754,8 +13307,8 @@ var ts; var canParseTag = true; var seenAsterisk = true; nextJSDocToken(); - while (token() !== 1 /* EndOfFileToken */) { - switch (token()) { + while (token !== 1 /* EndOfFileToken */) { + switch (token) { case 55 /* AtToken */: if (canParseTag) { parseTag(); @@ -13800,12 +13353,12 @@ var ts; return finishNode(result, end); } function skipWhitespace() { - while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + while (token === 5 /* WhitespaceTrivia */ || token === 4 /* NewLineTrivia */) { nextJSDocToken(); } } function parseTag() { - ts.Debug.assert(token() === 55 /* AtToken */); + ts.Debug.assert(token === 55 /* AtToken */); var atToken = createNode(55 /* AtToken */, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); @@ -13851,7 +13404,7 @@ var ts; } } function tryParseTypeExpression() { - if (token() !== 15 /* OpenBraceToken */) { + if (token !== 15 /* OpenBraceToken */) { return undefined; } var typeExpression = parseJSDocTypeExpression(); @@ -13872,7 +13425,7 @@ var ts; } parseExpected(20 /* CloseBracketToken */); } - else if (ts.tokenIsIdentifierOrKeyword(token())) { + else if (ts.tokenIsIdentifierOrKeyword(token)) { name = parseJSDocIdentifierName(); } if (!name) { @@ -13965,15 +13518,12 @@ var ts; var canParseTag = true; var seenAsterisk = false; var parentTagTerminated = false; - while (token() !== 1 /* EndOfFileToken */ && !parentTagTerminated) { + while (token !== 1 /* EndOfFileToken */ && !parentTagTerminated) { nextJSDocToken(); - switch (token()) { + switch (token) { case 55 /* AtToken */: if (canParseTag) { parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral); - if (!parentTagTerminated) { - resumePos = scanner.getStartPos(); - } } seenAsterisk = false; break; @@ -13999,7 +13549,7 @@ var ts; } } function tryParseChildTag(parentTag) { - ts.Debug.assert(token() === 55 /* AtToken */); + ts.Debug.assert(token === 55 /* AtToken */); var atToken = createNode(55 /* AtToken */, scanner.getStartPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); @@ -14043,7 +13593,7 @@ var ts; typeParameter.name = name_9; finishNode(typeParameter); typeParameters.push(typeParameter); - if (token() === 24 /* CommaToken */) { + if (token === 24 /* CommaToken */) { nextJSDocToken(); } else { @@ -14059,10 +13609,10 @@ var ts; return result; } function nextJSDocToken() { - return currentToken = scanner.scanJSDocToken(); + return token = scanner.scanJSDocToken(); } function parseJSDocIdentifierName() { - return createJSDocIdentifier(ts.tokenIsIdentifierOrKeyword(token())); + return createJSDocIdentifier(ts.tokenIsIdentifierOrKeyword(token)); } function createJSDocIdentifier(isIdentifier) { if (!isIdentifier) { @@ -14189,8 +13739,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { - var node = array_9[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } } @@ -14327,8 +13877,8 @@ var ts; array._children = undefined; // Adjust the pos or end (or both) of the intersecting array accordingly. adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_10 = array; _i < array_10.length; _i++) { - var node = array_10[_i]; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; visitNode(node); } return; @@ -14556,545 +14106,12 @@ var ts; })(InvalidPosition || (InvalidPosition = {})); })(IncrementalParser || (IncrementalParser = {})); })(ts || (ts = {})); -/// -/// -var ts; -(function (ts) { - function tryReadTypesSection(packageJsonPath, baseDirectory, state) { - var jsonContent = ts.readJson(packageJsonPath, state.host); - function tryReadFromField(fieldName) { - if (ts.hasProperty(jsonContent, fieldName)) { - var typesFile = jsonContent[fieldName]; - if (typeof typesFile === "string") { - var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1); - } - return typesFilePath_1; - } - else { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); - } - } - } - } - var typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); - if (typesFilePath) { - return typesFilePath; - } - // Use the main module for inferring types if no types package specified and the allowJs is set - if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); - } - var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); - return mainFilePath; - } - return undefined; - } - /** Return the file if it exists. */ - function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures && state.host.fileExists(fileName)) { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); - } - return fileName; - } - else { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); - } - failedLookupLocation.push(fileName); - return undefined; - } - } - /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ - function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures) { - // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing - var directory = ts.getDirectoryPath(candidate); - if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); - } - } - return ts.forEach(extensions, function (ext) { - return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); - }); - } - /** - * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary - * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. - */ - function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); - if (resolvedByAddingExtension) { - return resolvedByAddingExtension; - } - // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; - // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" - if (ts.hasJavaScriptFileExtension(candidate)) { - var extensionless = ts.removeFileExtension(candidate); - if (state.traceEnabled) { - var extension = candidate.substring(extensionless.length); - ts.trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); - } - return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); - } - } - /* @internal */ - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { - var packageJsonPath = pathToPackageJson(candidate); - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - if (directoryExists && state.host.fileExists(packageJsonPath)) { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); - if (typesFile) { - var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); - // A package.json "typings" may specify an exact filename, or may choose to omit an extension. - var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) || - tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state); - if (result) { - return result; - } - } - else { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field); - } - } - } - else { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); - } - // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results - failedLookupLocation.push(packageJsonPath); - } - return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); - } - ts.loadNodeModuleFromDirectory = loadNodeModuleFromDirectory; - function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { - var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions); - var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - } - /* @internal */ - function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state, checkOneLevel) { - directory = ts.normalizeSlashes(directory); - while (true) { - var baseName = ts.getBaseFileName(directory); - if (baseName !== "node_modules") { - // Try to load source from the package - var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); - if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { - // Always prefer a TypeScript (.ts, .tsx, .d.ts) file shipped with the package - return packageResult; - } - else { - // Else prefer a types package over non-TypeScript results (e.g. JavaScript files) - var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); - if (typesResult || packageResult) { - return typesResult || packageResult; - } - } - } - var parentPath = ts.getDirectoryPath(directory); - if (parentPath === directory || checkOneLevel) { - break; - } - directory = parentPath; - } - return undefined; - } - ts.loadModuleFromNodeModules = loadModuleFromNodeModules; - function moduleHasNonRelativeName(moduleName) { - return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); - } - function classicNameResolver(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = ts.isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; - var failedLookupLocations = []; - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var containingDirectory = ts.getDirectoryPath(containingFile); - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); - if (resolvedFileName) { - return ts.createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/ false, failedLookupLocations); - } - var referencedSourceFile; - if (moduleHasNonRelativeName(moduleName)) { - while (true) { - var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); - if (referencedSourceFile) { - break; - } - var parentPath = ts.getDirectoryPath(containingDirectory); - if (parentPath === containingDirectory) { - break; - } - containingDirectory = parentPath; - } - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); - } - return referencedSourceFile - ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } - : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; - } - ts.classicNameResolver = classicNameResolver; - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { - var containingDirectory = ts.getDirectoryPath(containingFile); - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var traceEnabled = ts.isTraceEnabled(compilerOptions, host); - var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); - var isExternalLibraryImport = false; - if (!resolvedFileName) { - if (moduleHasNonRelativeName(moduleName)) { - if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); - } - resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state, /*checkOneLevel*/ false); - isExternalLibraryImport = resolvedFileName !== undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); - } - } - if (resolvedFileName && host.realpath) { - var originalFileName = resolvedFileName; - resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName)); - if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); - } - } - return ts.createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; - function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); - } - var resolvedFileName = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); - return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); - } - function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.rootDirs) { - return undefined; - } - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); - } - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var matchedRootDir; - var matchedNormalizedPrefix; - for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { - var rootDir = _a[_i]; - // rootDirs are expected to be absolute - // in case of tsconfig.json this will happen automatically - compiler will expand relative names - // using location of tsconfig.json as base location - var normalizedRoot = ts.normalizePath(rootDir); - if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { - normalizedRoot += ts.directorySeparator; - } - var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && - (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); - } - if (isLongestMatchingPrefix) { - matchedNormalizedPrefix = normalizedRoot; - matchedRootDir = rootDir; - } - } - if (matchedNormalizedPrefix) { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); - } - var suffix = candidate.substr(matchedNormalizedPrefix.length); - // first - try to load from a initial location - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); - } - // then try to resolve using remaining entries in rootDirs - for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { - var rootDir = _c[_b]; - if (rootDir === matchedRootDir) { - // skip the initially matched entry - continue; - } - var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); - } - var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); - if (resolvedFileName_1) { - return resolvedFileName_1; - } - } - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); - } - } - return undefined; - } - function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.baseUrl) { - return undefined; - } - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); - } - // string is for exact match - var matchedPattern = undefined; - if (state.compilerOptions.paths) { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); - } - matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName); - var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern); - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); - } - for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) { - var subst = _a[_i]; - var path = matchedStar ? subst.replace("*", matchedStar) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - } - return undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - } - } - /** - * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to - * mitigate differences between design time structure of the project and its runtime counterpart so the same import name - * can be resolved successfully by TypeScript compiler and runtime module loader. - * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will - * fallback to standard resolution routine. - * - * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative - * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will - * be '/a/b/c/d' - * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names - * will be resolved based on the content of the module name. - * Structure of 'paths' compiler options - * 'paths': { - * pattern-1: [...substitutions], - * pattern-2: [...substitutions], - * ... - * pattern-n: [...substitutions] - * } - * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against - * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case. - * If pattern contains '*' then to match pattern "*" module name must start with the and end with . - * denotes part of the module name between and . - * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked. - * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module - * from the candidate location. - * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every - * substitution in the list and replace '*' with string. If candidate location is not rooted it - * will be converted to absolute using baseUrl. - * For example: - * baseUrl: /a/b/c - * "paths": { - * // match all module names - * "*": [ - * "*", // use matched name as is, - * // will be looked as /a/b/c/ - * - * "folder1/*" // substitution will convert matched name to 'folder1/', - * // since it is not rooted then final candidate location will be /a/b/c/folder1/ - * ], - * // match module names that start with 'components/' - * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/ to '/root/components/folder1/', - * // it is rooted so it will be final candidate location - * } - * - * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if - * they were in the same location. For example lets say there are two files - * '/local/src/content/file1.ts' - * '/shared/components/contracts/src/content/protocols/file2.ts' - * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so - * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime. - * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all - * root dirs were merged together. - * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ]. - * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file: - * '/local/src/content/protocols/file2' and try to load it - failure. - * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will - * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining - * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. - */ - function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (moduleHasNonRelativeName(moduleName)) { - return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); - } - else { - return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); - } - } - function resolveModuleName(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = ts.isTraceEnabled(compilerOptions, host); - if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); - } - var moduleResolution = compilerOptions.moduleResolution; - if (moduleResolution === undefined) { - moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; - if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - else { - if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - var result; - switch (moduleResolution) { - case ts.ModuleResolutionKind.NodeJs: - result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); - break; - case ts.ModuleResolutionKind.Classic: - result = classicNameResolver(moduleName, containingFile, compilerOptions, host); - break; - } - if (traceEnabled) { - if (result.resolvedModule) { - ts.trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); - } - else { - ts.trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); - } - } - return result; - } - ts.resolveModuleName = resolveModuleName; - /** - * patternStrings contains both pattern strings (containing "*") and regular strings. - * Return an exact match if possible, or a pattern match, or undefined. - * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.) - */ - function matchPatternOrExact(patternStrings, candidate) { - var patterns = []; - for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { - var patternString = patternStrings_1[_i]; - var pattern = tryParsePattern(patternString); - if (pattern) { - patterns.push(pattern); - } - else if (patternString === candidate) { - // pattern was matched as is - no need to search further - return patternString; - } - } - return findBestPatternMatch(patterns, function (_) { return _; }, candidate); - } - function patternText(_a) { - var prefix = _a.prefix, suffix = _a.suffix; - return prefix + "*" + suffix; - } - /** - * Given that candidate matches pattern, returns the text matching the '*'. - * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar" - */ - function matchedText(pattern, candidate) { - ts.Debug.assert(isPatternMatch(pattern, candidate)); - return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); - } - /** Return the object corresponding to the best pattern to match `candidate`. */ - /* @internal */ - function findBestPatternMatch(values, getPattern, candidate) { - var matchedValue = undefined; - // use length of prefix as betterness criteria - var longestMatchPrefixLength = -1; - for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { - var v = values_1[_i]; - var pattern = getPattern(v); - if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { - longestMatchPrefixLength = pattern.prefix.length; - matchedValue = v; - } - } - return matchedValue; - } - ts.findBestPatternMatch = findBestPatternMatch; - function isPatternMatch(_a, candidate) { - var prefix = _a.prefix, suffix = _a.suffix; - return candidate.length >= prefix.length + suffix.length && - ts.startsWith(candidate, prefix) && - ts.endsWith(candidate, suffix); - } - /* @internal */ - function tryParsePattern(pattern) { - // This should be verified outside of here and a proper error thrown. - ts.Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern)); - var indexOfStar = pattern.indexOf("*"); - return indexOfStar === -1 ? undefined : { - prefix: pattern.substr(0, indexOfStar), - suffix: pattern.substr(indexOfStar + 1) - }; - } - ts.tryParsePattern = tryParsePattern; - /* @internal */ - function directoryProbablyExists(directoryName, host) { - // if host does not support 'directoryExists' assume that directory will exist - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - /* @internal */ - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - ts.pathToPackageJson = pathToPackageJson; -})(ts || (ts = {})); /// -/// /// /* @internal */ var ts; (function (ts) { + ts.bindTime = 0; (function (ModuleInstanceState) { ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated"; ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated"; @@ -15166,10 +14183,9 @@ var ts; })(ContainerFlags || (ContainerFlags = {})); var binder = createBinder(); function bindSourceFile(file, options) { - ts.performance.mark("beforeBind"); + var start = new Date().getTime(); binder(file, options); - ts.performance.mark("afterBind"); - ts.performance.measure("Bind", "beforeBind", "afterBind"); + ts.bindTime += new Date().getTime() - start; } ts.bindSourceFile = bindSourceFile; function createBinder() { @@ -15207,7 +14223,7 @@ var ts; options = opts; languageVersion = ts.getEmitScriptTarget(options); inStrictMode = !!file.externalModuleIndicator; - classifiableNames = ts.createMap(); + classifiableNames = {}; symbolCount = 0; Symbol = ts.objectAllocator.getSymbolConstructor(); if (!file.locals) { @@ -15246,10 +14262,10 @@ var ts; } symbol.declarations.push(node); if (symbolFlags & 1952 /* HasExports */ && !symbol.exports) { - symbol.exports = ts.createMap(); + symbol.exports = {}; } if (symbolFlags & 6240 /* HasMembers */ && !symbol.members) { - symbol.members = ts.createMap(); + symbol.members = {}; } if (symbolFlags & 107455 /* Value */) { var valueDeclaration = symbol.valueDeclaration; @@ -15351,10 +14367,7 @@ var ts; // The exported symbol for an export default function/class node is always named "default" var name = isDefaultExport && parent ? "default" : getDeclarationName(node); var symbol; - if (name === undefined) { - symbol = createSymbol(0 /* None */, "__missing"); - } - else { + if (name !== undefined) { // Check and see if the symbol table already has a symbol with this name. If not, // create a new symbol with this name and add it to the table. Note that we don't // give the new symbol any flags *yet*. This ensures that it will not conflict @@ -15366,11 +14379,6 @@ var ts; // declaration we have for this symbol, and then create a new symbol for this // declaration. // - // Note that when properties declared in Javascript constructors - // (marked by isReplaceableByMethod) conflict with another symbol, the property loses. - // Always. This allows the common Javascript pattern of overwriting a prototype method - // with an bound instance method of the same type: `this.method = this.method.bind(this)` - // // If we created a new symbol, either because we didn't have a symbol with this name // in the symbol table, or we conflicted with an existing symbol, then just add this // node as the sole declaration of the new symbol. @@ -15378,38 +14386,36 @@ var ts; // Otherwise, we'll be merging into a compatible existing symbol (for example when // you have multiple 'vars' with the same name in the same container). In this case // just add this node into the declarations list of the symbol. - symbol = symbolTable[name] || (symbolTable[name] = createSymbol(0 /* None */, name)); + symbol = ts.hasProperty(symbolTable, name) + ? symbolTable[name] + : (symbolTable[name] = createSymbol(0 /* None */, name)); if (name && (includes & 788448 /* Classifiable */)) { classifiableNames[name] = name; } if (symbol.flags & excludes) { - if (symbol.isReplaceableByMethod) { - // Javascript constructor-declared symbols can be discarded in favor of - // prototype symbols like methods. - symbol = symbolTable[name] = createSymbol(0 /* None */, name); + if (node.name) { + node.name.parent = node; } - else { - if (node.name) { - node.name.parent = node; + // Report errors every position with duplicate declaration + // Report errors on previous encountered declarations + var message_1 = symbol.flags & 2 /* BlockScopedVariable */ + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + : ts.Diagnostics.Duplicate_identifier_0; + ts.forEach(symbol.declarations, function (declaration) { + if (declaration.flags & 512 /* Default */) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; } - // Report errors every position with duplicate declaration - // Report errors on previous encountered declarations - var message_1 = symbol.flags & 2 /* BlockScopedVariable */ - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - ts.forEach(symbol.declarations, function (declaration) { - if (declaration.flags & 512 /* Default */) { - message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; - } - }); - ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); - }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); - symbol = createSymbol(0 /* None */, name); - } + }); + ts.forEach(symbol.declarations, function (declaration) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); + }); + file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); + symbol = createSymbol(0 /* None */, name); } } + else { + symbol = createSymbol(0 /* None */, "__missing"); + } addDeclarationToSymbol(symbol, node, includes); symbol.parent = parent; return symbol; @@ -15442,8 +14448,8 @@ var ts; // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. if (!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 8192 /* ExportContext */)) { var exportKind = (symbolFlags & 107455 /* Value */ ? 1048576 /* ExportValue */ : 0) | - (symbolFlags & 793064 /* Type */ ? 2097152 /* ExportType */ : 0) | - (symbolFlags & 1920 /* Namespace */ ? 4194304 /* ExportNamespace */ : 0); + (symbolFlags & 793056 /* Type */ ? 2097152 /* ExportType */ : 0) | + (symbolFlags & 1536 /* Namespace */ ? 4194304 /* ExportNamespace */ : 0); var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; @@ -15483,7 +14489,7 @@ var ts; if (containerFlags & 1 /* IsContainer */) { container = blockScopeContainer = node; if (containerFlags & 32 /* HasLocals */) { - container.locals = ts.createMap(); + container.locals = {}; } addToContainerChain(container); } @@ -15665,9 +14671,15 @@ var ts; } return false; } + function isNarrowingNullCheckOperands(expr1, expr2) { + return (expr1.kind === 93 /* NullKeyword */ || expr1.kind === 69 /* Identifier */ && expr1.text === "undefined") && isNarrowableOperand(expr2); + } function isNarrowingTypeofOperands(expr1, expr2) { return expr1.kind === 182 /* TypeOfExpression */ && isNarrowableOperand(expr1.expression) && expr2.kind === 9 /* StringLiteral */; } + function isNarrowingDiscriminant(expr) { + return expr.kind === 172 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); + } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { case 56 /* EqualsToken */: @@ -15676,8 +14688,9 @@ var ts; case 31 /* ExclamationEqualsToken */: case 32 /* EqualsEqualsEqualsToken */: case 33 /* ExclamationEqualsEqualsToken */: - return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || - isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); + return isNarrowingNullCheckOperands(expr.right, expr.left) || isNarrowingNullCheckOperands(expr.left, expr.right) || + isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right) || + isNarrowingDiscriminant(expr.left) || isNarrowingDiscriminant(expr.right); case 91 /* InstanceOfKeyword */: return isNarrowableOperand(expr.left); case 24 /* CommaToken */: @@ -15699,6 +14712,10 @@ var ts; } return isNarrowableReference(expr); } + function isNarrowingSwitchStatement(switchStatement) { + var expr = switchStatement.expression; + return expr.kind === 172 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); + } function createBranchLabel() { return { flags: 4 /* BranchLabel */, @@ -15743,7 +14760,7 @@ var ts; }; } function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { - if (!isNarrowingExpression(switchStatement.expression)) { + if (!isNarrowingSwitchStatement(switchStatement)) { return antecedent; } setFlowNodeReferenced(antecedent); @@ -16381,8 +15398,8 @@ var ts; addDeclarationToSymbol(symbol, node, 131072 /* Signature */); var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type"); addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */); - typeLiteralSymbol.members = ts.createMap(); - typeLiteralSymbol.members[symbol.name] = symbol; + typeLiteralSymbol.members = (_a = {}, _a[symbol.name] = symbol, _a); + var _a; } function bindObjectLiteralExpression(node) { var ElementKind; @@ -16391,7 +15408,7 @@ var ts; ElementKind[ElementKind["Accessor"] = 2] = "Accessor"; })(ElementKind || (ElementKind = {})); if (inStrictMode) { - var seen = ts.createMap(); + var seen = {}; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; if (prop.name.kind !== 69 /* Identifier */) { @@ -16439,7 +15456,7 @@ var ts; // fall through. default: if (!blockScopeContainer.locals) { - blockScopeContainer.locals = ts.createMap(); + blockScopeContainer.locals = {}; addToContainerChain(blockScopeContainer); } declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); @@ -16700,7 +15717,7 @@ var ts; case 154 /* TypePredicate */: return checkTypePredicate(node); case 141 /* TypeParameter */: - return declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 530920 /* TypeParameterExcludes */); + return declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 530912 /* TypeParameterExcludes */); case 142 /* Parameter */: return bindParameter(node); case 218 /* VariableDeclaration */: @@ -16716,7 +15733,7 @@ var ts; case 254 /* ShorthandPropertyAssignment */: return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); case 255 /* EnumMember */: - return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */); + return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 107455 /* EnumMemberExcludes */); case 247 /* JsxSpreadAttribute */: emitFlags |= 1073741824 /* HasJsxSpreadAttribute */; return; @@ -16764,10 +15781,10 @@ var ts; inStrictMode = true; return bindClassLikeDeclaration(node); case 222 /* InterfaceDeclaration */: - return bindBlockScopedDeclaration(node, 64 /* Interface */, 792968 /* InterfaceExcludes */); + return bindBlockScopedDeclaration(node, 64 /* Interface */, 792960 /* InterfaceExcludes */); case 279 /* JSDocTypedefTag */: case 223 /* TypeAliasDeclaration */: - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793056 /* TypeAliasExcludes */); case 224 /* EnumDeclaration */: return bindEnumDeclaration(node); case 225 /* ModuleDeclaration */: @@ -16818,15 +15835,18 @@ var ts; bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\""); } function bindExportAssignment(node) { + var boundExpression = node.kind === 235 /* ExportAssignment */ ? node.expression : node.right; if (!container.symbol || !container.symbol.exports) { // Export assignment in some sort of block construct bindAnonymousDeclaration(node, 8388608 /* Alias */, getDeclarationName(node)); } + else if (boundExpression.kind === 69 /* Identifier */ && node.kind === 235 /* ExportAssignment */) { + // An export default clause with an identifier exports all meanings of that identifier + declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* Alias */, 0 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); + } else { - var flags = node.kind === 235 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) - ? 8388608 /* Alias */ - : 4 /* Property */; - declareSymbol(container.symbol.exports, container.symbol, node, flags, 0 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); + // An export default clause with an expression exports a value + declareSymbol(container.symbol.exports, container.symbol, node, 4 /* Property */, 0 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); } } function bindNamespaceExportDeclaration(node) { @@ -16848,7 +15868,7 @@ var ts; return; } } - file.symbol.globalExports = file.symbol.globalExports || ts.createMap(); + file.symbol.globalExports = file.symbol.globalExports || {}; declareSymbol(file.symbol.globalExports, file.symbol, node, 8388608 /* Alias */, 8388608 /* AliasExcludes */); } function bindExportDeclaration(node) { @@ -16884,25 +15904,20 @@ var ts; declareSymbol(file.symbol.exports, file.symbol, node, 4 /* Property */ | 7340032 /* Export */ | 512 /* ValueModule */, 0 /* None */); } function bindThisPropertyAssignment(node) { - ts.Debug.assert(ts.isInJavaScriptFile(node)); - // Declare a 'member' if the container is an ES5 class or ES6 constructor - if (container.kind === 220 /* FunctionDeclaration */ || container.kind === 179 /* FunctionExpression */) { - container.symbol.members = container.symbol.members || ts.createMap(); - // It's acceptable for multiple 'this' assignments of the same identifier to occur - declareSymbol(container.symbol.members, container.symbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */); + // Declare a 'member' in case it turns out the container was an ES5 class or ES6 constructor + var assignee; + if (container.kind === 220 /* FunctionDeclaration */ || container.kind === 220 /* FunctionDeclaration */) { + assignee = container; } else if (container.kind === 148 /* Constructor */) { - // this.foo assignment in a JavaScript class - // Bind this property to the containing class - var saveContainer = container; - container = container.parent; - var symbol = bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* None */); - if (symbol) { - // constructor-declared symbols can be overwritten by subsequent method declarations - symbol.isReplaceableByMethod = true; - } - container = saveContainer; + assignee = container.parent; } + else { + return; + } + assignee.symbol.members = assignee.symbol.members || {}; + // It's acceptable for multiple 'this' assignments of the same identifier to occur + declareSymbol(assignee.symbol.members, assignee.symbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */); } function bindPrototypePropertyAssignment(node) { // We saw a node of the form 'x.prototype.y = z'. Declare a 'member' y on x if x was a function. @@ -16921,7 +15936,7 @@ var ts; } // Set up the members collection if it doesn't exist already if (!funcSymbol.members) { - funcSymbol.members = ts.createMap(); + funcSymbol.members = {}; } // Declare the method/property declareSymbol(funcSymbol.members, funcSymbol, leftSideOfAssignment, 4 /* Property */, 0 /* PropertyExcludes */); @@ -16964,7 +15979,7 @@ var ts; // module might have an exported variable called 'prototype'. We can't allow that as // that would clash with the built-in 'prototype' for the class. var prototypeSymbol = createSymbol(4 /* Property */ | 134217728 /* Prototype */, "prototype"); - if (symbol.exports[prototypeSymbol.name]) { + if (ts.hasProperty(symbol.exports, prototypeSymbol.name)) { if (node.name) { node.name.parent = node; } @@ -17119,7 +16134,6 @@ var ts; /* @internal */ var ts; (function (ts) { - var ambientModuleSymbolRegex = /^".+"$/; var nextSymbolId = 1; var nextNodeId = 1; var nextMergeId = 1; @@ -17132,6 +16146,7 @@ var ts; return node.id; } ts.getNodeId = getNodeId; + ts.checkTime = 0; function getSymbolId(symbol) { if (!symbol.id) { symbol.id = nextSymbolId; @@ -17157,7 +16172,7 @@ var ts; var typeCount = 0; var symbolCount = 0; var emptyArray = []; - var emptySymbols = ts.createMap(); + var emptySymbols = {}; var compilerOptions = host.getCompilerOptions(); var languageVersion = compilerOptions.target || 0 /* ES3 */; var modulekind = ts.getEmitModuleKind(compilerOptions); @@ -17209,45 +16224,36 @@ var ts; getAliasedSymbol: resolveAlias, getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, - getAmbientModules: getAmbientModules, getJsxElementAttributesType: getJsxElementAttributesType, getJsxIntrinsicTagNames: getJsxIntrinsicTagNames, isOptionalParameter: isOptionalParameter }; - var tupleTypes = []; - var unionTypes = ts.createMap(); - var intersectionTypes = ts.createMap(); - var stringLiteralTypes = ts.createMap(); - var numericLiteralTypes = ts.createMap(); var unknownSymbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "unknown"); var resolvingSymbol = createSymbol(67108864 /* Transient */, "__resolving__"); var anyType = createIntrinsicType(1 /* Any */, "any"); - var unknownType = createIntrinsicType(1 /* Any */, "unknown"); - var undefinedType = createIntrinsicType(2048 /* Undefined */, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 /* Undefined */ | 33554432 /* ContainsWideningType */, "undefined"); - var nullType = createIntrinsicType(4096 /* Null */, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(4096 /* Null */ | 33554432 /* ContainsWideningType */, "null"); var stringType = createIntrinsicType(2 /* String */, "string"); var numberType = createIntrinsicType(4 /* Number */, "number"); - var trueType = createIntrinsicType(128 /* BooleanLiteral */, "true"); - var falseType = createIntrinsicType(128 /* BooleanLiteral */, "false"); - var booleanType = createBooleanType([trueType, falseType]); - var esSymbolType = createIntrinsicType(512 /* ESSymbol */, "symbol"); - var voidType = createIntrinsicType(1024 /* Void */, "void"); - var neverType = createIntrinsicType(8192 /* Never */, "never"); + var booleanType = createIntrinsicType(8 /* Boolean */, "boolean"); + var esSymbolType = createIntrinsicType(16777216 /* ESSymbol */, "symbol"); + var voidType = createIntrinsicType(16 /* Void */, "void"); + var undefinedType = createIntrinsicType(32 /* Undefined */, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32 /* Undefined */ | 2097152 /* ContainsWideningType */, "undefined"); + var nullType = createIntrinsicType(64 /* Null */, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(64 /* Null */ | 2097152 /* ContainsWideningType */, "null"); + var unknownType = createIntrinsicType(1 /* Any */, "unknown"); + var neverType = createIntrinsicType(134217728 /* Never */, "never"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - emptyGenericType.instantiations = ts.createMap(); + emptyGenericType.instantiations = {}; var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. - anyFunctionType.flags |= 134217728 /* ContainsAnyFunctionType */; + anyFunctionType.flags |= 8388608 /* ContainsAnyFunctionType */; var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var anySignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var unknownSignature = createSignature(undefined, undefined, undefined, emptyArray, unknownType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var resolvingSignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var anySignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false); + var unknownSignature = createSignature(undefined, undefined, undefined, emptyArray, unknownType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false); var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); - var globals = ts.createMap(); + var globals = {}; /** * List of every ambient module with a "*" wildcard. * Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches. @@ -17291,8 +16297,10 @@ var ts; var flowLoopStart = 0; var flowLoopCount = 0; var visitedFlowCount = 0; - var emptyStringType = getLiteralTypeForText(32 /* StringLiteral */, ""); - var zeroType = getLiteralTypeForText(64 /* NumberLiteral */, "0"); + var tupleTypes = {}; + var unionTypes = {}; + var intersectionTypes = {}; + var stringLiteralTypes = {}; var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; @@ -17333,45 +16341,26 @@ var ts; TypeFacts[TypeFacts["NEUndefinedOrNull"] = 524288] = "NEUndefinedOrNull"; TypeFacts[TypeFacts["Truthy"] = 1048576] = "Truthy"; TypeFacts[TypeFacts["Falsy"] = 2097152] = "Falsy"; - TypeFacts[TypeFacts["Discriminatable"] = 4194304] = "Discriminatable"; - TypeFacts[TypeFacts["All"] = 8388607] = "All"; + TypeFacts[TypeFacts["All"] = 4194303] = "All"; // The following members encode facts about particular kinds of types for use in the getTypeFacts function. // The presence of a particular fact means that the given test is true for some (and possibly all) values // of that kind of type. - TypeFacts[TypeFacts["BaseStringStrictFacts"] = 933633] = "BaseStringStrictFacts"; - TypeFacts[TypeFacts["BaseStringFacts"] = 3145473] = "BaseStringFacts"; TypeFacts[TypeFacts["StringStrictFacts"] = 4079361] = "StringStrictFacts"; TypeFacts[TypeFacts["StringFacts"] = 4194049] = "StringFacts"; - TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 3030785] = "EmptyStringStrictFacts"; - TypeFacts[TypeFacts["EmptyStringFacts"] = 3145473] = "EmptyStringFacts"; - TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 1982209] = "NonEmptyStringStrictFacts"; - TypeFacts[TypeFacts["NonEmptyStringFacts"] = 4194049] = "NonEmptyStringFacts"; - TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 933506] = "BaseNumberStrictFacts"; - TypeFacts[TypeFacts["BaseNumberFacts"] = 3145346] = "BaseNumberFacts"; TypeFacts[TypeFacts["NumberStrictFacts"] = 4079234] = "NumberStrictFacts"; TypeFacts[TypeFacts["NumberFacts"] = 4193922] = "NumberFacts"; - TypeFacts[TypeFacts["ZeroStrictFacts"] = 3030658] = "ZeroStrictFacts"; - TypeFacts[TypeFacts["ZeroFacts"] = 3145346] = "ZeroFacts"; - TypeFacts[TypeFacts["NonZeroStrictFacts"] = 1982082] = "NonZeroStrictFacts"; - TypeFacts[TypeFacts["NonZeroFacts"] = 4193922] = "NonZeroFacts"; - TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 933252] = "BaseBooleanStrictFacts"; - TypeFacts[TypeFacts["BaseBooleanFacts"] = 3145092] = "BaseBooleanFacts"; TypeFacts[TypeFacts["BooleanStrictFacts"] = 4078980] = "BooleanStrictFacts"; TypeFacts[TypeFacts["BooleanFacts"] = 4193668] = "BooleanFacts"; - TypeFacts[TypeFacts["FalseStrictFacts"] = 3030404] = "FalseStrictFacts"; - TypeFacts[TypeFacts["FalseFacts"] = 3145092] = "FalseFacts"; - TypeFacts[TypeFacts["TrueStrictFacts"] = 1981828] = "TrueStrictFacts"; - TypeFacts[TypeFacts["TrueFacts"] = 4193668] = "TrueFacts"; TypeFacts[TypeFacts["SymbolStrictFacts"] = 1981320] = "SymbolStrictFacts"; TypeFacts[TypeFacts["SymbolFacts"] = 4193160] = "SymbolFacts"; - TypeFacts[TypeFacts["ObjectStrictFacts"] = 6166480] = "ObjectStrictFacts"; - TypeFacts[TypeFacts["ObjectFacts"] = 8378320] = "ObjectFacts"; - TypeFacts[TypeFacts["FunctionStrictFacts"] = 6164448] = "FunctionStrictFacts"; - TypeFacts[TypeFacts["FunctionFacts"] = 8376288] = "FunctionFacts"; + TypeFacts[TypeFacts["ObjectStrictFacts"] = 1972176] = "ObjectStrictFacts"; + TypeFacts[TypeFacts["ObjectFacts"] = 4184016] = "ObjectFacts"; + TypeFacts[TypeFacts["FunctionStrictFacts"] = 1970144] = "FunctionStrictFacts"; + TypeFacts[TypeFacts["FunctionFacts"] = 4181984] = "FunctionFacts"; TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts"; TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts"; })(TypeFacts || (TypeFacts = {})); - var typeofEQFacts = ts.createMap({ + var typeofEQFacts = { "string": 1 /* TypeofEQString */, "number": 2 /* TypeofEQNumber */, "boolean": 4 /* TypeofEQBoolean */, @@ -17379,8 +16368,8 @@ var ts; "undefined": 16384 /* EQUndefined */, "object": 16 /* TypeofEQObject */, "function": 32 /* TypeofEQFunction */ - }); - var typeofNEFacts = ts.createMap({ + }; + var typeofNEFacts = { "string": 128 /* TypeofNEString */, "number": 256 /* TypeofNENumber */, "boolean": 512 /* TypeofNEBoolean */, @@ -17388,17 +16377,17 @@ var ts; "undefined": 131072 /* NEUndefined */, "object": 2048 /* TypeofNEObject */, "function": 4096 /* TypeofNEFunction */ - }); - var typeofTypesByName = ts.createMap({ + }; + var typeofTypesByName = { "string": stringType, "number": numberType, "boolean": booleanType, "symbol": esSymbolType, "undefined": undefinedType - }); + }; var jsxElementType; /** Things we lazy load from the JSX namespace */ - var jsxTypes = ts.createMap(); + var jsxTypes = {}; var JsxNames = { JSX: "JSX", IntrinsicElements: "IntrinsicElements", @@ -17408,11 +16397,10 @@ var ts; IntrinsicAttributes: "IntrinsicAttributes", IntrinsicClassAttributes: "IntrinsicClassAttributes" }; - var subtypeRelation = ts.createMap(); - var assignableRelation = ts.createMap(); - var comparableRelation = ts.createMap(); - var identityRelation = ts.createMap(); - var enumRelation = ts.createMap(); + var subtypeRelation = {}; + var assignableRelation = {}; + var comparableRelation = {}; + var identityRelation = {}; // This is for caching the result of getSymbolDisplayBuilder. Do not access directly. var _displayBuilder; var TypeSystemPropertyName; @@ -17422,8 +16410,10 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); - var builtinGlobals = ts.createMap(); - builtinGlobals[undefinedSymbol.name] = undefinedSymbol; + var builtinGlobals = (_a = {}, + _a[undefinedSymbol.name] = undefinedSymbol, + _a + ); initializeTypeChecker(); return checker; function getEmitResolver(sourceFile, cancellationToken) { @@ -17451,13 +16441,13 @@ var ts; if (flags & 4 /* Property */) result |= 0 /* PropertyExcludes */; if (flags & 8 /* EnumMember */) - result |= 900095 /* EnumMemberExcludes */; + result |= 107455 /* EnumMemberExcludes */; if (flags & 16 /* Function */) result |= 106927 /* FunctionExcludes */; if (flags & 32 /* Class */) result |= 899519 /* ClassExcludes */; if (flags & 64 /* Interface */) - result |= 792968 /* InterfaceExcludes */; + result |= 792960 /* InterfaceExcludes */; if (flags & 256 /* RegularEnum */) result |= 899327 /* RegularEnumExcludes */; if (flags & 128 /* ConstEnum */) @@ -17471,9 +16461,9 @@ var ts; if (flags & 65536 /* SetAccessor */) result |= 74687 /* SetAccessorExcludes */; if (flags & 262144 /* TypeParameter */) - result |= 530920 /* TypeParameterExcludes */; + result |= 530912 /* TypeParameterExcludes */; if (flags & 524288 /* TypeAlias */) - result |= 793064 /* TypeAliasExcludes */; + result |= 793056 /* TypeAliasExcludes */; if (flags & 8388608 /* Alias */) result |= 8388608 /* AliasExcludes */; return result; @@ -17494,9 +16484,9 @@ var ts; if (symbol.constEnumOnlyModule) result.constEnumOnlyModule = true; if (symbol.members) - result.members = ts.cloneMap(symbol.members); + result.members = cloneSymbolTable(symbol.members); if (symbol.exports) - result.exports = ts.cloneMap(symbol.exports); + result.exports = cloneSymbolTable(symbol.exports); recordMergedSymbol(result, symbol); return result; } @@ -17518,12 +16508,12 @@ var ts; }); if (source.members) { if (!target.members) - target.members = ts.createMap(); + target.members = {}; mergeSymbolTable(target.members, source.members); } if (source.exports) { if (!target.exports) - target.exports = ts.createMap(); + target.exports = {}; mergeSymbolTable(target.exports, source.exports); } recordMergedSymbol(target, source); @@ -17539,17 +16529,28 @@ var ts; }); } } + function cloneSymbolTable(symbolTable) { + var result = {}; + for (var id in symbolTable) { + if (ts.hasProperty(symbolTable, id)) { + result[id] = symbolTable[id]; + } + } + return result; + } function mergeSymbolTable(target, source) { for (var id in source) { - var targetSymbol = target[id]; - if (!targetSymbol) { - target[id] = source[id]; - } - else { - if (!(targetSymbol.flags & 33554432 /* Merged */)) { - target[id] = targetSymbol = cloneSymbol(targetSymbol); + if (ts.hasProperty(source, id)) { + if (!ts.hasProperty(target, id)) { + target[id] = source[id]; + } + else { + var symbol = target[id]; + if (!(symbol.flags & 33554432 /* Merged */)) { + target[id] = symbol = cloneSymbol(symbol); + } + mergeSymbol(symbol, source[id]); } - mergeSymbol(targetSymbol, source[id]); } } } @@ -17577,7 +16578,7 @@ var ts; } // obtain item referenced by 'export=' mainModule = resolveExternalModuleSymbol(mainModule); - if (mainModule.flags & 1920 /* Namespace */) { + if (mainModule.flags & 1536 /* Namespace */) { // if module symbol has already been merged - it is safe to use it. // otherwise clone it mainModule = mainModule.flags & 33554432 /* Merged */ ? mainModule : cloneSymbol(mainModule); @@ -17590,12 +16591,14 @@ var ts; } function addToSymbolTable(target, source, message) { for (var id in source) { - if (target[id]) { - // Error on redeclarations - ts.forEach(target[id].declarations, addDeclarationDiagnostic(id, message)); - } - else { - target[id] = source[id]; + if (ts.hasProperty(source, id)) { + if (ts.hasProperty(target, id)) { + // Error on redeclarations + ts.forEach(target[id].declarations, addDeclarationDiagnostic(id, message)); + } + else { + target[id] = source[id]; + } } } function addDeclarationDiagnostic(id, message) { @@ -17610,26 +16613,24 @@ var ts; } function getNodeLinks(node) { var nodeId = getNodeId(node); - return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); + return nodeLinks[nodeId] || (nodeLinks[nodeId] = {}); } function isGlobalSourceFile(node) { return node.kind === 256 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { - if (meaning) { + if (meaning && ts.hasProperty(symbols, name)) { var symbol = symbols[name]; - if (symbol) { - ts.Debug.assert((symbol.flags & 16777216 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); - if (symbol.flags & meaning) { + ts.Debug.assert((symbol.flags & 16777216 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); + if (symbol.flags & meaning) { + return symbol; + } + if (symbol.flags & 8388608 /* Alias */) { + var target = resolveAlias(symbol); + // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors + if (target === unknownSymbol || target.flags & meaning) { return symbol; } - if (symbol.flags & 8388608 /* Alias */) { - var target = resolveAlias(symbol); - // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors - if (target === unknownSymbol || target.flags & meaning) { - return symbol; - } - } } } // return undefined if we can't find a symbol. @@ -17738,7 +16739,7 @@ var ts; // - parameters are only in the scope of function body // This restriction does not apply to JSDoc comment types because they are parented // at a higher level than type parameters would normally be - if (meaning & result.flags & 793064 /* Type */ && lastLocation.kind !== 273 /* JSDocComment */) { + if (meaning & result.flags & 793056 /* Type */ && lastLocation.kind !== 273 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ ? lastLocation === location.type || lastLocation.kind === 142 /* Parameter */ || @@ -17792,7 +16793,7 @@ var ts; // 2. We check === SymbolFlags.Alias in order to check that the symbol is *purely* // an alias. If we used &, we'd be throwing out symbols that have non alias aspects, // which is not the desired behavior. - if (moduleExports[name] && + if (ts.hasProperty(moduleExports, name) && moduleExports[name].flags === 8388608 /* Alias */ && ts.getDeclarationOfKind(moduleExports[name], 238 /* ExportSpecifier */)) { break; @@ -17828,7 +16829,7 @@ var ts; case 221 /* ClassDeclaration */: case 192 /* ClassExpression */: case 222 /* InterfaceDeclaration */: - if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064 /* Type */)) { + if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056 /* Type */)) { if (lastLocation && lastLocation.flags & 32 /* Static */) { // TypeScript 1.0 spec (April 2014): 3.4.1 // The scope of a type parameter extends over the entire declaration with which the type @@ -17858,7 +16859,7 @@ var ts; grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 222 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error - if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793064 /* Type */)) { + if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793056 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -17923,9 +16924,8 @@ var ts; } if (!result) { if (nameNotFoundMessage) { - if (!errorLocation || - !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && - !checkAndReportErrorForExtendingInterface(errorLocation)) { + if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForExtendingInterface(errorLocation)) { error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); } } @@ -17957,8 +16957,8 @@ var ts; checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } - // If we're in an external module, we can't reference value symbols created from UMD export declarations - if (result && isInExternalModule && (meaning & 107455 /* Value */) === 107455 /* Value */) { + // If we're in an external module, we can't reference symbols created from UMD export declarations + if (result && isInExternalModule) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 228 /* NamespaceExportDeclaration */) { error(errorLocation, ts.Diagnostics.Identifier_0_must_be_imported_from_a_module, name); @@ -17968,7 +16968,7 @@ var ts; return result; } function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { - if ((errorLocation.kind === 69 /* Identifier */ && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { + if (!errorLocation || (errorLocation.kind === 69 /* Identifier */ && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { return false; } var container = ts.getThisContainer(errorLocation, /* includeArrowFunctions */ true); @@ -18000,35 +17000,34 @@ var ts; return false; } function checkAndReportErrorForExtendingInterface(errorLocation) { - var expression = getEntityNameForExtendingInterface(errorLocation); - var isError = !!(expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)); - if (isError) { + var parentClassExpression = errorLocation; + while (parentClassExpression) { + var kind = parentClassExpression.kind; + if (kind === 69 /* Identifier */ || kind === 172 /* PropertyAccessExpression */) { + parentClassExpression = parentClassExpression.parent; + continue; + } + if (kind === 194 /* ExpressionWithTypeArguments */) { + break; + } + return false; + } + if (!parentClassExpression) { + return false; + } + var expression = parentClassExpression.expression; + if (resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)) { error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); + return true; } - return isError; - } - /** - * Climbs up parents to an ExpressionWithTypeArguments, and returns its expression, - * but returns undefined if that expression is not an EntityNameExpression. - */ - function getEntityNameForExtendingInterface(node) { - switch (node.kind) { - case 69 /* Identifier */: - case 172 /* PropertyAccessExpression */: - return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; - case 194 /* ExpressionWithTypeArguments */: - ts.Debug.assert(ts.isEntityNameExpression(node.expression)); - return node.expression; - default: - return undefined; - } + return false; } function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert((result.flags & 2 /* BlockScopedVariable */) !== 0); // Block-scoped variables cannot be used before their definition var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) ? d : undefined; }); ts.Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined"); - if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 218 /* VariableDeclaration */), errorLocation)) { + if (!isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 218 /* VariableDeclaration */), errorLocation)) { error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); } } @@ -18070,7 +17069,7 @@ var ts; function getTargetOfImportClause(node) { var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { - var exportDefaultSymbol = ts.isShorthandAmbientModuleSymbol(moduleSymbol) ? + var exportDefaultSymbol = ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration) ? moduleSymbol : moduleSymbol.exports["export="] ? getPropertyOfType(getTypeOfSymbol(moduleSymbol.exports["export="]), "default") : @@ -18107,7 +17106,7 @@ var ts; // An 'import { Point } from "graphics"' needs to create a symbol that combines the value side 'Point' // property with the type/namespace side interface 'Point'. function combineValueAndTypeSymbols(valueSymbol, typeSymbol) { - if (valueSymbol.flags & (793064 /* Type */ | 1920 /* Namespace */)) { + if (valueSymbol.flags & (793056 /* Type */ | 1536 /* Namespace */)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.name); @@ -18123,9 +17122,9 @@ var ts; } function getExportOfModule(symbol, name) { if (symbol.flags & 1536 /* Module */) { - var exportedSymbol = getExportsOfSymbol(symbol)[name]; - if (exportedSymbol) { - return resolveSymbol(exportedSymbol); + var exports = getExportsOfSymbol(symbol); + if (ts.hasProperty(exports, name)) { + return resolveSymbol(exports[name]); } } } @@ -18143,7 +17142,7 @@ var ts; if (targetSymbol) { var name_10 = specifier.propertyName || specifier.name; if (name_10.text) { - if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + if (ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration)) { return moduleSymbol; } var symbolFromVariable = void 0; @@ -18157,10 +17156,6 @@ var ts; // if symbolFromVariable is export - get its final target symbolFromVariable = resolveSymbol(symbolFromVariable); var symbolFromModule = getExportOfModule(targetSymbol, name_10.text); - // If the export member we're looking for is default, and there is no real default but allowSyntheticDefaultImports is on, return the entire module as the default - if (!symbolFromModule && allowSyntheticDefaultImports && name_10.text === "default") { - symbolFromModule = resolveExternalModuleSymbol(moduleSymbol) || resolveSymbol(moduleSymbol); - } var symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; @@ -18180,10 +17175,10 @@ var ts; function getTargetOfExportSpecifier(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */); + resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */); } function getTargetOfExportAssignment(node) { - return resolveEntityName(node.expression, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */); + return resolveEntityName(node.expression, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */); } function getTargetOfAliasDeclaration(node) { switch (node.kind) { @@ -18204,7 +17199,7 @@ var ts; } } function resolveSymbol(symbol) { - return symbol && symbol.flags & 8388608 /* Alias */ && !(symbol.flags & (107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */)) ? resolveAlias(symbol) : symbol; + return symbol && symbol.flags & 8388608 /* Alias */ && !(symbol.flags & (107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */)) ? resolveAlias(symbol) : symbol; } function resolveAlias(symbol) { ts.Debug.assert((symbol.flags & 8388608 /* Alias */) !== 0, "Should only get Alias here."); @@ -18212,7 +17207,6 @@ var ts; if (!links.target) { links.target = resolvingSymbol; var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); var target = getTargetOfAliasDeclaration(node); if (links.target === resolvingSymbol) { links.target = target || unknownSymbol; @@ -18245,7 +17239,6 @@ var ts; if (!links.referenced) { links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); if (node.kind === 235 /* ExportAssignment */) { // export default checkExpressionCached(node.expression); @@ -18273,13 +17266,13 @@ var ts; } // Check for case 1 and 3 in the above example if (entityName.kind === 69 /* Identifier */ || entityName.parent.kind === 139 /* QualifiedName */) { - return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + return resolveEntityName(entityName, 1536 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } else { // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier ts.Debug.assert(entityName.parent.kind === 229 /* ImportEqualsDeclaration */); - return resolveEntityName(entityName, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + return resolveEntityName(entityName, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } function getFullyQualifiedName(symbol) { @@ -18292,7 +17285,7 @@ var ts; } var symbol; if (name.kind === 69 /* Identifier */) { - var message = meaning === 1920 /* Namespace */ ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; + var message = meaning === 1536 /* Namespace */ ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; symbol = resolveName(name, name.text, meaning, ignoreErrors ? undefined : message, name); if (!symbol) { return undefined; @@ -18301,7 +17294,7 @@ var ts; else if (name.kind === 139 /* QualifiedName */ || name.kind === 172 /* PropertyAccessExpression */) { var left = name.kind === 139 /* QualifiedName */ ? name.left : name.expression; var right = name.kind === 139 /* QualifiedName */ ? name.right : name.name; - var namespace = resolveEntityName(left, 1920 /* Namespace */, ignoreErrors); + var namespace = resolveEntityName(left, 1536 /* Namespace */, ignoreErrors); if (!namespace || ts.nodeIsMissing(right)) { return undefined; } @@ -18365,14 +17358,7 @@ var ts; } if (moduleNotFoundError) { // report errors only if it was requested - var tsExtension = ts.tryExtractTypeScriptExtension(moduleName); - if (tsExtension) { - var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; - error(moduleReferenceLiteral, diag, tsExtension, ts.removeExtension(moduleName, tsExtension)); - } - else { - error(moduleReferenceLiteral, moduleNotFoundError, moduleName); - } + error(moduleReferenceLiteral, moduleNotFoundError, moduleName); } return undefined; } @@ -18411,7 +17397,7 @@ var ts; */ function extendExportSymbols(target, source, lookupTable, exportNode) { for (var id in source) { - if (id !== "default" && !target[id]) { + if (id !== "default" && !ts.hasProperty(target, id)) { target[id] = source[id]; if (lookupTable && exportNode) { lookupTable[id] = { @@ -18419,7 +17405,7 @@ var ts; }; } } - else if (lookupTable && exportNode && id !== "default" && target[id] && resolveSymbol(target[id]) !== resolveSymbol(source[id])) { + else if (lookupTable && exportNode && id !== "default" && ts.hasProperty(target, id) && resolveSymbol(target[id]) !== resolveSymbol(source[id])) { if (!lookupTable[id].exportsWithDuplicate) { lookupTable[id].exportsWithDuplicate = [exportNode]; } @@ -18439,12 +17425,12 @@ var ts; return; } visitedSymbols.push(symbol); - var symbols = ts.cloneMap(symbol.exports); + var symbols = cloneSymbolTable(symbol.exports); // All export * declarations are collected in an __export symbol by the binder var exportStars = symbol.exports["__export"]; if (exportStars) { - var nestedSymbols = ts.createMap(); - var lookupTable = ts.createMap(); + var nestedSymbols = {}; + var lookupTable = {}; for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { var node = _a[_i]; var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); @@ -18454,7 +17440,7 @@ var ts; for (var id in lookupTable) { var exportsWithDuplicate = lookupTable[id].exportsWithDuplicate; // It's not an error if the file with multiple `export *`s with duplicate names exports a member with that name itself - if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols[id]) { + if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || ts.hasProperty(symbols, id)) { continue; } for (var _b = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _b < exportsWithDuplicate_1.length; _b++) { @@ -18509,8 +17495,8 @@ var ts; } function createType(flags) { var result = new Type(checker, flags); - typeCount++; result.id = typeCount; + typeCount++; return result; } function createIntrinsicType(kind, intrinsicName) { @@ -18518,12 +17504,6 @@ var ts; type.intrinsicName = intrinsicName; return type; } - function createBooleanType(trueFalseTypes) { - var type = getUnionType(trueFalseTypes); - type.flags |= 8 /* Boolean */; - type.intrinsicName = "boolean"; - return type; - } function createObjectType(kind, symbol) { var type = createType(kind); type.symbol = symbol; @@ -18542,12 +17522,14 @@ var ts; function getNamedMembers(members) { var result; for (var id in members) { - if (!isReservedMemberName(id)) { - if (!result) - result = []; - var symbol = members[id]; - if (symbolIsValue(symbol)) { - result.push(symbol); + if (ts.hasProperty(members, id)) { + if (!isReservedMemberName(id)) { + if (!result) + result = []; + var symbol = members[id]; + if (symbolIsValue(symbol)) { + result.push(symbol); + } } } } @@ -18565,7 +17547,7 @@ var ts; return type; } function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { - return setObjectTypeMembers(createObjectType(2097152 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + return setObjectTypeMembers(createObjectType(65536 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function forEachSymbolTableInScope(enclosingDeclaration, callback) { var result; @@ -18592,7 +17574,7 @@ var ts; } function getQualifiedLeftMeaning(rightMeaning) { // If we are looking in value space, the parent meaning is value, other wise it is namespace - return rightMeaning === 107455 /* Value */ ? 107455 /* Value */ : 1920 /* Namespace */; + return rightMeaning === 107455 /* Value */ ? 107455 /* Value */ : 1536 /* Namespace */; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { function getAccessibleSymbolChainFromSymbolTable(symbols) { @@ -18615,11 +17597,11 @@ var ts; } } // If symbol is directly available by its name in the symbol table - if (isAccessible(symbols[symbol.name])) { + if (isAccessible(ts.lookUp(symbols, symbol.name))) { return [symbol]; } // Check if symbol is any of the alias - return ts.forEachProperty(symbols, function (symbolFromSymbolTable) { + return ts.forEachValue(symbols, function (symbolFromSymbolTable) { if (symbolFromSymbolTable.flags & 8388608 /* Alias */ && symbolFromSymbolTable.name !== "export=" && !ts.getDeclarationOfKind(symbolFromSymbolTable, 238 /* ExportSpecifier */)) { @@ -18650,12 +17632,12 @@ var ts; var qualify = false; forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { // If symbol of this name is not available in the symbol table we are ok - var symbolFromSymbolTable = symbolTable[symbol.name]; - if (!symbolFromSymbolTable) { + if (!ts.hasProperty(symbolTable, symbol.name)) { // Continue to the next symbol table return false; } // If the symbol with this name is present it should refer to the symbol + var symbolFromSymbolTable = symbolTable[symbol.name]; if (symbolFromSymbolTable === symbol) { // No need to qualify return true; @@ -18702,7 +17684,7 @@ var ts; return { accessibility: 1 /* NotAccessible */, errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920 /* Namespace */) : undefined + errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1536 /* Namespace */) : undefined }; } return hasAccessibleDeclarations; @@ -18796,11 +17778,11 @@ var ts; entityName.parent.kind === 229 /* ImportEqualsDeclaration */) { // Left identifier from type reference or TypeAlias // Entity name of the import declaration - meaning = 1920 /* Namespace */; + meaning = 1536 /* Namespace */; } else { // Type Reference or TypeAlias entity = Identifier - meaning = 793064 /* Type */; + meaning = 793056 /* Type */; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.text, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); @@ -18852,31 +17834,6 @@ var ts; ts.releaseStringWriter(writer); return result; } - function formatUnionTypes(types) { - var result = []; - var flags = 0; - for (var i = 0; i < types.length; i++) { - var t = types[i]; - flags |= t.flags; - if (!(t.flags & 6144 /* Nullable */)) { - if (t.flags & (128 /* BooleanLiteral */ | 256 /* EnumLiteral */)) { - var baseType = t.flags & 128 /* BooleanLiteral */ ? booleanType : t.baseType; - var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { - result.push(baseType); - i += count - 1; - continue; - } - } - result.push(t); - } - } - if (flags & 4096 /* Null */) - result.push(nullType); - if (flags & 2048 /* Undefined */) - result.push(undefinedType); - return result || types; - } function visibilityToString(flags) { if (flags === 8 /* Private */) { return "private"; @@ -19026,53 +17983,38 @@ var ts; var inObjectTypeLiteral = false; return writeType(type, globalFlags); function writeType(type, flags) { - var nextFlags = flags & ~512 /* InTypeAlias */; // Write undefined/null type as any - if (type.flags & 16015 /* Intrinsic */) { + if (type.flags & 150995071 /* Intrinsic */) { // Special handling for unknown / resolving types, they should show up as any and not unknown or __resolving writer.writeKeyword(!(globalFlags & 16 /* WriteOwnNameForAnyLike */) && isTypeAny(type) ? "any" : type.intrinsicName); } - else if (type.flags & 268435456 /* ThisType */) { + else if (type.flags & 33554432 /* ThisType */) { if (inObjectTypeLiteral) { writer.reportInaccessibleThisError(); } writer.writeKeyword("this"); } - else if (type.flags & 131072 /* Reference */) { - writeTypeReference(type, nextFlags); + else if (type.flags & 4096 /* Reference */) { + writeTypeReference(type, flags); } - else if (type.flags & 256 /* EnumLiteral */) { - buildSymbolDisplay(getParentOfSymbol(type.symbol), writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); - writePunctuation(writer, 21 /* DotToken */); - appendSymbolNameOnly(type.symbol, writer); - } - else if (type.flags & (32768 /* Class */ | 65536 /* Interface */ | 16 /* Enum */ | 16384 /* TypeParameter */)) { + else if (type.flags & (1024 /* Class */ | 2048 /* Interface */ | 128 /* Enum */ | 512 /* TypeParameter */)) { // The specified symbol flags need to be reinterpreted as type flags - buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); + buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793056 /* Type */, 0 /* None */, flags); } - else if (!(flags & 512 /* InTypeAlias */) && type.flags & (2097152 /* Anonymous */ | 1572864 /* UnionOrIntersection */) && type.aliasSymbol) { - if (type.flags & 2097152 /* Anonymous */ || !(flags & 1024 /* UseTypeAliasValue */)) { - var typeArguments = type.aliasTypeArguments; - writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); - } - else { - writeUnionOrIntersectionType(type, nextFlags); - } + else if (type.flags & 8192 /* Tuple */) { + writeTupleType(type); } - else if (type.flags & 1572864 /* UnionOrIntersection */) { - writeUnionOrIntersectionType(type, nextFlags); + else if (type.flags & 49152 /* UnionOrIntersection */) { + writeUnionOrIntersectionType(type, flags); } - else if (type.flags & 2097152 /* Anonymous */) { - writeAnonymousType(type, nextFlags); + else if (type.flags & 65536 /* Anonymous */) { + writeAnonymousType(type, flags); } - else if (type.flags & 32 /* StringLiteral */) { + else if (type.flags & 256 /* StringLiteral */) { writer.writeStringLiteral("\"" + ts.escapeString(type.text) + "\""); } - else if (type.flags & 64 /* NumberLiteral */) { - writer.writeStringLiteral(type.text); - } else { // Should never get here // { ... } @@ -19098,7 +18040,7 @@ var ts; function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { // Unnamed function expressions and arrow functions have reserved names that we don't want to display if (symbol.flags & 32 /* Class */ || !isReservedMemberName(symbol.name)) { - buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, flags); + buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793056 /* Type */, 0 /* None */, flags); } if (pos < end) { writePunctuation(writer, 25 /* LessThanToken */); @@ -19120,11 +18062,6 @@ var ts; writePunctuation(writer, 19 /* OpenBracketToken */); writePunctuation(writer, 20 /* CloseBracketToken */); } - else if (type.target.flags & 262144 /* Tuple */) { - writePunctuation(writer, 19 /* OpenBracketToken */); - writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 24 /* CommaToken */); - writePunctuation(writer, 20 /* CloseBracketToken */); - } else { // Write the type reference in the format f.g.C where A and B are type arguments // for outer type parameters, and f and g are the respective declaring containers of those @@ -19152,16 +18089,16 @@ var ts; writeSymbolTypeReference(type.symbol, typeArguments, i, typeParameterCount, flags); } } + function writeTupleType(type) { + writePunctuation(writer, 19 /* OpenBracketToken */); + writeTypeList(type.elementTypes, 24 /* CommaToken */); + writePunctuation(writer, 20 /* CloseBracketToken */); + } function writeUnionOrIntersectionType(type, flags) { if (flags & 64 /* InElementType */) { writePunctuation(writer, 17 /* OpenParenToken */); } - if (type.flags & 524288 /* Union */) { - writeTypeList(formatUnionTypes(type.types), 47 /* BarToken */); - } - else { - writeTypeList(type.types, 46 /* AmpersandToken */); - } + writeTypeList(type.types, type.flags & 16384 /* Union */ ? 47 /* BarToken */ : 46 /* AmpersandToken */); if (flags & 64 /* InElementType */) { writePunctuation(writer, 18 /* CloseParenToken */); } @@ -19181,7 +18118,7 @@ var ts; var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, flags); + buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793056 /* Type */, 0 /* None */, flags); } else { // Recursive usage, use any @@ -19604,13 +18541,13 @@ var ts; function collectLinkedAliases(node) { var exportSymbol; if (node.parent && node.parent.kind === 235 /* ExportAssignment */) { - exportSymbol = resolveName(node.parent, node.text, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */, ts.Diagnostics.Cannot_find_name_0, node); + exportSymbol = resolveName(node.parent, node.text, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */, ts.Diagnostics.Cannot_find_name_0, node); } else if (node.parent.kind === 238 /* ExportSpecifier */) { var exportSpecifier = node.parent; exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : - resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */); + resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */); } var result = []; if (exportSymbol) { @@ -19628,7 +18565,7 @@ var ts; // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.text, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, undefined, undefined); + var importSymbol = resolveName(declaration, firstIdentifier.text, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */, undefined, undefined); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -19681,7 +18618,7 @@ var ts; return getSymbolLinks(target).declaredType; } if (propertyName === 1 /* ResolvedBaseConstructorType */) { - ts.Debug.assert(!!(target.flags & 32768 /* Class */)); + ts.Debug.assert(!!(target.flags & 1024 /* Class */)); return target.resolvedBaseConstructorType; } if (propertyName === 3 /* ResolvedReturnType */) { @@ -19730,7 +18667,7 @@ var ts; return type && (type.flags & 1 /* Any */) !== 0; } function isTypeNever(type) { - return type && (type.flags & 8192 /* Never */) !== 0; + return type && (type.flags & 134217728 /* Never */) !== 0; } // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been // assigned by contextual typing. @@ -19807,7 +18744,7 @@ var ts; : elementType; if (!type) { if (isTupleType(parentType)) { - error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); + error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), parentType.elementTypes.length, pattern.elements.length); } else { error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), propName); @@ -19822,12 +18759,10 @@ var ts; } // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 2048 /* Undefined */)) { + if (strictNullChecks && declaration.initializer && !(getCombinedTypeFlags(checkExpressionCached(declaration.initializer)) & 32 /* Undefined */)) { type = getTypeWithFacts(type, 131072 /* NEUndefined */); } - return declaration.initializer ? - getUnionType([type, checkExpressionCached(declaration.initializer)], /*subtypeReduction*/ true) : - type; + return type; } function getTypeForVariableLikeDeclarationFromJSDocComment(declaration) { var jsDocType = getJSDocTypeForVariableLikeDeclarationFromJSDocComment(declaration); @@ -19861,7 +18796,7 @@ var ts; return undefined; } function addOptionality(type, optional) { - return strictNullChecks && optional ? includeFalsyTypes(type, 2048 /* Undefined */) : type; + return strictNullChecks && optional ? addTypeKind(type, 32 /* Undefined */) : type; } // Return the inferred type for a variable, parameter, or property declaration function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { @@ -19909,14 +18844,9 @@ var ts; } } // Use contextual parameter type if one is available - var type = void 0; - if (declaration.symbol.name === "this") { - var thisParameter = getContextualThisParameter(func); - type = thisParameter ? getTypeOfSymbol(thisParameter) : undefined; - } - else { - type = getContextuallyTypedParameterType(declaration); - } + var type = declaration.symbol.name === "this" + ? getContextuallyTypedThisType(func) + : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, /*optional*/ declaration.questionToken && includeOptionality); } @@ -19931,7 +18861,7 @@ var ts; } // If the declaration specifies a binding pattern, use the type implied by the binding pattern if (ts.isBindingPattern(declaration.name)) { - return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true); + return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false); } // No type specified and nothing can be inferred return undefined; @@ -19939,21 +18869,23 @@ var ts; // Return the type implied by a binding pattern element. This is the type of the initializer of the element if // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding // pattern. Otherwise, it is the type any. - function getTypeFromBindingElement(element, includePatternInType, reportErrors) { + function getTypeFromBindingElement(element, includePatternInType) { if (element.initializer) { - return checkExpressionCached(element.initializer); + var type = checkExpressionCached(element.initializer); + reportErrorsFromWidening(element, type); + return getWidenedType(type); } if (ts.isBindingPattern(element.name)) { - return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); + return getTypeFromBindingPattern(element.name, includePatternInType); } - if (reportErrors && compilerOptions.noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { + if (compilerOptions.noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { reportImplicitAnyError(element, anyType); } return anyType; } // Return the type implied by an object binding pattern - function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { - var members = ts.createMap(); + function getTypeFromObjectBindingPattern(pattern, includePatternInType) { + var members = {}; var hasComputedProperties = false; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; @@ -19965,7 +18897,7 @@ var ts; var text = getTextOfPropertyName(name); var flags = 4 /* Property */ | 67108864 /* Transient */ | (e.initializer ? 536870912 /* Optional */ : 0); var symbol = createSymbol(flags, text); - symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); + symbol.type = getTypeFromBindingElement(e, includePatternInType); symbol.bindingElement = e; members[symbol.name] = symbol; }); @@ -19974,24 +18906,24 @@ var ts; result.pattern = pattern; } if (hasComputedProperties) { - result.flags |= 536870912 /* ObjectLiteralPatternWithComputedProperties */; + result.flags |= 67108864 /* ObjectLiteralPatternWithComputedProperties */; } return result; } // Return the type implied by an array binding pattern - function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { + function getTypeFromArrayBindingPattern(pattern, includePatternInType) { var elements = pattern.elements; if (elements.length === 0 || elements[elements.length - 1].dotDotDotToken) { return languageVersion >= 2 /* ES6 */ ? createIterableType(anyType) : anyArrayType; } // If the pattern has at least one element, and no rest element, then it should imply a tuple type. - var elementTypes = ts.map(elements, function (e) { return e.kind === 193 /* OmittedExpression */ ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); }); - var result = createTupleType(elementTypes); + var elementTypes = ts.map(elements, function (e) { return e.kind === 193 /* OmittedExpression */ ? anyType : getTypeFromBindingElement(e, includePatternInType); }); if (includePatternInType) { - result = cloneTypeReference(result); + var result = createNewTupleType(elementTypes); result.pattern = pattern; + return result; } - return result; + return createTupleType(elementTypes); } // Return the type implied by a binding pattern. This is the type implied purely by the binding pattern itself // and without regard to its context (i.e. without regard any type annotation or initializer associated with the @@ -20000,10 +18932,10 @@ var ts; // used as the contextual type of an initializer associated with the binding pattern. Also, for a destructuring // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of // the parameter. - function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { + function getTypeFromBindingPattern(pattern, includePatternInType) { return pattern.kind === 167 /* ObjectBindingPattern */ - ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) - : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); + ? getTypeFromObjectBindingPattern(pattern, includePatternInType) + : getTypeFromArrayBindingPattern(pattern, includePatternInType); } // Return the type associated with a variable, parameter, or property declaration. In the simple case this is the type // specified in a type annotation or inferred from an initializer. However, in the case of a destructuring declaration it @@ -20059,34 +18991,24 @@ var ts; if (declaration.kind === 235 /* ExportAssignment */) { return links.type = checkExpression(declaration.expression); } - if (declaration.flags & 134217728 /* JavaScriptFile */ && declaration.kind === 280 /* JSDocPropertyTag */ && declaration.typeExpression) { - return links.type = getTypeFromTypeNode(declaration.typeExpression.type); - } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { return unknownType; } - var type = void 0; - // Handle certain special assignment kinds, which happen to union across multiple declarations: - // * module.exports = expr - // * exports.p = expr - // * this.p = expr - // * className.prototype.method = expr - if (declaration.kind === 187 /* BinaryExpression */ || - declaration.kind === 172 /* PropertyAccessExpression */ && declaration.parent.kind === 187 /* BinaryExpression */) { - // Use JS Doc type if present on parent expression statement - if (declaration.flags & 134217728 /* JavaScriptFile */) { - var typeTag = ts.getJSDocTypeTag(declaration.parent); - if (typeTag && typeTag.typeExpression) { - return links.type = getTypeFromTypeNode(typeTag.typeExpression.type); - } - } - var declaredTypes = ts.map(symbol.declarations, function (decl) { return decl.kind === 187 /* BinaryExpression */ ? - checkExpressionCached(decl.right) : - checkExpressionCached(decl.parent.right); }); - type = getUnionType(declaredTypes, /*subtypeReduction*/ true); + var type = undefined; + // Handle module.exports = expr or this.p = expr + if (declaration.kind === 187 /* BinaryExpression */) { + type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); })); } - else { + else if (declaration.kind === 172 /* PropertyAccessExpression */) { + // Declarations only exist for property access expressions for certain + // special assignment kinds + if (declaration.parent.kind === 187 /* BinaryExpression */) { + // Handle exports.p = expr or className.prototype.method = expr + type = checkExpressionCached(declaration.parent.right); + } + } + if (type === undefined) { type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); } if (!popTypeResolution()) { @@ -20159,13 +19081,7 @@ var ts; } else { if (compilerOptions.noImplicitAny) { - if (setter) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } + error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation, symbolToString(symbol)); } type = anyType; } @@ -20185,13 +19101,13 @@ var ts; function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbol.valueDeclaration.kind === 225 /* ModuleDeclaration */ && ts.isShorthandAmbientModuleSymbol(symbol)) { + if (symbol.valueDeclaration.kind === 225 /* ModuleDeclaration */ && ts.isShorthandAmbientModule(symbol.valueDeclaration)) { links.type = anyType; } else { - var type = createObjectType(2097152 /* Anonymous */, symbol); + var type = createObjectType(65536 /* Anonymous */, symbol); links.type = strictNullChecks && symbol.flags & 536870912 /* Optional */ ? - includeFalsyTypes(type, 2048 /* Undefined */) : type; + addTypeKind(type, 32 /* Undefined */) : type; } } return links.type; @@ -20247,7 +19163,7 @@ var ts; return unknownType; } function getTargetType(type) { - return type.flags & 131072 /* Reference */ ? type.target : type; + return type.flags & 4096 /* Reference */ ? type.target : type; } function hasBaseType(type, checkBase) { return check(type); @@ -20318,7 +19234,7 @@ var ts; return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); } function isConstructorType(type) { - return type.flags & 2588672 /* ObjectType */ && getSignaturesOfType(type, 1 /* Construct */).length > 0; + return type.flags & 80896 /* ObjectType */ && getSignaturesOfType(type, 1 /* Construct */).length > 0; } function getBaseTypeNodeOfClass(type) { return ts.getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); @@ -20350,7 +19266,7 @@ var ts; return unknownType; } var baseConstructorType = checkExpression(baseTypeNode.expression); - if (baseConstructorType.flags & 2588672 /* ObjectType */) { + if (baseConstructorType.flags & 80896 /* ObjectType */) { // Resolving the members of a class requires us to resolve the base class of that class. // We force resolution here such that we catch circularities now. resolveStructuredTypeMembers(baseConstructorType); @@ -20368,28 +19284,25 @@ var ts; return type.resolvedBaseConstructorType; } function getBaseTypes(type) { + var isClass = type.symbol.flags & 32 /* Class */; + var isInterface = type.symbol.flags & 64 /* Interface */; if (!type.resolvedBaseTypes) { - if (type.flags & 262144 /* Tuple */) { - type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters))]; - } - else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) { - if (type.symbol.flags & 32 /* Class */) { - resolveBaseTypesOfClass(type); - } - if (type.symbol.flags & 64 /* Interface */) { - resolveBaseTypesOfInterface(type); - } - } - else { + if (!isClass && !isInterface) { ts.Debug.fail("type must be class or interface"); } + if (isClass) { + resolveBaseTypesOfClass(type); + } + if (isInterface) { + resolveBaseTypesOfInterface(type); + } } return type.resolvedBaseTypes; } function resolveBaseTypesOfClass(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; var baseConstructorType = getBaseConstructorTypeOfClass(type); - if (!(baseConstructorType.flags & 2588672 /* ObjectType */)) { + if (!(baseConstructorType.flags & 80896 /* ObjectType */)) { return; } var baseTypeNode = getBaseTypeNodeOfClass(type); @@ -20416,7 +19329,7 @@ var ts; if (baseType === unknownType) { return; } - if (!(getTargetType(baseType).flags & (32768 /* Class */ | 65536 /* Interface */))) { + if (!(getTargetType(baseType).flags & (1024 /* Class */ | 2048 /* Interface */))) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); return; } @@ -20451,7 +19364,7 @@ var ts; var node = _c[_b]; var baseType = getTypeFromTypeNode(node); if (baseType !== unknownType) { - if (getTargetType(baseType).flags & (32768 /* Class */ | 65536 /* Interface */)) { + if (getTargetType(baseType).flags & (1024 /* Class */ | 2048 /* Interface */)) { if (type !== baseType && !hasBaseType(baseType, type)) { if (type.resolvedBaseTypes === emptyArray) { type.resolvedBaseTypes = [baseType]; @@ -20486,8 +19399,8 @@ var ts; if (baseTypeNodes) { for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { var node = baseTypeNodes_1[_b]; - if (ts.isEntityNameExpression(node.expression)) { - var baseSymbol = resolveEntityName(node.expression, 793064 /* Type */, /*ignoreErrors*/ true); + if (ts.isSupportedExpressionWithTypeArguments(node)) { + var baseSymbol = resolveEntityName(node.expression, 793056 /* Type */, /*ignoreErrors*/ true); if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -20501,7 +19414,7 @@ var ts; function getDeclaredTypeOfClassOrInterface(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var kind = symbol.flags & 32 /* Class */ ? 32768 /* Class */ : 65536 /* Interface */; + var kind = symbol.flags & 32 /* Class */ ? 1024 /* Class */ : 2048 /* Interface */; var type = links.declaredType = createObjectType(kind, symbol); var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); @@ -20510,16 +19423,16 @@ var ts; // property types inferred from initializers and method return types inferred from return statements are very hard // to exhaustively analyze). We give interfaces a "this" type if we can't definitely determine that they are free of // "this" references. - if (outerTypeParameters || localTypeParameters || kind === 32768 /* Class */ || !isIndependentInterface(symbol)) { - type.flags |= 131072 /* Reference */; + if (outerTypeParameters || localTypeParameters || kind === 1024 /* Class */ || !isIndependentInterface(symbol)) { + type.flags |= 4096 /* Reference */; type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); type.outerTypeParameters = outerTypeParameters; type.localTypeParameters = localTypeParameters; - type.instantiations = ts.createMap(); + type.instantiations = {}; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 /* TypeParameter */ | 268435456 /* ThisType */); + type.thisType = createType(512 /* TypeParameter */ | 33554432 /* ThisType */); type.thisType.symbol = symbol; type.thisType.constraint = type; } @@ -20534,9 +19447,8 @@ var ts; if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) { return unknownType; } - var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - var declaration = ts.getDeclarationOfKind(symbol, 279 /* JSDocTypedefTag */); var type = void 0; + var declaration = ts.getDeclarationOfKind(symbol, 279 /* JSDocTypedefTag */); if (declaration) { if (declaration.jsDocTypeLiteral) { type = getTypeFromTypeNode(declaration.jsDocTypeLiteral); @@ -20547,14 +19459,14 @@ var ts; } else { declaration = ts.getDeclarationOfKind(symbol, 223 /* TypeAliasDeclaration */); - type = getTypeFromTypeNode(declaration.type, symbol, typeParameters); + type = getTypeFromTypeNode(declaration.type); } if (popTypeResolution()) { - links.typeParameters = typeParameters; - if (typeParameters) { + links.typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (links.typeParameters) { // Initialize the instantiation cache for generic type aliases. The declared type corresponds to // an instantiation of the type alias with the type parameters supplied as type arguments. - links.instantiations = ts.createMap(); + links.instantiations = {}; links.instantiations[getTypeListId(links.typeParameters)] = type; } } @@ -20566,80 +19478,19 @@ var ts; } return links.declaredType; } - function isLiteralEnumMember(symbol, member) { - var expr = member.initializer; - if (!expr) { - return !ts.isInAmbientContext(member); - } - return expr.kind === 8 /* NumericLiteral */ || - expr.kind === 185 /* PrefixUnaryExpression */ && expr.operator === 36 /* MinusToken */ && - expr.operand.kind === 8 /* NumericLiteral */ || - expr.kind === 69 /* Identifier */ && !!symbol.exports[expr.text]; - } - function enumHasLiteralMembers(symbol) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 224 /* EnumDeclaration */) { - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - if (!isLiteralEnumMember(symbol, member)) { - return false; - } - } - } - } - return true; - } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var enumType = links.declaredType = createType(16 /* Enum */); - enumType.symbol = symbol; - if (enumHasLiteralMembers(symbol)) { - var memberTypeList = []; - var memberTypes = ts.createMap(); - for (var _i = 0, _a = enumType.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 224 /* EnumDeclaration */) { - computeEnumMemberValues(declaration); - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - var memberSymbol = getSymbolOfNode(member); - var value = getEnumMemberValue(member); - if (!memberTypes[value]) { - var memberType = memberTypes[value] = createType(256 /* EnumLiteral */); - memberType.symbol = memberSymbol; - memberType.baseType = enumType; - memberType.text = "" + value; - memberTypeList.push(memberType); - } - } - } - } - enumType.memberTypes = memberTypes; - if (memberTypeList.length > 1) { - enumType.flags |= 524288 /* Union */; - enumType.types = memberTypeList; - unionTypes[getTypeListId(memberTypeList)] = enumType; - } - } - } - return links.declaredType; - } - function getDeclaredTypeOfEnumMember(symbol) { - var links = getSymbolLinks(symbol); - if (!links.declaredType) { - var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); - links.declaredType = enumType.flags & 524288 /* Union */ ? - enumType.memberTypes[getEnumMemberValue(symbol.valueDeclaration)] : - enumType; + var type = createType(128 /* Enum */); + type.symbol = symbol; + links.declaredType = type; } return links.declaredType; } function getDeclaredTypeOfTypeParameter(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var type = createType(16384 /* TypeParameter */); + var type = createType(512 /* TypeParameter */); type.symbol = symbol; if (!ts.getDeclarationOfKind(symbol, 141 /* TypeParameter */).constraint) { type.constraint = noConstraintType; @@ -20663,14 +19514,11 @@ var ts; if (symbol.flags & 524288 /* TypeAlias */) { return getDeclaredTypeOfTypeAlias(symbol); } - if (symbol.flags & 262144 /* TypeParameter */) { - return getDeclaredTypeOfTypeParameter(symbol); - } if (symbol.flags & 384 /* Enum */) { return getDeclaredTypeOfEnum(symbol); } - if (symbol.flags & 8 /* EnumMember */) { - return getDeclaredTypeOfEnumMember(symbol); + if (symbol.flags & 262144 /* TypeParameter */) { + return getDeclaredTypeOfTypeParameter(symbol); } if (symbol.flags & 8388608 /* Alias */) { return getDeclaredTypeOfAlias(symbol); @@ -20703,7 +19551,7 @@ var ts; case 135 /* UndefinedKeyword */: case 93 /* NullKeyword */: case 127 /* NeverKeyword */: - case 166 /* LiteralType */: + case 166 /* StringLiteralType */: return true; case 160 /* ArrayType */: return isIndependentType(node.elementType); @@ -20754,7 +19602,7 @@ var ts; return false; } function createSymbolTable(symbols) { - var result = ts.createMap(); + var result = {}; for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { var symbol = symbols_1[_i]; result[symbol.name] = symbol; @@ -20764,7 +19612,7 @@ var ts; // The mappingThisOnly flag indicates that the only type parameter being mapped is "this". When the flag is true, // we check symbols to see if we can quickly conclude they are free of "this" references, thus needing no instantiation. function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) { - var result = ts.createMap(); + var result = {}; for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { var symbol = symbols_2[_i]; result[symbol.name] = mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper); @@ -20774,7 +19622,7 @@ var ts; function addInheritedMembers(symbols, baseSymbols) { for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) { var s = baseSymbols_1[_i]; - if (!symbols[s.name]) { + if (!ts.hasProperty(symbols, s.name)) { symbols[s.name] = s; } } @@ -20791,27 +19639,19 @@ var ts; return type; } function getTypeWithThisArgument(type, thisArgument) { - if (type.flags & 131072 /* Reference */) { + if (type.flags & 4096 /* Reference */) { return createTypeReference(type.target, ts.concatenate(type.typeArguments, [thisArgument || type.target.thisType])); } return type; } function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { - var mapper; - var members; - var callSignatures; - var constructSignatures; - var stringIndexInfo; - var numberIndexInfo; - if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { - mapper = identityMapper; - members = source.symbol ? source.symbol.members : createSymbolTable(source.declaredProperties); - callSignatures = source.declaredCallSignatures; - constructSignatures = source.declaredConstructSignatures; - stringIndexInfo = source.declaredStringIndexInfo; - numberIndexInfo = source.declaredNumberIndexInfo; - } - else { + var mapper = identityMapper; + var members = source.symbol.members; + var callSignatures = source.declaredCallSignatures; + var constructSignatures = source.declaredConstructSignatures; + var stringIndexInfo = source.declaredStringIndexInfo; + var numberIndexInfo = source.declaredNumberIndexInfo; + if (!ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { mapper = createTypeMapper(typeParameters, typeArguments); members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1); callSignatures = instantiateList(source.declaredCallSignatures, mapper, instantiateSignature); @@ -20821,7 +19661,7 @@ var ts; } var baseTypes = getBaseTypes(source); if (baseTypes.length) { - if (source.symbol && members === source.symbol.members) { + if (members === source.symbol.members) { members = createSymbolTable(source.declaredProperties); } var thisArgument = ts.lastOrUndefined(typeArguments); @@ -20847,7 +19687,7 @@ var ts; type.typeArguments : ts.concatenate(type.typeArguments, [type]); resolveObjectTypeMembers(type, source, typeParameters, typeArguments); } - function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasStringLiterals) { var sig = new Signature(checker); sig.declaration = declaration; sig.typeParameters = typeParameters; @@ -20857,17 +19697,17 @@ var ts; sig.typePredicate = typePredicate; sig.minArgumentCount = minArgumentCount; sig.hasRestParameter = hasRestParameter; - sig.hasLiteralTypes = hasLiteralTypes; + sig.hasStringLiterals = hasStringLiterals; return sig; } function cloneSignature(sig) { - return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); + return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); } function getDefaultConstructSignatures(classType) { var baseConstructorType = getBaseConstructorTypeOfClass(classType); var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); if (baseSignatures.length === 0) { - return [createSignature(undefined, classType.localTypeParameters, undefined, emptyArray, classType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; + return [createSignature(undefined, classType.localTypeParameters, undefined, emptyArray, classType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false)]; } var baseTypeNode = getBaseTypeNodeOfClass(classType); var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); @@ -20885,6 +19725,23 @@ var ts; } return result; } + function createTupleTypeMemberSymbols(memberTypes) { + var members = {}; + for (var i = 0; i < memberTypes.length; i++) { + var symbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "" + i); + symbol.type = memberTypes[i]; + members[i] = symbol; + } + return members; + } + function resolveTupleTypeMembers(type) { + var arrayElementType = getUnionType(type.elementTypes, /*noSubtypeReduction*/ true); + // Make the tuple type itself the 'this' type by including an extra type argument + var arrayType = resolveStructuredTypeMembers(createTypeFromGenericGlobalType(globalArrayType, [arrayElementType, type])); + var members = createTupleTypeMemberSymbols(type.elementTypes); + addInheritedMembers(members, arrayType.properties); + setObjectTypeMembers(type, members, arrayType.callSignatures, arrayType.constructSignatures, arrayType.stringIndexInfo, arrayType.numberIndexInfo); + } function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) { for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { var s = signatureList_1[_i]; @@ -20939,7 +19796,7 @@ var ts; if (unionSignatures.length > 1) { s = cloneSignature(signature); if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { - var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; }), /*subtypeReduction*/ true); + var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; })); s.thisParameter = createTransientSymbol(signature.thisParameter, thisType); } // Clear resolved return type we possibly got from cloneSignature @@ -20965,7 +19822,7 @@ var ts; indexTypes.push(indexInfo.type); isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; } - return createIndexInfo(getUnionType(indexTypes, /*subtypeReduction*/ true), isAnyReadonly); + return createIndexInfo(getUnionType(indexTypes), isAnyReadonly); } function resolveUnionTypeMembers(type) { // The members and properties collections are empty for union types. To get all properties of a union @@ -21030,7 +19887,7 @@ var ts; constructSignatures = getDefaultConstructSignatures(classType); } var baseConstructorType = getBaseConstructorTypeOfClass(classType); - if (baseConstructorType.flags & 2588672 /* ObjectType */) { + if (baseConstructorType.flags & 80896 /* ObjectType */) { members = createSymbolTable(getNamedMembers(members)); addInheritedMembers(members, getPropertiesOfObjectType(baseConstructorType)); } @@ -21048,19 +19905,22 @@ var ts; } function resolveStructuredTypeMembers(type) { if (!type.members) { - if (type.flags & 131072 /* Reference */) { + if (type.flags & 4096 /* Reference */) { resolveTypeReferenceMembers(type); } - else if (type.flags & (32768 /* Class */ | 65536 /* Interface */)) { + else if (type.flags & (1024 /* Class */ | 2048 /* Interface */)) { resolveClassOrInterfaceMembers(type); } - else if (type.flags & 2097152 /* Anonymous */) { + else if (type.flags & 65536 /* Anonymous */) { resolveAnonymousTypeMembers(type); } - else if (type.flags & 524288 /* Union */) { + else if (type.flags & 8192 /* Tuple */) { + resolveTupleTypeMembers(type); + } + else if (type.flags & 16384 /* Union */) { resolveUnionTypeMembers(type); } - else if (type.flags & 1048576 /* Intersection */) { + else if (type.flags & 32768 /* Intersection */) { resolveIntersectionTypeMembers(type); } } @@ -21068,7 +19928,7 @@ var ts; } /** Return properties of an object type or an empty array for other types */ function getPropertiesOfObjectType(type) { - if (type.flags & 2588672 /* ObjectType */) { + if (type.flags & 80896 /* ObjectType */) { return resolveStructuredTypeMembers(type).properties; } return emptyArray; @@ -21076,11 +19936,13 @@ var ts; /** If the given type is an object type and that type has a property by the given name, * return the symbol for that property. Otherwise return undefined. */ function getPropertyOfObjectType(type, name) { - if (type.flags & 2588672 /* ObjectType */) { + if (type.flags & 80896 /* ObjectType */) { var resolved = resolveStructuredTypeMembers(type); - var symbol = resolved.members[name]; - if (symbol && symbolIsValue(symbol)) { - return symbol; + if (ts.hasProperty(resolved.members, name)) { + var symbol = resolved.members[name]; + if (symbolIsValue(symbol)) { + return symbol; + } } } } @@ -21093,7 +19955,7 @@ var ts; } // The properties of a union type are those that are present in all constituent types, so // we only need to check the properties of the first type - if (type.flags & 524288 /* Union */) { + if (type.flags & 16384 /* Union */) { break; } } @@ -21101,7 +19963,7 @@ var ts; } function getPropertiesOfType(type) { type = getApparentType(type); - return type.flags & 1572864 /* UnionOrIntersection */ ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); + return type.flags & 49152 /* UnionOrIntersection */ ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } /** * The apparent type of a type parameter is the base constraint instantiated with the type parameter @@ -21110,7 +19972,7 @@ var ts; function getApparentTypeOfTypeParameter(type) { if (!type.resolvedApparentType) { var constraintType = getConstraintOfTypeParameter(type); - while (constraintType && constraintType.flags & 16384 /* TypeParameter */) { + while (constraintType && constraintType.flags & 512 /* TypeParameter */) { constraintType = getConstraintOfTypeParameter(constraintType); } type.resolvedApparentType = getTypeWithThisArgument(constraintType || emptyObjectType, type); @@ -21123,19 +19985,19 @@ var ts; * type itself. Note that the apparent type of a union type is the union type itself. */ function getApparentType(type) { - if (type.flags & 16384 /* TypeParameter */) { + if (type.flags & 512 /* TypeParameter */) { type = getApparentTypeOfTypeParameter(type); } - if (type.flags & 34 /* StringLike */) { + if (type.flags & 258 /* StringLike */) { type = globalStringType; } - else if (type.flags & 340 /* NumberLike */) { + else if (type.flags & 132 /* NumberLike */) { type = globalNumberType; } - else if (type.flags & 136 /* BooleanLike */) { + else if (type.flags & 8 /* Boolean */) { type = globalBooleanType; } - else if (type.flags & 512 /* ESSymbol */) { + else if (type.flags & 16777216 /* ESSymbol */) { type = getGlobalESSymbolType(); } return type; @@ -21144,7 +20006,7 @@ var ts; var types = containingType.types; var props; // Flags we want to propagate to the result if they exist in all source symbols - var commonFlags = (containingType.flags & 1048576 /* Intersection */) ? 536870912 /* Optional */ : 0 /* None */; + var commonFlags = (containingType.flags & 32768 /* Intersection */) ? 536870912 /* Optional */ : 0 /* None */; var isReadonly = false; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var current = types_2[_i]; @@ -21163,7 +20025,7 @@ var ts; isReadonly = true; } } - else if (containingType.flags & 524288 /* Union */) { + else if (containingType.flags & 16384 /* Union */) { // A union type requires the property to be present in all constituent types return undefined; } @@ -21177,20 +20039,11 @@ var ts; } var propTypes = []; var declarations = []; - var commonType = undefined; - var hasCommonType = true; for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { var prop = props_1[_a]; if (prop.declarations) { ts.addRange(declarations, prop.declarations); } - var type = getTypeOfSymbol(prop); - if (!commonType) { - commonType = type; - } - else if (type !== commonType) { - hasCommonType = false; - } propTypes.push(getTypeOfSymbol(prop)); } var result = createSymbol(4 /* Property */ | @@ -21198,54 +20051,50 @@ var ts; 268435456 /* SyntheticProperty */ | commonFlags, name); result.containingType = containingType; - result.hasCommonType = hasCommonType; result.declarations = declarations; result.isReadonly = isReadonly; - result.type = containingType.flags & 524288 /* Union */ ? getUnionType(propTypes) : getIntersectionType(propTypes); + result.type = containingType.flags & 16384 /* Union */ ? getUnionType(propTypes) : getIntersectionType(propTypes); return result; } function getPropertyOfUnionOrIntersectionType(type, name) { - var properties = type.resolvedProperties || (type.resolvedProperties = ts.createMap()); - var property = properties[name]; - if (!property) { - property = createUnionOrIntersectionProperty(type, name); - if (property) { - properties[name] = property; - } + var properties = type.resolvedProperties || (type.resolvedProperties = {}); + if (ts.hasProperty(properties, name)) { + return properties[name]; + } + var property = createUnionOrIntersectionProperty(type, name); + if (property) { + properties[name] = property; } return property; } - /** - * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when - * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from - * Object and Function as appropriate. - * - * @param type a type to look up property from - * @param name a name of property to look up in a given type - */ + // Return the symbol for the property with the given name in the given type. Creates synthetic union properties when + // necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from + // Object and Function as appropriate. function getPropertyOfType(type, name) { type = getApparentType(type); - if (type.flags & 2588672 /* ObjectType */) { + if (type.flags & 80896 /* ObjectType */) { var resolved = resolveStructuredTypeMembers(type); - var symbol = resolved.members[name]; - if (symbol && symbolIsValue(symbol)) { - return symbol; + if (ts.hasProperty(resolved.members, name)) { + var symbol = resolved.members[name]; + if (symbolIsValue(symbol)) { + return symbol; + } } if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); - if (symbol_1) { - return symbol_1; + var symbol = getPropertyOfObjectType(globalFunctionType, name); + if (symbol) { + return symbol; } } return getPropertyOfObjectType(globalObjectType, name); } - if (type.flags & 1572864 /* UnionOrIntersection */) { + if (type.flags & 49152 /* UnionOrIntersection */) { return getPropertyOfUnionOrIntersectionType(type, name); } return undefined; } function getSignaturesOfStructuredType(type, kind) { - if (type.flags & 4161536 /* StructuredType */) { + if (type.flags & 130048 /* StructuredType */) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures; } @@ -21259,7 +20108,7 @@ var ts; return getSignaturesOfStructuredType(getApparentType(type), kind); } function getIndexInfoOfStructuredType(type, kind) { - if (type.flags & 4161536 /* StructuredType */) { + if (type.flags & 130048 /* StructuredType */) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo; } @@ -21288,7 +20137,7 @@ var ts; } } if (propTypes.length) { - return getUnionType(propTypes, /*subtypeReduction*/ true); + return getUnionType(propTypes); } } return undefined; @@ -21373,7 +20222,7 @@ var ts; var links = getNodeLinks(declaration); if (!links.resolvedSignature) { var parameters = []; - var hasLiteralTypes = false; + var hasStringLiterals = false; var minArgumentCount = -1; var thisParameter = undefined; var hasThisParameter = void 0; @@ -21396,8 +20245,8 @@ var ts; else { parameters.push(paramSymbol); } - if (param.type && param.type.kind === 166 /* LiteralType */) { - hasLiteralTypes = true; + if (param.type && param.type.kind === 166 /* StringLiteralType */) { + hasStringLiterals = true; } if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { if (minArgumentCount < 0) { @@ -21425,9 +20274,6 @@ var ts; if (isJSConstructSignature) { minArgumentCount--; } - if (!thisParameter && ts.isObjectLiteralMethod(declaration)) { - thisParameter = getContextualThisParameter(declaration); - } var classType = declaration.kind === 148 /* Constructor */ ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; @@ -21438,7 +20284,7 @@ var ts; var typePredicate = declaration.type && declaration.type.kind === 154 /* TypePredicate */ ? createTypePredicateFromTypePredicateNode(declaration.type) : undefined; - links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasLiteralTypes); + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasStringLiterals); } return links.resolvedSignature; } @@ -21528,7 +20374,7 @@ var ts; type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); } else if (signature.unionSignatures) { - type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); + type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature)); } else { type = getReturnTypeFromBody(signature.declaration); @@ -21552,7 +20398,7 @@ var ts; function getRestTypeOfSignature(signature) { if (signature.hasRestParameter) { var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); - if (type.flags & 131072 /* Reference */ && type.target === globalArrayType) { + if (type.flags & 4096 /* Reference */ && type.target === globalArrayType) { return type.typeArguments[0]; } } @@ -21576,7 +20422,7 @@ var ts; // will result in a different declaration kind. if (!signature.isolatedSignatureType) { var isConstructor = signature.declaration.kind === 148 /* Constructor */ || signature.declaration.kind === 152 /* ConstructSignature */; - var type = createObjectType(2097152 /* Anonymous */); + var type = createObjectType(65536 /* Anonymous */ | 262144 /* FromSignature */); type.members = emptySymbols; type.properties = emptyArray; type.callSignatures = !isConstructor ? [signature] : emptyArray; @@ -21620,7 +20466,7 @@ var ts; } function hasConstraintReferenceTo(type, target) { var checked; - while (type && !(type.flags & 268435456 /* ThisType */) && type.flags & 16384 /* TypeParameter */ && !ts.contains(checked, type)) { + while (type && !(type.flags & 33554432 /* ThisType */) && type.flags & 512 /* TypeParameter */ && !ts.contains(checked, type)) { if (type === target) { return true; } @@ -21652,27 +20498,24 @@ var ts; return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 141 /* TypeParameter */).parent); } function getTypeListId(types) { - var result = ""; if (types) { - var length_3 = types.length; - var i = 0; - while (i < length_3) { - var startId = types[i].id; - var count = 1; - while (i + count < length_3 && types[i + count].id === startId + count) { - count++; - } - if (result.length) { - result += ","; - } - result += startId; - if (count > 1) { - result += ":" + count; - } - i += count; + switch (types.length) { + case 1: + return "" + types[0].id; + case 2: + return types[0].id + "," + types[1].id; + default: + var result = ""; + for (var i = 0; i < types.length; i++) { + if (i > 0) { + result += ","; + } + result += types[i].id; + } + return result; } } - return result; + return ""; } // This function is used to propagate certain flags when creating new object type references and union types. // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type @@ -21686,29 +20529,20 @@ var ts; result |= type.flags; } } - return result & 234881024 /* PropagatingFlags */; + return result & 14680064 /* PropagatingFlags */; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); var type = target.instantiations[id]; if (!type) { var propagatedFlags = typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0; - var flags = 131072 /* Reference */ | propagatedFlags; + var flags = 4096 /* Reference */ | propagatedFlags; type = target.instantiations[id] = createObjectType(flags, target.symbol); type.target = target; type.typeArguments = typeArguments; } return type; } - function cloneTypeReference(source) { - var type = createObjectType(source.flags, source.symbol); - type.target = source.target; - type.typeArguments = source.typeArguments; - return type; - } - function getTypeReferenceArity(type) { - return type.target.typeParameters ? type.target.typeParameters.length : 0; - } // Get type from reference to class or interface function getTypeFromClassOrInterfaceReference(node, symbol) { var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); @@ -21768,9 +20602,8 @@ var ts; case 194 /* ExpressionWithTypeArguments */: // We only support expressions that are simple qualified names. For other // expressions this produces undefined. - var expr = node.expression; - if (ts.isEntityNameExpression(expr)) { - return expr; + if (ts.isSupportedExpressionWithTypeArguments(node)) { + return node.expression; } } return undefined; @@ -21779,7 +20612,7 @@ var ts; if (!typeReferenceName) { return unknownSymbol; } - return resolveEntityName(typeReferenceName, 793064 /* Type */) || unknownSymbol; + return resolveEntityName(typeReferenceName, 793056 /* Type */) || unknownSymbol; } function getTypeReferenceType(node, symbol) { if (symbol === unknownSymbol) { @@ -21808,15 +20641,15 @@ var ts; var typeReferenceName = getTypeReferenceName(node); symbol = resolveTypeReferenceName(node, typeReferenceName); type = getTypeReferenceType(node, symbol); + links.resolvedSymbol = symbol; + links.resolvedType = type; } else { // We only support expressions that are simple qualified names. For other expressions this produces undefined. - var typeNameOrExpression = node.kind === 155 /* TypeReference */ - ? node.typeName - : ts.isEntityNameExpression(node.expression) - ? node.expression - : undefined; - symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793064 /* Type */) || unknownSymbol; + var typeNameOrExpression = node.kind === 155 /* TypeReference */ ? node.typeName : + ts.isSupportedExpressionWithTypeArguments(node) ? node.expression : + undefined; + symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793056 /* Type */) || unknownSymbol; type = symbol === unknownSymbol ? unknownType : symbol.flags & (32 /* Class */ | 64 /* Interface */) ? getTypeFromClassOrInterfaceReference(node, symbol) : symbol.flags & 524288 /* TypeAlias */ ? getTypeFromTypeAliasReference(node, symbol) : @@ -21857,7 +20690,7 @@ var ts; return arity ? emptyGenericType : emptyObjectType; } var type = getDeclaredTypeOfSymbol(symbol); - if (!(type.flags & 2588672 /* ObjectType */)) { + if (!(type.flags & 80896 /* ObjectType */)) { error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbol.name); return arity ? emptyGenericType : emptyObjectType; } @@ -21871,7 +20704,7 @@ var ts; return getGlobalSymbol(name, 107455 /* Value */, ts.Diagnostics.Cannot_find_global_value_0); } function getGlobalTypeSymbol(name) { - return getGlobalSymbol(name, 793064 /* Type */, ts.Diagnostics.Cannot_find_global_type_0); + return getGlobalSymbol(name, 793056 /* Type */, ts.Diagnostics.Cannot_find_global_type_0); } function getGlobalSymbol(name, meaning, diagnostic) { return resolveName(undefined, name, meaning, diagnostic, name); @@ -21885,8 +20718,8 @@ var ts; * getExportedTypeFromNamespace('JSX', 'Element') returns the JSX.Element type */ function getExportedTypeFromNamespace(namespace, name) { - var namespaceSymbol = getGlobalSymbol(namespace, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); - var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793064 /* Type */); + var namespaceSymbol = getGlobalSymbol(namespace, 1536 /* Namespace */, /*diagnosticMessage*/ undefined); + var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793056 /* Type */); return typeSymbol && getDeclaredTypeOfSymbol(typeSymbol); } /** @@ -21920,45 +20753,15 @@ var ts; } return links.resolvedType; } - // We represent tuple types as type references to synthesized generic interface types created by - // this function. The types are of the form: - // - // interface Tuple extends Array { 0: T0, 1: T1, 2: T2, ... } - // - // Note that the generic type created by this function has no symbol associated with it. The same - // is true for each of the synthesized type parameters. - function createTupleTypeOfArity(arity) { - var typeParameters = []; - var properties = []; - for (var i = 0; i < arity; i++) { - var typeParameter = createType(16384 /* TypeParameter */); - typeParameters.push(typeParameter); - var property = createSymbol(4 /* Property */ | 67108864 /* Transient */, "" + i); - property.type = typeParameter; - properties.push(property); - } - var type = createObjectType(262144 /* Tuple */ | 131072 /* Reference */); - type.typeParameters = typeParameters; - type.outerTypeParameters = undefined; - type.localTypeParameters = typeParameters; - type.instantiations = ts.createMap(); - type.instantiations[getTypeListId(type.typeParameters)] = type; - type.target = type; - type.typeArguments = type.typeParameters; - type.thisType = createType(16384 /* TypeParameter */ | 268435456 /* ThisType */); - type.thisType.constraint = type; - type.declaredProperties = properties; - type.declaredCallSignatures = emptyArray; - type.declaredConstructSignatures = emptyArray; - type.declaredStringIndexInfo = undefined; - type.declaredNumberIndexInfo = undefined; - return type; - } - function getTupleTypeOfArity(arity) { - return tupleTypes[arity] || (tupleTypes[arity] = createTupleTypeOfArity(arity)); - } function createTupleType(elementTypes) { - return createTypeReference(getTupleTypeOfArity(elementTypes.length), elementTypes); + var id = getTypeListId(elementTypes); + return tupleTypes[id] || (tupleTypes[id] = createNewTupleType(elementTypes)); + } + function createNewTupleType(elementTypes) { + var propagatedFlags = getPropagatingFlagsOfTypes(elementTypes, /*excludeKinds*/ 0); + var type = createObjectType(8192 /* Tuple */ | propagatedFlags); + type.elementTypes = elementTypes; + return type; } function getTypeFromTupleTypeNode(node) { var links = getNodeLinks(node); @@ -21967,70 +20770,32 @@ var ts; } return links.resolvedType; } - function binarySearchTypes(types, type) { - var low = 0; - var high = types.length - 1; - var typeId = type.id; - while (low <= high) { - var middle = low + ((high - low) >> 1); - var id = types[middle].id; - if (id === typeId) { - return middle; - } - else if (id > typeId) { - high = middle - 1; - } - else { - low = middle + 1; - } + function addTypeToSet(typeSet, type, typeSetKind) { + if (type.flags & typeSetKind) { + addTypesToSet(typeSet, type.types, typeSetKind); } - return ~low; - } - function containsType(types, type) { - return binarySearchTypes(types, type) >= 0; - } - function addTypeToUnion(typeSet, type) { - if (type.flags & 524288 /* Union */) { - addTypesToUnion(typeSet, type.types); - } - else if (type.flags & 1 /* Any */) { - typeSet.containsAny = true; - } - else if (!strictNullChecks && type.flags & 6144 /* Nullable */) { - if (type.flags & 2048 /* Undefined */) + else if (type.flags & (1 /* Any */ | 32 /* Undefined */ | 64 /* Null */)) { + if (type.flags & 1 /* Any */) + typeSet.containsAny = true; + if (type.flags & 32 /* Undefined */) typeSet.containsUndefined = true; - if (type.flags & 4096 /* Null */) + if (type.flags & 64 /* Null */) typeSet.containsNull = true; - if (!(type.flags & 33554432 /* ContainsWideningType */)) + if (!(type.flags & 2097152 /* ContainsWideningType */)) typeSet.containsNonWideningType = true; } - else if (!(type.flags & 8192 /* Never */)) { - var len = typeSet.length; - var index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type); - if (index < 0) { - if (!(type.flags & 2097152 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); - } - } + else if (type !== neverType && !ts.contains(typeSet, type)) { + typeSet.push(type); } } // Add the given types to the given type set. Order is preserved, duplicates are removed, // and nested types of the given kind are flattened into the set. - function addTypesToUnion(typeSet, types) { + function addTypesToSet(typeSet, types, typeSetKind) { for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { var type = types_4[_i]; - addTypeToUnion(typeSet, type); + addTypeToSet(typeSet, type, typeSetKind); } } - function containsIdenticalType(types, type) { - for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { - var t = types_5[_i]; - if (isTypeIdenticalTo(t, type)) { - return true; - } - } - return false; - } function isSubtypeOfAny(candidate, types) { for (var i = 0, len = types.length; i < len; i++) { if (candidate !== types[i] && isTypeSubtypeOf(candidate, types[i])) { @@ -22048,14 +20813,14 @@ var ts; } } } - // We sort and deduplicate the constituent types based on object identity. If the subtypeReduction - // flag is specified we also reduce the constituent type set to only include types that aren't subtypes - // of other types. Subtype reduction is expensive for large union types and is possible only when union - // types are known not to circularly reference themselves (as is the case with union types created by - // expression constructs such as array literals and the || and ?: operators). Named types can - // circularly reference themselves and therefore cannot be subtype reduced during their declaration. - // For example, "type Item = string | (() => Item" is a named type that circularly references itself. - function getUnionType(types, subtypeReduction, aliasSymbol, aliasTypeArguments) { + // We reduce the constituent type set to only include types that aren't subtypes of other types, unless + // the noSubtypeReduction flag is specified, in which case we perform a simple deduplication based on + // object identity. Subtype reduction is possible only when union types are known not to circularly + // reference themselves (as is the case with union types created by expression constructs such as array + // literals and the || and ?: operators). Named types can circularly reference themselves and therefore + // cannot be deduplicated during their declaration. For example, "type Item = string | (() => Item" is + // a named type that circularly references itself. + function getUnionType(types, noSubtypeReduction) { if (types.length === 0) { return neverType; } @@ -22063,11 +20828,17 @@ var ts; return types[0]; } var typeSet = []; - addTypesToUnion(typeSet, types); + addTypesToSet(typeSet, types, 16384 /* Union */); if (typeSet.containsAny) { return anyType; } - if (subtypeReduction) { + if (strictNullChecks) { + if (typeSet.containsNull) + typeSet.push(nullType); + if (typeSet.containsUndefined) + typeSet.push(undefinedType); + } + if (!noSubtypeReduction) { removeSubtypes(typeSet); } if (typeSet.length === 0) { @@ -22075,112 +20846,84 @@ var ts; typeSet.containsUndefined ? typeSet.containsNonWideningType ? undefinedType : undefinedWideningType : neverType; } - return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments); - } - // This function assumes the constituent type list is sorted and deduplicated. - function getUnionTypeFromSortedList(types, aliasSymbol, aliasTypeArguments) { - if (types.length === 0) { - return neverType; + else if (typeSet.length === 1) { + return typeSet[0]; } - if (types.length === 1) { - return types[0]; - } - var id = getTypeListId(types); + var id = getTypeListId(typeSet); var type = unionTypes[id]; if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 6144 /* Nullable */); - type = unionTypes[id] = createObjectType(524288 /* Union */ | propagatedFlags); - type.types = types; - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = aliasTypeArguments; + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 96 /* Nullable */); + type = unionTypes[id] = createObjectType(16384 /* Union */ | propagatedFlags); + type.types = typeSet; } return type; } - function getTypeFromUnionTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getTypeFromUnionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), /*subtypeReduction*/ false, aliasSymbol, aliasTypeArguments); + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), /*noSubtypeReduction*/ true); } return links.resolvedType; } - function addTypeToIntersection(typeSet, type) { - if (type.flags & 1048576 /* Intersection */) { - addTypesToIntersection(typeSet, type.types); - } - else if (type.flags & 1 /* Any */) { - typeSet.containsAny = true; - } - else if (!(type.flags & 8192 /* Never */) && (strictNullChecks || !(type.flags & 6144 /* Nullable */)) && !ts.contains(typeSet, type)) { - typeSet.push(type); - } - } - // Add the given types to the given type set. Order is preserved, duplicates are removed, - // and nested types of the given kind are flattened into the set. - function addTypesToIntersection(typeSet, types) { - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type = types_6[_i]; - addTypeToIntersection(typeSet, type); - } - } // We do not perform structural deduplication on intersection types. Intersection types are created only by the & // type operator and we can't reduce those because we want to support recursive intersection types. For example, // a type alias of the form "type List = T & { next: List }" cannot be reduced during its declaration. // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution // for intersections of types with signatures can be deterministic. - function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { + function getIntersectionType(types) { if (types.length === 0) { return emptyObjectType; } var typeSet = []; - addTypesToIntersection(typeSet, types); + addTypesToSet(typeSet, types, 32768 /* Intersection */); if (typeSet.containsAny) { return anyType; } + if (strictNullChecks) { + if (typeSet.containsNull) + typeSet.push(nullType); + if (typeSet.containsUndefined) + typeSet.push(undefinedType); + } if (typeSet.length === 1) { return typeSet[0]; } var id = getTypeListId(typeSet); var type = intersectionTypes[id]; if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 6144 /* Nullable */); - type = intersectionTypes[id] = createObjectType(1048576 /* Intersection */ | propagatedFlags); + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 96 /* Nullable */); + type = intersectionTypes[id] = createObjectType(32768 /* Intersection */ | propagatedFlags); type.types = typeSet; - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = aliasTypeArguments; } return type; } - function getTypeFromIntersectionTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getTypeFromIntersectionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, aliasTypeArguments); + links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode)); } return links.resolvedType; } - function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { // Deferred resolution of members is handled by resolveObjectTypeMembers - var type = createObjectType(2097152 /* Anonymous */, node.symbol); - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = aliasTypeArguments; - links.resolvedType = type; + links.resolvedType = createObjectType(65536 /* Anonymous */, node.symbol); } return links.resolvedType; } - function createLiteralType(flags, text) { - var type = createType(flags); + function getStringLiteralTypeForText(text) { + if (ts.hasProperty(stringLiteralTypes, text)) { + return stringLiteralTypes[text]; + } + var type = stringLiteralTypes[text] = createType(256 /* StringLiteral */); type.text = text; return type; } - function getLiteralTypeForText(flags, text) { - var map = flags & 32 /* StringLiteral */ ? stringLiteralTypes : numericLiteralTypes; - return map[text] || (map[text] = createLiteralType(flags, text)); - } - function getTypeFromLiteralTypeNode(node) { + function getTypeFromStringLiteralTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = checkExpression(node.literal); + links.resolvedType = getStringLiteralTypeForText(ts.unescapeIdentifier(node.text)); } return links.resolvedType; } @@ -22219,7 +20962,7 @@ var ts; } return links.resolvedType; } - function getTypeFromTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getTypeFromTypeNode(node) { switch (node.kind) { case 117 /* AnyKeyword */: case 258 /* JSDocAllType */: @@ -22241,19 +20984,11 @@ var ts; return nullType; case 127 /* NeverKeyword */: return neverType; - case 283 /* JSDocNullKeyword */: - return nullType; - case 284 /* JSDocUndefinedKeyword */: - return undefinedType; - case 285 /* JSDocNeverKeyword */: - return neverType; case 165 /* ThisType */: case 97 /* ThisKeyword */: return getTypeFromThisTypeNode(node); - case 166 /* LiteralType */: - return getTypeFromLiteralTypeNode(node); - case 282 /* JSDocLiteralType */: - return getTypeFromLiteralTypeNode(node.literal); + case 166 /* StringLiteralType */: + return getTypeFromStringLiteralTypeNode(node); case 155 /* TypeReference */: case 267 /* JSDocTypeReference */: return getTypeFromTypeReference(node); @@ -22270,9 +21005,9 @@ var ts; return getTypeFromTupleTypeNode(node); case 162 /* UnionType */: case 261 /* JSDocUnionType */: - return getTypeFromUnionTypeNode(node, aliasSymbol, aliasTypeArguments); + return getTypeFromUnionTypeNode(node); case 163 /* IntersectionType */: - return getTypeFromIntersectionTypeNode(node, aliasSymbol, aliasTypeArguments); + return getTypeFromIntersectionTypeNode(node); case 164 /* ParenthesizedType */: case 263 /* JSDocNullableType */: case 264 /* JSDocNonNullableType */: @@ -22286,7 +21021,7 @@ var ts; case 281 /* JSDocTypeLiteral */: case 269 /* JSDocFunctionType */: case 265 /* JSDocRecordType */: - return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node, aliasSymbol, aliasTypeArguments); + return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); // This function assumes that an identifier or qualified name is a type expression // Callers should first ensure this by calling isTypeNode case 69 /* Identifier */: @@ -22334,7 +21069,6 @@ var ts; count == 2 ? createBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : createArrayTypeMapper(sources, targets); mapper.mappedTypes = sources; - mapper.targetTypes = targets; return mapper; } function createTypeEraser(sources) { @@ -22367,7 +21101,7 @@ var ts; return mapper; } function cloneTypeParameter(typeParameter) { - var result = createType(16384 /* TypeParameter */); + var result = createType(512 /* TypeParameter */); result.symbol = typeParameter.symbol; result.target = typeParameter; return result; @@ -22405,7 +21139,7 @@ var ts; if (signature.typePredicate) { freshTypePredicate = cloneTypePredicate(signature.typePredicate, mapper); } - var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); + var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasStringLiterals); result.target = signature; result.mapper = mapper; return result; @@ -22442,11 +21176,9 @@ var ts; mapper.instantiations = []; } // Mark the anonymous type as instantiated such that our infinite instantiation detection logic can recognize it - var result = createObjectType(2097152 /* Anonymous */ | 4194304 /* Instantiated */, type.symbol); + var result = createObjectType(65536 /* Anonymous */ | 131072 /* Instantiated */, type.symbol); result.target = type; result.mapper = mapper; - result.aliasSymbol = type.aliasSymbol; - result.aliasTypeArguments = mapper.targetTypes; mapper.instantiations[type.id] = result; return result; } @@ -22501,10 +21233,10 @@ var ts; } function instantiateType(type, mapper) { if (type && mapper !== identityMapper) { - if (type.flags & 16384 /* TypeParameter */) { + if (type.flags & 512 /* TypeParameter */) { return mapper(type); } - if (type.flags & 2097152 /* Anonymous */) { + if (type.flags & 65536 /* Anonymous */) { // If the anonymous type originates in a declaration of a function, method, class, or // interface, in an object type literal, or in an object literal expression, we may need // to instantiate the type because it might reference a type parameter. We skip instantiation @@ -22513,17 +21245,20 @@ var ts; // instantiation. return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && - (type.flags & 4194304 /* Instantiated */ || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? + (type.flags & 131072 /* Instantiated */ || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? instantiateAnonymousType(type, mapper) : type; } - if (type.flags & 131072 /* Reference */) { + if (type.flags & 4096 /* Reference */) { return createTypeReference(type.target, instantiateList(type.typeArguments, mapper, instantiateType)); } - if (type.flags & 524288 /* Union */ && !(type.flags & 8190 /* Primitive */)) { - return getUnionType(instantiateList(type.types, mapper, instantiateType), /*subtypeReduction*/ false, type.aliasSymbol, mapper.targetTypes); + if (type.flags & 8192 /* Tuple */) { + return createTupleType(instantiateList(type.elementTypes, mapper, instantiateType)); } - if (type.flags & 1048576 /* Intersection */) { - return getIntersectionType(instantiateList(type.types, mapper, instantiateType), type.aliasSymbol, mapper.targetTypes); + if (type.flags & 16384 /* Union */) { + return getUnionType(instantiateList(type.types, mapper, instantiateType), /*noSubtypeReduction*/ true); + } + if (type.flags & 32768 /* Intersection */) { + return getIntersectionType(instantiateList(type.types, mapper, instantiateType)); } } return type; @@ -22568,10 +21303,10 @@ var ts; return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { - if (type.flags & 2588672 /* ObjectType */) { + if (type.flags & 80896 /* ObjectType */) { var resolved = resolveStructuredTypeMembers(type); if (resolved.constructSignatures.length) { - var result = createObjectType(2097152 /* Anonymous */, type.symbol); + var result = createObjectType(65536 /* Anonymous */, type.symbol); result.members = resolved.members; result.properties = resolved.properties; result.callSignatures = emptyArray; @@ -22583,32 +21318,26 @@ var ts; } // TYPE CHECKING function isTypeIdenticalTo(source, target) { - return isTypeRelatedTo(source, target, identityRelation); + return checkTypeRelatedTo(source, target, identityRelation, /*errorNode*/ undefined); } function compareTypesIdentical(source, target) { - return isTypeRelatedTo(source, target, identityRelation) ? -1 /* True */ : 0 /* False */; + return checkTypeRelatedTo(source, target, identityRelation, /*errorNode*/ undefined) ? -1 /* True */ : 0 /* False */; } function compareTypesAssignable(source, target) { - return isTypeRelatedTo(source, target, assignableRelation) ? -1 /* True */ : 0 /* False */; + return checkTypeRelatedTo(source, target, assignableRelation, /*errorNode*/ undefined) ? -1 /* True */ : 0 /* False */; } function isTypeSubtypeOf(source, target) { - return isTypeRelatedTo(source, target, subtypeRelation); + return checkTypeSubtypeOf(source, target, /*errorNode*/ undefined); } function isTypeAssignableTo(source, target) { - return isTypeRelatedTo(source, target, assignableRelation); - } - // A type S is considered to be an instance of a type T if S and T are the same type or if S is a - // subtype of T but not structurally identical to T. This specifically means that two distinct but - // structurally identical types (such as two classes) are not considered instances of each other. - function isTypeInstanceOf(source, target) { - return source === target || isTypeSubtypeOf(source, target) && !isTypeIdenticalTo(source, target); + return checkTypeAssignableTo(source, target, /*errorNode*/ undefined); } /** * This is *not* a bi-directional relationship. * If one needs to check both directions for comparability, use a second call to this function or 'checkTypeComparableTo'. */ function isTypeComparableTo(source, target) { - return isTypeRelatedTo(source, target, comparableRelation); + return checkTypeComparableTo(source, target, /*errorNode*/ undefined); } function areTypesComparable(type1, type2) { return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); @@ -22734,8 +21463,8 @@ var ts; var sourceReturnType = getReturnTypeOfSignature(erasedSource); var targetReturnType = getReturnTypeOfSignature(erasedTarget); if (targetReturnType === voidType - || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation) - || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) { + || checkTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation, /*errorNode*/ undefined) + || checkTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation, /*errorNode*/ undefined)) { return isSignatureAssignableTo(erasedSource, erasedTarget, /*ignoreReturnTypes*/ true); } return false; @@ -22764,88 +21493,6 @@ var ts; sourceNonRestParamCount; } } - function isEnumTypeRelatedTo(source, target, errorReporter) { - if (source === target) { - return true; - } - var id = source.id + "," + target.id; - if (enumRelation[id] !== undefined) { - return enumRelation[id]; - } - if (source.symbol.name !== target.symbol.name || - !(source.symbol.flags & 256 /* RegularEnum */) || !(target.symbol.flags & 256 /* RegularEnum */) || - (source.flags & 524288 /* Union */) !== (target.flags & 524288 /* Union */)) { - return enumRelation[id] = false; - } - var targetEnumType = getTypeOfSymbol(target.symbol); - for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { - var property = _a[_i]; - if (property.flags & 8 /* EnumMember */) { - var targetProperty = getPropertyOfType(targetEnumType, property.name); - if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { - if (errorReporter) { - errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */)); - } - return enumRelation[id] = false; - } - } - } - return enumRelation[id] = true; - } - function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { - if (target.flags & 8192 /* Never */) - return false; - if (target.flags & 1 /* Any */ || source.flags & 8192 /* Never */) - return true; - if (source.flags & 34 /* StringLike */ && target.flags & 2 /* String */) - return true; - if (source.flags & 340 /* NumberLike */ && target.flags & 4 /* Number */) - return true; - if (source.flags & 136 /* BooleanLike */ && target.flags & 8 /* Boolean */) - return true; - if (source.flags & 256 /* EnumLiteral */ && target.flags & 16 /* Enum */ && source.baseType === target) - return true; - if (source.flags & 16 /* Enum */ && target.flags & 16 /* Enum */ && isEnumTypeRelatedTo(source, target, errorReporter)) - return true; - if (source.flags & 2048 /* Undefined */ && (!strictNullChecks || target.flags & (2048 /* Undefined */ | 1024 /* Void */))) - return true; - if (source.flags & 4096 /* Null */ && (!strictNullChecks || target.flags & 4096 /* Null */)) - return true; - if (relation === assignableRelation || relation === comparableRelation) { - if (source.flags & 1 /* Any */) - return true; - if ((source.flags & 4 /* Number */ | source.flags & 64 /* NumberLiteral */) && target.flags & 272 /* EnumLike */) - return true; - if (source.flags & 256 /* EnumLiteral */ && - target.flags & 256 /* EnumLiteral */ && - source.text === target.text && - isEnumTypeRelatedTo(source.baseType, target.baseType, errorReporter)) { - return true; - } - if (source.flags & 256 /* EnumLiteral */ && - target.flags & 16 /* Enum */ && - isEnumTypeRelatedTo(target, source.baseType, errorReporter)) { - return true; - } - } - return false; - } - function isTypeRelatedTo(source, target, relation) { - if (source === target || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { - return true; - } - if (source.flags & 2588672 /* ObjectType */ && target.flags & 2588672 /* ObjectType */) { - var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; - var related = relation[id]; - if (related !== undefined) { - return related === 1 /* Succeeded */; - } - } - if (source.flags & 4177920 /* StructuredOrTypeParameter */ || target.flags & 4177920 /* StructuredOrTypeParameter */) { - return checkTypeRelatedTo(source, target, relation, undefined, undefined, undefined); - } - return false; - } /** * Checks if 'source' is related to 'target' (e.g.: is a assignable to). * @param source The left-hand-side of the relation. @@ -22894,16 +21541,6 @@ var ts; } reportError(message, sourceType, targetType); } - function tryElaborateErrorsForPrimitivesAndObjects(source, target) { - var sourceType = typeToString(source); - var targetType = typeToString(target); - if ((globalStringType === source && stringType === target) || - (globalNumberType === source && numberType === target) || - (globalBooleanType === source && booleanType === target) || - (getGlobalESSymbolType() === source && esSymbolType === target)) { - reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); - } - } // Compare two types and return // Ternary.True if they are related with no assumptions, // Ternary.Maybe if they are related with assumptions of other relationships, or @@ -22916,9 +21553,37 @@ var ts; if (relation === identityRelation) { return isIdenticalTo(source, target); } - if (isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) - return -1 /* True */; - if (source.flags & 16777216 /* FreshObjectLiteral */) { + if (!(target.flags & 134217728 /* Never */)) { + if (target.flags & 1 /* Any */ || source.flags & 134217728 /* Never */) + return -1 /* True */; + if (source.flags & 32 /* Undefined */) { + if (!strictNullChecks || target.flags & (32 /* Undefined */ | 16 /* Void */)) + return -1 /* True */; + } + if (source.flags & 64 /* Null */) { + if (!strictNullChecks || target.flags & 64 /* Null */) + return -1 /* True */; + } + if (source.flags & 128 /* Enum */ && target === numberType) + return -1 /* True */; + if (source.flags & 128 /* Enum */ && target.flags & 128 /* Enum */) { + if (result = enumRelatedTo(source, target, reportErrors)) { + return result; + } + } + if (source.flags & 256 /* StringLiteral */ && target === stringType) + return -1 /* True */; + if (relation === assignableRelation || relation === comparableRelation) { + if (source.flags & 1 /* Any */) + return -1 /* True */; + if (source === numberType && target.flags & 128 /* Enum */) + return -1 /* True */; + } + if (source.flags & 8 /* Boolean */ && target.flags & 8 /* Boolean */) { + return -1 /* True */; + } + } + if (source.flags & 1048576 /* FreshObjectLiteral */) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { reportRelationError(headMessage, source, target); @@ -22929,24 +21594,24 @@ var ts; // and intersection types are further deconstructed on the target side, we don't want to // make the check again (as it might fail for a partial target type). Therefore we obtain // the regular source type and proceed with that. - if (target.flags & 1572864 /* UnionOrIntersection */) { + if (target.flags & 49152 /* UnionOrIntersection */) { source = getRegularTypeOfObjectLiteral(source); } } var saveErrorInfo = errorInfo; // Note that these checks are specifically ordered to produce correct results. - if (source.flags & 524288 /* Union */) { + if (source.flags & 16384 /* Union */) { if (relation === comparableRelation) { - result = someTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */)); + result = someTypeRelatedToType(source, target, reportErrors); } else { - result = eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */)); + result = eachTypeRelatedToType(source, target, reportErrors); } if (result) { return result; } } - else if (target.flags & 1048576 /* Intersection */) { + else if (target.flags & 32768 /* Intersection */) { result = typeRelatedToEachType(source, target, reportErrors); if (result) { return result; @@ -22956,7 +21621,7 @@ var ts; // It is necessary to try these "some" checks on both sides because there may be nested "each" checks // on either side that need to be prioritized. For example, A | B = (A | B) & (C | D) or // A & B = (A & B) | (C & D). - if (source.flags & 1048576 /* Intersection */) { + if (source.flags & 32768 /* Intersection */) { // Check to see if any constituents of the intersection are immediately related to the target. // // Don't report errors though. Checking whether a constituent is related to the source is not actually @@ -22974,13 +21639,13 @@ var ts; return result; } } - if (target.flags & 524288 /* Union */) { - if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */) && !(target.flags & 8190 /* Primitive */))) { + if (target.flags & 16384 /* Union */) { + if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 16777726 /* Primitive */))) { return result; } } } - if (source.flags & 16384 /* TypeParameter */) { + if (source.flags & 512 /* TypeParameter */) { var constraint = getConstraintOfTypeParameter(source); if (!constraint || constraint.flags & 1 /* Any */) { constraint = emptyObjectType; @@ -22995,7 +21660,7 @@ var ts; } } else { - if (source.flags & 131072 /* Reference */ && target.flags & 131072 /* Reference */ && source.target === target.target) { + if (source.flags & 4096 /* Reference */ && target.flags & 4096 /* Reference */ && source.target === target.target) { // We have type references to same target type, see if relationship holds for all type arguments if (result = typeArgumentsRelatedTo(source, target, reportErrors)) { return result; @@ -23007,9 +21672,9 @@ var ts; // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. - if (apparentSource.flags & (2588672 /* ObjectType */ | 1048576 /* Intersection */) && target.flags & 2588672 /* ObjectType */) { + if (apparentSource.flags & (80896 /* ObjectType */ | 32768 /* Intersection */) && target.flags & 80896 /* ObjectType */) { // Report structural errors only if we haven't reported any errors yet - var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !(source.flags & 8190 /* Primitive */); + var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !(source.flags & 16777726 /* Primitive */); if (result = objectTypeRelatedTo(apparentSource, source, target, reportStructuralErrors)) { errorInfo = saveErrorInfo; return result; @@ -23017,17 +21682,14 @@ var ts; } } if (reportErrors) { - if (source.flags & 2588672 /* ObjectType */ && target.flags & 8190 /* Primitive */) { - tryElaborateErrorsForPrimitivesAndObjects(source, target); - } reportRelationError(headMessage, source, target); } return 0 /* False */; } function isIdenticalTo(source, target) { var result; - if (source.flags & 2588672 /* ObjectType */ && target.flags & 2588672 /* ObjectType */) { - if (source.flags & 131072 /* Reference */ && target.flags & 131072 /* Reference */ && source.target === target.target) { + if (source.flags & 80896 /* ObjectType */ && target.flags & 80896 /* ObjectType */) { + if (source.flags & 4096 /* Reference */ && target.flags & 4096 /* Reference */ && source.target === target.target) { // We have type references to same target type, see if all type arguments are identical if (result = typeArgumentsRelatedTo(source, target, /*reportErrors*/ false)) { return result; @@ -23035,8 +21697,8 @@ var ts; } return objectTypeRelatedTo(source, source, target, /*reportErrors*/ false); } - if (source.flags & 524288 /* Union */ && target.flags & 524288 /* Union */ || - source.flags & 1048576 /* Intersection */ && target.flags & 1048576 /* Intersection */) { + if (source.flags & 16384 /* Union */ && target.flags & 16384 /* Union */ || + source.flags & 32768 /* Intersection */ && target.flags & 32768 /* Intersection */) { if (result = eachTypeRelatedToSomeType(source, target, /*reportErrors*/ false)) { if (result &= eachTypeRelatedToSomeType(target, source, /*reportErrors*/ false)) { return result; @@ -23050,7 +21712,7 @@ var ts; // index signatures, or if the property is actually declared in the object type. In a union or intersection // type, a property is considered known if it is known in any constituent type. function isKnownProperty(type, name) { - if (type.flags & 2588672 /* ObjectType */) { + if (type.flags & 80896 /* ObjectType */) { var resolved = resolveStructuredTypeMembers(type); if ((relation === assignableRelation || relation === comparableRelation) && (type === globalObjectType || isEmptyObjectType(resolved)) || resolved.stringIndexInfo || @@ -23059,7 +21721,7 @@ var ts; return true; } } - else if (type.flags & 1572864 /* UnionOrIntersection */) { + else if (type.flags & 49152 /* UnionOrIntersection */) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; if (isKnownProperty(t, name)) { @@ -23077,7 +21739,7 @@ var ts; !t.numberIndexInfo; } function hasExcessProperties(source, target, reportErrors) { - if (!(target.flags & 536870912 /* ObjectLiteralPatternWithComputedProperties */) && maybeTypeOfKind(target, 2588672 /* ObjectType */)) { + if (!(target.flags & 67108864 /* ObjectLiteralPatternWithComputedProperties */) && maybeTypeOfKind(target, 80896 /* ObjectType */)) { for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; if (!isKnownProperty(target, prop.name)) { @@ -23110,10 +21772,18 @@ var ts; } function typeRelatedToSomeType(source, target, reportErrors) { var targetTypes = target.types; - if (target.flags & 524288 /* Union */ && containsType(targetTypes, source)) { - return -1 /* True */; - } var len = targetTypes.length; + // The null and undefined types are guaranteed to be at the end of the constituent type list. In order + // to produce the best possible errors we first check the nullable types, such that the last type we + // check and report errors from is a non-nullable type if one is present. + while (len >= 2 && targetTypes[len - 1].flags & 96 /* Nullable */) { + var related = isRelatedTo(source, targetTypes[len - 1], /*reportErrors*/ false); + if (related) { + return related; + } + len--; + } + // Now check the non-nullable types and report errors on the last one. for (var i = 0; i < len; i++) { var related = isRelatedTo(source, targetTypes[i], reportErrors && i === len - 1); if (related) { @@ -23137,10 +21807,18 @@ var ts; } function someTypeRelatedToType(source, target, reportErrors) { var sourceTypes = source.types; - if (source.flags & 524288 /* Union */ && containsType(sourceTypes, target)) { - return -1 /* True */; - } var len = sourceTypes.length; + // The null and undefined types are guaranteed to be at the end of the constituent type list. In order + // to produce the best possible errors we first check the nullable types, such that the last type we + // check and report errors from is a non-nullable type if one is present. + while (len >= 2 && sourceTypes[len - 1].flags & 96 /* Nullable */) { + var related = isRelatedTo(sourceTypes[len - 1], target, /*reportErrors*/ false); + if (related) { + return related; + } + len--; + } + // Now check the non-nullable types and report errors on the last one. for (var i = 0; i < len; i++) { var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); if (related) { @@ -23220,7 +21898,7 @@ var ts; } sourceStack[depth] = source; targetStack[depth] = target; - maybeStack[depth] = ts.createMap(); + maybeStack[depth] = {}; maybeStack[depth][id] = 1 /* Succeeded */; depth++; var saveExpandingFlags = expandingFlags; @@ -23253,7 +21931,7 @@ var ts; var maybeCache = maybeStack[depth]; // If result is definitely true, copy assumptions to global cache, else copy to next level up var destinationCache = (result === -1 /* True */ || depth === 0) ? relation : maybeStack[depth - 1]; - ts.copyProperties(maybeCache, destinationCache); + ts.copyMap(maybeCache, destinationCache); } else { // A false result goes straight into global cache (when something is false under assumptions it @@ -23268,7 +21946,7 @@ var ts; } var result = -1 /* True */; var properties = getPropertiesOfObjectType(target); - var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 8388608 /* ObjectLiteral */); + var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 524288 /* ObjectLiteral */); for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) { var targetProp = properties_1[_i]; var sourceProp = getPropertyOfType(source, targetProp.name); @@ -23341,7 +22019,7 @@ var ts; return result; } function propertiesIdenticalTo(source, target) { - if (!(source.flags & 2588672 /* ObjectType */ && target.flags & 2588672 /* ObjectType */)) { + if (!(source.flags & 80896 /* ObjectType */ && target.flags & 80896 /* ObjectType */)) { return 0 /* False */; } var sourceProperties = getPropertiesOfObjectType(source); @@ -23462,7 +22140,7 @@ var ts; return indexTypesIdenticalTo(source, target, kind); } var targetInfo = getIndexInfoOfType(target, kind); - if (!targetInfo || ((targetInfo.type.flags & 1 /* Any */) && !(originalSource.flags & 8190 /* Primitive */))) { + if (!targetInfo || ((targetInfo.type.flags & 1 /* Any */) && !(originalSource.flags & 16777726 /* Primitive */))) { // Index signature of type any permits assignment from everything but primitives return -1 /* True */; } @@ -23500,6 +22178,27 @@ var ts; } return 0 /* False */; } + function enumRelatedTo(source, target, reportErrors) { + if (source.symbol.name !== target.symbol.name || + source.symbol.flags & 128 /* ConstEnum */ || + target.symbol.flags & 128 /* ConstEnum */) { + return 0 /* False */; + } + var targetEnumType = getTypeOfSymbol(target.symbol); + for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { + var property = _a[_i]; + if (property.flags & 8 /* EnumMember */) { + var targetProperty = getPropertyOfType(targetEnumType, property.name); + if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */)); + } + return 0 /* False */; + } + } + } + return -1 /* True */; + } function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) { if (!sourceSignature.declaration || !targetSignature.declaration) { return true; @@ -23526,7 +22225,7 @@ var ts; } // Return true if the given type is the constructor type for an abstract class function isAbstractConstructorType(type) { - if (type.flags & 2097152 /* Anonymous */) { + if (type.flags & 65536 /* Anonymous */) { var symbol = type.symbol; if (symbol && symbol.flags & 32 /* Class */) { var declaration = getClassLikeDeclarationOfSymbol(symbol); @@ -23544,12 +22243,12 @@ var ts; // some level beyond that. function isDeeplyNestedGeneric(type, stack, depth) { // We track type references (created by createTypeReference) and instantiated types (created by instantiateType) - if (type.flags & (131072 /* Reference */ | 4194304 /* Instantiated */) && depth >= 5) { + if (type.flags & (4096 /* Reference */ | 131072 /* Instantiated */) && depth >= 5) { var symbol = type.symbol; var count = 0; for (var i = 0; i < depth; i++) { var t = stack[i]; - if (t.flags & (131072 /* Reference */ | 4194304 /* Instantiated */) && t.symbol === symbol) { + if (t.flags & (4096 /* Reference */ | 131072 /* Instantiated */) && t.symbol === symbol) { count++; if (count >= 5) return true; @@ -23599,10 +22298,8 @@ var ts; // A source signature partially matches a target signature if the target signature has no fewer required // parameters and no more overall parameters than the source signature (where a signature with a rest // parameter is always considered to have more overall parameters than one without). - var sourceRestCount = source.hasRestParameter ? 1 : 0; - var targetRestCount = target.hasRestParameter ? 1 : 0; - if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (sourceRestCount > targetRestCount || - sourceRestCount === targetRestCount && source.parameters.length >= target.parameters.length)) { + if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (source.hasRestParameter && !target.hasRestParameter || + source.hasRestParameter === target.hasRestParameter && source.parameters.length >= target.parameters.length)) { return true; } return false; @@ -23663,23 +22360,31 @@ var ts; return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } function isSupertypeOfEach(candidate, types) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var t = types_5[_i]; if (candidate !== t && !isTypeSubtypeOf(t, candidate)) return false; } return true; } + function getCombinedFlagsOfTypes(types) { + var flags = 0; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var t = types_6[_i]; + flags |= t.flags; + } + return flags; + } function getCommonSupertype(types) { if (!strictNullChecks) { return ts.forEach(types, function (t) { return isSupertypeOfEach(t, types) ? t : undefined; }); } - var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 6144 /* Nullable */); }); + var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 96 /* Nullable */); }); if (!primaryTypes.length) { - return getUnionType(types, /*subtypeReduction*/ true); + return getUnionType(types); } var supertype = ts.forEach(primaryTypes, function (t) { return isSupertypeOfEach(t, primaryTypes) ? t : undefined; }); - return supertype && includeFalsyTypes(supertype, getFalsyFlagsOfTypes(types) & 6144 /* Nullable */); + return supertype && addTypeKind(supertype, getCombinedFlagsOfTypes(types) & 96 /* Nullable */); } function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { // The downfallType/bestSupertypeDownfallType is the first type that caused a particular candidate @@ -23715,81 +22420,50 @@ var ts; checkTypeSubtypeOf(bestSupertypeDownfallType, bestSupertype, errorLocation, ts.Diagnostics.Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0, errorMessageChainHead); } function isArrayType(type) { - return type.flags & 131072 /* Reference */ && type.target === globalArrayType; + return type.flags & 4096 /* Reference */ && type.target === globalArrayType; } function isArrayLikeType(type) { // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, // or if it is not the undefined or null type and if it is assignable to ReadonlyArray - return type.flags & 131072 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || - !(type.flags & 6144 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); + return type.flags & 4096 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || + !(type.flags & 96 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); } function isTupleLikeType(type) { return !!getPropertyOfType(type, "0"); } - function isUnitType(type) { - return (type.flags & (480 /* Literal */ | 2048 /* Undefined */ | 4096 /* Null */)) !== 0; - } - function isUnitUnionType(type) { - return type.flags & 8 /* Boolean */ ? true : - type.flags & 524288 /* Union */ ? type.flags & 16 /* Enum */ ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : - isUnitType(type); - } - function getBaseTypeOfUnitType(type) { - return type.flags & 32 /* StringLiteral */ ? stringType : - type.flags & 64 /* NumberLiteral */ ? numberType : - type.flags & 128 /* BooleanLiteral */ ? booleanType : - type.flags & 256 /* EnumLiteral */ ? type.baseType : - type.flags & 524288 /* Union */ && !(type.flags & 16 /* Enum */) ? getUnionType(ts.map(type.types, getBaseTypeOfUnitType)) : - type; + function isStringLiteralUnionType(type) { + return type.flags & 256 /* StringLiteral */ ? true : + type.flags & 16384 /* Union */ ? ts.forEach(type.types, isStringLiteralUnionType) : + false; } /** * Check if a Type was written as a tuple type literal. * Prefer using isTupleLikeType() unless the use of `elementTypes` is required. */ function isTupleType(type) { - return !!(type.flags & 131072 /* Reference */ && type.target.flags & 262144 /* Tuple */); + return !!(type.flags & 8192 /* Tuple */); } - function getFalsyFlagsOfTypes(types) { - var result = 0; - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var t = types_8[_i]; - result |= getFalsyFlags(t); - } - return result; + function getCombinedTypeFlags(type) { + return type.flags & 16384 /* Union */ ? getCombinedFlagsOfTypes(type.types) : type.flags; } - // Returns the String, Number, Boolean, StringLiteral, NumberLiteral, BooleanLiteral, Void, Undefined, or Null - // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns - // no flags for all other types (including non-falsy literal types). - function getFalsyFlags(type) { - return type.flags & 524288 /* Union */ ? getFalsyFlagsOfTypes(type.types) : - type.flags & 32 /* StringLiteral */ ? type === emptyStringType ? 32 /* StringLiteral */ : 0 : - type.flags & 64 /* NumberLiteral */ ? type === zeroType ? 64 /* NumberLiteral */ : 0 : - type.flags & 128 /* BooleanLiteral */ ? type === falseType ? 128 /* BooleanLiteral */ : 0 : - type.flags & 7406 /* PossiblyFalsy */; - } - function includeFalsyTypes(type, flags) { - if ((getFalsyFlags(type) & flags) === flags) { + function addTypeKind(type, kind) { + if ((getCombinedTypeFlags(type) & kind) === kind) { return type; } var types = [type]; - if (flags & 34 /* StringLike */) - types.push(emptyStringType); - if (flags & 340 /* NumberLike */) - types.push(zeroType); - if (flags & 136 /* BooleanLike */) - types.push(falseType); - if (flags & 1024 /* Void */) + if (kind & 2 /* String */) + types.push(stringType); + if (kind & 4 /* Number */) + types.push(numberType); + if (kind & 8 /* Boolean */) + types.push(booleanType); + if (kind & 16 /* Void */) types.push(voidType); - if (flags & 2048 /* Undefined */) + if (kind & 32 /* Undefined */) types.push(undefinedType); - if (flags & 4096 /* Null */) + if (kind & 64 /* Null */) types.push(nullType); - return getUnionType(types, /*subtypeReduction*/ true); - } - function removeDefinitelyFalsyTypes(type) { - return getFalsyFlags(type) & 7392 /* DefinitelyFalsy */ ? - filterType(type, function (t) { return !(getFalsyFlags(t) & 7392 /* DefinitelyFalsy */); }) : - type; + return getUnionType(types); } function getNonNullableType(type) { return strictNullChecks ? getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */) : type; @@ -23815,7 +22489,7 @@ var ts; return symbol; } function transformTypeOfMembers(type, f) { - var members = ts.createMap(); + var members = {}; for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { var property = _a[_i]; var original = getTypeOfSymbol(property); @@ -23831,7 +22505,7 @@ var ts; * Leave signatures alone since they are not subject to the check. */ function getRegularTypeOfObjectLiteral(type) { - if (!(type.flags & 16777216 /* FreshObjectLiteral */)) { + if (!(type.flags & 1048576 /* FreshObjectLiteral */)) { return type; } var regularType = type.regularType; @@ -23841,7 +22515,7 @@ var ts; var resolved = type; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); - regularNew.flags = resolved.flags & ~16777216 /* FreshObjectLiteral */; + regularNew.flags = resolved.flags & ~1048576 /* FreshObjectLiteral */; type.regularType = regularNew; return regularNew; } @@ -23855,21 +22529,24 @@ var ts; return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); } function getWidenedConstituentType(type) { - return type.flags & 6144 /* Nullable */ ? type : getWidenedType(type); + return type.flags & 96 /* Nullable */ ? type : getWidenedType(type); } function getWidenedType(type) { - if (type.flags & 100663296 /* RequiresWidening */) { - if (type.flags & 6144 /* Nullable */) { + if (type.flags & 6291456 /* RequiresWidening */) { + if (type.flags & 96 /* Nullable */) { return anyType; } - if (type.flags & 8388608 /* ObjectLiteral */) { + if (type.flags & 524288 /* ObjectLiteral */) { return getWidenedTypeOfObjectLiteral(type); } - if (type.flags & 524288 /* Union */) { - return getUnionType(ts.map(type.types, getWidenedConstituentType)); + if (type.flags & 16384 /* Union */) { + return getUnionType(ts.map(type.types, getWidenedConstituentType), /*noSubtypeReduction*/ true); } - if (isArrayType(type) || isTupleType(type)) { - return createTypeReference(type.target, ts.map(type.typeArguments, getWidenedType)); + if (isArrayType(type)) { + return createArrayType(getWidenedType(type.typeArguments[0])); + } + if (isTupleType(type)) { + return createTupleType(ts.map(type.elementTypes, getWidenedType)); } } return type; @@ -23887,7 +22564,7 @@ var ts; */ function reportWideningErrorsInType(type) { var errorReported = false; - if (type.flags & 524288 /* Union */) { + if (type.flags & 16384 /* Union */) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; if (reportWideningErrorsInType(t)) { @@ -23895,19 +22572,22 @@ var ts; } } } - if (isArrayType(type) || isTupleType(type)) { - for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) { + if (isArrayType(type)) { + return reportWideningErrorsInType(type.typeArguments[0]); + } + if (isTupleType(type)) { + for (var _b = 0, _c = type.elementTypes; _b < _c.length; _b++) { var t = _c[_b]; if (reportWideningErrorsInType(t)) { errorReported = true; } } } - if (type.flags & 8388608 /* ObjectLiteral */) { + if (type.flags & 524288 /* ObjectLiteral */) { for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); - if (t.flags & 33554432 /* ContainsWideningType */) { + if (t.flags & 2097152 /* ContainsWideningType */) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, p.name, typeToString(getWidenedType(t))); } @@ -23952,7 +22632,7 @@ var ts; error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); } function reportErrorsFromWidening(declaration, type) { - if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 33554432 /* ContainsWideningType */) { + if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 2097152 /* ContainsWideningType */) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAnyError(declaration, type); @@ -23995,27 +22675,12 @@ var ts; isFixed: false }; } - // Return true if the given type could possibly reference a type parameter for which - // we perform type inference (i.e. a type parameter of a generic function). We cache - // results for union and intersection types for performance reasons. - function couldContainTypeParameters(type) { - return !!(type.flags & 16384 /* TypeParameter */ || - type.flags & 131072 /* Reference */ && ts.forEach(type.typeArguments, couldContainTypeParameters) || - type.flags & 2097152 /* Anonymous */ && type.symbol && type.symbol.flags & (8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */) || - type.flags & 1572864 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeParameters(type)); - } - function couldUnionOrIntersectionContainTypeParameters(type) { - if (type.couldContainTypeParameters === undefined) { - type.couldContainTypeParameters = ts.forEach(type.types, couldContainTypeParameters); - } - return type.couldContainTypeParameters; - } function inferTypes(context, source, target) { var sourceStack; var targetStack; var depth = 0; var inferiority = 0; - var visited = ts.createMap(); + var visited = {}; inferFromTypes(source, target); function isInProcess(source, target) { for (var i = 0; i < depth; i++) { @@ -24026,27 +22691,16 @@ var ts; return false; } function inferFromTypes(source, target) { - if (!couldContainTypeParameters(target)) { - return; - } - if (source.flags & 524288 /* Union */ && target.flags & 524288 /* Union */ && !(source.flags & 16 /* Enum */ && target.flags & 16 /* Enum */) || - source.flags & 1048576 /* Intersection */ && target.flags & 1048576 /* Intersection */) { - // Source and target are both unions or both intersections. If source and target - // are the same type, just relate each constituent type to itself. - if (source === target) { - for (var _i = 0, _a = source.types; _i < _a.length; _i++) { - var t = _a[_i]; - inferFromTypes(t, t); - } - return; - } - // Find each target constituent type that has an identically matching source - // constituent type, and for each such target constituent type infer from the type to - // itself. When inferring from a type to itself we effectively find all type parameter + if (source.flags & 16384 /* Union */ && target.flags & 16384 /* Union */ || + source.flags & 32768 /* Intersection */ && target.flags & 32768 /* Intersection */) { + // Source and target are both unions or both intersections. First, find each + // target constituent type that has an identically matching source constituent + // type, and for each such target constituent type infer from the type to itself. + // When inferring from a type to itself we effectively find all type parameter // occurrences within that type and infer themselves as their type arguments. var matchingTypes = void 0; - for (var _b = 0, _c = target.types; _b < _c.length; _b++) { - var t = _c[_b]; + for (var _i = 0, _a = target.types; _i < _a.length; _i++) { + var t = _a[_i]; if (typeIdenticalToSomeType(t, source.types)) { (matchingTypes || (matchingTypes = [])).push(t); inferFromTypes(t, t); @@ -24060,14 +22714,14 @@ var ts; target = removeTypesFromUnionOrIntersection(target, matchingTypes); } } - if (target.flags & 16384 /* TypeParameter */) { + if (target.flags & 512 /* TypeParameter */) { // If target is a type parameter, make an inference, unless the source type contains // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). // Because the anyFunctionType is internal, it should not be exposed to the user by adding // it as an inference candidate. Hopefully, a better candidate will come along that does // not contain anyFunctionType when we come back to this argument for its second round // of inference. - if (source.flags & 134217728 /* ContainsAnyFunctionType */) { + if (source.flags & 8388608 /* ContainsAnyFunctionType */) { return; } var typeParameters = context.typeParameters; @@ -24092,7 +22746,7 @@ var ts; } } } - else if (source.flags & 131072 /* Reference */ && target.flags & 131072 /* Reference */ && source.target === target.target) { + else if (source.flags & 4096 /* Reference */ && target.flags & 4096 /* Reference */ && source.target === target.target) { // If source and target are references to the same generic type, infer from type arguments var sourceTypes = source.typeArguments || emptyArray; var targetTypes = target.typeArguments || emptyArray; @@ -24101,14 +22755,22 @@ var ts; inferFromTypes(sourceTypes[i], targetTypes[i]); } } - else if (target.flags & 1572864 /* UnionOrIntersection */) { + else if (source.flags & 8192 /* Tuple */ && target.flags & 8192 /* Tuple */ && source.elementTypes.length === target.elementTypes.length) { + // If source and target are tuples of the same size, infer from element types + var sourceTypes = source.elementTypes; + var targetTypes = target.elementTypes; + for (var i = 0; i < sourceTypes.length; i++) { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } + } + else if (target.flags & 49152 /* UnionOrIntersection */) { var targetTypes = target.types; var typeParameterCount = 0; var typeParameter = void 0; // First infer to each type in union or intersection that isn't a type parameter - for (var _d = 0, targetTypes_2 = targetTypes; _d < targetTypes_2.length; _d++) { - var t = targetTypes_2[_d]; - if (t.flags & 16384 /* TypeParameter */ && ts.contains(context.typeParameters, t)) { + for (var _b = 0, targetTypes_2 = targetTypes; _b < targetTypes_2.length; _b++) { + var t = targetTypes_2[_b]; + if (t.flags & 512 /* TypeParameter */ && ts.contains(context.typeParameters, t)) { typeParameter = t; typeParameterCount++; } @@ -24125,17 +22787,21 @@ var ts; inferiority--; } } - else if (source.flags & 1572864 /* UnionOrIntersection */) { + else if (source.flags & 49152 /* UnionOrIntersection */) { // Source is a union or intersection type, infer from each constituent type var sourceTypes = source.types; - for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { - var sourceType = sourceTypes_3[_e]; + for (var _c = 0, sourceTypes_3 = sourceTypes; _c < sourceTypes_3.length; _c++) { + var sourceType = sourceTypes_3[_c]; inferFromTypes(sourceType, target); } } else { source = getApparentType(source); - if (source.flags & 2588672 /* ObjectType */) { + if (source.flags & 80896 /* ObjectType */ && (target.flags & 4096 /* Reference */ && target.typeArguments || + target.flags & 8192 /* Tuple */ || + target.flags & 65536 /* Anonymous */ && target.symbol && target.symbol.flags & (8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */))) { + // If source is an object type, and target is a type reference with type arguments, a tuple type, + // the type of a method, or a type literal, infer from members if (isInProcess(source, target)) { return; } @@ -24143,7 +22809,7 @@ var ts; return; } var key = source.id + "," + target.id; - if (visited[key]) { + if (ts.hasProperty(visited, key)) { return; } visited[key] = true; @@ -24212,8 +22878,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var t = types_7[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -24232,7 +22898,7 @@ var ts; reducedTypes.push(t); } } - return type.flags & 524288 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); + return type.flags & 16384 /* Union */ ? getUnionType(reducedTypes, /*noSubtypeReduction*/ true) : getIntersectionType(reducedTypes); } function getInferenceCandidates(context, index) { var inferences = context.inferences[index]; @@ -24245,7 +22911,7 @@ var ts; var inferences = getInferenceCandidates(context, index); if (inferences.length) { // Infer widened union or supertype, or the unknown type for no common supertype - var unionOrSuperType = context.inferUnionTypes ? getUnionType(inferences, /*subtypeReduction*/ true) : getCommonSupertype(inferences); + var unionOrSuperType = context.inferUnionTypes ? getUnionType(inferences) : getCommonSupertype(inferences); inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType; inferenceSucceeded = !!unionOrSuperType; } @@ -24327,6 +22993,10 @@ var ts; } return undefined; } + function isNullOrUndefinedLiteral(node) { + return node.kind === 93 /* NullKeyword */ || + node.kind === 69 /* Identifier */ && getResolvedSymbol(node) === undefinedSymbol; + } function getLeftmostIdentifierOrThis(node) { switch (node.kind) { case 69 /* Identifier */: @@ -24338,17 +23008,16 @@ var ts; return undefined; } function isMatchingReference(source, target) { - switch (source.kind) { - case 69 /* Identifier */: - return target.kind === 69 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || - (target.kind === 218 /* VariableDeclaration */ || target.kind === 169 /* BindingElement */) && - getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); - case 97 /* ThisKeyword */: - return target.kind === 97 /* ThisKeyword */; - case 172 /* PropertyAccessExpression */: - return target.kind === 172 /* PropertyAccessExpression */ && - source.name.text === target.name.text && - isMatchingReference(source.expression, target.expression); + if (source.kind === target.kind) { + switch (source.kind) { + case 69 /* Identifier */: + return getResolvedSymbol(source) === getResolvedSymbol(target); + case 97 /* ThisKeyword */: + return true; + case 172 /* PropertyAccessExpression */: + return source.name.text === target.name.text && + isMatchingReference(source.expression, target.expression); + } } return false; } @@ -24361,48 +23030,6 @@ var ts; } return false; } - // Return true if target is a property access xxx.yyy, source is a property access xxx.zzz, the declared - // type of xxx is a union type, and yyy is a property that is possibly a discriminant. We consider a property - // a possible discriminant if its type differs in the constituents of containing union type, and if every - // choice is a unit type or a union of unit types. - function containsMatchingReferenceDiscriminant(source, target) { - return target.kind === 172 /* PropertyAccessExpression */ && - containsMatchingReference(source, target.expression) && - isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.text); - } - function getDeclaredTypeOfReference(expr) { - if (expr.kind === 69 /* Identifier */) { - return getTypeOfSymbol(getResolvedSymbol(expr)); - } - if (expr.kind === 172 /* PropertyAccessExpression */) { - var type = getDeclaredTypeOfReference(expr.expression); - return type && getTypeOfPropertyOfType(type, expr.name.text); - } - return undefined; - } - function isDiscriminantProperty(type, name) { - if (type && type.flags & 524288 /* Union */) { - var prop = getPropertyOfType(type, name); - if (!prop) { - // The type may be a union that includes nullable or primitive types. If filtering - // those out produces a different type, get the property from that type instead. - // Effectively, we're checking if this *could* be a discriminant property once nullable - // and primitive types are removed by other type guards. - var filteredType = getTypeWithFacts(type, 4194304 /* Discriminatable */); - if (filteredType !== type && filteredType.flags & 524288 /* Union */) { - prop = getPropertyOfType(filteredType, name); - } - } - if (prop && prop.flags & 268435456 /* SyntheticProperty */) { - if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !prop.hasCommonType && - isUnitUnionType(getTypeOfSymbol(prop)); - } - return prop.isDiscriminantProperty; - } - } - return false; - } function isOrContainsMatchingReference(source, target) { return isMatchingReference(source, target) || containsMatchingReference(source, target); } @@ -24429,7 +23056,7 @@ var ts; return flow.id; } function typeMaybeAssignableTo(source, target) { - if (!(source.flags & 524288 /* Union */)) { + if (!(source.flags & 16384 /* Union */)) { return isTypeAssignableTo(source, target); } for (var _i = 0, _a = source.types; _i < _a.length; _i++) { @@ -24444,81 +23071,70 @@ var ts; // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, // we remove type string. function getAssignmentReducedType(declaredType, assignedType) { - if (declaredType !== assignedType) { - var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); - if (reducedType !== neverType) { - return reducedType; + if (declaredType !== assignedType && declaredType.flags & 16384 /* Union */) { + var reducedTypes = ts.filter(declaredType.types, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (reducedTypes.length) { + return reducedTypes.length === 1 ? reducedTypes[0] : getUnionType(reducedTypes); } } return declaredType; } - function getTypeFactsOfTypes(types) { - var result = 0 /* None */; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; - result |= getTypeFacts(t); - } - return result; - } - function isFunctionObjectType(type) { - // We do a quick check for a "bind" property before performing the more expensive subtype - // check. This gives us a quicker out in the common case where an object type is not a function. - var resolved = resolveStructuredTypeMembers(type); - return !!(resolved.callSignatures.length || resolved.constructSignatures.length || - resolved.members["bind"] && isTypeSubtypeOf(type, globalFunctionType)); - } function getTypeFacts(type) { var flags = type.flags; - if (flags & 2 /* String */) { + if (flags & 258 /* StringLike */) { return strictNullChecks ? 4079361 /* StringStrictFacts */ : 4194049 /* StringFacts */; } - if (flags & 32 /* StringLiteral */) { - return strictNullChecks ? - type === emptyStringType ? 3030785 /* EmptyStringStrictFacts */ : 1982209 /* NonEmptyStringStrictFacts */ : - type === emptyStringType ? 3145473 /* EmptyStringFacts */ : 4194049 /* NonEmptyStringFacts */; - } - if (flags & (4 /* Number */ | 16 /* Enum */)) { + if (flags & 132 /* NumberLike */) { return strictNullChecks ? 4079234 /* NumberStrictFacts */ : 4193922 /* NumberFacts */; } - if (flags & (64 /* NumberLiteral */ | 256 /* EnumLiteral */)) { - var isZero = type === zeroType || type.flags & 256 /* EnumLiteral */ && type.text === "0"; - return strictNullChecks ? - isZero ? 3030658 /* ZeroStrictFacts */ : 1982082 /* NonZeroStrictFacts */ : - isZero ? 3145346 /* ZeroFacts */ : 4193922 /* NonZeroFacts */; - } if (flags & 8 /* Boolean */) { return strictNullChecks ? 4078980 /* BooleanStrictFacts */ : 4193668 /* BooleanFacts */; } - if (flags & 136 /* BooleanLike */) { - return strictNullChecks ? - type === falseType ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : - type === falseType ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; + if (flags & 80896 /* ObjectType */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length || resolved.constructSignatures.length || isTypeSubtypeOf(type, globalFunctionType) ? + strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : + strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; } - if (flags & 2588672 /* ObjectType */) { - return isFunctionObjectType(type) ? - strictNullChecks ? 6164448 /* FunctionStrictFacts */ : 8376288 /* FunctionFacts */ : - strictNullChecks ? 6166480 /* ObjectStrictFacts */ : 8378320 /* ObjectFacts */; - } - if (flags & (1024 /* Void */ | 2048 /* Undefined */)) { + if (flags & (16 /* Void */ | 32 /* Undefined */)) { return 2457472 /* UndefinedFacts */; } - if (flags & 4096 /* Null */) { + if (flags & 64 /* Null */) { return 2340752 /* NullFacts */; } - if (flags & 512 /* ESSymbol */) { + if (flags & 16777216 /* ESSymbol */) { return strictNullChecks ? 1981320 /* SymbolStrictFacts */ : 4193160 /* SymbolFacts */; } - if (flags & 16384 /* TypeParameter */) { + if (flags & 512 /* TypeParameter */) { var constraint = getConstraintOfTypeParameter(type); - return getTypeFacts(constraint || emptyObjectType); + return constraint ? getTypeFacts(constraint) : 4194303 /* All */; } - if (flags & 1572864 /* UnionOrIntersection */) { - return getTypeFactsOfTypes(type.types); + if (flags & 32768 /* Intersection */) { + return ts.reduceLeft(type.types, function (flags, type) { return flags |= getTypeFacts(type); }, 0 /* None */); } - return 8388607 /* All */; + return 4194303 /* All */; } function getTypeWithFacts(type, include) { - return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); + if (!(type.flags & 16384 /* Union */)) { + return getTypeFacts(type) & include ? type : neverType; + } + var firstType; + var types; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (getTypeFacts(t) & include) { + if (!firstType) { + firstType = t; + } + else { + if (!types) { + types = [firstType]; + } + types.push(t); + } + } + } + return firstType ? types ? getUnionType(types, /*noSubtypeReduction*/ true) : firstType : neverType; } function getTypeWithDefault(type, defaultExpression) { if (defaultExpression) { @@ -24615,31 +23231,26 @@ var ts; getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } - function getInitialOrAssignedType(node) { - return node.kind === 218 /* VariableDeclaration */ || node.kind === 169 /* BindingElement */ ? - getInitialType(node) : - getAssignedType(node); - } - function getReferenceCandidate(node) { + function getReferenceFromExpression(node) { switch (node.kind) { case 178 /* ParenthesizedExpression */: - return getReferenceCandidate(node.expression); + return getReferenceFromExpression(node.expression); case 187 /* BinaryExpression */: switch (node.operatorToken.kind) { case 56 /* EqualsToken */: - return getReferenceCandidate(node.left); + return getReferenceFromExpression(node.left); case 24 /* CommaToken */: - return getReferenceCandidate(node.right); + return getReferenceFromExpression(node.right); } } return node; } function getTypeOfSwitchClause(clause) { if (clause.kind === 249 /* CaseClause */) { - var caseType = checkExpression(clause.expression); - return isUnitType(caseType) ? caseType : undefined; + var expr = clause.expression; + return expr.kind === 9 /* StringLiteral */ ? getStringLiteralTypeForText(expr.text) : checkExpression(expr); } - return neverType; + return undefined; } function getSwitchClauseTypes(switchStatement) { var links = getNodeLinks(switchStatement); @@ -24647,56 +23258,26 @@ var ts; // If all case clauses specify expressions that have unit types, we return an array // of those unit types. Otherwise we return an empty array. var types = ts.map(switchStatement.caseBlock.clauses, getTypeOfSwitchClause); - links.switchTypes = !ts.contains(types, undefined) ? types : emptyArray; + links.switchTypes = ts.forEach(types, function (t) { return !t || t.flags & 256 /* StringLiteral */; }) ? types : emptyArray; } return links.switchTypes; } function eachTypeContainedIn(source, types) { - return source.flags & 524288 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); - } - function isTypeSubsetOf(source, target) { - return source === target || target.flags & 524288 /* Union */ && isTypeSubsetOfUnion(source, target); - } - function isTypeSubsetOfUnion(source, target) { - if (source.flags & 524288 /* Union */) { - for (var _i = 0, _a = source.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (!containsType(target.types, t)) { - return false; - } - } - return true; - } - if (source.flags & 256 /* EnumLiteral */ && target.flags & 16 /* Enum */ && source.baseType === target) { - return true; - } - return containsType(target.types, source); + return source.flags & 16384 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } function filterType(type, f) { - if (type.flags & 524288 /* Union */) { - var types = type.types; - var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered); - } - return f(type) ? type : neverType; + return type.flags & 16384 /* Union */ ? + getUnionType(ts.filter(type.types, f)) : + f(type) ? type : neverType; } - function isIncomplete(flowType) { - return flowType.flags === 0; - } - function getTypeFromFlowType(flowType) { - return flowType.flags === 0 ? flowType.type : flowType; - } - function createFlowType(type, incomplete) { - return incomplete ? { flags: 0, type: type } : type; - } - function getFlowTypeOfReference(reference, declaredType, assumeInitialized, flowContainer) { + function getFlowTypeOfReference(reference, declaredType, assumeInitialized, includeOuterFunctions) { var key; - if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 4178943 /* Narrowable */)) { + if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 16908175 /* Narrowable */)) { return declaredType; } - var initialType = assumeInitialized ? declaredType : includeFalsyTypes(declaredType, 2048 /* Undefined */); + var initialType = assumeInitialized ? declaredType : addTypeKind(declaredType, 32 /* Undefined */); var visitedFlowStart = visitedFlowCount; - var result = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); + var result = getTypeAtFlowNode(reference.flowNode); visitedFlowCount = visitedFlowStart; if (reference.parent.kind === 196 /* NonNullExpression */ && getTypeWithFacts(result, 524288 /* NEUndefinedOrNull */) === neverType) { return declaredType; @@ -24740,7 +23321,7 @@ var ts; else if (flow.flags & 2 /* Start */) { // Check if we should continue with the control flow of the containing function. var container = flow.container; - if (container && container !== flowContainer && reference.kind !== 172 /* PropertyAccessExpression */) { + if (container && includeOuterFunctions) { flow = container.flowNode; continue; } @@ -24765,9 +23346,19 @@ var ts; var node = flow.node; // Assignments only narrow the computed type if the declared type is a union type. Thus, we // only need to evaluate the assigned type if the declared type is a union type. + if ((node.kind === 218 /* VariableDeclaration */ || node.kind === 169 /* BindingElement */) && + reference.kind === 69 /* Identifier */ && + getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(reference)) === getSymbolOfNode(node)) { + return declaredType.flags & 16384 /* Union */ ? + getAssignmentReducedType(declaredType, getInitialType(node)) : + declaredType; + } + // If the node is not a variable declaration or binding element, it is an identifier + // or a dotted name that is the target of an assignment. If we have a match, reduce + // the declared type by the assigned type. if (isMatchingReference(reference, node)) { - return declaredType.flags & 524288 /* Union */ ? - getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : + return declaredType.flags & 16384 /* Union */ ? + getAssignmentReducedType(declaredType, getAssignedType(node)) : declaredType; } // We didn't have a direct match. However, if the reference is a dotted name, this @@ -24781,43 +23372,32 @@ var ts; return undefined; } function getTypeAtFlowCondition(flow) { - var flowType = getTypeAtFlowNode(flow.antecedent); - var type = getTypeFromFlowType(flowType); + var type = getTypeAtFlowNode(flow.antecedent); if (type !== neverType) { // If we have an antecedent type (meaning we're reachable in some way), we first - // attempt to narrow the antecedent type. If that produces the never type, and if - // the antecedent type is incomplete (i.e. a transient type in a loop), then we - // take the type guard as an indication that control *could* reach here once we - // have the complete type. We proceed by reverting to the declared type and then + // attempt to narrow the antecedent type. If that produces the nothing type, then + // we take the type guard as an indication that control could reach here in a + // manner not understood by the control flow analyzer (e.g. a function argument + // has an invalid type, or a nested function has possibly made an assignment to a + // captured variable). We proceed by reverting to the declared type and then // narrow that. var assumeTrue = (flow.flags & 32 /* TrueCondition */) !== 0; type = narrowType(type, flow.expression, assumeTrue); - if (type === neverType && isIncomplete(flowType)) { + if (type === neverType) { type = narrowType(declaredType, flow.expression, assumeTrue); } } - return createFlowType(type, isIncomplete(flowType)); + return type; } function getTypeAtSwitchClause(flow) { - var flowType = getTypeAtFlowNode(flow.antecedent); - var type = getTypeFromFlowType(flowType); - var expr = flow.switchStatement.expression; - if (isMatchingReference(reference, expr)) { - type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); - } - else if (isMatchingReferenceDiscriminant(expr)) { - type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); - } - return createFlowType(type, isIncomplete(flowType)); + var type = getTypeAtFlowNode(flow.antecedent); + return narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } function getTypeAtFlowBranchLabel(flow) { var antecedentTypes = []; - var subtypeReduction = false; - var seenIncomplete = false; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { var antecedent = _a[_i]; - var flowType = getTypeAtFlowNode(antecedent); - var type = getTypeFromFlowType(flowType); + var type = getTypeAtFlowNode(antecedent); // If the type at a particular antecedent path is the declared type and the // reference is known to always be assigned (i.e. when declared and initial types // are the same), there is no reason to process more antecedents since the only @@ -24828,23 +23408,14 @@ var ts; if (!ts.contains(antecedentTypes, type)) { antecedentTypes.push(type); } - // If an antecedent type is not a subset of the declared type, we need to perform - // subtype reduction. This happens when a "foreign" type is injected into the control - // flow using the instanceof operator or a user defined type predicate. - if (!isTypeSubsetOf(type, declaredType)) { - subtypeReduction = true; - } - if (isIncomplete(flowType)) { - seenIncomplete = true; - } } - return createFlowType(getUnionType(antecedentTypes, subtypeReduction), seenIncomplete); + return getUnionType(antecedentTypes); } function getTypeAtFlowLoopLabel(flow) { // If we have previously computed the control flow type for the reference at // this flow loop junction, return the cached type. var id = getFlowNodeId(flow); - var cache = flowLoopCaches[id] || (flowLoopCaches[id] = ts.createMap()); + var cache = flowLoopCaches[id] || (flowLoopCaches[id] = {}); if (!key) { key = getFlowCacheKey(reference); } @@ -24852,31 +23423,25 @@ var ts; return cache[key]; } // If this flow loop junction and reference are already being processed, return - // the union of the types computed for each branch so far, marked as incomplete. - // We should never see an empty array here because the first antecedent of a loop - // junction is always the non-looping control flow path that leads to the top. + // the union of the types computed for each branch so far. We should never see + // an empty array here because the first antecedent of a loop junction is always + // the non-looping control flow path that leads to the top. for (var i = flowLoopStart; i < flowLoopCount; i++) { if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key) { - return createFlowType(getUnionType(flowLoopTypes[i]), /*incomplete*/ true); + return getUnionType(flowLoopTypes[i]); } } // Add the flow loop junction and reference to the in-process stack and analyze // each antecedent code path. var antecedentTypes = []; - var subtypeReduction = false; - var firstAntecedentType; flowLoopNodes[flowLoopCount] = flow; flowLoopKeys[flowLoopCount] = key; flowLoopTypes[flowLoopCount] = antecedentTypes; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { var antecedent = _a[_i]; flowLoopCount++; - var flowType = getTypeAtFlowNode(antecedent); + var type = getTypeAtFlowNode(antecedent); flowLoopCount--; - if (!firstAntecedentType) { - firstAntecedentType = flowType; - } - var type = getTypeFromFlowType(flowType); // If we see a value appear in the cache it is a sign that control flow analysis // was restarted and completed by checkExpressionCached. We can simply pick up // the resulting type and bail out. @@ -24886,12 +23451,6 @@ var ts; if (!ts.contains(antecedentTypes, type)) { antecedentTypes.push(type); } - // If an antecedent type is not a subset of the declared type, we need to perform - // subtype reduction. This happens when a "foreign" type is injected into the control - // flow using the instanceof operator or a user defined type predicate. - if (!isTypeSubsetOf(type, declaredType)) { - subtypeReduction = true; - } // If the type at a particular antecedent path is the declared type there is no // reason to process more antecedents since the only possible outcome is subtypes // that will be removed in the final union type anyway. @@ -24899,37 +23458,10 @@ var ts; break; } } - // The result is incomplete if the first antecedent (the non-looping control flow path) - // is incomplete. - var result = getUnionType(antecedentTypes, subtypeReduction); - if (isIncomplete(firstAntecedentType)) { - return createFlowType(result, /*incomplete*/ true); - } - return cache[key] = result; - } - function isMatchingReferenceDiscriminant(expr) { - return expr.kind === 172 /* PropertyAccessExpression */ && - declaredType.flags & 524288 /* Union */ && - isMatchingReference(reference, expr.expression) && - isDiscriminantProperty(declaredType, expr.name.text); - } - function narrowTypeByDiscriminant(type, propAccess, narrowType) { - var propName = propAccess.name.text; - var propType = getTypeOfPropertyOfType(type, propName); - var narrowedPropType = propType && narrowType(propType); - return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); + return cache[key] = getUnionType(antecedentTypes); } function narrowTypeByTruthiness(type, expr, assumeTrue) { - if (isMatchingReference(reference, expr)) { - return getTypeWithFacts(type, assumeTrue ? 1048576 /* Truthy */ : 2097152 /* Falsy */); - } - if (isMatchingReferenceDiscriminant(expr)) { - return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 1048576 /* Truthy */ : 2097152 /* Falsy */); }); - } - if (containsMatchingReferenceDiscriminant(reference, expr)) { - return declaredType; - } - return type; + return isMatchingReference(reference, expr) ? getTypeWithFacts(type, assumeTrue ? 1048576 /* Truthy */ : 2097152 /* Falsy */) : type; } function narrowTypeByBinaryExpression(type, expr, assumeTrue) { switch (expr.operatorToken.kind) { @@ -24939,29 +23471,26 @@ var ts; case 31 /* ExclamationEqualsToken */: case 32 /* EqualsEqualsEqualsToken */: case 33 /* ExclamationEqualsEqualsToken */: - var operator_1 = expr.operatorToken.kind; - var left_1 = getReferenceCandidate(expr.left); - var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 182 /* TypeOfExpression */ && right_1.kind === 9 /* StringLiteral */) { - return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); + var left = expr.left; + var operator = expr.operatorToken.kind; + var right = expr.right; + if (isNullOrUndefinedLiteral(right)) { + return narrowTypeByNullCheck(type, left, operator, right, assumeTrue); } - if (right_1.kind === 182 /* TypeOfExpression */ && left_1.kind === 9 /* StringLiteral */) { - return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); + if (isNullOrUndefinedLiteral(left)) { + return narrowTypeByNullCheck(type, right, operator, left, assumeTrue); } - if (isMatchingReference(reference, left_1)) { - return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); + if (left.kind === 182 /* TypeOfExpression */ && right.kind === 9 /* StringLiteral */) { + return narrowTypeByTypeof(type, left, operator, right, assumeTrue); } - if (isMatchingReference(reference, right_1)) { - return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); + if (right.kind === 182 /* TypeOfExpression */ && left.kind === 9 /* StringLiteral */) { + return narrowTypeByTypeof(type, right, operator, left, assumeTrue); } - if (isMatchingReferenceDiscriminant(left_1)) { - return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); + if (left.kind === 172 /* PropertyAccessExpression */) { + return narrowTypeByDiscriminant(type, left, operator, right, assumeTrue); } - if (isMatchingReferenceDiscriminant(right_1)) { - return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); - } - if (containsMatchingReferenceDiscriminant(reference, left_1) || containsMatchingReferenceDiscriminant(reference, right_1)) { - return declaredType; + if (right.kind === 172 /* PropertyAccessExpression */) { + return narrowTypeByDiscriminant(type, right, operator, left, assumeTrue); } break; case 91 /* InstanceOfKeyword */: @@ -24971,38 +23500,25 @@ var ts; } return type; } - function narrowTypeByEquality(type, operator, value, assumeTrue) { - if (type.flags & 1 /* Any */) { - return type; - } + function narrowTypeByNullCheck(type, target, operator, literal, assumeTrue) { + // We have '==', '!=', '===', or '!==' operator with 'null' or 'undefined' as value if (operator === 31 /* ExclamationEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } - var valueType = checkExpression(value); - if (valueType.flags & 6144 /* Nullable */) { - if (!strictNullChecks) { - return type; - } - var doubleEquals = operator === 30 /* EqualsEqualsToken */ || operator === 31 /* ExclamationEqualsToken */; - var facts = doubleEquals ? - assumeTrue ? 65536 /* EQUndefinedOrNull */ : 524288 /* NEUndefinedOrNull */ : - value.kind === 93 /* NullKeyword */ ? - assumeTrue ? 32768 /* EQNull */ : 262144 /* NENull */ : - assumeTrue ? 16384 /* EQUndefined */ : 131072 /* NEUndefined */; - return getTypeWithFacts(type, facts); - } - if (type.flags & 2589191 /* NotUnionOrUnit */) { + if (!strictNullChecks || !isMatchingReference(reference, getReferenceFromExpression(target))) { return type; } - if (assumeTrue) { - var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType !== neverType ? narrowedType : type; - } - return isUnitType(valueType) ? filterType(type, function (t) { return t !== valueType; }) : type; + var doubleEquals = operator === 30 /* EqualsEqualsToken */ || operator === 31 /* ExclamationEqualsToken */; + var facts = doubleEquals ? + assumeTrue ? 65536 /* EQUndefinedOrNull */ : 524288 /* NEUndefinedOrNull */ : + literal.kind === 93 /* NullKeyword */ ? + assumeTrue ? 32768 /* EQNull */ : 262144 /* NENull */ : + assumeTrue ? 16384 /* EQUndefined */ : 131072 /* NEUndefined */; + return getTypeWithFacts(type, facts); } function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { // We have '==', '!=', '====', or !==' operator with 'typeof xxx' and string literal operands - var target = getReferenceCandidate(typeOfExpr.expression); + var target = getReferenceFromExpression(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the // narrowed type of 'y' to its declared type. @@ -25014,38 +23530,72 @@ var ts; if (operator === 31 /* ExclamationEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } - if (assumeTrue && !(type.flags & 524288 /* Union */)) { + if (assumeTrue && !(type.flags & 16384 /* Union */)) { // We narrow a non-union type to an exact primitive type if the non-union type - // is a supertype of that primitive type. For example, type 'any' can be narrowed + // is a supertype of that primtive type. For example, type 'any' can be narrowed // to one of the primitive types. - var targetType = typeofTypesByName[literal.text]; + var targetType = ts.getProperty(typeofTypesByName, literal.text); if (targetType && isTypeSubtypeOf(targetType, type)) { return targetType; } } var facts = assumeTrue ? - typeofEQFacts[literal.text] || 64 /* TypeofEQHostObject */ : - typeofNEFacts[literal.text] || 8192 /* TypeofNEHostObject */; + ts.getProperty(typeofEQFacts, literal.text) || 64 /* TypeofEQHostObject */ : + ts.getProperty(typeofNEFacts, literal.text) || 8192 /* TypeofNEHostObject */; return getTypeWithFacts(type, facts); } + function narrowTypeByDiscriminant(type, propAccess, operator, value, assumeTrue) { + // We have '==', '!=', '===', or '!==' operator with property access as target + if (!isMatchingReference(reference, propAccess.expression)) { + return type; + } + var propName = propAccess.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return type; + } + var discriminantType = value.kind === 9 /* StringLiteral */ ? getStringLiteralTypeForText(value.text) : checkExpression(value); + if (!isStringLiteralUnionType(discriminantType)) { + return type; + } + if (operator === 31 /* ExclamationEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */) { + assumeTrue = !assumeTrue; + } + if (assumeTrue) { + return filterType(type, function (t) { return areTypesComparable(getTypeOfPropertyOfType(t, propName), discriminantType); }); + } + if (discriminantType.flags & 256 /* StringLiteral */) { + return filterType(type, function (t) { return getTypeOfPropertyOfType(t, propName) !== discriminantType; }); + } + return type; + } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { - // We only narrow if all case expressions specify values with unit types + // We have switch statement with property access expression + if (!isMatchingReference(reference, switchStatement.expression.expression)) { + return type; + } + var propName = switchStatement.expression.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return type; + } var switchTypes = getSwitchClauseTypes(switchStatement); if (!switchTypes.length) { return type; } var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); - var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); - var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType === neverType ? neverType : filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }); + var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, undefined); + var caseTypes = hasDefaultClause ? ts.filter(clauseTypes, function (t) { return !!t; }) : clauseTypes; + var discriminantType = caseTypes.length ? getUnionType(caseTypes) : undefined; + var caseType = discriminantType && filterType(type, function (t) { return isTypeComparableTo(discriminantType, getTypeOfPropertyOfType(t, propName)); }); if (!hasDefaultClause) { return caseType; } - var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, t)); }); - return caseType === neverType ? defaultType : getUnionType([caseType, defaultType]); + var defaultType = filterType(type, function (t) { return !eachTypeContainedIn(getTypeOfPropertyOfType(t, propName), switchTypes); }); + return caseType ? getUnionType([caseType, defaultType]) : defaultType; } function narrowTypeByInstanceof(type, expr, assumeTrue) { - var left = getReferenceCandidate(expr.left); + var left = getReferenceFromExpression(expr.left); if (!isMatchingReference(reference, left)) { // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the // narrowed type of 'y' to its declared type. @@ -25054,6 +23604,10 @@ var ts; } return type; } + // We never narrow type any in an instanceof guard + if (isTypeAny(type)) { + return type; + } // Check that right operand is a function type with a prototype property var rightType = checkExpression(expr.right); if (!isTypeSubtypeOf(rightType, globalFunctionType)) { @@ -25068,17 +23622,13 @@ var ts; targetType = prototypePropertyType; } } - // Don't narrow from 'any' if the target type is exactly 'Object' or 'Function' - if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) { - return type; - } if (!targetType) { // Target type is type of construct signature var constructSignatures = void 0; - if (rightType.flags & 65536 /* Interface */) { + if (rightType.flags & 2048 /* Interface */) { constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; } - else if (rightType.flags & 2097152 /* Anonymous */) { + else if (rightType.flags & 65536 /* Anonymous */) { constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); } if (constructSignatures && constructSignatures.length) { @@ -25092,29 +23642,28 @@ var ts; } function getNarrowedType(type, candidate, assumeTrue) { if (!assumeTrue) { - return filterType(type, function (t) { return !isTypeInstanceOf(t, candidate); }); + return type.flags & 16384 /* Union */ ? + getUnionType(ts.filter(type.types, function (t) { return !isTypeSubtypeOf(t, candidate); })) : + type; } - // If the current type is a union type, remove all constituents that couldn't be instances of + // If the current type is a union type, remove all constituents that aren't assignable to // the candidate type. If one or more constituents remain, return a union of those. - if (type.flags & 524288 /* Union */) { - var assignableType = filterType(type, function (t) { return isTypeInstanceOf(t, candidate); }); - if (assignableType !== neverType) { - return assignableType; + if (type.flags & 16384 /* Union */) { + var assignableConstituents = ts.filter(type.types, function (t) { return isTypeAssignableTo(t, candidate); }); + if (assignableConstituents.length) { + return getUnionType(assignableConstituents); } } - // If the candidate type is a subtype of the target type, narrow to the candidate type. - // Otherwise, if the target type is assignable to the candidate type, keep the target type. - // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate - // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the - // two types. - var targetType = type.flags & 16384 /* TypeParameter */ ? getApparentType(type) : type; - return isTypeSubtypeOf(candidate, type) ? candidate : + // If the candidate type is assignable to the target type, narrow to the candidate type. + // Otherwise, if the current type is assignable to the candidate, keep the current type. + // Otherwise, the types are completely unrelated, so narrow to the empty type. + var targetType = type.flags & 512 /* TypeParameter */ ? getApparentType(type) : type; + return isTypeAssignableTo(candidate, targetType) ? candidate : isTypeAssignableTo(type, candidate) ? type : - isTypeAssignableTo(candidate, targetType) ? candidate : - getIntersectionType([type, candidate]); + getIntersectionType([type, candidate]); } function narrowTypeByTypePredicate(type, callExpression, assumeTrue) { - if (!hasMatchingArgument(callExpression, reference)) { + if (type.flags & 1 /* Any */ || !hasMatchingArgument(callExpression, reference)) { return type; } var signature = getResolvedSignature(callExpression); @@ -25122,10 +23671,6 @@ var ts; if (!predicate) { return type; } - // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function' - if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { - return type; - } if (ts.isIdentifierTypePredicate(predicate)) { var predicateArgument = callExpression.arguments[predicate.parameterIndex]; if (predicateArgument) { @@ -25207,49 +23752,20 @@ var ts; function getControlFlowContainer(node) { while (true) { node = node.parent; - if (ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || - node.kind === 226 /* ModuleBlock */ || - node.kind === 256 /* SourceFile */ || - node.kind === 145 /* PropertyDeclaration */) { + if (ts.isFunctionLike(node) || node.kind === 226 /* ModuleBlock */ || node.kind === 256 /* SourceFile */ || node.kind === 145 /* PropertyDeclaration */) { return node; } } } - // Check if a parameter is assigned anywhere within its declaring function. - function isParameterAssigned(symbol) { - var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; - var links = getNodeLinks(func); - if (!(links.flags & 4194304 /* AssignmentsMarked */)) { - links.flags |= 4194304 /* AssignmentsMarked */; - if (!hasParentWithAssignmentsMarked(func)) { - markParameterAssignments(func); - } - } - return symbol.isAssigned || false; - } - function hasParentWithAssignmentsMarked(node) { - while (true) { - node = node.parent; - if (!node) { - return false; - } - if (ts.isFunctionLike(node) && getNodeLinks(node).flags & 4194304 /* AssignmentsMarked */) { - return true; - } - } - } - function markParameterAssignments(node) { - if (node.kind === 69 /* Identifier */) { - if (ts.isAssignmentTarget(node)) { - var symbol = getResolvedSymbol(node); - if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 142 /* Parameter */) { - symbol.isAssigned = true; - } - } - } - else { - ts.forEachChild(node, markParameterAssignments); + function isDeclarationIncludedInFlow(reference, declaration, includeOuterFunctions) { + var declarationContainer = getControlFlowContainer(declaration); + var container = getControlFlowContainer(reference); + while (container !== declarationContainer && + (container.kind === 179 /* FunctionExpression */ || container.kind === 180 /* ArrowFunction */) && + (includeOuterFunctions || ts.getImmediatelyInvokedFunctionExpression(container))) { + container = getControlFlowContainer(container); } + return container === declarationContainer; } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); @@ -25295,37 +23811,16 @@ var ts; checkCollisionWithCapturedThisVariable(node, node); checkNestedBlockScopedBinding(node, symbol); var type = getTypeOfSymbol(localOrExportSymbol); - var declaration = localOrExportSymbol.valueDeclaration; - // We only narrow variables and parameters occurring in a non-assignment position. For all other - // entities we simply return the declared type. - if (!(localOrExportSymbol.flags & 3 /* Variable */) || ts.isAssignmentTarget(node) || !declaration) { + if (!(localOrExportSymbol.flags & 3 /* Variable */) || ts.isAssignmentTarget(node)) { return type; } - // The declaration container is the innermost function that encloses the declaration of the variable - // or parameter. The flow container is the innermost function starting with which we analyze the control - // flow graph to determine the control flow based type. - var isParameter = ts.getRootDeclaration(declaration).kind === 142 /* Parameter */; - var declarationContainer = getControlFlowContainer(declaration); - var flowContainer = getControlFlowContainer(node); - var isOuterVariable = flowContainer !== declarationContainer; - // When the control flow originates in a function expression or arrow function and we are referencing - // a const variable or parameter from an outer function, we extend the origin of the control flow - // analysis to include the immediately enclosing function. - while (flowContainer !== declarationContainer && - (flowContainer.kind === 179 /* FunctionExpression */ || flowContainer.kind === 180 /* ArrowFunction */) && - (isReadonlySymbol(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { - flowContainer = getControlFlowContainer(flowContainer); - } - // We only look for uninitialized variables in strict null checking mode, and only when we can analyze - // the entire control flow graph from the variable's declaration (i.e. when the flow container and - // declaration container are the same). - var assumeInitialized = !strictNullChecks || (type.flags & 1 /* Any */) !== 0 || isParameter || - isOuterVariable || ts.isInAmbientContext(declaration); - var flowType = getFlowTypeOfReference(node, type, assumeInitialized, flowContainer); - // A variable is considered uninitialized when it is possible to analyze the entire control flow graph - // from declaration to use, and when the variable's declared type doesn't include undefined but the - // control flow based type does include undefined. - if (!assumeInitialized && !(getFalsyFlags(type) & 2048 /* Undefined */) && getFalsyFlags(flowType) & 2048 /* Undefined */) { + var declaration = localOrExportSymbol.valueDeclaration; + var includeOuterFunctions = isReadonlySymbol(localOrExportSymbol); + var assumeInitialized = !strictNullChecks || (type.flags & 1 /* Any */) !== 0 || !declaration || + ts.getRootDeclaration(declaration).kind === 142 /* Parameter */ || ts.isInAmbientContext(declaration) || + !isDeclarationIncludedInFlow(node, declaration, includeOuterFunctions); + var flowType = getFlowTypeOfReference(node, type, assumeInitialized, includeOuterFunctions); + if (!assumeInitialized && !(getCombinedTypeFlags(type) & 32 /* Undefined */) && getCombinedTypeFlags(flowType) & 32 /* Undefined */) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); // Return the declared type to reduce follow-on errors return type; @@ -25533,6 +24028,10 @@ var ts; return getInferredClassType(classSymbol); } } + var type = getContextuallyTypedThisType(container); + if (type) { + return type; + } var thisType = getThisTypeOfDeclaration(container); if (thisType) { return thisType; @@ -25541,7 +24040,7 @@ var ts; if (ts.isClassLike(container.parent)) { var symbol = getSymbolOfNode(container.parent); var type = container.flags & 32 /* Static */ ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; - return getFlowTypeOfReference(node, type, /*assumeInitialized*/ true, /*flowContainer*/ undefined); + return getFlowTypeOfReference(node, type, /*assumeInitialized*/ true, /*includeOuterFunctions*/ true); } if (ts.isInJavaScriptFile(node)) { var type = getTypeForThisExpressionFromJSDoc(container); @@ -25750,11 +24249,11 @@ var ts; return false; } } - function getContextualThisParameter(func) { + function getContextuallyTypedThisType(func) { if (isContextSensitiveFunctionOrObjectLiteralMethod(func) && func.kind !== 180 /* ArrowFunction */) { var contextualSignature = getContextualSignature(func); if (contextualSignature) { - return contextualSignature.thisParameter; + return getThisTypeOfSignature(contextualSignature); } } return undefined; @@ -25821,7 +24320,7 @@ var ts; } } if (ts.isBindingPattern(declaration.name)) { - return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false); + return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true); } if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; @@ -25909,10 +24408,6 @@ var ts; var binaryExpression = node.parent; var operator = binaryExpression.operatorToken.kind; if (operator >= 56 /* FirstAssignment */ && operator <= 68 /* LastAssignment */) { - // Don't do this for special property assignments to avoid circularity - if (ts.getSpecialPropertyAssignmentKind(binaryExpression) !== 0 /* None */) { - return undefined; - } // In an assignment expression, the right operand is contextually typed by the type of the left operand. if (node === binaryExpression.right) { return checkExpression(binaryExpression.left); @@ -25938,14 +24433,14 @@ var ts; // is a union type, the mapping function is applied to each constituent type and a union of the resulting // types is returned. function applyToContextualType(type, mapper) { - if (!(type.flags & 524288 /* Union */)) { + if (!(type.flags & 16384 /* Union */)) { return mapper(type); } var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var current = types_11[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var current = types_8[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -25963,7 +24458,7 @@ var ts; } function getTypeOfPropertyOfContextualType(type, name) { return applyToContextualType(type, function (t) { - var prop = t.flags & 4161536 /* StructuredType */ ? getPropertyOfType(t, name) : undefined; + var prop = t.flags & 130048 /* StructuredType */ ? getPropertyOfType(t, name) : undefined; return prop ? getTypeOfSymbol(prop) : undefined; }); } @@ -25972,7 +24467,7 @@ var ts; } // Return true if the given contextual type is a tuple-like type function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 524288 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); + return !!(type.flags & 16384 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); } // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one @@ -26110,30 +24605,6 @@ var ts; } return undefined; } - function isLiteralTypeLocation(node) { - var parent = node.parent; - switch (parent.kind) { - case 187 /* BinaryExpression */: - switch (parent.operatorToken.kind) { - case 32 /* EqualsEqualsEqualsToken */: - case 33 /* ExclamationEqualsEqualsToken */: - case 30 /* EqualsEqualsToken */: - case 31 /* ExclamationEqualsToken */: - return true; - } - break; - case 188 /* ConditionalExpression */: - return (node === parent.whenTrue || - node === parent.whenFalse) && - isLiteralTypeLocation(parent); - case 178 /* ParenthesizedExpression */: - return isLiteralTypeLocation(parent); - case 249 /* CaseClause */: - case 166 /* LiteralType */: - return true; - } - return false; - } // If the given type is an object or union type, if that type has a single signature, and if // that signature is non-generic, return the signature. Otherwise return undefined. function getNonGenericSignature(type) { @@ -26170,13 +24641,13 @@ var ts; if (!type) { return undefined; } - if (!(type.flags & 524288 /* Union */)) { + if (!(type.flags & 16384 /* Union */)) { return getNonGenericSignature(type); } var signatureList; var types = type.types; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var current = types_12[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var current = types_9[_i]; var signature = getNonGenericSignature(current); if (signature) { if (!signatureList) { @@ -26272,7 +24743,7 @@ var ts; // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". if (inDestructuringPattern && elementTypes.length) { - var type = cloneTypeReference(createTupleType(elementTypes)); + var type = createNewTupleType(elementTypes); type.pattern = node; return type; } @@ -26286,7 +24757,7 @@ var ts; for (var i = elementTypes.length; i < patternElements.length; i++) { var patternElement = patternElements[i]; if (hasDefaultValue(patternElement)) { - elementTypes.push(contextualType.typeArguments[i]); + elementTypes.push(contextualType.elementTypes[i]); } else { if (patternElement.kind !== 193 /* OmittedExpression */) { @@ -26301,9 +24772,7 @@ var ts; } } } - return createArrayType(elementTypes.length ? - getUnionType(elementTypes, /*subtypeReduction*/ true) : - strictNullChecks ? neverType : undefinedWideningType); + return createArrayType(elementTypes.length ? getUnionType(elementTypes) : strictNullChecks ? neverType : undefinedWideningType); } function isNumericName(name) { return name.kind === 140 /* ComputedPropertyName */ ? isNumericComputedName(name) : isNumericLiteralName(name.text); @@ -26311,7 +24780,7 @@ var ts; function isNumericComputedName(name) { // It seems odd to consider an expression of type Any to result in a numeric name, // but this behavior is consistent with checkIndexedAccess - return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 340 /* NumberLike */); + return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 132 /* NumberLike */); } function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { return isTypeAny(type) || isTypeOfKind(type, kind); @@ -26346,7 +24815,7 @@ var ts; links.resolvedType = checkExpression(node.expression); // This will allow types number, string, symbol or any. It will also allow enums, the unknown // type, and any union of these types (like string | number). - if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 340 /* NumberLike */ | 34 /* StringLike */ | 512 /* ESSymbol */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 132 /* NumberLike */ | 258 /* StringLike */ | 16777216 /* ESSymbol */)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -26362,14 +24831,14 @@ var ts; propTypes.push(getTypeOfSymbol(properties[i])); } } - var unionType = propTypes.length ? getUnionType(propTypes, /*subtypeReduction*/ true) : undefinedType; + var unionType = propTypes.length ? getUnionType(propTypes) : undefinedType; return createIndexInfo(unionType, /*isReadonly*/ false); } function checkObjectLiteral(node, contextualMapper) { var inDestructuringPattern = ts.isAssignmentTarget(node); // Grammar checking checkGrammarObjectLiteralExpression(node, inDestructuringPattern); - var propertiesTable = ts.createMap(); + var propertiesTable = {}; var propertiesArray = []; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && @@ -26409,7 +24878,7 @@ var ts; patternWithComputedProperties = true; } } - else if (contextualTypeHasPattern && !(contextualType.flags & 536870912 /* ObjectLiteralPatternWithComputedProperties */)) { + else if (contextualTypeHasPattern && !(contextualType.flags & 67108864 /* ObjectLiteralPatternWithComputedProperties */)) { // If object literal is contextually typed by the implied type of a binding pattern, and if the // binding pattern specifies a default value for the property, make the property optional. var impliedProp = getPropertyOfType(contextualType, member.name); @@ -26456,7 +24925,7 @@ var ts; if (contextualTypeHasPattern) { for (var _b = 0, _c = getPropertiesOfType(contextualType); _b < _c.length; _b++) { var prop = _c[_b]; - if (!propertiesTable[prop.name]) { + if (!ts.hasProperty(propertiesTable, prop.name)) { if (!(prop.flags & 536870912 /* Optional */)) { error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } @@ -26468,8 +24937,8 @@ var ts; var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 0 /* String */) : undefined; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 1 /* Number */) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16777216 /* FreshObjectLiteral */; - result.flags |= 8388608 /* ObjectLiteral */ | 67108864 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 234881024 /* PropagatingFlags */) | (patternWithComputedProperties ? 536870912 /* ObjectLiteralPatternWithComputedProperties */ : 0); + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576 /* FreshObjectLiteral */; + result.flags |= 524288 /* ObjectLiteral */ | 4194304 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 14680064 /* PropagatingFlags */) | (patternWithComputedProperties ? 67108864 /* ObjectLiteralPatternWithComputedProperties */ : 0); if (inDestructuringPattern) { result.pattern = node; } @@ -26536,9 +25005,10 @@ var ts; var correspondingPropSymbol = getPropertyOfType(elementAttributesType, node.name.text); correspondingPropType = correspondingPropSymbol && getTypeOfSymbol(correspondingPropSymbol); if (isUnhyphenatedJsxName(node.name.text)) { - var attributeType = getTypeOfPropertyOfType(elementAttributesType, getTextOfPropertyName(node.name)) || getIndexTypeOfType(elementAttributesType, 0 /* String */); - if (attributeType) { - correspondingPropType = attributeType; + // Maybe there's a string indexer? + var indexerType = getIndexTypeOfType(elementAttributesType, 0 /* String */); + if (indexerType) { + correspondingPropType = indexerType; } else { // If there's no corresponding property with this name, error @@ -26629,7 +25099,7 @@ var ts; * For example, in the element , the element instance type is `MyClass` (not `typeof MyClass`). */ function getJsxElementInstanceType(node, valueType) { - ts.Debug.assert(!(valueType.flags & 524288 /* Union */)); + ts.Debug.assert(!(valueType.flags & 16384 /* Union */)); if (isTypeAny(valueType)) { // Short-circuit if the class tag is using an element type 'any' return anyType; @@ -26645,7 +25115,7 @@ var ts; return unknownType; } } - return getUnionType(signatures.map(getReturnTypeOfSignature), /*subtypeReduction*/ true); + return getUnionType(signatures.map(getReturnTypeOfSignature)); } /// e.g. "props" for React.d.ts, /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all @@ -26654,9 +25124,9 @@ var ts; /// non-intrinsic elements' attributes type is the element instance type) function getJsxElementPropertiesName() { // JSX - var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); + var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1536 /* Namespace */, /*diagnosticMessage*/ undefined); // JSX.ElementAttributesProperty [symbol] - var attribsPropTypeSym = jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.ElementAttributesPropertyNameContainer, 793064 /* Type */); + var attribsPropTypeSym = jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.ElementAttributesPropertyNameContainer, 793056 /* Type */); // JSX.ElementAttributesProperty [type] var attribPropType = attribsPropTypeSym && getDeclaredTypeOfSymbol(attribsPropTypeSym); // The properties of JSX.ElementAttributesProperty @@ -26687,17 +25157,17 @@ var ts; if (!elemType) { elemType = checkExpression(node.tagName); } - if (elemType.flags & 524288 /* Union */) { + if (elemType.flags & 16384 /* Union */) { var types = elemType.types; return getUnionType(types.map(function (type) { return getResolvedJsxType(node, type, elemClassType); - }), /*subtypeReduction*/ true); + })); } // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type if (elemType.flags & 2 /* String */) { return anyType; } - else if (elemType.flags & 32 /* StringLiteral */) { + else if (elemType.flags & 256 /* StringLiteral */) { // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { @@ -26761,7 +25231,7 @@ var ts; // Props is of type 'any' or unknown return attributesType; } - else if (attributesType.flags & 524288 /* Union */) { + else if (attributesType.flags & 16384 /* Union */) { // Props cannot be a union type error(node.tagName, ts.Diagnostics.JSX_element_attributes_type_0_may_not_be_a_union_type, typeToString(attributesType)); return anyType; @@ -26859,7 +25329,7 @@ var ts; getSymbolLinks(reactSym).referenced = true; } var targetAttributesType = getJsxElementAttributesType(node); - var nameTable = ts.createMap(); + var nameTable = {}; // Process this array in right-to-left order so we know which // attributes (mostly from spreads) are being overwritten and // thus should have their types ignored @@ -26882,7 +25352,7 @@ var ts; var targetProperties = getPropertiesOfType(targetAttributesType); for (var i = 0; i < targetProperties.length; i++) { if (!(targetProperties[i].flags & 536870912 /* Optional */) && - !nameTable[targetProperties[i].name]) { + nameTable[targetProperties[i].name] === undefined) { error(node, ts.Diagnostics.Property_0_is_missing_in_type_1, targetProperties[i].name, typeToString(targetAttributesType)); } } @@ -26975,12 +25445,12 @@ var ts; return true; } // An instance property must be accessed through an instance of the enclosing class - if (type.flags & 268435456 /* ThisType */) { + if (type.flags & 33554432 /* ThisType */) { // get the original type -- represented as the type constraint of the 'this' type type = getConstraintOfTypeParameter(type); } // TODO: why is the first part of this check here? - if (!(getTargetType(type).flags & (32768 /* Class */ | 65536 /* Interface */) && hasBaseType(type, enclosingClass))) { + if (!(getTargetType(type).flags & (1024 /* Class */ | 2048 /* Interface */) && hasBaseType(type, enclosingClass))) { error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); return false; } @@ -26989,9 +25459,9 @@ var ts; function checkNonNullExpression(node) { var type = checkExpression(node); if (strictNullChecks) { - var kind = getFalsyFlags(type) & 6144 /* Nullable */; + var kind = getCombinedTypeFlags(type) & 96 /* Nullable */; if (kind) { - error(node, kind & 2048 /* Undefined */ ? kind & 4096 /* Null */ ? + error(node, kind & 32 /* Undefined */ ? kind & 64 /* Null */ ? ts.Diagnostics.Object_is_possibly_null_or_undefined : ts.Diagnostics.Object_is_possibly_undefined : ts.Diagnostics.Object_is_possibly_null); @@ -27012,14 +25482,14 @@ var ts; return type; } var apparentType = getApparentType(getWidenedType(type)); - if (apparentType === unknownType || (type.flags & 16384 /* TypeParameter */ && isTypeAny(apparentType))) { + if (apparentType === unknownType || (type.flags & 512 /* TypeParameter */ && isTypeAny(apparentType))) { // handle cases when type is Type parameter with invalid or any constraint return apparentType; } var prop = getPropertyOfType(apparentType, right.text); if (!prop) { if (right.text && !checkAndReportErrorForExtendingInterface(node)) { - error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type.flags & 268435456 /* ThisType */ ? apparentType : type)); + error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type.flags & 33554432 /* ThisType */ ? apparentType : type)); } return unknownType; } @@ -27038,18 +25508,15 @@ var ts; checkClassPropertyAccess(node, left, apparentType, prop); } var propType = getTypeOfSymbol(prop); - if (prop.flags & 8 /* EnumMember */ && isLiteralContextForType(node, propType)) { - propType = getDeclaredTypeOfSymbol(prop); - } // Only compute control flow type if this is a property access expression that isn't an // assignment target, and the referenced property was declared as a variable, property, // accessor, or optional method. if (node.kind !== 172 /* PropertyAccessExpression */ || ts.isAssignmentTarget(node) || !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && - !(prop.flags & 8192 /* Method */ && propType.flags & 524288 /* Union */)) { + !(prop.flags & 8192 /* Method */ && propType.flags & 16384 /* Union */)) { return propType; } - return getFlowTypeOfReference(node, propType, /*assumeInitialized*/ true, /*flowContainer*/ undefined); + return getFlowTypeOfReference(node, propType, /*assumeInitialized*/ true, /*includeOuterFunctions*/ false); } function isValidPropertyAccess(node, propertyName) { var left = node.kind === 172 /* PropertyAccessExpression */ @@ -27162,10 +25629,9 @@ var ts; } } // Check for compatible indexer types. - var allowedNullableFlags = strictNullChecks ? 0 : 6144 /* Nullable */; - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 34 /* StringLike */ | 340 /* NumberLike */ | 512 /* ESSymbol */ | allowedNullableFlags)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 258 /* StringLike */ | 132 /* NumberLike */ | 16777216 /* ESSymbol */)) { // Try to use a number indexer. - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 /* NumberLike */ | allowedNullableFlags) || isForInVariableForNumericPropertyNames(node.argumentExpression)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 132 /* NumberLike */) || isForInVariableForNumericPropertyNames(node.argumentExpression)) { var numberIndexInfo = getIndexInfoOfType(objectType, 1 /* Number */); if (numberIndexInfo) { getNodeLinks(node).resolvedIndexInfo = numberIndexInfo; @@ -27229,7 +25695,7 @@ var ts; return false; } // Make sure the property type is the primitive symbol type - if ((expressionType.flags & 512 /* ESSymbol */) === 0) { + if ((expressionType.flags & 16777216 /* ESSymbol */) === 0) { if (reportError) { error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); } @@ -27308,7 +25774,7 @@ var ts; lastSymbol = symbol; // specialized signatures always need to be placed before non-specialized signatures regardless // of the cutoff position; see GH#1133 - if (signature.hasLiteralTypes) { + if (signature.hasStringLiterals) { specializedIndex++; spliceIndex = specializedIndex; // The cutoff index always needs to be greater than or equal to the specialized signature index @@ -27401,7 +25867,7 @@ var ts; } // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. function getSingleCallSignature(type) { - if (type.flags & 2588672 /* ObjectType */) { + if (type.flags & 80896 /* ObjectType */) { var resolved = resolveStructuredTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -27535,7 +26001,9 @@ var ts; // If the effective argument type is 'undefined', there is no synthetic type // for the argument. In that case, we should check the argument. if (argType === undefined) { - argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + argType = arg.kind === 9 /* StringLiteral */ && !reportErrors + ? getStringLiteralTypeForText(arg.text) + : checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); } // Use argument expression as error location when reporting errors var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; @@ -27720,10 +26188,10 @@ var ts; case 69 /* Identifier */: case 8 /* NumericLiteral */: case 9 /* StringLiteral */: - return getLiteralTypeForText(32 /* StringLiteral */, element.name.text); + return getStringLiteralTypeForText(element.name.text); case 140 /* ComputedPropertyName */: var nameType = checkComputedPropertyName(element.name); - if (isTypeOfKind(nameType, 512 /* ESSymbol */)) { + if (isTypeOfKind(nameType, 16777216 /* ESSymbol */)) { return nameType; } else { @@ -28074,10 +26542,16 @@ var ts; // that the user will not add any. var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - // TS 1.0 Spec: 4.12 - // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual + // TS 1.0 spec: 4.12 + // If FuncExpr is of type Any, or of an object type that has no call or construct signatures + // but is a subtype of the Function interface, the call is an untyped function call. In an + // untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual // types are provided for the argument expressions, and the result is always of type Any. - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + // We exclude union types because we may have a union of function types that happen to have + // no common signatures. + if (isTypeAny(funcType) || + (isTypeAny(apparentType) && funcType.flags & 512 /* TypeParameter */) || + (!callSignatures.length && !constructSignatures.length && !(funcType.flags & 16384 /* Union */) && isTypeAssignableTo(funcType, globalFunctionType))) { // The unknownType indicates that an error already occurred (and was reported). No // need to report another error in this case. if (funcType !== unknownType && node.typeArguments) { @@ -28099,28 +26573,6 @@ var ts; } return resolveCall(node, callSignatures, candidatesOutArray); } - /** - * TS 1.0 spec: 4.12 - * If FuncExpr is of type Any, or of an object type that has no call or construct signatures - * but is a subtype of the Function interface, the call is an untyped function call. - */ - function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { - if (isTypeAny(funcType)) { - return true; - } - if (isTypeAny(apparentFuncType) && funcType.flags & 16384 /* TypeParameter */) { - return true; - } - if (!numCallSignatures && !numConstructSignatures) { - // We exclude union types because we may have a union of function types that happen to have - // no common signatures. - if (funcType.flags & 524288 /* Union */) { - return false; - } - return isTypeAssignableTo(funcType, globalFunctionType); - } - return false; - } function resolveNewExpression(node, candidatesOutArray) { if (node.arguments && languageVersion < 1 /* ES5 */) { var spreadIndex = getSpreadArgumentIndex(node.arguments); @@ -28198,20 +26650,8 @@ var ts; } var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); - // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected) + // A private or protected constructor can only be instantiated within it's own class if (!isNodeWithinClass(node, declaringClassDeclaration)) { - var containingClass = ts.getContainingClass(node); - if (containingClass) { - var containingType = getTypeOfNode(containingClass); - var baseTypes = getBaseTypes(containingType); - if (baseTypes.length) { - var baseType = baseTypes[0]; - if (flags & 16 /* Protected */ && - baseType.symbol === declaration.parent.symbol) { - return true; - } - } - } if (flags & 8 /* Private */) { error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); } @@ -28230,8 +26670,7 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { + if (isTypeAny(tagType) || (!callSignatures.length && !(tagType.flags & 16384 /* Union */) && isTypeAssignableTo(tagType, globalFunctionType))) { return resolveUntypedCall(node); } if (!callSignatures.length) { @@ -28268,8 +26707,7 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + if (funcType === anyType || (!callSignatures.length && !(funcType.flags & 16384 /* Union */) && isTypeAssignableTo(funcType, globalFunctionType))) { return resolveUntypedCall(node); } var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); @@ -28304,10 +26742,10 @@ var ts; // or that a different candidatesOutArray was passed in. Therefore, we need to redo the work // to correctly fill the candidatesOutArray. var cached = links.resolvedSignature; - if (cached && cached !== resolvingSignature && !candidatesOutArray) { + if (cached && cached !== anySignature && !candidatesOutArray) { return cached; } - links.resolvedSignature = resolvingSignature; + links.resolvedSignature = anySignature; var result = resolveSignature(node, candidatesOutArray); // If signature resolution originated in control flow type analysis (for example to compute the // assigned type in a flow assignment) we don't cache the result as it may be based on temporary @@ -28318,12 +26756,12 @@ var ts; function getResolvedOrAnySignature(node) { // If we're already in the process of resolving the given signature, don't resolve again as // that could cause infinite recursion. Instead, return anySignature. - return getNodeLinks(node).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(node); + return getNodeLinks(node).resolvedSignature === anySignature ? anySignature : getResolvedSignature(node); } function getInferredClassType(symbol) { var links = getSymbolLinks(symbol); if (!links.inferredClassType) { - links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined); + links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined); } return links.inferredClassType; } @@ -28392,7 +26830,7 @@ var ts; if (strictNullChecks) { var declaration = symbol.valueDeclaration; if (declaration && declaration.initializer) { - return includeFalsyTypes(type, 2048 /* Undefined */); + return addTypeKind(type, 32 /* Undefined */); } } return type; @@ -28404,12 +26842,6 @@ var ts; } function assignContextualParameterTypes(signature, context, mapper) { var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); - if (context.thisParameter) { - if (!signature.thisParameter) { - signature.thisParameter = createTransientSymbol(context.thisParameter, undefined); - } - assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter), mapper); - } for (var i = 0; i < len; i++) { var parameter = signature.parameters[i]; var contextualParameterType = getTypeAtPosition(context, i); @@ -28549,7 +26981,7 @@ var ts; } // When yield/return statements are contextually typed we allow the return type to be a union type. // Otherwise we require the yield/return expressions to have a best common supertype. - type = contextualSignature ? getUnionType(types, /*subtypeReduction*/ true) : getCommonSupertype(types); + type = contextualSignature ? getUnionType(types) : getCommonSupertype(types); if (!type) { if (funcIsGenerator) { error(func, ts.Diagnostics.No_best_common_type_exists_among_yield_expressions); @@ -28558,7 +26990,7 @@ var ts; else { error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); // Defer to unioning the return types so we get a) downstream errors earlier and b) better Salsa experience - return isAsync ? createPromiseReturnType(func, getUnionType(types, /*subtypeReduction*/ true)) : getUnionType(types, /*subtypeReduction*/ true); + return isAsync ? createPromiseReturnType(func, getUnionType(types)) : getUnionType(types); } } if (funcIsGenerator) { @@ -28592,18 +27024,24 @@ var ts; return aggregatedTypes; } function isExhaustiveSwitchStatement(node) { - if (!node.possiblyExhaustive) { + var expr = node.expression; + if (!node.possiblyExhaustive || expr.kind !== 172 /* PropertyAccessExpression */) { return false; } - var type = checkExpression(node.expression); - if (!isUnitUnionType(type)) { + var type = checkExpression(expr.expression); + if (!(type.flags & 16384 /* Union */)) { + return false; + } + var propName = expr.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { return false; } var switchTypes = getSwitchClauseTypes(node); if (!switchTypes.length) { return false; } - return eachTypeContainedIn(type, switchTypes); + return eachTypeContainedIn(propType, switchTypes); } function functionHasImplicitReturn(func) { if (!(func.flags & 32768 /* HasImplicitReturn */)) { @@ -28667,7 +27105,7 @@ var ts; return; } // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. - if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 1024 /* Void */)) { + if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 16 /* Void */)) { return; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. @@ -28796,7 +27234,7 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 340 /* NumberLike */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 132 /* NumberLike */)) { error(operand, diagnostic); return false; } @@ -28908,22 +27346,16 @@ var ts; } function checkPrefixUnaryExpression(node) { var operandType = checkExpression(node.operand); - if (node.operator === 36 /* MinusToken */ && node.operand.kind === 8 /* NumericLiteral */ && isLiteralContextForType(node, numberType)) { - return getLiteralTypeForText(64 /* NumberLiteral */, "" + -node.operand.text); - } switch (node.operator) { case 35 /* PlusToken */: case 36 /* MinusToken */: case 50 /* TildeToken */: - if (maybeTypeOfKind(operandType, 512 /* ESSymbol */)) { + if (maybeTypeOfKind(operandType, 16777216 /* ESSymbol */)) { error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } return numberType; case 49 /* ExclamationToken */: - var facts = getTypeFacts(operandType) & (1048576 /* Truthy */ | 2097152 /* Falsy */); - return facts === 1048576 /* Truthy */ ? falseType : - facts === 2097152 /* Falsy */ ? trueType : - booleanType; + return booleanType; case 41 /* PlusPlusToken */: case 42 /* MinusMinusToken */: var ok = checkArithmeticOperandType(node.operand, getNonNullableType(operandType), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); @@ -28950,10 +27382,10 @@ var ts; if (type.flags & kind) { return true; } - if (type.flags & 1572864 /* UnionOrIntersection */) { + if (type.flags & 49152 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -28968,20 +27400,20 @@ var ts; if (type.flags & kind) { return true; } - if (type.flags & 524288 /* Union */) { + if (type.flags & 16384 /* Union */) { var types = type.types; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; if (!isTypeOfKind(t, kind)) { return false; } } return true; } - if (type.flags & 1048576 /* Intersection */) { + if (type.flags & 32768 /* Intersection */) { var types = type.types; - for (var _a = 0, types_15 = types; _a < types_15.length; _a++) { - var t = types_15[_a]; + for (var _a = 0, types_12 = types; _a < types_12.length; _a++) { + var t = types_12[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -28990,7 +27422,7 @@ var ts; return false; } function isConstEnumObjectType(type) { - return type.flags & (2588672 /* ObjectType */ | 2097152 /* Anonymous */) && type.symbol && isConstEnumSymbol(type.symbol); + return type.flags & (80896 /* ObjectType */ | 65536 /* Anonymous */) && type.symbol && isConstEnumSymbol(type.symbol); } function isConstEnumSymbol(symbol) { return (symbol.flags & 128 /* ConstEnum */) !== 0; @@ -29001,7 +27433,7 @@ var ts; // and the right operand to be of type Any or a subtype of the 'Function' interface type. // The result is always of the Boolean primitive type. // NOTE: do not raise error if leftType is unknown as related error was already reported - if (isTypeOfKind(leftType, 8190 /* Primitive */)) { + if (isTypeOfKind(leftType, 16777726 /* Primitive */)) { error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } // NOTE: do not raise error if right is unknown as related error was already reported @@ -29015,10 +27447,10 @@ var ts; // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, // and the right operand to be of type Any, an object type, or a type parameter type. // The result is always of the Boolean primitive type. - if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 34 /* StringLike */ | 340 /* NumberLike */ | 512 /* ESSymbol */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258 /* StringLike */ | 132 /* NumberLike */ | 16777216 /* ESSymbol */)) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 2588672 /* ObjectType */ | 16384 /* TypeParameter */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 80896 /* ObjectType */ | 512 /* TypeParameter */)) { error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; @@ -29089,11 +27521,8 @@ var ts; return checkDestructuringAssignment(element, type, contextualMapper); } else { - // We still need to check element expression here because we may need to set appropriate flag on the expression - // such as NodeCheckFlags.LexicalThis on "this"expression. - checkExpression(element); if (isTupleType(sourceType)) { - error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); + error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), sourceType.elementTypes.length, elements.length); } else { error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); @@ -29125,7 +27554,7 @@ var ts; // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. if (strictNullChecks && - !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 2048 /* Undefined */)) { + !(getCombinedTypeFlags(checkExpression(prop.objectAssignmentInitializer)) & 32 /* Undefined */)) { sourceType = getTypeWithFacts(sourceType, 131072 /* NEUndefined */); } checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, contextualMapper); @@ -29155,14 +27584,7 @@ var ts; return sourceType; } function isTypeEqualityComparableTo(source, target) { - return (target.flags & 6144 /* Nullable */) !== 0 || isTypeComparableTo(source, target); - } - function getBestChoiceType(type1, type2) { - var firstAssignableToSecond = isTypeAssignableTo(type1, type2); - var secondAssignableToFirst = isTypeAssignableTo(type2, type1); - return secondAssignableToFirst && !firstAssignableToSecond ? type1 : - firstAssignableToSecond && !secondAssignableToFirst ? type2 : - getUnionType([type1, type2], /*subtypeReduction*/ true); + return (target.flags & 96 /* Nullable */) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, contextualMapper) { return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, contextualMapper, node); @@ -29203,17 +27625,17 @@ var ts; // as having the primitive type Number. If one operand is the null or undefined value, // it is treated as having the type of the other operand. // The result is always of the Number primitive type. - if (leftType.flags & 6144 /* Nullable */) + if (leftType.flags & 96 /* Nullable */) leftType = rightType; - if (rightType.flags & 6144 /* Nullable */) + if (rightType.flags & 96 /* Nullable */) rightType = leftType; leftType = getNonNullableType(leftType); rightType = getNonNullableType(rightType); var suggestedOperator = void 0; // if a user tries to apply a bitwise operator to 2 boolean operands // try and return them a helpful suggestion - if ((leftType.flags & 136 /* BooleanLike */) && - (rightType.flags & 136 /* BooleanLike */) && + if ((leftType.flags & 8 /* Boolean */) && + (rightType.flags & 8 /* Boolean */) && (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator)); } @@ -29232,20 +27654,20 @@ var ts; // The binary + operator requires both operands to be of the Number primitive type or an enum type, // or at least one of the operands to be of type Any or the String primitive type. // If one operand is the null or undefined value, it is treated as having the type of the other operand. - if (leftType.flags & 6144 /* Nullable */) + if (leftType.flags & 96 /* Nullable */) leftType = rightType; - if (rightType.flags & 6144 /* Nullable */) + if (rightType.flags & 96 /* Nullable */) rightType = leftType; leftType = getNonNullableType(leftType); rightType = getNonNullableType(rightType); var resultType = void 0; - if (isTypeOfKind(leftType, 340 /* NumberLike */) && isTypeOfKind(rightType, 340 /* NumberLike */)) { + if (isTypeOfKind(leftType, 132 /* NumberLike */) && isTypeOfKind(rightType, 132 /* NumberLike */)) { // Operands of an enum type are treated as having the primitive type Number. // If both operands are of the Number primitive type, the result is of the Number primitive type. resultType = numberType; } else { - if (isTypeOfKind(leftType, 34 /* StringLike */) || isTypeOfKind(rightType, 34 /* StringLike */)) { + if (isTypeOfKind(leftType, 258 /* StringLike */) || isTypeOfKind(rightType, 258 /* StringLike */)) { // If one or both operands are of the String primitive type, the result is of the String primitive type. resultType = stringType; } @@ -29281,12 +27703,6 @@ var ts; case 31 /* ExclamationEqualsToken */: case 32 /* EqualsEqualsEqualsToken */: case 33 /* ExclamationEqualsEqualsToken */: - var leftIsUnit = isUnitUnionType(leftType); - var rightIsUnit = isUnitUnionType(rightType); - if (!leftIsUnit || !rightIsUnit) { - leftType = leftIsUnit ? getBaseTypeOfUnitType(leftType) : leftType; - rightType = rightIsUnit ? getBaseTypeOfUnitType(rightType) : rightType; - } if (!isTypeEqualityComparableTo(leftType, rightType) && !isTypeEqualityComparableTo(rightType, leftType)) { reportOperatorError(); } @@ -29296,13 +27712,9 @@ var ts; case 90 /* InKeyword */: return checkInExpression(left, right, leftType, rightType); case 51 /* AmpersandAmpersandToken */: - return getTypeFacts(leftType) & 1048576 /* Truthy */ ? - includeFalsyTypes(rightType, getFalsyFlags(strictNullChecks ? leftType : getBaseTypeOfUnitType(rightType))) : - leftType; + return strictNullChecks ? addTypeKind(rightType, getCombinedTypeFlags(leftType) & 112 /* Falsy */) : rightType; case 52 /* BarBarToken */: - return getTypeFacts(leftType) & 2097152 /* Falsy */ ? - getBestChoiceType(removeDefinitelyFalsyTypes(leftType), rightType) : - leftType; + return getUnionType([getNonNullableType(leftType), rightType]); case 56 /* EqualsToken */: checkAssignmentOperator(rightType); return getRegularTypeOfObjectLiteral(rightType); @@ -29311,8 +27723,8 @@ var ts; } // Return true if there was no error, false if there was an error. function checkForDisallowedESSymbolOperand(operator) { - var offendingSymbolOperand = maybeTypeOfKind(leftType, 512 /* ESSymbol */) ? left : - maybeTypeOfKind(rightType, 512 /* ESSymbol */) ? right : + var offendingSymbolOperand = maybeTypeOfKind(leftType, 16777216 /* ESSymbol */) ? left : + maybeTypeOfKind(rightType, 16777216 /* ESSymbol */) ? right : undefined; if (offendingSymbolOperand) { error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); @@ -29412,66 +27824,14 @@ var ts; checkExpression(node.condition); var type1 = checkExpression(node.whenTrue, contextualMapper); var type2 = checkExpression(node.whenFalse, contextualMapper); - return getBestChoiceType(type1, type2); + return getUnionType([type1, type2]); } - function typeContainsLiteralFromEnum(type, enumType) { - if (type.flags & 524288 /* Union */) { - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (t.flags & 256 /* EnumLiteral */ && t.baseType === enumType) { - return true; - } - } - } - if (type.flags & 256 /* EnumLiteral */) { - return type.baseType === enumType; - } - return false; - } - function isLiteralContextForType(node, type) { - if (isLiteralTypeLocation(node)) { - return true; - } + function checkStringLiteralExpression(node) { var contextualType = getContextualType(node); - if (contextualType) { - if (contextualType.flags & 16384 /* TypeParameter */) { - var apparentType = getApparentTypeOfTypeParameter(contextualType); - // If the type parameter is constrained to the base primitive type we're checking for, - // consider this a literal context. For example, given a type parameter 'T extends string', - // this causes us to infer string literal types for T. - if (type === apparentType) { - return true; - } - contextualType = apparentType; - } - if (type.flags & 2 /* String */) { - return maybeTypeOfKind(contextualType, 32 /* StringLiteral */); - } - if (type.flags & 4 /* Number */) { - return maybeTypeOfKind(contextualType, (64 /* NumberLiteral */ | 256 /* EnumLiteral */)); - } - if (type.flags & 8 /* Boolean */) { - return maybeTypeOfKind(contextualType, 128 /* BooleanLiteral */); - } - if (type.flags & 16 /* Enum */) { - return typeContainsLiteralFromEnum(contextualType, type); - } - } - return false; - } - function checkLiteralExpression(node) { - if (node.kind === 8 /* NumericLiteral */) { - checkGrammarNumericLiteral(node); - } - switch (node.kind) { - case 9 /* StringLiteral */: - return isLiteralContextForType(node, stringType) ? getLiteralTypeForText(32 /* StringLiteral */, node.text) : stringType; - case 8 /* NumericLiteral */: - return isLiteralContextForType(node, numberType) ? getLiteralTypeForText(64 /* NumberLiteral */, node.text) : numberType; - case 99 /* TrueKeyword */: - case 84 /* FalseKeyword */: - return isLiteralContextForType(node, booleanType) ? node.kind === 99 /* TrueKeyword */ ? trueType : falseType : booleanType; + if (contextualType && isStringLiteralUnionType(contextualType)) { + return getStringLiteralTypeForText(node.text); } + return stringType; } function checkTemplateExpression(node) { // We just want to check each expressions, but we are unconcerned with @@ -29570,6 +27930,11 @@ var ts; } return type; } + function checkNumericLiteral(node) { + // Grammar checking + checkGrammarNumericLiteral(node); + return numberType; + } function checkExpressionWorker(node, contextualMapper) { switch (node.kind) { case 69 /* Identifier */: @@ -29580,13 +27945,15 @@ var ts; return checkSuperExpression(node); case 93 /* NullKeyword */: return nullWideningType; - case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: case 99 /* TrueKeyword */: case 84 /* FalseKeyword */: - return checkLiteralExpression(node); + return booleanType; + case 8 /* NumericLiteral */: + return checkNumericLiteral(node); case 189 /* TemplateExpression */: return checkTemplateExpression(node); + case 9 /* StringLiteral */: + return checkStringLiteralExpression(node); case 11 /* NoSubstitutionTemplateLiteral */: return stringType; case 10 /* RegularExpressionLiteral */: @@ -29835,27 +28202,22 @@ var ts; checkAsyncFunctionReturnType(node); } } - if (noUnusedIdentifiers && !node.body) { + if (!node.body) { checkUnusedTypeParameters(node); } } } function checkClassForDuplicateDeclarations(node) { - var Accessor; - (function (Accessor) { - Accessor[Accessor["Getter"] = 1] = "Getter"; - Accessor[Accessor["Setter"] = 2] = "Setter"; - Accessor[Accessor["Property"] = 3] = "Property"; - })(Accessor || (Accessor = {})); - var instanceNames = ts.createMap(); - var staticNames = ts.createMap(); + var getter = 1, setter = 2, property = getter | setter; + var instanceNames = {}; + var staticNames = {}; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; if (member.kind === 148 /* Constructor */) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var param = _c[_b]; if (ts.isParameterPropertyDeclaration(param)) { - addName(instanceNames, param.name, param.name.text, 3 /* Property */); + addName(instanceNames, param.name, param.name.text, property); } } } @@ -29866,21 +28228,21 @@ var ts; if (memberName) { switch (member.kind) { case 149 /* GetAccessor */: - addName(names, member.name, memberName, 1 /* Getter */); + addName(names, member.name, memberName, getter); break; case 150 /* SetAccessor */: - addName(names, member.name, memberName, 2 /* Setter */); + addName(names, member.name, memberName, setter); break; case 145 /* PropertyDeclaration */: - addName(names, member.name, memberName, 3 /* Property */); + addName(names, member.name, memberName, property); break; } } } } function addName(names, location, name, meaning) { - var prev = names[name]; - if (prev) { + if (ts.hasProperty(names, name)) { + var prev = names[name]; if (prev & meaning) { error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); } @@ -29894,7 +28256,7 @@ var ts; } } function checkObjectTypeForDuplicateDeclarations(node) { - var names = ts.createMap(); + var names = {}; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; if (member.kind == 144 /* PropertySignature */) { @@ -29908,7 +28270,7 @@ var ts; default: continue; } - if (names[memberName]) { + if (ts.hasProperty(names, memberName)) { error(member.symbol.valueDeclaration.name, ts.Diagnostics.Duplicate_identifier_0, memberName); error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); } @@ -30075,7 +28437,12 @@ var ts; checkSignatureDeclaration(node); if (node.kind === 149 /* GetAccessor */) { if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 32768 /* HasImplicitReturn */)) { - if (!(node.flags & 65536 /* HasExplicitReturn */)) { + if (node.flags & 65536 /* HasExplicitReturn */) { + if (compilerOptions.noImplicitReturns) { + error(node.name, ts.Diagnostics.Not_all_code_paths_return_a_value); + } + } + else { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); } } @@ -30104,10 +28471,7 @@ var ts; checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type); } } - var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 149 /* GetAccessor */) { - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); - } + getTypeOfAccessors(getSymbolOfNode(node)); } if (node.parent.kind !== 171 /* ObjectLiteralExpression */) { checkSourceElement(node.body); @@ -30161,9 +28525,6 @@ var ts; checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } - if (type.flags & 16 /* Enum */ && !type.memberTypes && getNodeLinks(node).resolvedSymbol.flags & 8 /* EnumMember */) { - error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); - } } } function checkTypeQuery(node) { @@ -30471,10 +28832,10 @@ var ts; case 224 /* EnumDeclaration */: return 2097152 /* ExportType */ | 1048576 /* ExportValue */; case 229 /* ImportEqualsDeclaration */: - var result_2 = 0; + var result_1 = 0; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_2 |= getDeclarationSpaces(d); }); - return result_2; + ts.forEach(target.declarations, function (d) { result_1 |= getDeclarationSpaces(d); }); + return result_1; default: return 1048576 /* ExportValue */; } @@ -30511,7 +28872,7 @@ var ts; if (isTypeAny(promise)) { return undefined; } - if (promise.flags & 131072 /* Reference */) { + if (promise.flags & 4096 /* Reference */) { if (promise.target === tryGetGlobalPromiseType() || promise.target === getGlobalPromiseLikeType()) { return promise.typeArguments[0]; @@ -30537,7 +28898,7 @@ var ts; if (onfulfilledParameterSignatures.length === 0) { return undefined; } - return getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), /*subtypeReduction*/ true); + return getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); } function getTypeOfFirstParameterOfSignature(signature) { return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType; @@ -30555,13 +28916,13 @@ var ts; function checkAwaitedType(type, location, message) { return checkAwaitedTypeWorker(type); function checkAwaitedTypeWorker(type) { - if (type.flags & 524288 /* Union */) { + if (type.flags & 16384 /* Union */) { var types = []; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var constituentType = _a[_i]; types.push(checkAwaitedTypeWorker(constituentType)); } - return getUnionType(types, /*subtypeReduction*/ true); + return getUnionType(types); } else { var promisedType = getPromisedType(type); @@ -30783,7 +29144,7 @@ var ts; // serialize the type metadata. if (node && node.kind === 155 /* TypeReference */) { var root = getFirstIdentifier(node.typeName); - var meaning = root.parent.kind === 155 /* TypeReference */ ? 793064 /* Type */ : 1920 /* Namespace */; + var meaning = root.parent.kind === 155 /* TypeReference */ ? 793056 /* Type */ : 1536 /* Namespace */; // Resolve type so we know which symbol is referenced var rootSymbol = resolveName(root, root.text, meaning | 8388608 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); // Resolved symbol is alias @@ -30973,19 +29334,20 @@ var ts; function checkUnusedLocalsAndParameters(node) { if (node.parent.kind !== 222 /* InterfaceDeclaration */ && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { var _loop_1 = function(key) { - var local = node.locals[key]; - if (!local.isReferenced) { - if (local.valueDeclaration && local.valueDeclaration.kind === 142 /* Parameter */) { - var parameter = local.valueDeclaration; - if (compilerOptions.noUnusedParameters && - !ts.isParameterPropertyDeclaration(parameter) && - !parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(parameter)) { - error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); + if (ts.hasProperty(node.locals, key)) { + var local_1 = node.locals[key]; + if (!local_1.isReferenced) { + if (local_1.valueDeclaration && local_1.valueDeclaration.kind === 142 /* Parameter */) { + var parameter = local_1.valueDeclaration; + if (compilerOptions.noUnusedParameters && + !ts.isParameterPropertyDeclaration(parameter) && + !parameterNameStartsWithUnderscore(parameter)) { + error(local_1.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local_1.name); + } + } + else if (compilerOptions.noUnusedLocals) { + ts.forEach(local_1.declarations, function (d) { return error(d.name || d, ts.Diagnostics._0_is_declared_but_never_used, local_1.name); }); } - } - else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return error(d.name || d, ts.Diagnostics._0_is_declared_but_never_used, local.name); }); } } }; @@ -30994,9 +29356,6 @@ var ts; } } } - function parameterIsThisKeyword(parameter) { - return parameter.name && parameter.name.originalKeywordKind === 97 /* ThisKeyword */; - } function parameterNameStartsWithUnderscore(parameter) { return parameter.name && parameter.name.kind === 69 /* Identifier */ && parameter.name.text.charCodeAt(0) === 95 /* _ */; } @@ -31014,7 +29373,7 @@ var ts; for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; if (!parameter.symbol.isReferenced && parameter.flags & 8 /* Private */) { - error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_never_used, parameter.symbol.name); + error(parameter.name, ts.Diagnostics._0_is_declared_but_never_used, parameter.symbol.name); } } } @@ -31025,16 +29384,9 @@ var ts; function checkUnusedTypeParameters(node) { if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { if (node.typeParameters) { - // Only report errors on the last declaration for the type parameter container; - // this ensures that all uses have been accounted for. - var symbol = getSymbolOfNode(node); - var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations); - if (lastDeclaration !== node) { - return; - } for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { var typeParameter = _a[_i]; - if (!getMergedSymbol(typeParameter.symbol).isReferenced) { + if (!typeParameter.symbol.isReferenced) { error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name); } } @@ -31044,12 +29396,14 @@ var ts; function checkUnusedModuleMembers(node) { if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { for (var key in node.locals) { - var local = node.locals[key]; - if (!local.isReferenced && !local.exportSymbol) { - for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (!ts.isAmbientModule(declaration)) { - error(declaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); + if (ts.hasProperty(node.locals, key)) { + var local = node.locals[key]; + if (!local.isReferenced && !local.exportSymbol) { + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (!ts.isAmbientModule(declaration)) { + error(declaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); + } } } } @@ -31538,7 +29892,7 @@ var ts; if (varExpr.kind === 170 /* ArrayLiteralExpression */ || varExpr.kind === 171 /* ObjectLiteralExpression */) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } - else if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 34 /* StringLike */)) { + else if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258 /* StringLike */)) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); } else { @@ -31549,7 +29903,7 @@ var ts; var rightType = checkNonNullExpression(node.expression); // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved // in this case error about missing name is already reported - do not report extra one - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 2588672 /* ObjectType */ | 16384 /* TypeParameter */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 80896 /* ObjectType */ | 512 /* TypeParameter */)) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); } checkSourceElement(node.statement); @@ -31631,7 +29985,7 @@ var ts; if (!typeAsIterable.iterableElementType) { // As an optimization, if the type is instantiated directly using the globalIterableType (Iterable), // then just grab its type argument. - if ((type.flags & 131072 /* Reference */) && type.target === getGlobalIterableType()) { + if ((type.flags & 4096 /* Reference */) && type.target === getGlobalIterableType()) { typeAsIterable.iterableElementType = type.typeArguments[0]; } else { @@ -31646,7 +30000,7 @@ var ts; } return undefined; } - typeAsIterable.iterableElementType = getElementTypeOfIterator(getUnionType(ts.map(iteratorFunctionSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true), errorNode); + typeAsIterable.iterableElementType = getElementTypeOfIterator(getUnionType(ts.map(iteratorFunctionSignatures, getReturnTypeOfSignature)), errorNode); } } return typeAsIterable.iterableElementType; @@ -31672,7 +30026,7 @@ var ts; if (!typeAsIterator.iteratorElementType) { // As an optimization, if the type is instantiated directly using the globalIteratorType (Iterator), // then just grab its type argument. - if ((type.flags & 131072 /* Reference */) && type.target === getGlobalIteratorType()) { + if ((type.flags & 4096 /* Reference */) && type.target === getGlobalIteratorType()) { typeAsIterator.iteratorElementType = type.typeArguments[0]; } else { @@ -31687,7 +30041,7 @@ var ts; } return undefined; } - var iteratorNextResult = getUnionType(ts.map(iteratorNextFunctionSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); + var iteratorNextResult = getUnionType(ts.map(iteratorNextFunctionSignatures, getReturnTypeOfSignature)); if (isTypeAny(iteratorNextResult)) { return undefined; } @@ -31709,7 +30063,7 @@ var ts; } // As an optimization, if the type is instantiated directly using the globalIterableIteratorType (IterableIterator), // then just grab its type argument. - if ((type.flags & 131072 /* Reference */) && type.target === getGlobalIterableIteratorType()) { + if ((type.flags & 4096 /* Reference */) && type.target === getGlobalIterableIteratorType()) { return type.typeArguments[0]; } return getElementTypeOfIterable(type, /*errorNode*/ undefined) || @@ -31737,10 +30091,10 @@ var ts; // After we remove all types that are StringLike, we will know if there was a string constituent // based on whether the remaining type is the same as the initial type. var arrayType = arrayOrStringType; - if (arrayOrStringType.flags & 524288 /* Union */) { - arrayType = getUnionType(ts.filter(arrayOrStringType.types, function (t) { return !(t.flags & 34 /* StringLike */); }), /*subtypeReduction*/ true); + if (arrayOrStringType.flags & 16384 /* Union */) { + arrayType = getUnionType(ts.filter(arrayOrStringType.types, function (t) { return !(t.flags & 258 /* StringLike */); })); } - else if (arrayOrStringType.flags & 34 /* StringLike */) { + else if (arrayOrStringType.flags & 258 /* StringLike */) { arrayType = neverType; } var hasStringConstituent = arrayOrStringType !== arrayType; @@ -31772,10 +30126,10 @@ var ts; var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */) || unknownType; if (hasStringConstituent) { // This is just an optimization for the case where arrayOrStringType is string | string[] - if (arrayElementType.flags & 34 /* StringLike */) { + if (arrayElementType.flags & 258 /* StringLike */) { return stringType; } - return getUnionType([arrayElementType, stringType], /*subtypeReduction*/ true); + return getUnionType([arrayElementType, stringType]); } return arrayElementType; } @@ -31789,7 +30143,7 @@ var ts; } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { var unwrappedReturnType = ts.isAsyncFunctionLike(func) ? getPromisedType(returnType) : returnType; - return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 1024 /* Void */ | 1 /* Any */); + return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16 /* Void */ | 1 /* Any */); } function checkReturnStatement(node) { // Grammar checking @@ -31941,7 +30295,7 @@ var ts; else { var identifierName = catchClause.variableDeclaration.name.text; var locals = catchClause.block.locals; - if (locals) { + if (locals && ts.hasProperty(locals, identifierName)) { var localSymbol = locals[identifierName]; if (localSymbol && (localSymbol.flags & 2 /* BlockScopedVariable */) !== 0) { grammarErrorOnNode(localSymbol.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, identifierName); @@ -31966,7 +30320,7 @@ var ts; checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); }); - if (type.flags & 32768 /* Class */ && ts.isClassLike(type.symbol.valueDeclaration)) { + if (type.flags & 1024 /* Class */ && ts.isClassLike(type.symbol.valueDeclaration)) { var classDeclaration = type.symbol.valueDeclaration; for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; @@ -31985,7 +30339,7 @@ var ts; if (stringIndexType && numberIndexType) { errorNode = declaredNumberIndexer || declaredStringIndexer; // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer - if (!errorNode && (type.flags & 65536 /* Interface */)) { + if (!errorNode && (type.flags & 2048 /* Interface */)) { var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); }); errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; } @@ -32010,7 +30364,7 @@ var ts; else if (indexDeclaration) { errorNode = indexDeclaration; } - else if (containingType.flags & 65536 /* Interface */) { + else if (containingType.flags & 2048 /* Interface */) { // for interfaces property and indexer might be inherited from different bases // check if any base class already has both property and indexer. // check should be performed only if 'type' is the first type that brings property\indexer together @@ -32125,11 +30479,6 @@ var ts; } checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); - if (baseType_1.symbol.valueDeclaration && !ts.isInAmbientContext(baseType_1.symbol.valueDeclaration)) { - if (!isBlockScopedNameDeclaredBeforeUse(baseType_1.symbol.valueDeclaration, node)) { - error(baseTypeNode, ts.Diagnostics.A_class_must_be_declared_after_its_base_class); - } - } if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */)) { // When the static base type is a "class-like" constructor function (but not actually a class), we verify // that all instantiated base constructor signatures return the same type. We can simply compare the type @@ -32147,15 +30496,15 @@ var ts; if (implementedTypeNodes) { for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { var typeRefNode = implementedTypeNodes_1[_b]; - if (!ts.isEntityNameExpression(typeRefNode.expression)) { + if (!ts.isSupportedExpressionWithTypeArguments(typeRefNode)) { error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); } checkTypeReferenceNode(typeRefNode); if (produceDiagnostics) { var t = getTypeFromTypeNode(typeRefNode); if (t !== unknownType) { - var declaredType = (t.flags & 131072 /* Reference */) ? t.target : t; - if (declaredType.flags & (32768 /* Class */ | 65536 /* Interface */)) { + var declaredType = (t.flags & 4096 /* Reference */) ? t.target : t; + if (declaredType.flags & (1024 /* Class */ | 2048 /* Interface */)) { checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_implements_interface_1); } else { @@ -32309,7 +30658,7 @@ var ts; if (baseTypes.length < 2) { return true; } - var seen = ts.createMap(); + var seen = {}; ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen[p.name] = { prop: p, containingType: type }; }); var ok = true; for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { @@ -32317,11 +30666,11 @@ var ts; var properties = getPropertiesOfObjectType(getTypeWithThisArgument(base, type.thisType)); for (var _a = 0, properties_4 = properties; _a < properties_4.length; _a++) { var prop = properties_4[_a]; - var existing = seen[prop.name]; - if (!existing) { + if (!ts.hasProperty(seen, prop.name)) { seen[prop.name] = { prop: prop, containingType: base }; } else { + var existing = seen[prop.name]; var isInheritedProperty = existing.containingType !== type; if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) { ok = false; @@ -32362,7 +30711,7 @@ var ts; checkObjectTypeForDuplicateDeclarations(node); } ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) { - if (!ts.isEntityNameExpression(heritageElement.expression)) { + if (!ts.isSupportedExpressionWithTypeArguments(heritageElement)) { error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); } checkTypeReferenceNode(heritageElement); @@ -32370,7 +30719,7 @@ var ts; ts.forEach(node.members, checkSourceElement); if (produceDiagnostics) { checkTypeForDuplicateIndexSignatures(node); - registerForUnusedIdentifiersCheck(node); + checkUnusedTypeParameters(node); } } function checkTypeAliasDeclaration(node) { @@ -32723,6 +31072,10 @@ var ts; } } } + if (compilerOptions.noImplicitAny && !node.body) { + // Ambient shorthand module is an implicit any + reportImplicitAnyError(node, anyType); + } if (node.body) { checkSourceElement(node.body); if (!ts.isGlobalScopeAugmentation(node)) { @@ -32784,20 +31137,19 @@ var ts; } } function getFirstIdentifier(node) { - switch (node.kind) { - case 69 /* Identifier */: - return node; - case 139 /* QualifiedName */: - do { - node = node.left; - } while (node.kind !== 69 /* Identifier */); - return node; - case 172 /* PropertyAccessExpression */: - do { - node = node.expression; - } while (node.kind !== 69 /* Identifier */); - return node; + while (true) { + if (node.kind === 139 /* QualifiedName */) { + node = node.left; + } + else if (node.kind === 172 /* PropertyAccessExpression */) { + node = node.expression; + } + else { + break; + } } + ts.Debug.assert(node.kind === 69 /* Identifier */); + return node; } function checkExternalImportOrExportDeclaration(node) { var moduleName = ts.getExternalModuleName(node); @@ -32837,8 +31189,8 @@ var ts; // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). var excludedMeanings = (symbol.flags & (107455 /* Value */ | 1048576 /* ExportValue */) ? 107455 /* Value */ : 0) | - (symbol.flags & 793064 /* Type */ ? 793064 /* Type */ : 0) | - (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); + (symbol.flags & 793056 /* Type */ ? 793056 /* Type */ : 0) | + (symbol.flags & 1536 /* Namespace */ ? 1536 /* Namespace */ : 0); if (target.flags & excludedMeanings) { var message = node.kind === 238 /* ExportSpecifier */ ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : @@ -32895,11 +31247,11 @@ var ts; if (target.flags & 107455 /* Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 107455 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { + if (!(resolveEntityName(moduleName, 107455 /* Value */ | 1536 /* Namespace */).flags & 1536 /* Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 793064 /* Type */) { + if (target.flags & 793056 /* Type */) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -32949,7 +31301,7 @@ var ts; if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) - var symbol = resolveName(exportedName, exportedName.text, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */, + var symbol = resolveName(exportedName, exportedName.text, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, exportedName.text); @@ -33019,7 +31371,7 @@ var ts; var _a = exports[id], declarations = _a.declarations, flags = _a.flags; // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries. // (TS Exceptions: namespaces, function overloads, enums, and interfaces) - if (flags & (1920 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) { + if (flags & (1536 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) { continue; } var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverload); @@ -33202,10 +31554,9 @@ var ts; } } function checkSourceFile(node) { - ts.performance.mark("beforeCheck"); + var start = new Date().getTime(); checkSourceFileWorker(node); - ts.performance.mark("afterCheck"); - ts.performance.measure("Check", "beforeCheck", "afterCheck"); + ts.checkTime += new Date().getTime() - start; } // Fully type check a source file and collect the relevant diagnostics. function checkSourceFileWorker(node) { @@ -33285,7 +31636,7 @@ var ts; return false; } function getSymbolsInScope(location, meaning) { - var symbols = ts.createMap(); + var symbols = {}; var memberFlags = 0; if (isInsideWithStatementBody(location)) { // We cannot answer semantic questions within a with block, do not proceed any further @@ -33323,7 +31674,7 @@ var ts; // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. // Note: that the memberFlags come from previous iteration. if (!(memberFlags & 32 /* Static */)) { - copySymbols(getSymbolOfNode(location).members, meaning & 793064 /* Type */); + copySymbols(getSymbolOfNode(location).members, meaning & 793056 /* Type */); } break; case 179 /* FunctionExpression */: @@ -33354,7 +31705,7 @@ var ts; // We will copy all symbol regardless of its reserved name because // symbolsToArray will check whether the key is a reserved name and // it will not copy symbol with reserved name to the array - if (!symbols[id]) { + if (!ts.hasProperty(symbols, id)) { symbols[id] = symbol; } } @@ -33443,15 +31794,17 @@ var ts; default: } } - if (entityName.parent.kind === 235 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { + if (entityName.parent.kind === 235 /* ExportAssignment */) { return resolveEntityName(entityName, - /*all meanings*/ 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */); + /*all meanings*/ 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */); } - if (entityName.kind !== 172 /* PropertyAccessExpression */ && isInRightSideOfImportOrExportAssignment(entityName)) { - // Since we already checked for ExportAssignment, this really could only be an Import - var importEqualsDeclaration = ts.getAncestor(entityName, 229 /* ImportEqualsDeclaration */); - ts.Debug.assert(importEqualsDeclaration !== undefined); - return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importEqualsDeclaration, /*dontResolveAlias*/ true); + if (entityName.kind !== 172 /* PropertyAccessExpression */) { + if (isInRightSideOfImportOrExportAssignment(entityName)) { + // Since we already checked for ExportAssignment, this really could only be an Import + var importEqualsDeclaration = ts.getAncestor(entityName, 229 /* ImportEqualsDeclaration */); + ts.Debug.assert(importEqualsDeclaration !== undefined); + return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importEqualsDeclaration, /*dontResolveAlias*/ true); + } } if (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; @@ -33460,14 +31813,14 @@ var ts; var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. if (entityName.parent.kind === 194 /* ExpressionWithTypeArguments */) { - meaning = 793064 /* Type */; + meaning = 793056 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { meaning |= 107455 /* Value */; } } else { - meaning = 1920 /* Namespace */; + meaning = 1536 /* Namespace */; } meaning |= 8388608 /* Alias */; return resolveEntityName(entityName, meaning); @@ -33499,7 +31852,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = (entityName.parent.kind === 155 /* TypeReference */ || entityName.parent.kind === 267 /* JSDocTypeReference */) ? 793064 /* Type */ : 1920 /* Namespace */; + var meaning = (entityName.parent.kind === 155 /* TypeReference */ || entityName.parent.kind === 267 /* JSDocTypeReference */) ? 793056 /* Type */ : 1536 /* Namespace */; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.parent.kind === 246 /* JsxAttribute */) { @@ -33603,7 +31956,7 @@ var ts; function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */); + resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */); } function getTypeOfNode(node) { if (isInsideWithStatementBody(node)) { @@ -33717,7 +32070,7 @@ var ts; var propsByName = createSymbolTable(getPropertiesOfType(type)); if (getSignaturesOfType(type, 0 /* Call */).length || getSignaturesOfType(type, 1 /* Construct */).length) { ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { - if (!propsByName[p.name]) { + if (!ts.hasProperty(propsByName, p.name)) { propsByName[p.name] = p; } }); @@ -33754,8 +32107,8 @@ var ts; } function moduleExportsSomeValue(moduleReferenceExpression) { var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); - if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { - // If the module is not found or is shorthand, assume that it may export a value. + if (!moduleSymbol) { + // module not found - be conservative return true; } var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol); @@ -33768,7 +32121,7 @@ var ts; // otherwise - check if at least one export is value symbolLinks.exportsSomeValue = hasExportAssignment ? !!(moduleSymbol.flags & 107455 /* Value */) - : ts.forEachProperty(getExportsOfModule(moduleSymbol), isValue); + : ts.forEachValue(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { @@ -33956,7 +32309,7 @@ var ts; return undefined; } function isFunctionType(type) { - return type.flags & 2588672 /* ObjectType */ && getSignaturesOfType(type, 0 /* Call */).length > 0; + return type.flags & 80896 /* ObjectType */ && getSignaturesOfType(type, 0 /* Call */).length > 0; } function getTypeReferenceSerializationKind(typeName) { // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. @@ -33966,7 +32319,7 @@ var ts; return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue; } // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. - var typeSymbol = resolveEntityName(typeName, 793064 /* Type */, /*ignoreErrors*/ true); + var typeSymbol = resolveEntityName(typeName, 793056 /* Type */, /*ignoreErrors*/ true); // We might not be able to resolve type symbol so use unknown type in that case (eg error case) if (!typeSymbol) { return ts.TypeReferenceSerializationKind.ObjectType; @@ -33978,22 +32331,22 @@ var ts; else if (type.flags & 1 /* Any */) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (isTypeOfKind(type, 1024 /* Void */)) { + else if (isTypeOfKind(type, 16 /* Void */)) { return ts.TypeReferenceSerializationKind.VoidType; } - else if (isTypeOfKind(type, 136 /* BooleanLike */)) { + else if (isTypeOfKind(type, 8 /* Boolean */)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeOfKind(type, 340 /* NumberLike */)) { + else if (isTypeOfKind(type, 132 /* NumberLike */)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (isTypeOfKind(type, 34 /* StringLike */)) { + else if (isTypeOfKind(type, 258 /* StringLike */)) { return ts.TypeReferenceSerializationKind.StringLikeType; } - else if (isTupleType(type)) { + else if (isTypeOfKind(type, 8192 /* Tuple */)) { return ts.TypeReferenceSerializationKind.ArrayLikeType; } - else if (isTypeOfKind(type, 512 /* ESSymbol */)) { + else if (isTypeOfKind(type, 16777216 /* ESSymbol */)) { return ts.TypeReferenceSerializationKind.ESSymbolType; } else if (isFunctionType(type)) { @@ -34029,7 +32382,7 @@ var ts; getSymbolDisplayBuilder().buildTypeDisplay(baseType, writer, enclosingDeclaration, flags); } function hasGlobalName(name) { - return !!globals[name]; + return ts.hasProperty(globals, name); } function getReferencedValueSymbol(reference) { return getNodeLinks(reference).resolvedSymbol || @@ -34050,14 +32403,14 @@ var ts; // populate reverse mapping: file path -> type reference directive that was resolved to this file fileToDirective = ts.createFileMap(); for (var key in resolvedTypeReferenceDirectives) { + if (!ts.hasProperty(resolvedTypeReferenceDirectives, key)) { + continue; + } var resolvedDirective = resolvedTypeReferenceDirectives[key]; if (!resolvedDirective) { continue; } var file = host.getSourceFile(resolvedDirective.resolvedFileName); - if (!file) { - continue; - } fileToDirective.set(file.path, key); } } @@ -34101,7 +32454,7 @@ var ts; // identifiers are treated as values only if they appear in type queries var meaning = (node.kind === 172 /* PropertyAccessExpression */) || (node.kind === 69 /* Identifier */ && isInTypeQuery(node)) ? 107455 /* Value */ | 1048576 /* ExportValue */ - : 793064 /* Type */ | 1920 /* Namespace */; + : 793056 /* Type */ | 1536 /* Namespace */; var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; } @@ -34186,13 +32539,7 @@ var ts; (augmentations || (augmentations = [])).push(file.moduleAugmentations); } if (file.symbol && file.symbol.globalExports) { - // Merge in UMD exports with first-in-wins semantics (see #9771) - var source = file.symbol.globalExports; - for (var id in source) { - if (!(id in globals)) { - globals[id] = source[id]; - } - } + mergeSymbolTable(globals, file.symbol.globalExports); } }); if (augmentations) { @@ -34227,7 +32574,7 @@ var ts; getGlobalTypedPropertyDescriptorType = ts.memoize(function () { return getGlobalType("TypedPropertyDescriptor", /*arity*/ 1); }); getGlobalESSymbolConstructorSymbol = ts.memoize(function () { return getGlobalValueSymbol("Symbol"); }); getGlobalPromiseType = ts.memoize(function () { return getGlobalType("Promise", /*arity*/ 1); }); - tryGetGlobalPromiseType = ts.memoize(function () { return getGlobalSymbol("Promise", 793064 /* Type */, /*diagnostic*/ undefined) && getGlobalPromiseType(); }); + tryGetGlobalPromiseType = ts.memoize(function () { return getGlobalSymbol("Promise", 793056 /* Type */, /*diagnostic*/ undefined) && getGlobalPromiseType(); }); getGlobalPromiseLikeType = ts.memoize(function () { return getGlobalType("PromiseLike", /*arity*/ 1); }); getInstantiatedGlobalPromiseLikeType = ts.memoize(createInstantiatedPromiseLikeType); getGlobalPromiseConstructorSymbol = ts.memoize(function () { return getGlobalValueSymbol("Promise"); }); @@ -34247,7 +32594,7 @@ var ts; getGlobalIterableIteratorType = ts.memoize(function () { return emptyGenericType; }); } anyArrayType = createArrayType(anyType); - var symbol = getGlobalSymbol("ReadonlyArray", 793064 /* Type */, /*diagnostic*/ undefined); + var symbol = getGlobalSymbol("ReadonlyArray", 793056 /* Type */, /*diagnostic*/ undefined); globalReadonlyArrayType = symbol && getTypeOfGlobalSymbol(symbol, /*arity*/ 1); anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; } @@ -34262,7 +32609,7 @@ var ts; // build the thenable type that is used to verify against a non-promise "thenable" operand to `await`. var thenPropertySymbol = createSymbol(67108864 /* Transient */ | 4 /* Property */, "then"); getSymbolLinks(thenPropertySymbol).type = globalFunctionType; - var thenableType = createObjectType(2097152 /* Anonymous */); + var thenableType = createObjectType(65536 /* Anonymous */); thenableType.properties = [thenPropertySymbol]; thenableType.members = createSymbolTable(thenableType.properties); thenableType.callSignatures = []; @@ -34291,9 +32638,49 @@ var ts; return false; } function checkGrammarModifiers(node) { - var quickResult = reportObviousModifierErrors(node); - if (quickResult !== undefined) { - return quickResult; + switch (node.kind) { + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + case 148 /* Constructor */: + case 145 /* PropertyDeclaration */: + case 144 /* PropertySignature */: + case 147 /* MethodDeclaration */: + case 146 /* MethodSignature */: + case 153 /* IndexSignature */: + case 225 /* ModuleDeclaration */: + case 230 /* ImportDeclaration */: + case 229 /* ImportEqualsDeclaration */: + case 236 /* ExportDeclaration */: + case 235 /* ExportAssignment */: + case 179 /* FunctionExpression */: + case 180 /* ArrowFunction */: + case 142 /* Parameter */: + break; + case 220 /* FunctionDeclaration */: + if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 118 /* AsyncKeyword */) && + node.parent.kind !== 226 /* ModuleBlock */ && node.parent.kind !== 256 /* SourceFile */) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + break; + case 221 /* ClassDeclaration */: + case 222 /* InterfaceDeclaration */: + case 200 /* VariableStatement */: + case 223 /* TypeAliasDeclaration */: + if (node.modifiers && node.parent.kind !== 226 /* ModuleBlock */ && node.parent.kind !== 256 /* SourceFile */) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + break; + case 224 /* EnumDeclaration */: + if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 74 /* ConstKeyword */) && + node.parent.kind !== 226 /* ModuleBlock */ && node.parent.kind !== 256 /* SourceFile */) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + break; + default: + return false; + } + if (!node.modifiers) { + return; } var lastStatic, lastPrivate, lastProtected, lastDeclare, lastAsync, lastReadonly; var flags = 0; @@ -34487,60 +32874,6 @@ var ts; return checkGrammarAsyncModifier(node, lastAsync); } } - /** - * true | false: Early return this value from checkGrammarModifiers. - * undefined: Need to do full checking on the modifiers. - */ - function reportObviousModifierErrors(node) { - return !node.modifiers - ? false - : shouldReportBadModifier(node) - ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here) - : undefined; - } - function shouldReportBadModifier(node) { - switch (node.kind) { - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 148 /* Constructor */: - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 153 /* IndexSignature */: - case 225 /* ModuleDeclaration */: - case 230 /* ImportDeclaration */: - case 229 /* ImportEqualsDeclaration */: - case 236 /* ExportDeclaration */: - case 235 /* ExportAssignment */: - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - case 142 /* Parameter */: - return false; - default: - if (node.parent.kind === 226 /* ModuleBlock */ || node.parent.kind === 256 /* SourceFile */) { - return false; - } - switch (node.kind) { - case 220 /* FunctionDeclaration */: - return nodeHasAnyModifiersExcept(node, 118 /* AsyncKeyword */); - case 221 /* ClassDeclaration */: - return nodeHasAnyModifiersExcept(node, 115 /* AbstractKeyword */); - case 222 /* InterfaceDeclaration */: - case 200 /* VariableStatement */: - case 223 /* TypeAliasDeclaration */: - return true; - case 224 /* EnumDeclaration */: - return nodeHasAnyModifiersExcept(node, 74 /* ConstKeyword */); - default: - ts.Debug.fail(); - return false; - } - } - } - function nodeHasAnyModifiersExcept(node, allowedModifier) { - return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier; - } function checkGrammarAsyncModifier(node, asyncModifier) { if (languageVersion < 2 /* ES6 */) { return grammarErrorOnNode(asyncModifier, ts.Diagnostics.Async_functions_are_only_available_when_targeting_ECMAScript_2015_or_higher); @@ -34778,7 +33111,7 @@ var ts; } } function checkGrammarObjectLiteralExpression(node, inDestructuring) { - var seen = ts.createMap(); + var seen = {}; var Property = 1; var GetAccessor = 2; var SetAccessor = 4; @@ -34834,7 +33167,7 @@ var ts; if (effectiveName === undefined) { return "continue"; } - if (!seen[effectiveName]) { + if (!ts.hasProperty(seen, effectiveName)) { seen[effectiveName] = currentKind; } else { @@ -34862,7 +33195,7 @@ var ts; } } function checkGrammarJsxElement(node) { - var seen = ts.createMap(); + var seen = {}; for (var _i = 0, _a = node.attributes; _i < _a.length; _i++) { var attr = _a[_i]; if (attr.kind === 247 /* JsxSpreadAttribute */) { @@ -34870,7 +33203,7 @@ var ts; } var jsxAttr = attr; var name_22 = jsxAttr.name; - if (!seen[name_22.text]) { + if (!ts.hasProperty(seen, name_22.text)) { seen[name_22.text] = true; } else { @@ -35220,7 +33553,7 @@ var ts; } } function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { - // A declare modifier is required for any top level .d.ts declaration except export=, export default, export as namespace + // A declare modifier is required for any top level .d.ts declaration except export=, export default, // interfaces and imports categories: // // DeclarationElement: @@ -35238,7 +33571,6 @@ var ts; node.kind === 229 /* ImportEqualsDeclaration */ || node.kind === 236 /* ExportDeclaration */ || node.kind === 235 /* ExportAssignment */ || - node.kind === 228 /* NamespaceExportDeclaration */ || (node.flags & 2 /* Ambient */) || (node.flags & (1 /* Export */ | 512 /* Default */))) { return false; @@ -35299,15 +33631,7 @@ var ts; return true; } } - function getAmbientModules() { - var result = []; - for (var sym in globals) { - if (ambientModuleSymbolRegex.test(sym)) { - result.push(globals[sym]); - } - } - return result; - } + var _a; } ts.createTypeChecker = createTypeChecker; })(ts || (ts = {})); @@ -35344,7 +33668,6 @@ var ts; ts.getNullSourceMapWriter = getNullSourceMapWriter; function createSourceMapWriter(host, writer) { var compilerOptions = host.getCompilerOptions(); - var extendedDiagnostics = compilerOptions.extendedDiagnostics; var currentSourceFile; var sourceMapDir; // The directory in which sourcemap will be var stopOverridingSpan = false; @@ -35508,9 +33831,6 @@ var ts; if (pos === -1) { return; } - if (extendedDiagnostics) { - ts.performance.mark("beforeSourcemap"); - } var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos); // Convert the location to be one-based. sourceLinePos.line++; @@ -35543,10 +33863,6 @@ var ts; lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; } updateLastEncodedAndRecordedSpans(); - if (extendedDiagnostics) { - ts.performance.mark("afterSourcemap"); - ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); - } } function getStartPos(range) { var rangeHasDecorators = !!range.decorators; @@ -35649,11 +33965,11 @@ var ts; return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined); function getDeclarationDiagnosticsFromFile(_a, sources, isBundledEmit) { var declarationFilePath = _a.declarationFilePath; - emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit, /*emitOnlyDtsFiles*/ false); + emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit); } } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles) { + function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit) { var newLine = host.getNewLine(); var compilerOptions = host.getCompilerOptions(); var write; @@ -35700,7 +34016,7 @@ var ts; // global file reference is added only // - if it is not bundled emit (because otherwise it would be self reference) // - and it is not already added - if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference, emitOnlyDtsFiles)) { + if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference)) { addedGlobalFileReference = true; } emittedReferencedFiles.push(referencedFile); @@ -35754,7 +34070,9 @@ var ts; }); if (usedTypeDirectiveReferences) { for (var directive in usedTypeDirectiveReferences) { - referencesOutput += "/// " + newLine; + if (ts.hasProperty(usedTypeDirectiveReferences, directive)) { + referencesOutput += "/// " + newLine; + } } } return { @@ -35852,11 +34170,11 @@ var ts; return; } if (!usedTypeDirectiveReferences) { - usedTypeDirectiveReferences = ts.createMap(); + usedTypeDirectiveReferences = {}; } for (var _i = 0, typeReferenceDirectives_1 = typeReferenceDirectives; _i < typeReferenceDirectives_1.length; _i++) { var directive = typeReferenceDirectives_1[_i]; - if (!(directive in usedTypeDirectiveReferences)) { + if (!ts.hasProperty(usedTypeDirectiveReferences, directive)) { usedTypeDirectiveReferences[directive] = directive; } } @@ -35901,7 +34219,7 @@ var ts; } else { errorNameNode = declaration.name; - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); + resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); errorNameNode = undefined; } } @@ -35914,7 +34232,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); errorNameNode = undefined; } } @@ -35964,7 +34282,7 @@ var ts; case 93 /* NullKeyword */: case 127 /* NeverKeyword */: case 165 /* ThisType */: - case 166 /* LiteralType */: + case 166 /* StringLiteralType */: return writeTextOfNode(currentText, type); case 194 /* ExpressionWithTypeArguments */: return emitExpressionWithTypeArguments(type); @@ -36015,7 +34333,7 @@ var ts; writeEntityName(entityName); } function emitExpressionWithTypeArguments(node) { - if (ts.isEntityNameExpression(node.expression)) { + if (ts.isSupportedExpressionWithTypeArguments(node)) { ts.Debug.assert(node.expression.kind === 69 /* Identifier */ || node.expression.kind === 172 /* PropertyAccessExpression */); emitEntityName(node.expression); if (node.typeArguments) { @@ -36089,14 +34407,14 @@ var ts; // do not need to keep track of created temp names. function getExportDefaultTempVariableName() { var baseName = "_default"; - if (!(baseName in currentIdentifiers)) { + if (!ts.hasProperty(currentIdentifiers, baseName)) { return baseName; } var count = 0; while (true) { count++; var name_23 = baseName + "_" + count; - if (!(name_23 in currentIdentifiers)) { + if (!ts.hasProperty(currentIdentifiers, name_23)) { return name_23; } } @@ -36116,7 +34434,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); + resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); write(";"); writeLine(); write(node.isExportEquals ? "export = " : "export default "); @@ -36529,7 +34847,7 @@ var ts; emitCommaList(typeReferences, emitTypeOfTypeReference); } function emitTypeOfTypeReference(node) { - if (ts.isEntityNameExpression(node.expression)) { + if (ts.isSupportedExpressionWithTypeArguments(node)) { emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError); } else if (!isImplementsList && node.expression.kind === 93 /* NullKeyword */) { @@ -36537,7 +34855,7 @@ var ts; } else { writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); + resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); } function getHeritageClauseVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; @@ -36635,10 +34953,8 @@ var ts; // it if it's not a well known symbol. In that case, the text of the name will be exactly // what we want, namely the name expression enclosed in brackets. writeTextOfNode(currentText, node.name); - // If optional property emit ? but in the case of parameterProperty declaration with "?" indicating optional parameter for the constructor - // we don't want to emit property declaration with "?" - if ((node.kind === 145 /* PropertyDeclaration */ || node.kind === 144 /* PropertySignature */ || - (node.kind === 142 /* Parameter */ && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { + // If optional property emit ? + if ((node.kind === 145 /* PropertyDeclaration */ || node.kind === 144 /* PropertySignature */ || node.kind === 142 /* Parameter */) && ts.hasQuestionToken(node)) { write("?"); } if ((node.kind === 145 /* PropertyDeclaration */ || node.kind === 144 /* PropertySignature */) && node.parent.kind === 159 /* TypeLiteral */) { @@ -37174,7 +35490,7 @@ var ts; * @param referencedFile * @param addBundledFileReference Determines if global file reference corresponding to bundled file should be emitted or not */ - function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { + function writeReferencePath(referencedFile, addBundledFileReference) { var declFileName; var addedBundledEmitReference = false; if (ts.isDeclarationFile(referencedFile)) { @@ -37183,7 +35499,7 @@ var ts; } else { // Get the declaration file path - ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile, emitOnlyDtsFiles); + ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile); } if (declFileName) { declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, @@ -37203,8 +35519,8 @@ var ts; } } /* @internal */ - function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) { - var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles); + function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) { + var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit); var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; if (!emitSkipped) { var declarationOutput = emitDeclarationResult.referencesOutput @@ -37253,7 +35569,7 @@ var ts; Jump[Jump["Continue"] = 4] = "Continue"; Jump[Jump["Return"] = 8] = "Return"; })(Jump || (Jump = {})); - var entities = ts.createMap({ + var entities = { "quot": 0x0022, "amp": 0x0026, "apos": 0x0027, @@ -37507,7 +35823,7 @@ var ts; "clubs": 0x2663, "hearts": 0x2665, "diams": 0x2666 - }); + }; // Flags enum to track count of temp variables and a few dedicated names var TempFlags; (function (TempFlags) { @@ -37521,7 +35837,7 @@ var ts; CopyDirection[CopyDirection["ToOutParameter"] = 1] = "ToOutParameter"; })(CopyDirection || (CopyDirection = {})); // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature - function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles) { + function emitFiles(resolver, host, targetSourceFile) { // emit output for the __extends helper function var extendsHelper = "\nvar __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n};"; var assignHelper = "\nvar __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n};"; @@ -37541,7 +35857,7 @@ var ts; var emitSkipped = false; var newLine = host.getNewLine(); var emitJavaScript = createFileEmitter(); - ts.forEachExpectedEmitFile(host, emitFile, targetSourceFile, emitOnlyDtsFiles); + ts.forEachExpectedEmitFile(host, emitFile, targetSourceFile); return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -37550,7 +35866,7 @@ var ts; }; function isUniqueLocalName(name, container) { for (var node = container; ts.isNodeDescendentOf(node, container); node = node.nextContainer) { - if (node.locals && name in node.locals) { + if (node.locals && ts.hasProperty(node.locals, name)) { // We conservatively include alias symbols to cover cases where they're emitted as locals if (node.locals[name].flags & (107455 /* Value */ | 1048576 /* ExportValue */ | 8388608 /* Alias */)) { return false; @@ -37562,13 +35878,13 @@ var ts; function setLabeledJump(state, isBreak, labelText, labelMarker) { if (isBreak) { if (!state.labeledNonLocalBreaks) { - state.labeledNonLocalBreaks = ts.createMap(); + state.labeledNonLocalBreaks = {}; } state.labeledNonLocalBreaks[labelText] = labelMarker; } else { if (!state.labeledNonLocalContinues) { - state.labeledNonLocalContinues = ts.createMap(); + state.labeledNonLocalContinues = {}; } state.labeledNonLocalContinues[labelText] = labelMarker; } @@ -37635,26 +35951,26 @@ var ts; /** If removeComments is true, no leading-comments needed to be emitted **/ var emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos) { } : emitLeadingCommentsOfPositionWorker; var setSourceMapWriterEmit = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? changeSourceMapEmit : function (writer) { }; - var moduleEmitDelegates = ts.createMap((_a = {}, + var moduleEmitDelegates = (_a = {}, _a[ts.ModuleKind.ES6] = emitES6Module, _a[ts.ModuleKind.AMD] = emitAMDModule, _a[ts.ModuleKind.System] = emitSystemModule, _a[ts.ModuleKind.UMD] = emitUMDModule, _a[ts.ModuleKind.CommonJS] = emitCommonJSModule, _a - )); - var bundleEmitDelegates = ts.createMap((_b = {}, + ); + var bundleEmitDelegates = (_b = {}, _b[ts.ModuleKind.ES6] = function () { }, _b[ts.ModuleKind.AMD] = emitAMDModule, _b[ts.ModuleKind.System] = emitSystemModule, _b[ts.ModuleKind.UMD] = function () { }, _b[ts.ModuleKind.CommonJS] = function () { }, _b - )); + ); return doEmit; function doEmit(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit) { sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); - generatedNameSet = ts.createMap(); + generatedNameSet = {}; nodeToGeneratedName = []; decoratedClassAliases = []; isOwnFileEmit = !isBundledEmit; @@ -37667,7 +35983,7 @@ var ts; writeLine(); var sourceMappingURL = sourceMap.getSourceMappingURL(); if (sourceMappingURL) { - write("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Sometimes tools can sometimes see this line as a source mapping url comment + write("//# sourceMappingURL=" + sourceMappingURL); } writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, /*writeByteOrderMark*/ compilerOptions.emitBOM, sourceFiles); // reset the state @@ -37716,8 +36032,8 @@ var ts; } function isUniqueName(name) { return !resolver.hasGlobalName(name) && - !(name in currentFileIdentifiers) && - !(name in generatedNameSet); + !ts.hasProperty(currentFileIdentifiers, name) && + !ts.hasProperty(generatedNameSet, name); } // Return the next available name in the pattern _a ... _z, _0, _1, ... // TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name. @@ -38743,10 +37059,6 @@ var ts; else if (node.parent.kind === 188 /* ConditionalExpression */ && node.parent.condition === node) { return true; } - else if (node.parent.kind === 185 /* PrefixUnaryExpression */ || node.parent.kind === 181 /* DeleteExpression */ || - node.parent.kind === 182 /* TypeOfExpression */ || node.parent.kind === 183 /* VoidExpression */) { - return true; - } return false; } function needsParenthesisForPropertyAccessOrInvocation(node) { @@ -39420,7 +37732,7 @@ var ts; operand.kind === 196 /* NonNullExpression */) { operand = operand.expression; } - // We have an expression of the form: (SubExpr) or (SubExpr as Type) + // We have an expression of the form: (SubExpr) // Emitting this as (SubExpr) is really not desirable. We would like to emit the subexpr as is. // Omitting the parentheses, however, could cause change in the semantics of the generated // code if the casted expression has a lower precedence than the rest of the expression, e.g.: @@ -39434,7 +37746,6 @@ var ts; operand.kind !== 181 /* DeleteExpression */ && operand.kind !== 186 /* PostfixUnaryExpression */ && operand.kind !== 175 /* NewExpression */ && - !(operand.kind === 187 /* BinaryExpression */ && node.expression.kind === 195 /* AsExpression */) && !(operand.kind === 174 /* CallExpression */ && node.parent.kind === 175 /* NewExpression */) && !(operand.kind === 179 /* FunctionExpression */ && node.parent.kind === 174 /* CallExpression */) && !(operand.kind === 8 /* NumericLiteral */ && node.parent.kind === 172 /* PropertyAccessExpression */)) { @@ -39476,7 +37787,7 @@ var ts; if (modulekind === ts.ModuleKind.System || node.kind !== 69 /* Identifier */ || ts.nodeIsSynthesized(node)) { return false; } - return !exportEquals && exportSpecifiers && node.text in exportSpecifiers; + return !exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, node.text); } function emitPrefixUnaryExpression(node) { var isPlusPlusOrMinusMinus = (node.operator === 41 /* PlusPlusToken */ @@ -39569,7 +37880,7 @@ var ts; * if we should also export the value after its it changed * - check if node is a source level declaration to emit it differently, * i.e non-exported variable statement 'var x = 1' is hoisted so - * when we emit variable statement 'var' should be dropped. + * we we emit variable statement 'var' should be dropped. */ function isSourceFileLevelDeclarationInSystemJsModule(node, isExported) { if (!node || !isCurrentFileSystemExternalModule()) { @@ -40021,12 +38332,12 @@ var ts; // Don't initialize seen unless we have at least one element. // Emit a comma to separate for all but the first element. if (!seen) { - seen = ts.createMap(); + seen = {}; } else { write(", "); } - if (!(id.text in seen)) { + if (!ts.hasProperty(seen, id.text)) { emit(id); seen[id.text] = id.text; } @@ -40550,7 +38861,7 @@ var ts; } if (convertedLoopState) { if (!convertedLoopState.labels) { - convertedLoopState.labels = ts.createMap(); + convertedLoopState.labels = {}; } convertedLoopState.labels[node.label.text] = node.label.text; } @@ -40653,7 +38964,7 @@ var ts; if (modulekind === ts.ModuleKind.System) { return; } - if (!exportEquals && exportSpecifiers && name.text in exportSpecifiers) { + if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { for (var _a = 0, _b = exportSpecifiers[name.text]; _a < _b.length; _a++) { var specifier = _b[_a]; writeLine(); @@ -41191,13 +39502,12 @@ var ts; } function emitRestParameter(node) { if (languageVersion < 2 /* ES6 */ && ts.hasDeclaredRestParameter(node)) { - var restParam = node.parameters[node.parameters.length - 1]; + var restIndex = node.parameters.length - 1; + var restParam = node.parameters[restIndex]; // A rest parameter cannot have a binding pattern, so let's just ignore it if it does. if (ts.isBindingPattern(restParam.name)) { return; } - var skipThisCount = node.parameters.length && node.parameters[0].name.originalKeywordKind === 97 /* ThisKeyword */ ? 1 : 0; - var restIndex = node.parameters.length - 1 - skipThisCount; var tempName = createTempVariable(268435456 /* _i */).text; writeLine(); emitLeadingComments(restParam); @@ -41332,7 +39642,7 @@ var ts; write("("); if (node) { var parameters = node.parameters; - var skipCount = node.parameters.length && node.parameters[0].name.originalKeywordKind === 97 /* ThisKeyword */ ? 1 : 0; + var skipCount = node.parameters.length && node.parameters[0].name.text === "this" ? 1 : 0; var omitCount = languageVersion < 2 /* ES6 */ && ts.hasDeclaredRestParameter(node) ? 1 : 0; emitList(parameters, skipCount, parameters.length - omitCount - skipCount, /*multiLine*/ false, /*trailingComma*/ false); } @@ -41854,22 +40164,18 @@ var ts; emitSignatureParameters(ctor); } else { - // The ES2015 spec specifies in 14.5.14. Runtime Semantics: ClassDefinitionEvaluation: - // If constructor is empty, then - // If ClassHeritag_eopt is present and protoParent is not null, then - // Let constructor be the result of parsing the source text - // constructor(...args) { super (...args);} - // using the syntactic grammar with the goal symbol MethodDefinition[~Yield]. + // Based on EcmaScript6 section 14.5.14: Runtime Semantics: ClassDefinitionEvaluation. + // If constructor is empty, then, + // If ClassHeritageopt is present, then + // Let constructor be the result of parsing the String "constructor(... args){ super (...args);}" using the syntactic grammar with the goal symbol MethodDefinition. // Else, - // Let constructor be the result of parsing the source text - // constructor( ){ } - // using the syntactic grammar with the goal symbol MethodDefinition[~Yield]. - // - // While we could emit the '...args' rest parameter, certain later tools in the pipeline might - // downlevel the '...args' portion less efficiently by naively copying the contents of 'arguments' to an array. - // Instead, we'll avoid using a rest parameter and spread into the super call as - // 'super(...arguments)' instead of 'super(...args)', as you can see below. - write("()"); + // Let constructor be the result of parsing the String "constructor( ){ }" using the syntactic grammar with the goal symbol MethodDefinition + if (baseTypeElement) { + write("(...args)"); + } + else { + write("()"); + } } } var startIndex = 0; @@ -41903,8 +40209,7 @@ var ts; write("_super.apply(this, arguments);"); } else { - // See comment above on using '...arguments' instead of '...args'. - write("super(...arguments);"); + write("super(...args);"); } emitEnd(baseTypeElement); } @@ -42042,13 +40347,13 @@ var ts; if (isES6ExportedDeclaration(node) && !(node.flags & 512 /* Default */) && decoratedClassAlias === undefined) { write("export "); } + if (!isHoistedDeclarationInSystemModule) { + write("let "); + } if (decoratedClassAlias !== undefined) { - write("let " + decoratedClassAlias); + write("" + decoratedClassAlias); } else { - if (!isHoistedDeclarationInSystemModule) { - write("let "); - } emitDeclarationName(node); } write(" = "); @@ -42063,17 +40368,11 @@ var ts; // If the class has static properties, and it's a class expression, then we'll need // to specialize the emit a bit. for a class expression of the form: // - // (class C { static a = 1; static b = 2; ... }) + // class C { static a = 1; static b = 2; ... } // // We'll emit: // - // ((C_1 = class C { - // // Normal class body - // }, - // C_1.a = 1, - // C_1.b = 2, - // C_1)); - // var C_1; + // (_temp = class C { ... }, _temp.a = 1, _temp.b = 2, _temp) // // This keeps the expression as an expression, while ensuring that the static parts // of it have been initialized by the time it is used. @@ -42081,7 +40380,7 @@ var ts; var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 192 /* ClassExpression */; var generatedName; if (isClassExpressionWithStaticProperties) { - generatedName = node.name ? getGeneratedNameForNode(node.name) : makeUniqueName("classExpression"); + generatedName = getGeneratedNameForNode(node.name); var synthesizedNode = ts.createSynthesizedNode(69 /* Identifier */); synthesizedNode.text = generatedName; recordTempDeclaration(synthesizedNode); @@ -42526,7 +40825,7 @@ var ts; write("Boolean"); return; case 132 /* StringKeyword */: - case 166 /* LiteralType */: + case 166 /* StringLiteralType */: write("String"); return; case 130 /* NumberKeyword */: @@ -42624,11 +40923,10 @@ var ts; } if (valueDeclaration) { var parameters = valueDeclaration.parameters; - var skipThisCount = parameters.length && parameters[0].name.originalKeywordKind === 97 /* ThisKeyword */ ? 1 : 0; var parameterCount = parameters.length; - if (parameterCount > skipThisCount) { - for (var i = skipThisCount; i < parameterCount; i++) { - if (i > skipThisCount) { + if (parameterCount > 0) { + for (var i = 0; i < parameterCount; i++) { + if (i > 0) { write(", "); } if (parameters[i].dotDotDotToken) { @@ -42896,7 +41194,7 @@ var ts; * Here we check if alternative name was provided for a given moduleName and return it if possible. */ function tryRenameExternalModule(moduleName) { - if (renamedDependencies && moduleName.text in renamedDependencies) { + if (renamedDependencies && ts.hasProperty(renamedDependencies, moduleName.text)) { return "\"" + renamedDependencies[moduleName.text] + "\""; } return undefined; @@ -43005,7 +41303,7 @@ var ts; // import { x, y } from "foo" // import d, * as x from "foo" // import d, { x, y } from "foo" - var isNakedImport = node.kind === 230 /* ImportDeclaration */ && !node.importClause; + var isNakedImport = 230 /* ImportDeclaration */ && !node.importClause; if (!isNakedImport) { write(varOrConst); write(getGeneratedNameForNode(node)); @@ -43216,7 +41514,7 @@ var ts; } function collectExternalModuleInfo(sourceFile) { externalImports = []; - exportSpecifiers = ts.createMap(); + exportSpecifiers = {}; exportEquals = undefined; hasExportStarsToExportValues = false; for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) { @@ -43344,7 +41642,7 @@ var ts; return undefined; } // local names set should only be added if we have anything exported - if (!exportedDeclarations && !ts.someProperties(exportSpecifiers)) { + if (!exportedDeclarations && ts.isEmpty(exportSpecifiers)) { // no exported declarations (export var ...) or export specifiers (export {x}) // check if we have any non star export declarations. var hasExportDeclarationWithExportClause = false; @@ -43467,7 +41765,7 @@ var ts; if (hoistedVars) { writeLine(); write("var "); - var seen = ts.createMap(); + var seen = {}; for (var i = 0; i < hoistedVars.length; i++) { var local = hoistedVars[i]; var name_32 = local.kind === 69 /* Identifier */ @@ -43476,7 +41774,7 @@ var ts; if (name_32) { // do not emit duplicate entries (in case of declaration merging) in the list of hoisted variables var text = ts.unescapeIdentifier(name_32.text); - if (text in seen) { + if (ts.hasProperty(seen, text)) { continue; } else { @@ -43792,7 +42090,7 @@ var ts; write("System.register("); writeModuleName(node, emitRelativePathAsModuleName); write("["); - var groupIndices = ts.createMap(); + var groupIndices = {}; var dependencyGroups = []; for (var i = 0; i < externalImports.length; i++) { var text = getExternalModuleNameText(externalImports[i], emitRelativePathAsModuleName); @@ -43802,7 +42100,7 @@ var ts; // text should be quoted string // for deduplication purposes in key remove leading and trailing quotes so 'a' and "a" will be considered the same var key = text.substr(1, text.length - 2); - if (key in groupIndices) { + if (ts.hasProperty(groupIndices, key)) { // deduplicate/group entries in dependency list by the dependency name var groupIndex = groupIndices[key]; dependencyGroups[groupIndex].push(externalImports[i]); @@ -44603,26 +42901,22 @@ var ts; } var _a, _b; } - function emitFile(_a, sourceFiles, isBundledEmit, emitOnlyDtsFiles) { + function emitFile(_a, sourceFiles, isBundledEmit) { var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath; - if (!emitOnlyDtsFiles) { - // Make sure not to write js File and source map file if any of them cannot be written - if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { - emitJavaScript(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); - } - else { - emitSkipped = true; - } + // Make sure not to write js File and source map file if any of them cannot be written + if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { + emitJavaScript(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + } + else { + emitSkipped = true; } if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; + emitSkipped = ts.writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; } if (!emitSkipped && emittedFilesList) { - if (!emitOnlyDtsFiles) { - emittedFilesList.push(jsFilePath); - if (sourceMapFilePath) { - emittedFilesList.push(sourceMapFilePath); - } + emittedFilesList.push(jsFilePath); + if (sourceMapFilePath) { + emittedFilesList.push(sourceMapFilePath); } if (declarationFilePath) { emittedFilesList.push(declarationFilePath); @@ -44637,13 +42931,17 @@ var ts; /// var ts; (function (ts) { + /* @internal */ ts.programTime = 0; + /* @internal */ ts.emitTime = 0; + /* @internal */ ts.ioReadTime = 0; + /* @internal */ ts.ioWriteTime = 0; /** The version of the TypeScript compiler release */ - ts.version = "2.0.5"; + ts.version = "2.0.0"; var emptyArray = []; - function findConfigFile(searchPath, fileExists, configName) { - if (configName === void 0) { configName = "tsconfig.json"; } + var defaultTypeRoots = ["node_modules/@types"]; + function findConfigFile(searchPath, fileExists) { while (true) { - var fileName = ts.combinePaths(searchPath, configName); + var fileName = ts.combinePaths(searchPath, "tsconfig.json"); if (fileExists(fileName)) { return fileName; } @@ -44700,8 +42998,94 @@ var ts; return ts.getNormalizedPathFromPathComponents(commonPathComponents); } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; + function trace(host, message) { + host.trace(ts.formatMessage.apply(undefined, arguments)); + } + function isTraceEnabled(compilerOptions, host) { + return compilerOptions.traceResolution && host.trace !== undefined; + } + /* @internal */ + function hasZeroOrOneAsteriskCharacter(str) { + var seenAsterisk = false; + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) === 42 /* asterisk */) { + if (!seenAsterisk) { + seenAsterisk = true; + } + else { + // have already seen asterisk + return false; + } + } + } + return true; + } + ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; + function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { + return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; + } + function moduleHasNonRelativeName(moduleName) { + if (ts.isRootedDiskPath(moduleName)) { + return false; + } + var i = moduleName.lastIndexOf("./", 1); + var startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === 46 /* dot */); + return !startsWithDotSlashOrDotDotSlash; + } + function tryReadTypesSection(packageJsonPath, baseDirectory, state) { + var jsonContent; + try { + var jsonText = state.host.readFile(packageJsonPath); + jsonContent = jsonText ? JSON.parse(jsonText) : {}; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + jsonContent = {}; + } + var typesFile; + var fieldName; + // first try to read content of 'typings' section (backward compatibility) + if (jsonContent.typings) { + if (typeof jsonContent.typings === "string") { + fieldName = "typings"; + typesFile = jsonContent.typings; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, "typings", typeof jsonContent.typings); + } + } + } + // then read 'types' + if (!typesFile && jsonContent.types) { + if (typeof jsonContent.types === "string") { + fieldName = "types"; + typesFile = jsonContent.types; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, "types", typeof jsonContent.types); + } + } + } + if (typesFile) { + var typesFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath); + } + return typesFilePath; + } + // Use the main module for inferring types if no types package specified and the allowJs is set + if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); + } + var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); + return mainFilePath; + } + return undefined; + } var typeReferenceExtensions = [".d.ts"]; - // @internal function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { return options.typeRoots; @@ -44713,39 +43097,18 @@ var ts; else if (host.getCurrentDirectory) { currentDirectory = host.getCurrentDirectory(); } - return currentDirectory && getDefaultTypeRoots(currentDirectory, host); - } - ts.getEffectiveTypeRoots = getEffectiveTypeRoots; - /** - * Returns the path to every node_modules/@types directory from some ancestor directory. - * Returns undefined if there are none. - */ - function getDefaultTypeRoots(currentDirectory, host) { - if (!host.directoryExists) { - return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + if (!currentDirectory) { + return undefined; } - var typeRoots; - while (true) { - var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes); - if (host.directoryExists(atTypes)) { - (typeRoots || (typeRoots = [])).push(atTypes); - } - var parent_15 = ts.getDirectoryPath(currentDirectory); - if (parent_15 === currentDirectory) { - break; - } - currentDirectory = parent_15; - } - return typeRoots; + return ts.map(defaultTypeRoots, function (d) { return ts.combinePaths(currentDirectory, d); }); } - var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); /** * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups * is assumed to be the same as root directory of the project. */ function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { - var traceEnabled = ts.isTraceEnabled(options, host); + var traceEnabled = isTraceEnabled(options, host); var moduleResolutionState = { compilerOptions: options, host: host, @@ -44756,18 +43119,18 @@ var ts; if (traceEnabled) { if (containingFile === undefined) { if (typeRoots === undefined) { - ts.trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); } else { - ts.trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); } } else { if (typeRoots === undefined) { - ts.trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); } else { - ts.trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); } } } @@ -44775,17 +43138,17 @@ var ts; // Check primary library paths if (typeRoots && typeRoots.length) { if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); } var primarySearchPaths = typeRoots; for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) { var typeRoot = primarySearchPaths_1[_i]; var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); - var resolvedFile_1 = ts.loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !ts.directoryProbablyExists(candidateDirectory, host), moduleResolutionState); + var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState); if (resolvedFile_1) { if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true); + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true); } return { resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 }, @@ -44796,7 +43159,7 @@ var ts; } else { if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); + trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); } } var resolvedFile; @@ -44807,21 +43170,21 @@ var ts; if (initialLocationForSecondaryLookup !== undefined) { // check secondary locations if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); + trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - resolvedFile = ts.loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*checkOneLevel*/ false); + resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState); if (traceEnabled) { if (resolvedFile) { - ts.trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); } else { - ts.trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); } } } else { if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); + trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); } } return { @@ -44832,8 +43195,494 @@ var ts; }; } ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; + function resolveModuleName(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + } + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + if (traceEnabled) { + trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + var result; + switch (moduleResolution) { + case ts.ModuleResolutionKind.NodeJs: + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); + break; + case ts.ModuleResolutionKind.Classic: + result = classicNameResolver(moduleName, containingFile, compilerOptions, host); + break; + } + if (traceEnabled) { + if (result.resolvedModule) { + trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); + } + else { + trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); + } + } + return result; + } + ts.resolveModuleName = resolveModuleName; + /** + * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to + * mitigate differences between design time structure of the project and its runtime counterpart so the same import name + * can be resolved successfully by TypeScript compiler and runtime module loader. + * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will + * fallback to standard resolution routine. + * + * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative + * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will + * be '/a/b/c/d' + * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names + * will be resolved based on the content of the module name. + * Structure of 'paths' compiler options + * 'paths': { + * pattern-1: [...substitutions], + * pattern-2: [...substitutions], + * ... + * pattern-n: [...substitutions] + * } + * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against + * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case. + * If pattern contains '*' then to match pattern "*" module name must start with the and end with . + * denotes part of the module name between and . + * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked. + * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module + * from the candidate location. + * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every + * substitution in the list and replace '*' with string. If candidate location is not rooted it + * will be converted to absolute using baseUrl. + * For example: + * baseUrl: /a/b/c + * "paths": { + * // match all module names + * "*": [ + * "*", // use matched name as is, + * // will be looked as /a/b/c/ + * + * "folder1/*" // substitution will convert matched name to 'folder1/', + * // since it is not rooted then final candidate location will be /a/b/c/folder1/ + * ], + * // match module names that start with 'components/' + * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/ to '/root/components/folder1/', + * // it is rooted so it will be final candidate location + * } + * + * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if + * they were in the same location. For example lets say there are two files + * '/local/src/content/file1.ts' + * '/shared/components/contracts/src/content/protocols/file2.ts' + * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so + * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime. + * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all + * root dirs were merged together. + * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ]. + * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file: + * '/local/src/content/protocols/file2' and try to load it - failure. + * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will + * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining + * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. + */ + function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (moduleHasNonRelativeName(moduleName)) { + return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); + } + else { + return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); + } + } + function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.rootDirs) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var matchedRootDir; + var matchedNormalizedPrefix; + for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { + var rootDir = _a[_i]; + // rootDirs are expected to be absolute + // in case of tsconfig.json this will happen automatically - compiler will expand relative names + // using location of tsconfig.json as base location + var normalizedRoot = ts.normalizePath(rootDir); + if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { + normalizedRoot += ts.directorySeparator; + } + var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && + (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); + } + if (isLongestMatchingPrefix) { + matchedNormalizedPrefix = normalizedRoot; + matchedRootDir = rootDir; + } + } + if (matchedNormalizedPrefix) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); + } + var suffix = candidate.substr(matchedNormalizedPrefix.length); + // first - try to load from a initial location + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); + } + // then try to resolve using remaining entries in rootDirs + for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { + var rootDir = _c[_b]; + if (rootDir === matchedRootDir) { + // skip the initially matched entry + continue; + } + var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); + } + var baseDirectory = ts.getDirectoryPath(candidate_1); + var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + if (resolvedFileName_1) { + return resolvedFileName_1; + } + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); + } + } + return undefined; + } + function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.baseUrl) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + } + // string is for exact match + var matchedPattern = undefined; + if (state.compilerOptions.paths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + matchedPattern = matchPatternOrExact(ts.getKeys(state.compilerOptions.paths), moduleName); + } + if (matchedPattern) { + var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName); + var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) { + var subst = _a[_i]; + var path = matchedStar ? subst.replace("*", matchedStar) : subst; + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + } + return undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); + } + return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + } + } + /** + * patternStrings contains both pattern strings (containing "*") and regular strings. + * Return an exact match if possible, or a pattern match, or undefined. + * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.) + */ + function matchPatternOrExact(patternStrings, candidate) { + var patterns = []; + for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { + var patternString = patternStrings_1[_i]; + var pattern = tryParsePattern(patternString); + if (pattern) { + patterns.push(pattern); + } + else if (patternString === candidate) { + // pattern was matched as is - no need to search further + return patternString; + } + } + return findBestPatternMatch(patterns, function (_) { return _; }, candidate); + } + function patternText(_a) { + var prefix = _a.prefix, suffix = _a.suffix; + return prefix + "*" + suffix; + } + /** + * Given that candidate matches pattern, returns the text matching the '*'. + * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar" + */ + function matchedText(pattern, candidate) { + ts.Debug.assert(isPatternMatch(pattern, candidate)); + return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); + } + /** Return the object corresponding to the best pattern to match `candidate`. */ + /* @internal */ + function findBestPatternMatch(values, getPattern, candidate) { + var matchedValue = undefined; + // use length of prefix as betterness criteria + var longestMatchPrefixLength = -1; + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var v = values_1[_i]; + var pattern = getPattern(v); + if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { + longestMatchPrefixLength = pattern.prefix.length; + matchedValue = v; + } + } + return matchedValue; + } + ts.findBestPatternMatch = findBestPatternMatch; + function isPatternMatch(_a, candidate) { + var prefix = _a.prefix, suffix = _a.suffix; + return candidate.length >= prefix.length + suffix.length && + ts.startsWith(candidate, prefix) && + ts.endsWith(candidate, suffix); + } + /* @internal */ + function tryParsePattern(pattern) { + // This should be verified outside of here and a proper error thrown. + ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); + var indexOfStar = pattern.indexOf("*"); + return indexOfStar === -1 ? undefined : { + prefix: pattern.substr(0, indexOfStar), + suffix: pattern.substr(indexOfStar + 1) + }; + } + ts.tryParsePattern = tryParsePattern; + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { + var containingDirectory = ts.getDirectoryPath(containingFile); + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var traceEnabled = isTraceEnabled(compilerOptions, host); + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); + var isExternalLibraryImport = false; + if (!resolvedFileName) { + if (moduleHasNonRelativeName(moduleName)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); + } + resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state); + isExternalLibraryImport = resolvedFileName !== undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); + } + } + if (resolvedFileName && host.realpath) { + var originalFileName = resolvedFileName; + resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName)); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); + } + } + return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; + function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); + } + var resolvedFileName = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); + return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); + } + /* @internal */ + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + /** + * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary + * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. + */ + function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + // First try to keep/add an extension: importing "./foo.ts" can be matched by a file "./foo.ts", and "./foo" by "./foo.d.ts" + var resolvedByAddingOrKeepingExtension = loadModuleFromFileWorker(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); + if (resolvedByAddingOrKeepingExtension) { + return resolvedByAddingOrKeepingExtension; + } + // Then try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one, e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" + if (ts.hasJavaScriptFileExtension(candidate)) { + var extensionless = ts.removeFileExtension(candidate); + if (state.traceEnabled) { + var extension = candidate.substring(extensionless.length); + trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); + } + return loadModuleFromFileWorker(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); + } + } + function loadModuleFromFileWorker(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing + var directory = ts.getDirectoryPath(candidate); + if (directory) { + onlyRecordFailures = !directoryProbablyExists(directory, state.host); + } + } + return ts.forEach(extensions, tryLoad); + function tryLoad(ext) { + if (state.skipTsx && ts.isJsxOrTsxExtension(ext)) { + return undefined; + } + var fileName = ts.fileExtensionIs(candidate, ext) ? candidate : candidate + ext; + if (!onlyRecordFailures && state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); + } + return fileName; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); + } + failedLookupLocation.push(fileName); + return undefined; + } + } + } + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { + var packageJsonPath = ts.combinePaths(candidate, "package.json"); + var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); + if (directoryExists && state.host.fileExists(packageJsonPath)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); + if (typesFile) { + var result = loadModuleFromFile(typesFile, extensions, failedLookupLocation, !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host), state); + if (result) { + return result; + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field); + } + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); + } + // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results + failedLookupLocation.push(packageJsonPath); + } + return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); + } + function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { + var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); + var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions); + var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); + if (result) { + return result; + } + result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); + if (result) { + return result; + } + } + function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state) { + directory = ts.normalizeSlashes(directory); + while (true) { + var baseName = ts.getBaseFileName(directory); + if (baseName !== "node_modules") { + // Try to load source from the package + var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); + if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { + // Always prefer a TypeScript (.ts, .tsx, .d.ts) file shipped with the package + return packageResult; + } + else { + // Else prefer a types package over non-TypeScript results (e.g. JavaScript files) + var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); + if (typesResult || packageResult) { + return typesResult || packageResult; + } + } + } + var parentPath = ts.getDirectoryPath(directory); + if (parentPath === directory) { + break; + } + directory = parentPath; + } + return undefined; + } + function classicNameResolver(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; + var failedLookupLocations = []; + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var containingDirectory = ts.getDirectoryPath(containingFile); + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); + if (resolvedFileName) { + return createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/ false, failedLookupLocations); + } + var referencedSourceFile; + if (moduleHasNonRelativeName(moduleName)) { + while (true) { + var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); + if (referencedSourceFile) { + break; + } + var parentPath = ts.getDirectoryPath(containingDirectory); + if (parentPath === containingDirectory) { + break; + } + containingDirectory = parentPath; + } + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); + } + return referencedSourceFile + ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } + : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; + } + ts.classicNameResolver = classicNameResolver; + /* @internal */ + ts.defaultInitCompilerOptions = { + module: ts.ModuleKind.CommonJS, + target: 1 /* ES5 */, + noImplicitAny: false, + sourceMap: false + }; function createCompilerHost(options, setParentNodes) { - var existingDirectories = ts.createMap(); + var existingDirectories = {}; function getCanonicalFileName(fileName) { // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. // otherwise use toLowerCase as a canonical form. @@ -44844,10 +43693,9 @@ var ts; function getSourceFile(fileName, languageVersion, onError) { var text; try { - ts.performance.mark("beforeIORead"); + var start = new Date().getTime(); text = ts.sys.readFile(fileName, options.charset); - ts.performance.mark("afterIORead"); - ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); + ts.ioReadTime += new Date().getTime() - start; } catch (e) { if (onError) { @@ -44860,7 +43708,7 @@ var ts; return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined; } function directoryExists(directoryPath) { - if (directoryPath in existingDirectories) { + if (ts.hasProperty(existingDirectories, directoryPath)) { return true; } if (ts.sys.directoryExists(directoryPath)) { @@ -44879,11 +43727,11 @@ var ts; var outputFingerprints; function writeFileIfUpdated(fileName, data, writeByteOrderMark) { if (!outputFingerprints) { - outputFingerprints = ts.createMap(); + outputFingerprints = {}; } var hash = ts.sys.createHash(data); var mtimeBefore = ts.sys.getModifiedTime(fileName); - if (mtimeBefore && fileName in outputFingerprints) { + if (mtimeBefore && ts.hasProperty(outputFingerprints, fileName)) { var fingerprint = outputFingerprints[fileName]; // If output has not been changed, and the file has no external modification if (fingerprint.byteOrderMark === writeByteOrderMark && @@ -44902,7 +43750,7 @@ var ts; } function writeFile(fileName, data, writeByteOrderMark, onError) { try { - ts.performance.mark("beforeIOWrite"); + var start = new Date().getTime(); ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { writeFileIfUpdated(fileName, data, writeByteOrderMark); @@ -44910,8 +43758,7 @@ var ts; else { ts.sys.writeFile(fileName, data, writeByteOrderMark); } - ts.performance.mark("afterIOWrite"); - ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + ts.ioWriteTime += new Date().getTime() - start; } catch (e) { if (onError) { @@ -44950,22 +43797,6 @@ var ts; return ts.sortAndDeduplicateDiagnostics(diagnostics); } ts.getPreEmitDiagnostics = getPreEmitDiagnostics; - function formatDiagnostics(diagnostics, host) { - var output = ""; - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; - if (diagnostic.file) { - var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; - var fileName = diagnostic.file.fileName; - var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }); - output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): "; - } - var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); - output += category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine(); - } - return output; - } - ts.formatDiagnostics = formatDiagnostics; function flattenDiagnosticMessageText(messageText, newLine) { if (typeof messageText === "string") { return messageText; @@ -44994,25 +43825,33 @@ var ts; return []; } var resolutions = []; - var cache = ts.createMap(); + var cache = {}; for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { var name_34 = names_1[_i]; - var result = name_34 in cache - ? cache[name_34] - : cache[name_34] = loader(name_34, containingFile); + var result = void 0; + if (ts.hasProperty(cache, name_34)) { + result = cache[name_34]; + } + else { + result = loader(name_34, containingFile); + cache[name_34] = result; + } resolutions.push(result); } return resolutions; } + function getInferredTypesRoot(options, rootFiles, host) { + return computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } /** - * Given a set of options, returns the set of type directive names + * Given a set of options and a set of root files, returns the set of type directive names * that should be included for this program automatically. * This list could either come from the config file, * or from enumerating the types root + initial secondary types lookup location. * More type directives might appear in the program later as a result of loading actual source files; * this list is only the set of defaults that are implicitly included. */ - function getAutomaticTypeDirectiveNames(options, host) { + function getAutomaticTypeDirectiveNames(options, rootFiles, host) { // Use explicit type list from tsconfig.json if (options.types) { return options.types; @@ -45025,17 +43864,7 @@ var ts; for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { var root = typeRoots_1[_i]; if (host.directoryExists(root)) { - for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { - var typeDirectivePath = _b[_a]; - var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = ts.pathToPackageJson(ts.combinePaths(root, normalized)); - // tslint:disable-next-line:no-null-keyword - var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null; - if (!isNotNeededPackage) { - // Return just the type directive names - result.push(ts.getBaseFileName(normalized)); - } - } + result = result.concat(host.getDirectories(root)); } } } @@ -45050,7 +43879,7 @@ var ts; var diagnosticsProducingTypeChecker; var noDiagnosticsTypeChecker; var classifiableNames; - var resolvedTypeReferenceDirectives = ts.createMap(); + var resolvedTypeReferenceDirectives = {}; var fileProcessingDiagnostics = ts.createDiagnosticCollection(); // The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules. // This works as imported modules are discovered recursively in a depth first manner, specifically: @@ -45059,14 +43888,14 @@ var ts; // - This calls resolveModuleNames, and then calls findSourceFile for each resolved module. // As all these operations happen - and are nested - within the createProgram call, they close over the below variables. // The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses. - var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; - var currentNodeModulesDepth = 0; + var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 2; + var currentNodeModulesJsDepth = 0; // If a module has some of its imports skipped due to being at the depth limit under node_modules, then track // this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed. - var modulesWithElidedImports = ts.createMap(); - // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled. - var sourceFilesFoundSearchingNodeModules = ts.createMap(); - ts.performance.mark("beforeProgram"); + var modulesWithElidedImports = {}; + // Track source files that are JavaScript files found by searching under node_modules, as these shouldn't be compiled. + var sourceFilesFoundSearchingNodeModules = {}; + var start = new Date().getTime(); host = host || createCompilerHost(options); var skipDefaultLib = options.noLib; var programDiagnostics = ts.createDiagnosticCollection(); @@ -45079,7 +43908,7 @@ var ts; resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }; } else { - var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; + var loader_1 = function (moduleName, containingFile) { return resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(moduleNames, containingFile, loader_1); }; } var resolveTypeReferenceDirectiveNamesWorker; @@ -45097,10 +43926,10 @@ var ts; if (!tryReuseStructureFromOldProgram()) { ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false); }); // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders - var typeReferences = getAutomaticTypeDirectiveNames(options, host); + var typeReferences = getAutomaticTypeDirectiveNames(options, rootNames, host); if (typeReferences) { - // This containingFilename needs to match with the one used in managed-side - var containingFilename = ts.combinePaths(host.getCurrentDirectory(), "__inferred type names__.ts"); + var inferredRoot = getInferredTypesRoot(options, rootNames, host); + var containingFilename = ts.combinePaths(inferredRoot, "__inferred type names__.ts"); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i]); @@ -45148,12 +43977,10 @@ var ts; getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, - getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, - dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker + getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; } }; verifyCompilerOptions(); - ts.performance.mark("afterProgram"); - ts.performance.measure("Program", "beforeProgram", "afterProgram"); + ts.programTime += new Date().getTime() - start; return program; function getCommonSourceDirectory() { if (typeof commonSourceDirectory === "undefined") { @@ -45177,10 +44004,10 @@ var ts; if (!classifiableNames) { // Initialize a checker so that all our files are bound. getTypeChecker(); - classifiableNames = ts.createMap(); + classifiableNames = {}; for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { var sourceFile = files_2[_i]; - ts.copyProperties(sourceFile.classifiableNames, classifiableNames); + ts.copyMap(sourceFile.classifiableNames, classifiableNames); } } return classifiableNames; @@ -45205,7 +44032,7 @@ var ts; (oldOptions.maxNodeModuleJsDepth !== options.maxNodeModuleJsDepth) || !ts.arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) || !ts.arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) || - !ts.equalOwnProperties(oldOptions.paths, options.paths)) { + !ts.mapIsEqualTo(oldOptions.paths, options.paths)) { return false; } ts.Debug.assert(!oldProgram.structureIsReused); @@ -45311,7 +44138,7 @@ var ts; getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, - isSourceFileFromExternalLibrary: function (file) { return !!sourceFilesFoundSearchingNodeModules[file.path]; }, + isSourceFileFromExternalLibrary: function (file) { return !!ts.lookUp(sourceFilesFoundSearchingNodeModules, file.path); }, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked }; @@ -45319,19 +44146,17 @@ var ts; function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true)); } - function dropDiagnosticsProducingTypeChecker() { - diagnosticsProducingTypeChecker = undefined; - } function getTypeChecker() { return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false)); } - function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { - return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles); }); + function emit(sourceFile, writeFileCallback, cancellationToken) { + var _this = this; + return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); }); } function isEmitBlocked(emitFileName) { return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); } - function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { + function emitWorker(program, sourceFile, writeFileCallback, cancellationToken) { var declarationDiagnostics = []; if (options.noEmit) { return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; @@ -45362,10 +44187,9 @@ var ts; // files need to be type checked. And the way to specify that all files need to be type // checked is to not pass the file to getEmitResolver. var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); - ts.performance.mark("beforeEmit"); - var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles); - ts.performance.mark("afterEmit"); - ts.performance.measure("Emit", "beforeEmit", "afterEmit"); + var start = new Date().getTime(); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile); + ts.emitTime += new Date().getTime() - start; return emitResult; } function getSourceFile(fileName) { @@ -45517,16 +44341,16 @@ var ts; case 175 /* NewExpression */: var expression = node; if (expression.typeArguments && expression.typeArguments.length > 0) { - var start = expression.typeArguments.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, expression.typeArguments.end - start, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); + var start_2 = expression.typeArguments.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start_2, expression.typeArguments.end - start_2, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); return true; } break; case 142 /* Parameter */: var parameter = node; if (parameter.modifiers) { - var start = parameter.modifiers.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, parameter.modifiers.end - start, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); + var start_3 = parameter.modifiers.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start_3, parameter.modifiers.end - start_3, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); return true; } if (parameter.questionToken) { @@ -45570,8 +44394,8 @@ var ts; } function checkTypeParameters(typeParameters) { if (typeParameters) { - var start = typeParameters.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, typeParameters.end - start, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); + var start_4 = typeParameters.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start_4, typeParameters.end - start_4, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); return true; } return false; @@ -45779,19 +44603,9 @@ var ts; if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); } - // If the file was previously found via a node_modules search, but is now being processed as a root file, - // then everything it sucks in may also be marked incorrectly, and needs to be checked again. - if (file_1 && sourceFilesFoundSearchingNodeModules[file_1.path] && currentNodeModulesDepth == 0) { - sourceFilesFoundSearchingNodeModules[file_1.path] = false; - if (!options.noResolve) { - processReferencedFiles(file_1, ts.getDirectoryPath(fileName), isDefaultLib); - processTypeReferenceDirectives(file_1); - } - modulesWithElidedImports[file_1.path] = false; - processImportedModules(file_1, ts.getDirectoryPath(fileName)); - } - else if (file_1 && modulesWithElidedImports[file_1.path]) { - if (currentNodeModulesDepth < maxNodeModulesJsDepth) { + // See if we need to reprocess the imports due to prior skipped imports + if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) { + if (currentNodeModulesJsDepth < maxNodeModulesJsDepth) { modulesWithElidedImports[file_1.path] = false; processImportedModules(file_1, ts.getDirectoryPath(fileName)); } @@ -45809,7 +44623,6 @@ var ts; }); filesByName.set(path, file); if (file) { - sourceFilesFoundSearchingNodeModules[path] = (currentNodeModulesDepth > 0); file.path = path; if (host.useCaseSensitiveFileNames()) { // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case @@ -45845,16 +44658,14 @@ var ts; }); } function processTypeReferenceDirectives(file) { - // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. - var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); + var typeDirectives = ts.map(file.typeReferenceDirectives, function (l) { return l.fileName; }); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; var resolvedTypeReferenceDirective = resolutions[i]; // store resolved type directive on the file - var fileName = ref.fileName.toLocaleLowerCase(); - ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective); - processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end); + ts.setResolvedTypeReferenceDirective(file, ref.fileName, resolvedTypeReferenceDirective); + processTypeReferenceDirective(ref.fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end); } } function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, refFile, refPos, refEnd) { @@ -45875,7 +44686,7 @@ var ts; if (previousResolution) { var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) { - fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_to_resolve_this_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); } // don't overwrite previous resolution result saveResolution = false; @@ -45911,7 +44722,7 @@ var ts; function processImportedModules(file, basePath) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { - file.resolvedModules = ts.createMap(); + file.resolvedModules = {}; var moduleNames = ts.map(ts.concatenate(file.imports, file.moduleAugmentations), getTextOfLiteral); var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory)); for (var i = 0; i < moduleNames.length; i++) { @@ -45926,9 +44737,12 @@ var ts; var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport; var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName); if (isFromNodeModulesSearch) { - currentNodeModulesDepth++; + sourceFilesFoundSearchingNodeModules[resolvedPath] = true; } - var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth; + if (isJsFileFromNodeModules) { + currentNodeModulesJsDepth++; + } + var elideImport = isJsFileFromNodeModules && currentNodeModulesJsDepth > maxNodeModulesJsDepth; var shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport; if (elideImport) { modulesWithElidedImports[file.path] = true; @@ -45937,8 +44751,8 @@ var ts; findSourceFile(resolution.resolvedFileName, resolvedPath, /*isDefaultLib*/ false, /*isReference*/ false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); } - if (isFromNodeModulesSearch) { - currentNodeModulesDepth--; + if (isJsFileFromNodeModules) { + currentNodeModulesJsDepth--; } } } @@ -46006,18 +44820,15 @@ var ts; if (!ts.hasProperty(options.paths, key)) { continue; } - if (!ts.hasZeroOrOneAsteriskCharacter(key)) { + if (!hasZeroOrOneAsteriskCharacter(key)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); } if (ts.isArray(options.paths[key])) { - if (options.paths[key].length === 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key)); - } for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { var subst = _a[_i]; var typeOfSubst = typeof subst; if (typeOfSubst === "string") { - if (!ts.hasZeroOrOneAsteriskCharacter(subst)) { + if (!hasZeroOrOneAsteriskCharacter(subst)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key)); } } @@ -46059,7 +44870,7 @@ var ts; } var languageVersion = options.target || 0 /* ES3 */; var outFile = options.outFile || options.out; - var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); + var firstExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) ? f : undefined; }); if (options.isolatedModules) { if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES6 */) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); @@ -46070,19 +44881,19 @@ var ts; programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); } } - else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES6 */ && options.module === ts.ModuleKind.None) { + else if (firstExternalModuleSourceFile && languageVersion < 2 /* ES6 */ && options.module === ts.ModuleKind.None) { // We cannot use createDiagnosticFromNode because nodes do not have parents yet - var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); + var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } // Cannot specify module gen that isn't amd or system with --out if (outFile) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); } - else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) { - var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); + else if (options.module === undefined && firstExternalModuleSourceFile) { + var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); } } // there has to be common source directory if user specified --outdir || --sourceRoot @@ -46149,15 +44960,12 @@ var ts; /// var ts; (function (ts) { - /* @internal */ - ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; /* @internal */ ts.optionDeclarations = [ { name: "charset", type: "string" }, - ts.compileOnSaveCommandLineOption, { name: "declaration", shortName: "d", @@ -46174,10 +44982,6 @@ var ts; name: "diagnostics", type: "boolean" }, - { - name: "extendedDiagnostics", - type: "boolean" - }, { name: "emitBOM", type: "boolean" @@ -46208,10 +45012,10 @@ var ts; }, { name: "jsx", - type: ts.createMap({ + type: { "preserve": 1 /* Preserve */, "react": 2 /* React */ - }), + }, paramType: ts.Diagnostics.KIND, description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react }, @@ -46238,7 +45042,7 @@ var ts; { name: "module", shortName: "m", - type: ts.createMap({ + type: { "none": ts.ModuleKind.None, "commonjs": ts.ModuleKind.CommonJS, "amd": ts.ModuleKind.AMD, @@ -46246,16 +45050,16 @@ var ts; "umd": ts.ModuleKind.UMD, "es6": ts.ModuleKind.ES6, "es2015": ts.ModuleKind.ES2015 - }), + }, description: ts.Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015, paramType: ts.Diagnostics.KIND }, { name: "newLine", - type: ts.createMap({ + type: { "crlf": 0 /* CarriageReturnLineFeed */, "lf": 1 /* LineFeed */ - }), + }, description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix, paramType: ts.Diagnostics.NEWLINE }, @@ -46273,10 +45077,6 @@ var ts; type: "boolean", description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported }, - { - name: "noErrorTruncation", - type: "boolean" - }, { name: "noImplicitAny", type: "boolean", @@ -46290,12 +45090,12 @@ var ts; { name: "noUnusedLocals", type: "boolean", - description: ts.Diagnostics.Report_errors_on_unused_locals + description: ts.Diagnostics.Report_Errors_on_Unused_Locals }, { name: "noUnusedParameters", type: "boolean", - description: ts.Diagnostics.Report_errors_on_unused_parameters + description: ts.Diagnostics.Report_Errors_on_Unused_Parameters }, { name: "noLib", @@ -46401,12 +45201,12 @@ var ts; { name: "target", shortName: "t", - type: ts.createMap({ + type: { "es3": 0 /* ES3 */, "es5": 1 /* ES5 */, "es6": 2 /* ES6 */, "es2015": 2 /* ES2015 */ - }), + }, description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015, paramType: ts.Diagnostics.VERSION }, @@ -46435,10 +45235,10 @@ var ts; }, { name: "moduleResolution", - type: ts.createMap({ + type: { "node": ts.ModuleResolutionKind.NodeJs, "classic": ts.ModuleResolutionKind.Classic - }), + }, description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6 }, { @@ -46543,7 +45343,7 @@ var ts; type: "list", element: { name: "lib", - type: ts.createMap({ + type: { // JavaScript only "es5": "lib.es5.d.ts", "es6": "lib.es2015.d.ts", @@ -46568,7 +45368,7 @@ var ts; "es2016.array.include": "lib.es2016.array.include.d.ts", "es2017.object": "lib.es2017.object.d.ts", "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts" - }) + } }, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon }, @@ -46605,21 +45405,14 @@ var ts; } } ]; - /* @internal */ - ts.defaultInitCompilerOptions = { - module: ts.ModuleKind.CommonJS, - target: 1 /* ES5 */, - noImplicitAny: false, - sourceMap: false - }; var optionNameMapCache; /* @internal */ function getOptionNameMap() { if (optionNameMapCache) { return optionNameMapCache; } - var optionNameMap = ts.createMap(); - var shortOptionNames = ts.createMap(); + var optionNameMap = {}; + var shortOptionNames = {}; ts.forEach(ts.optionDeclarations, function (option) { optionNameMap[option.name.toLowerCase()] = option; if (option.shortName) { @@ -46633,9 +45426,9 @@ var ts; /* @internal */ function createCompilerDiagnosticForInvalidCustomType(opt) { var namesOfType = []; - for (var key in opt.type) { + ts.forEachKey(opt.type, function (key) { namesOfType.push(" '" + key + "'"); - } + }); return ts.createCompilerDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); } ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; @@ -46643,7 +45436,7 @@ var ts; function parseCustomTypeOption(opt, value, errors) { var key = trimString((value || "")).toLowerCase(); var map = opt.type; - if (key in map) { + if (ts.hasProperty(map, key)) { return map[key]; } else { @@ -46695,10 +45488,10 @@ var ts; else if (s.charCodeAt(0) === 45 /* minus */) { s = s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1).toLowerCase(); // Try to translate short option names to their full equivalents. - if (s in shortOptionNames) { + if (ts.hasProperty(shortOptionNames, s)) { s = shortOptionNames[s]; } - if (s in optionNameMap) { + if (ts.hasProperty(optionNameMap, s)) { var opt = optionNameMap[s]; if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -46800,101 +45593,16 @@ var ts; * @param fileName The path to the config file * @param jsonText The text of the config file */ - function parseConfigFileTextToJson(fileName, jsonText, stripComments) { - if (stripComments === void 0) { stripComments = true; } + function parseConfigFileTextToJson(fileName, jsonText) { try { - var jsonTextToParse = stripComments ? removeComments(jsonText) : jsonText; - return { config: /\S/.test(jsonTextToParse) ? JSON.parse(jsonTextToParse) : {} }; + var jsonTextWithoutComments = removeComments(jsonText); + return { config: /\S/.test(jsonTextWithoutComments) ? JSON.parse(jsonTextWithoutComments) : {} }; } catch (e) { return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) }; } } ts.parseConfigFileTextToJson = parseConfigFileTextToJson; - /** - * Generate tsconfig configuration when running command line "--init" - * @param options commandlineOptions to be generated into tsconfig.json - * @param fileNames array of filenames to be generated into tsconfig.json - */ - /* @internal */ - function generateTSConfig(options, fileNames) { - var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); - var configurations = { - compilerOptions: serializeCompilerOptions(compilerOptions) - }; - if (fileNames && fileNames.length) { - // only set the files property if we have at least one file - configurations.files = fileNames; - } - return configurations; - function getCustomTypeMapOfCommandLineOption(optionDefinition) { - if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { - // this is of a type CommandLineOptionOfPrimitiveType - return undefined; - } - else if (optionDefinition.type === "list") { - return getCustomTypeMapOfCommandLineOption(optionDefinition.element); - } - else { - return optionDefinition.type; - } - } - function getNameOfCompilerOptionValue(value, customTypeMap) { - // There is a typeMap associated with this command-line option so use it to map value back to its name - for (var key in customTypeMap) { - if (customTypeMap[key] === value) { - return key; - } - } - return undefined; - } - function serializeCompilerOptions(options) { - var result = ts.createMap(); - var optionsNameMap = getOptionNameMap().optionNameMap; - for (var name_35 in options) { - if (ts.hasProperty(options, name_35)) { - // tsconfig only options cannot be specified via command line, - // so we can assume that only types that can appear here string | number | boolean - switch (name_35) { - case "init": - case "watch": - case "version": - case "help": - case "project": - break; - default: - var value = options[name_35]; - var optionDefinition = optionsNameMap[name_35.toLowerCase()]; - if (optionDefinition) { - var customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition); - if (!customTypeMap) { - // There is no map associated with this compiler option then use the value as-is - // This is the case if the value is expect to be string, number, boolean or list of string - result[name_35] = value; - } - else { - if (optionDefinition.type === "list") { - var convertedValue = []; - for (var _i = 0, _a = value; _i < _a.length; _i++) { - var element = _a[_i]; - convertedValue.push(getNameOfCompilerOptionValue(element, customTypeMap)); - } - result[name_35] = convertedValue; - } - else { - // There is a typeMap associated with this command-line option so use it to map value back to its name - result[name_35] = getNameOfCompilerOptionValue(value, customTypeMap); - } - } - } - break; - } - } - } - return result; - } - } - ts.generateTSConfig = generateTSConfig; /** * Remove the comments from a json like text. * Comments can be single line comments (starting with # or //) or multiline comments using / * * / @@ -46919,6 +45627,9 @@ var ts; } return output; } + // Skip over any minified JavaScript files (ending in ".min.js") + // Skip over dotted files and folders as well + var ignoreFileNamePattern = /(\.min\.js$)|([\\/]\.[\w.])/; /** * Parse the contents of a config file (tsconfig.json). * @param json The contents of the config file to parse @@ -46934,15 +45645,13 @@ var ts; var typingOptions = convertTypingOptionsFromJsonWorker(json["typingOptions"], basePath, errors, configFileName); options.configFilePath = configFileName; var _a = getFileNames(errors), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; - var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); return { options: options, fileNames: fileNames, typingOptions: typingOptions, raw: json, errors: errors, - wildcardDirectories: wildcardDirectories, - compileOnSave: compileOnSave + wildcardDirectories: wildcardDirectories }; function getFileNames(errors) { var fileNames; @@ -46991,17 +45700,6 @@ var ts; } } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; - function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { - if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { - return false; - } - var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); - if (typeof result === "boolean" && result) { - return result; - } - return false; - } - ts.convertCompileOnSaveOptionFromJson = convertCompileOnSaveOptionFromJson; function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { var errors = []; var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); @@ -47015,7 +45713,7 @@ var ts; } ts.convertTypingOptionsFromJson = convertTypingOptionsFromJson; function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2 } : {}; + var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true } : {}; convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); return options; } @@ -47032,7 +45730,7 @@ var ts; } var optionNameMap = ts.arrayToMap(optionDeclarations, function (opt) { return opt.name; }); for (var id in jsonOptions) { - if (id in optionNameMap) { + if (ts.hasProperty(optionNameMap, id)) { var opt = optionNameMap[id]; defaultOptions[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors); } @@ -47067,7 +45765,7 @@ var ts; } function convertJsonOptionOfCustomType(opt, value, errors) { var key = value.toLowerCase(); - if (key in opt.type) { + if (ts.hasProperty(opt.type, key)) { return opt.type[key]; } else { @@ -47167,11 +45865,11 @@ var ts; // Literal file names (provided via the "files" array in tsconfig.json) are stored in a // file map with a possibly case insensitive key. We use this map later when when including // wildcard paths. - var literalFileMap = ts.createMap(); + var literalFileMap = {}; // Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a // file map with a possibly case insensitive key. We use this map to store paths matched // via wildcard, and to handle extension priority. - var wildcardFileMap = ts.createMap(); + var wildcardFileMap = {}; if (include) { include = validateSpecs(include, errors, /*allowTrailingRecursion*/ false); } @@ -47207,13 +45905,16 @@ var ts; if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { continue; } + if (ignoreFileNamePattern.test(file)) { + continue; + } // We may have included a wildcard path with a lower priority // extension due to the user-defined order of entries in the // "include" array. If there is a lower priority extension in the // same directory, we should remove it. removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); var key = keyMapper(file); - if (!(key in literalFileMap) && !(key in wildcardFileMap)) { + if (!ts.hasProperty(literalFileMap, key) && !ts.hasProperty(wildcardFileMap, key)) { wildcardFileMap[key] = file; } } @@ -47262,20 +45963,20 @@ var ts; // /a/b/a?z - Watch /a/b directly to catch any new file matching a?z var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); - var wildcardDirectories = ts.createMap(); + var wildcardDirectories = {}; if (include !== undefined) { var recursiveKeys = []; for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { var file = include_1[_i]; - var name_36 = ts.normalizePath(ts.combinePaths(path, file)); - if (excludeRegex && excludeRegex.test(name_36)) { + var name_35 = ts.normalizePath(ts.combinePaths(path, file)); + if (excludeRegex && excludeRegex.test(name_35)) { continue; } - var match = wildcardDirectoryPattern.exec(name_36); + var match = wildcardDirectoryPattern.exec(name_35); if (match) { var key = useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(); - var flags = watchRecursivePattern.test(name_36) ? 1 /* Recursive */ : 0 /* None */; - var existingFlags = wildcardDirectories[key]; + var flags = watchRecursivePattern.test(name_35) ? 1 /* Recursive */ : 0 /* None */; + var existingFlags = ts.getProperty(wildcardDirectories, key); if (existingFlags === undefined || existingFlags < flags) { wildcardDirectories[key] = flags; if (flags === 1 /* Recursive */) { @@ -47286,10 +45987,12 @@ var ts; } // Remove any subpaths under an existing recursively watched directory. for (var key in wildcardDirectories) { - for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { - var recursiveKey = recursiveKeys_1[_a]; - if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { - delete wildcardDirectories[key]; + if (ts.hasProperty(wildcardDirectories, key)) { + for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { + var recursiveKey = recursiveKeys_1[_a]; + if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { + delete wildcardDirectories[key]; + } } } } @@ -47310,7 +46013,7 @@ var ts; for (var i = 0 /* Highest */; i < adjustedExtensionPriority; i++) { var higherPriorityExtension = extensions[i]; var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); - if (higherPriorityPath in literalFiles || higherPriorityPath in wildcardFiles) { + if (ts.hasProperty(literalFiles, higherPriorityPath) || ts.hasProperty(wildcardFiles, higherPriorityPath)) { return true; } } @@ -47446,28 +46149,28 @@ var ts; switch (n.kind) { case 199 /* Block */: if (!ts.isFunctionBlock(n)) { - var parent_16 = n.parent; + var parent_15 = n.parent; var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile); var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile); // Check if the block is standalone, or 'attached' to some parent statement. // If the latter, we want to collapse the block, but consider its hint span // to be the entire span of the parent. - if (parent_16.kind === 204 /* DoStatement */ || - parent_16.kind === 207 /* ForInStatement */ || - parent_16.kind === 208 /* ForOfStatement */ || - parent_16.kind === 206 /* ForStatement */ || - parent_16.kind === 203 /* IfStatement */ || - parent_16.kind === 205 /* WhileStatement */ || - parent_16.kind === 212 /* WithStatement */ || - parent_16.kind === 252 /* CatchClause */) { - addOutliningSpan(parent_16, openBrace, closeBrace, autoCollapse(n)); + if (parent_15.kind === 204 /* DoStatement */ || + parent_15.kind === 207 /* ForInStatement */ || + parent_15.kind === 208 /* ForOfStatement */ || + parent_15.kind === 206 /* ForStatement */ || + parent_15.kind === 203 /* IfStatement */ || + parent_15.kind === 205 /* WhileStatement */ || + parent_15.kind === 212 /* WithStatement */ || + parent_15.kind === 252 /* CatchClause */) { + addOutliningSpan(parent_15, openBrace, closeBrace, autoCollapse(n)); break; } - if (parent_16.kind === 216 /* TryStatement */) { + if (parent_15.kind === 216 /* TryStatement */) { // Could be the try-block, or the finally-block. - var tryStatement = parent_16; + var tryStatement = parent_15; if (tryStatement.tryBlock === n) { - addOutliningSpan(parent_16, openBrace, closeBrace, autoCollapse(n)); + addOutliningSpan(parent_15, openBrace, closeBrace, autoCollapse(n)); break; } else if (tryStatement.finallyBlock === n) { @@ -47527,7 +46230,7 @@ var ts; (function (ts) { var NavigateTo; (function (NavigateTo) { - function getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount, excludeDts) { + function getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; // This means "compare in a case insensitive manner." @@ -47536,12 +46239,12 @@ var ts; ts.forEach(program.getSourceFiles(), function (sourceFile) { cancellationToken.throwIfCancellationRequested(); var nameToDeclarations = sourceFile.getNamedDeclarations(); - for (var name_37 in nameToDeclarations) { - var declarations = nameToDeclarations[name_37]; + for (var name_36 in nameToDeclarations) { + var declarations = ts.getProperty(nameToDeclarations, name_36); if (declarations) { // First do a quick check to see if the name of the declaration matches the // last portion of the (possibly) dotted name they're searching for. - var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_37); + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_36); if (!matches) { continue; } @@ -47554,17 +46257,14 @@ var ts; if (!containers) { return undefined; } - matches = patternMatcher.getMatches(containers, name_37); + matches = patternMatcher.getMatches(containers, name_36); if (!matches) { continue; } } var fileName = sourceFile.fileName; var matchKind = bestMatchKind(matches); - if (excludeDts && ts.fileExtensionIs(declaration.getSourceFile().fileName, ".d.ts")) { - continue; - } - rawItems.push({ name: name_37, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); + rawItems.push({ name: name_36, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); } } } @@ -47846,9 +46546,9 @@ var ts; case 169 /* BindingElement */: case 218 /* VariableDeclaration */: var decl = node; - var name_38 = decl.name; - if (ts.isBindingPattern(name_38)) { - addChildrenRecursively(name_38); + var name_37 = decl.name; + if (ts.isBindingPattern(name_37)) { + addChildrenRecursively(name_37); } else if (decl.initializer && isFunctionOrClassExpression(decl.initializer)) { // For `const x = function() {}`, just use the function node, not the const. @@ -47911,7 +46611,7 @@ var ts; } /** Merge declarations of the same kind. */ function mergeChildren(children) { - var nameToItems = ts.createMap(); + var nameToItems = {}; ts.filterMutate(children, function (child) { var decl = child.node; var name = decl.name && nodeText(decl.name); @@ -47919,7 +46619,7 @@ var ts; // Anonymous items are never merged. return true; } - var itemsWithSameName = nameToItems[name]; + var itemsWithSameName = ts.getProperty(nameToItems, name); if (!itemsWithSameName) { nameToItems[name] = child; return true; @@ -48162,7 +46862,7 @@ var ts; function convertToTopLevelItem(n) { return { text: getItemName(n.node), - kind: ts.getNodeKind(n.node), + kind: nodeKind(n.node), kindModifiers: ts.getNodeModifiers(n.node), spans: getSpans(n), childItems: ts.map(n.children, convertToChildItem) || emptyChildItemArray, @@ -48173,7 +46873,7 @@ var ts; function convertToChildItem(n) { return { text: getItemName(n.node), - kind: ts.getNodeKind(n.node), + kind: nodeKind(n.node), kindModifiers: ts.getNodeModifiers(n.node), spans: getSpans(n), childItems: emptyChildItemArray, @@ -48193,6 +46893,49 @@ var ts; return spans; } } + // TODO: GH#9145: We should just use getNodeKind. No reason why navigationBar and navigateTo should have different behaviors. + function nodeKind(node) { + switch (node.kind) { + case 256 /* SourceFile */: + return ts.ScriptElementKind.moduleElement; + case 255 /* EnumMember */: + return ts.ScriptElementKind.memberVariableElement; + case 218 /* VariableDeclaration */: + case 169 /* BindingElement */: + var variableDeclarationNode = void 0; + var name_38; + if (node.kind === 169 /* BindingElement */) { + name_38 = node.name; + variableDeclarationNode = node; + // binding elements are added only for variable declarations + // bubble up to the containing variable declaration + while (variableDeclarationNode && variableDeclarationNode.kind !== 218 /* VariableDeclaration */) { + variableDeclarationNode = variableDeclarationNode.parent; + } + ts.Debug.assert(!!variableDeclarationNode); + } + else { + ts.Debug.assert(!ts.isBindingPattern(node.name)); + variableDeclarationNode = node; + name_38 = node.name; + } + if (ts.isConst(variableDeclarationNode)) { + return ts.ScriptElementKind.constElement; + } + else if (ts.isLet(variableDeclarationNode)) { + return ts.ScriptElementKind.letElement; + } + else { + return ts.ScriptElementKind.variableElement; + } + case 180 /* ArrowFunction */: + return ts.ScriptElementKind.functionElement; + case 279 /* JSDocTypedefTag */: + return ts.ScriptElementKind.typeElement; + default: + return ts.getNodeKind(node); + } + } function getModuleName(moduleDeclaration) { // We want to maintain quotation marks. if (ts.isAmbientModule(moduleDeclaration)) { @@ -48272,7 +47015,7 @@ var ts; // we see the name of a module that is used everywhere, or the name of an overload). As // such, we cache the information we compute about the candidate for the life of this // pattern matcher so we don't have to compute it multiple times. - var stringToWordSpans = ts.createMap(); + var stringToWordSpans = {}; pattern = pattern.trim(); var dotSeparatedSegments = pattern.split(".").map(function (p) { return createSegment(p.trim()); }); var invalidPattern = dotSeparatedSegments.length === 0 || ts.forEach(dotSeparatedSegments, segmentIsInvalid); @@ -48328,7 +47071,7 @@ var ts; return totalMatch; } function getWordSpans(word) { - if (!(word in stringToWordSpans)) { + if (!ts.hasProperty(stringToWordSpans, word)) { stringToWordSpans[word] = breakIntoWordSpans(word); } return stringToWordSpans[word]; @@ -48344,7 +47087,7 @@ var ts; else { // b) Check if the part is a prefix of the candidate, in a case insensitive or sensitive // manner. If it does, return that there was a prefix match. - return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, /*isCaseSensitive:*/ ts.startsWith(candidate, chunk.text)); + return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, /*isCaseSensitive:*/ startsWith(candidate, chunk.text)); } } var isLowercase = chunk.isLowerCase; @@ -48610,6 +47353,14 @@ var ts; var str = String.fromCharCode(ch); return str === str.toLowerCase(); } + function startsWith(string, search) { + for (var i = 0, n = search.length; i < n; i++) { + if (string.charCodeAt(i) !== search.charCodeAt(i)) { + return false; + } + } + return true; + } // Assumes 'value' is already lowercase. function indexOfIgnoringCase(string, value) { for (var i = 0, n = string.length - value.length; i <= n; i++) { @@ -49000,7 +47751,7 @@ var ts; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; var nameToDeclarations = sourceFile.getNamedDeclarations(); - var declarations = nameToDeclarations[name.text]; + var declarations = ts.getProperty(nameToDeclarations, name.text); if (declarations) { for (var _b = 0, declarations_8 = declarations; _b < declarations_8.length; _b++) { var declaration = declarations_8[_b]; @@ -49359,8 +48110,6 @@ var ts; /* @internal */ var ts; (function (ts) { - // Matches the beginning of a triple slash directive - var tripleSlashDirectivePrefixRegex = /^\/\/\/\s*= node.end) { + if (c.kind === 282 /* SyntaxList */ && c.pos <= node.pos && c.end >= node.end) { return c; } }); @@ -49753,7 +48502,8 @@ var ts; ts.findPrecedingToken = findPrecedingToken; function isInString(sourceFile, position) { var previousToken = findPrecedingToken(position, sourceFile); - if (previousToken && previousToken.kind === 9 /* StringLiteral */) { + if (previousToken && + (previousToken.kind === 9 /* StringLiteral */ || previousToken.kind === 166 /* StringLiteralType */)) { var start = previousToken.getStart(); var end = previousToken.getEnd(); // To be "in" one of these literals, the position has to be: @@ -49936,6 +48686,7 @@ var ts; ts.isComment = isComment; function isStringOrRegularExpressionOrTemplateLiteral(kind) { if (kind === 9 /* StringLiteral */ + || kind === 166 /* StringLiteralType */ || kind === 10 /* RegularExpressionLiteral */ || ts.isTemplateLiteralKind(kind)) { return true; @@ -50005,27 +48756,6 @@ var ts; return false; } ts.isArrayLiteralOrObjectLiteralDestructuringPattern = isArrayLiteralOrObjectLiteralDestructuringPattern; - function hasTrailingDirectorySeparator(path) { - var lastCharacter = path.charAt(path.length - 1); - return lastCharacter === "/" || lastCharacter === "\\"; - } - ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; - function isInReferenceComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, isReferenceComment); - function isReferenceComment(c) { - var commentText = sourceFile.text.substring(c.pos, c.end); - return tripleSlashDirectivePrefixRegex.test(commentText); - } - } - ts.isInReferenceComment = isInReferenceComment; - function isInNonReferenceComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, isNonReferenceComment); - function isNonReferenceComment(c) { - var commentText = sourceFile.text.substring(c.pos, c.end); - return !tripleSlashDirectivePrefixRegex.test(commentText); - } - } - ts.isInNonReferenceComment = isInNonReferenceComment; })(ts || (ts = {})); // Display-part writer helpers /* @internal */ @@ -50260,43 +48990,16 @@ var ts; if (host && host.getScriptKind) { scriptKind = host.getScriptKind(fileName); } - if (!scriptKind) { + if (!scriptKind || scriptKind === 0 /* Unknown */) { scriptKind = ts.getScriptKindFromFileName(fileName); } return ts.ensureScriptKind(fileName, scriptKind); } ts.getScriptKind = getScriptKind; - function sanitizeConfigFile(configFileName, content) { - var options = { - fileName: "config.js", - compilerOptions: { - target: 2 /* ES6 */, - removeComments: true - }, - reportDiagnostics: true - }; - var _a = ts.transpileModule("(" + content + ")", options), outputText = _a.outputText, diagnostics = _a.diagnostics; - // Becasue the content was wrapped in "()", the start position of diagnostics needs to be subtract by 1 - // also, the emitted result will have "(" in the beginning and ");" in the end. We need to strip these - // as well - var trimmedOutput = outputText.trim(); - for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { - var diagnostic = diagnostics_3[_i]; - diagnostic.start = diagnostic.start - 1; - } - var _b = ts.parseConfigFileTextToJson(configFileName, trimmedOutput.substring(1, trimmedOutput.length - 2), /*stripComments*/ false), config = _b.config, error = _b.error; - return { - configJsonObject: config || {}, - diagnostics: error ? ts.concatenate(diagnostics, [error]) : diagnostics - }; - } - ts.sanitizeConfigFile = sanitizeConfigFile; })(ts || (ts = {})); // Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. // See LICENSE.txt in the project root for complete license information. -/// -/// -/// +/// /* @internal */ var ts; (function (ts) { @@ -50307,7 +49010,6 @@ var ts; // A map of loose file names to library names // that we are confident require typings var safeList; - var EmptySafeList = ts.createMap(); /** * @param host is the object providing I/O related operations. * @param fileNames are the file names that belong to the same project @@ -50319,18 +49021,21 @@ var ts; */ function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typingOptions, compilerOptions) { // A typing name to typing file path mapping - var inferredTypings = ts.createMap(); + var inferredTypings = {}; if (!typingOptions || !typingOptions.enableAutoDiscovery) { return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; } // Only infer typings for .js and .jsx files - fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { - var kind = ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)); - return kind === 1 /* JS */ || kind === 2 /* JSX */; - }); + fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { return ts.scriptKindIs(f, /*LanguageServiceHost*/ undefined, 1 /* JS */, 2 /* JSX */); }); if (!safeList) { var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); - safeList = result.config ? ts.createMap(result.config) : EmptySafeList; + if (result.config) { + safeList = result.config; + } + else { + safeList = {}; + } + ; } var filesToWatch = []; // Directories to search for package.json, bower.json and other typing information @@ -50355,7 +49060,7 @@ var ts; getTypingNamesFromSourceFileNames(fileNames); // Add the cached typing locations for inferred typings that are already installed for (var name_39 in packageNameToTypingLocation) { - if (name_39 in inferredTypings && !inferredTypings[name_39]) { + if (ts.hasProperty(inferredTypings, name_39) && !inferredTypings[name_39]) { inferredTypings[name_39] = packageNameToTypingLocation[name_39]; } } @@ -50384,7 +49089,7 @@ var ts; } for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) { var typing = typingNames_1[_i]; - if (!(typing in inferredTypings)) { + if (!ts.hasProperty(inferredTypings, typing)) { inferredTypings[typing] = undefined; } } @@ -50398,16 +49103,16 @@ var ts; var jsonConfig = result.config; filesToWatch.push(jsonPath); if (jsonConfig.dependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.dependencies)); + mergeTypings(ts.getKeys(jsonConfig.dependencies)); } if (jsonConfig.devDependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.devDependencies)); + mergeTypings(ts.getKeys(jsonConfig.devDependencies)); } if (jsonConfig.optionalDependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.optionalDependencies)); + mergeTypings(ts.getKeys(jsonConfig.optionalDependencies)); } if (jsonConfig.peerDependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.peerDependencies)); + mergeTypings(ts.getKeys(jsonConfig.peerDependencies)); } } } @@ -50421,10 +49126,13 @@ var ts; var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension); var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); }); var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); }); - if (safeList !== EmptySafeList) { - mergeTypings(ts.filter(cleanedTypingNames, function (f) { return f in safeList; })); + if (safeList === undefined) { + mergeTypings(cleanedTypingNames); } - var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)) === 2 /* JSX */; }); + else { + mergeTypings(ts.filter(cleanedTypingNames, function (f) { return ts.hasProperty(safeList, f); })); + } + var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.scriptKindIs(f, /*LanguageServiceHost*/ undefined, 2 /* JSX */); }); if (hasJsxFile) { mergeTypings(["react"]); } @@ -50439,7 +49147,7 @@ var ts; return; } var typingNames = []; - var fileNames = host.readDirectory(nodeModulesPath, [".json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); + var fileNames = host.readDirectory(nodeModulesPath, ["*.json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { var fileName = fileNames_2[_i]; var normalizedFileName = ts.normalizePath(fileName); @@ -50497,7 +49205,6 @@ var ts; ScanAction[ScanAction["RescanSlashToken"] = 2] = "RescanSlashToken"; ScanAction[ScanAction["RescanTemplateToken"] = 3] = "RescanTemplateToken"; ScanAction[ScanAction["RescanJsxIdentifier"] = 4] = "RescanJsxIdentifier"; - ScanAction[ScanAction["RescanJsxText"] = 5] = "RescanJsxText"; })(ScanAction || (ScanAction = {})); function getFormattingScanner(sourceFile, startPos, endPos) { ts.Debug.assert(scanner === undefined); @@ -50589,9 +49296,6 @@ var ts; } return false; } - function shouldRescanJsxText(node) { - return node && node.kind === 244 /* JsxText */; - } function shouldRescanSlashToken(container) { return container.kind === 10 /* RegularExpressionLiteral */; } @@ -50622,9 +49326,7 @@ var ts; ? 3 /* RescanTemplateToken */ : shouldRescanJsxIdentifier(n) ? 4 /* RescanJsxIdentifier */ - : shouldRescanJsxText(n) - ? 5 /* RescanJsxText */ - : 0 /* Scan */; + : 0 /* Scan */; if (lastTokenInfo && expectedScanAction === lastScanAction) { // readTokenInfo was called before with the same expected scan action. // No need to re-scan text, return existing 'lastTokenInfo' @@ -50659,10 +49361,6 @@ var ts; currentToken = scanner.scanJsxIdentifier(); lastScanAction = 4 /* RescanJsxIdentifier */; } - else if (expectedScanAction === 5 /* RescanJsxText */) { - currentToken = scanner.reScanJsxToken(); - lastScanAction = 5 /* RescanJsxText */; - } else { lastScanAction = 0 /* Scan */; } @@ -51052,7 +49750,7 @@ var ts; this.NoSpaceBetweenReturnAndSemicolon = new formatting.Rule(formatting.RuleDescriptor.create1(94 /* ReturnKeyword */, 23 /* SemicolonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // Add a space between statements. All keywords except (do,else,case) has open/close parens after them. // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any] - this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([18 /* CloseParenToken */, 79 /* DoKeyword */, 80 /* ElseKeyword */, 71 /* CaseKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNotForContext), 2 /* Space */)); + this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([18 /* CloseParenToken */, 79 /* DoKeyword */, 80 /* ElseKeyword */, 71 /* CaseKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isNonJsxElementContext, Rules.IsNotForContext), 2 /* Space */)); // This low-pri rule takes care of "try {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter. this.SpaceAfterTryFinally = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([100 /* TryKeyword */, 85 /* FinallyKeyword */]), 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); // get x() {} @@ -51099,12 +49797,6 @@ var ts; this.SpaceBetweenAsyncAndFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(118 /* AsyncKeyword */, 87 /* FunctionKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); // template string this.NoSpaceBetweenTagAndTemplateString = new formatting.Rule(formatting.RuleDescriptor.create3(69 /* Identifier */, formatting.Shared.TokenRange.FromTokens([11 /* NoSubstitutionTemplateLiteral */, 12 /* TemplateHead */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - // jsx opening element - this.SpaceBeforeJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 69 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNextTokenParentJsxAttribute, Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.SpaceBeforeSlashInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 39 /* SlashToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.NoSpaceBeforeGreaterThanTokenInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create1(39 /* SlashToken */, 27 /* GreaterThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 56 /* EqualsToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create3(56 /* EqualsToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // These rules are higher in priority than user-configurable rules. this.HighPriorityCommonRules = [ this.IgnoreBeforeComment, this.IgnoreAfterLineComment, @@ -51132,8 +49824,6 @@ var ts; this.SpaceAfterVoidOperator, this.SpaceBetweenAsyncAndOpenParen, this.SpaceBetweenAsyncAndFunctionKeyword, this.NoSpaceBetweenTagAndTemplateString, - this.SpaceBeforeJsxAttribute, this.SpaceBeforeSlashInJsxOpeningElement, this.NoSpaceBeforeGreaterThanTokenInJsxOpeningElement, - this.NoSpaceBeforeEqualInJsxAttribute, this.NoSpaceAfterEqualInJsxAttribute, // TypeScript-specific rules this.NoSpaceAfterConstructor, this.NoSpaceAfterModuleImport, this.SpaceAfterCertainTypeScriptKeywords, this.SpaceBeforeCertainTypeScriptKeywords, @@ -51167,8 +49857,8 @@ var ts; /// Rules controlled by user options /// // Insert space after comma delimiter - this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2 /* Space */)); - this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext), 8 /* Delete */)); + this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2 /* Space */)); + this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isNonJsxElementContext), 8 /* Delete */)); // Insert space before and after binary operators this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); this.SpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); @@ -51205,10 +49895,10 @@ var ts; this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([13 /* TemplateMiddle */, 14 /* TemplateTail */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); this.SpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([13 /* TemplateMiddle */, 14 /* TemplateTail */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); // No space after { and before } in JSX expression - this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8 /* Delete */)); - this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2 /* Space */)); - this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8 /* Delete */)); - this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2 /* Space */)); + this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isJsxExpressionContext), 8 /* Delete */)); + this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isJsxExpressionContext), 2 /* Space */)); + this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isJsxExpressionContext), 8 /* Delete */)); + this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isJsxExpressionContext), 2 /* Space */)); // Insert space after function keyword for anonymous functions this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(87 /* FunctionKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */)); this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(87 /* FunctionKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 8 /* Delete */)); @@ -51420,21 +50110,12 @@ var ts; Rules.IsNonJsxSameLineTokenContext = function (context) { return context.TokensAreOnSameLine() && context.contextNode.kind !== 244 /* JsxText */; }; - Rules.IsNonJsxElementContext = function (context) { + Rules.isNonJsxElementContext = function (context) { return context.contextNode.kind !== 241 /* JsxElement */; }; - Rules.IsJsxExpressionContext = function (context) { + Rules.isJsxExpressionContext = function (context) { return context.contextNode.kind === 248 /* JsxExpression */; }; - Rules.IsNextTokenParentJsxAttribute = function (context) { - return context.nextTokenParent.kind === 246 /* JsxAttribute */; - }; - Rules.IsJsxAttributeContext = function (context) { - return context.contextNode.kind === 246 /* JsxAttribute */; - }; - Rules.IsJsxSelfClosingElementContext = function (context) { - return context.contextNode.kind === 242 /* JsxSelfClosingElement */; - }; Rules.IsNotBeforeBlockInFunctionDeclarationContext = function (context) { return !Rules.IsFunctionDeclContext(context) && !Rules.IsBeforeBlockContext(context); }; @@ -51819,25 +50500,25 @@ var ts; }; RulesProvider.prototype.createActiveRules = function (options) { var rules = this.globalRules.HighPriorityCommonRules.slice(0); - if (options.insertSpaceAfterCommaDelimiter) { + if (options.InsertSpaceAfterCommaDelimiter) { rules.push(this.globalRules.SpaceAfterComma); } else { rules.push(this.globalRules.NoSpaceAfterComma); } - if (options.insertSpaceAfterFunctionKeywordForAnonymousFunctions) { + if (options.InsertSpaceAfterFunctionKeywordForAnonymousFunctions) { rules.push(this.globalRules.SpaceAfterAnonymousFunctionKeyword); } else { rules.push(this.globalRules.NoSpaceAfterAnonymousFunctionKeyword); } - if (options.insertSpaceAfterKeywordsInControlFlowStatements) { + if (options.InsertSpaceAfterKeywordsInControlFlowStatements) { rules.push(this.globalRules.SpaceAfterKeywordInControl); } else { rules.push(this.globalRules.NoSpaceAfterKeywordInControl); } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { + if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { rules.push(this.globalRules.SpaceAfterOpenParen); rules.push(this.globalRules.SpaceBeforeCloseParen); rules.push(this.globalRules.NoSpaceBetweenParens); @@ -51847,7 +50528,7 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseParen); rules.push(this.globalRules.NoSpaceBetweenParens); } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { + if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { rules.push(this.globalRules.SpaceAfterOpenBracket); rules.push(this.globalRules.SpaceBeforeCloseBracket); rules.push(this.globalRules.NoSpaceBetweenBrackets); @@ -51857,7 +50538,7 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseBracket); rules.push(this.globalRules.NoSpaceBetweenBrackets); } - if (options.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { + if (options.InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle); rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail); } @@ -51865,7 +50546,7 @@ var ts; rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle); rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail); } - if (options.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) { + if (options.InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) { rules.push(this.globalRules.SpaceAfterOpenBraceInJsxExpression); rules.push(this.globalRules.SpaceBeforeCloseBraceInJsxExpression); } @@ -51873,13 +50554,13 @@ var ts; rules.push(this.globalRules.NoSpaceAfterOpenBraceInJsxExpression); rules.push(this.globalRules.NoSpaceBeforeCloseBraceInJsxExpression); } - if (options.insertSpaceAfterSemicolonInForStatements) { + if (options.InsertSpaceAfterSemicolonInForStatements) { rules.push(this.globalRules.SpaceAfterSemicolonInFor); } else { rules.push(this.globalRules.NoSpaceAfterSemicolonInFor); } - if (options.insertSpaceBeforeAndAfterBinaryOperators) { + if (options.InsertSpaceBeforeAndAfterBinaryOperators) { rules.push(this.globalRules.SpaceBeforeBinaryOperator); rules.push(this.globalRules.SpaceAfterBinaryOperator); } @@ -51887,10 +50568,10 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeBinaryOperator); rules.push(this.globalRules.NoSpaceAfterBinaryOperator); } - if (options.placeOpenBraceOnNewLineForControlBlocks) { + if (options.PlaceOpenBraceOnNewLineForControlBlocks) { rules.push(this.globalRules.NewLineBeforeOpenBraceInControl); } - if (options.placeOpenBraceOnNewLineForFunctions) { + if (options.PlaceOpenBraceOnNewLineForFunctions) { rules.push(this.globalRules.NewLineBeforeOpenBraceInFunction); rules.push(this.globalRules.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock); } @@ -52128,7 +50809,7 @@ var ts; break; } if (formatting.SmartIndenter.shouldIndentChildNode(n, child)) { - return options.indentSize; + return options.IndentSize; } previousLine = line; child = n; @@ -52200,7 +50881,7 @@ var ts; } function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) { var indentation = inheritedIndentation; - var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0; + var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.IndentSize : 0; if (effectiveParentStartLine === startLine) { // if node is located on the same line with the parent // - inherit indentation from the parent @@ -52208,7 +50889,7 @@ var ts; indentation = startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(); - delta = Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta); + delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta(node) + delta); } else if (indentation === -1 /* Unknown */) { if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { @@ -52237,9 +50918,8 @@ var ts; case 147 /* MethodDeclaration */: if (node.asteriskToken) { return 37 /* AsteriskToken */; - } /* - fall-through - */ + } + // fall-through case 145 /* PropertyDeclaration */: case 142 /* Parameter */: return node.name.kind; @@ -52289,13 +50969,13 @@ var ts; recomputeIndentation: function (lineAdded) { if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent, node)) { if (lineAdded) { - indentation += options.indentSize; + indentation += options.IndentSize; } else { - indentation -= options.indentSize; + indentation -= options.IndentSize; } if (formatting.SmartIndenter.shouldIndentChildNode(node)) { - delta = options.indentSize; + delta = options.IndentSize; } else { delta = 0; @@ -52715,7 +51395,7 @@ var ts; // edit should not be applied only if we have one line feed between elements var lineDelta = currentStartLine - previousStartLine; if (lineDelta !== 1) { - recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.newLineCharacter); + recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.NewLineCharacter); } break; case 2 /* Space */: @@ -52776,14 +51456,14 @@ var ts; var internedSpacesIndentation; function getIndentationString(indentation, options) { // reset interned strings if FormatCodeOptions were changed - var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.tabSize || internedSizes.indentSize !== options.indentSize); + var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.TabSize || internedSizes.indentSize !== options.IndentSize); if (resetInternedStrings) { - internedSizes = { tabSize: options.tabSize, indentSize: options.indentSize }; + internedSizes = { tabSize: options.TabSize, indentSize: options.IndentSize }; internedTabsIndentation = internedSpacesIndentation = undefined; } - if (!options.convertTabsToSpaces) { - var tabs = Math.floor(indentation / options.tabSize); - var spaces = indentation - tabs * options.tabSize; + if (!options.ConvertTabsToSpaces) { + var tabs = Math.floor(indentation / options.TabSize); + var spaces = indentation - tabs * options.TabSize; var tabString = void 0; if (!internedTabsIndentation) { internedTabsIndentation = []; @@ -52798,13 +51478,13 @@ var ts; } else { var spacesString = void 0; - var quotient = Math.floor(indentation / options.indentSize); - var remainder = indentation % options.indentSize; + var quotient = Math.floor(indentation / options.IndentSize); + var remainder = indentation % options.IndentSize; if (!internedSpacesIndentation) { internedSpacesIndentation = []; } if (internedSpacesIndentation[quotient] === undefined) { - spacesString = repeat(" ", options.indentSize * quotient); + spacesString = repeat(" ", options.IndentSize * quotient); internedSpacesIndentation[quotient] = spacesString; } else { @@ -52841,7 +51521,7 @@ var ts; } // no indentation when the indent style is set to none, // so we can return fast - if (options.indentStyle === ts.IndentStyle.None) { + if (options.IndentStyle === ts.IndentStyle.None) { return 0; } var precedingToken = ts.findPrecedingToken(position, sourceFile); @@ -52857,7 +51537,7 @@ var ts; // indentation is first non-whitespace character in a previous line // for block indentation, we should look for a line which contains something that's not // whitespace. - if (options.indentStyle === ts.IndentStyle.Block) { + if (options.IndentStyle === ts.IndentStyle.Block) { // move backwards until we find a line with a non-whitespace character, // then find the first non-whitespace character for that line. var current_1 = position; @@ -52891,7 +51571,7 @@ var ts; indentationDelta = 0; } else { - indentationDelta = lineAtPosition !== currentStart.line ? options.indentSize : 0; + indentationDelta = lineAtPosition !== currentStart.line ? options.IndentSize : 0; } break; } @@ -52902,7 +51582,7 @@ var ts; } actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { - return actualIndentation + options.indentSize; + return actualIndentation + options.IndentSize; } previous = current; current = current.parent; @@ -52914,15 +51594,15 @@ var ts; return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, options); } SmartIndenter.getIndentation = getIndentation; + function getBaseIndentation(options) { + return options.BaseIndentSize || 0; + } + SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) { var start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, /*indentationDelta*/ 0, sourceFile, options); } SmartIndenter.getIndentationForNode = getIndentationForNode; - function getBaseIndentation(options) { - return options.baseIndentSize || 0; - } - SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, options) { var parent = current.parent; var parentStart; @@ -52957,7 +51637,7 @@ var ts; } // increase indentation if parent node wants its content to be indented and parent and child nodes don't start on the same line if (shouldIndentChildNode(parent, current) && !parentAndChildShareLine) { - indentationDelta += options.indentSize; + indentationDelta += options.IndentSize; } current = parent; currentStart = parentStart; @@ -53167,7 +51847,7 @@ var ts; break; } if (ch === 9 /* tab */) { - column += options.tabSize + (column % options.tabSize); + column += options.TabSize + (column % options.TabSize); } else { column++; @@ -53309,21 +51989,6 @@ var ts; } ScriptSnapshot.fromString = fromString; })(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {})); - function realizeDiagnostics(diagnostics, newLine) { - return diagnostics.map(function (d) { return realizeDiagnostic(d, newLine); }); - } - ts.realizeDiagnostics = realizeDiagnostics; - function realizeDiagnostic(diagnostic, newLine) { - return { - message: ts.flattenDiagnosticMessageText(diagnostic.messageText, newLine), - start: diagnostic.start, - length: diagnostic.length, - /// TODO: no need for the tolowerCase call - category: ts.DiagnosticCategory[diagnostic.category].toLowerCase(), - code: diagnostic.code - }; - } - ts.realizeDiagnostic = realizeDiagnostic; var scanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ true); var emptyArray = []; var jsDocTagNames = [ @@ -53368,20 +52033,19 @@ var ts; "version" ]; var jsDocCompletionEntries; - function createNode(kind, pos, end, parent) { - var node = kind >= 139 /* FirstNode */ ? new NodeObject(kind, pos, end) : - kind === 69 /* Identifier */ ? new IdentifierObject(kind, pos, end) : - new TokenObject(kind, pos, end); + function createNode(kind, pos, end, flags, parent) { + var node = new NodeObject(kind, pos, end); + node.flags = flags; node.parent = parent; return node; } var NodeObject = (function () { function NodeObject(kind, pos, end) { + this.kind = kind; this.pos = pos; this.end = end; this.flags = 0 /* None */; this.parent = undefined; - this.kind = kind; } NodeObject.prototype.getSourceFile = function () { return ts.getSourceFileOfNode(this); @@ -53416,14 +52080,14 @@ var ts; var token = useJSDocScanner ? scanner.scanJSDocToken() : scanner.scan(); var textPos = scanner.getTextPos(); if (textPos <= end) { - nodes.push(createNode(token, pos, textPos, this)); + nodes.push(createNode(token, pos, textPos, 0, this)); } pos = textPos; } return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(286 /* SyntaxList */, nodes.pos, nodes.end, this); + var list = createNode(282 /* SyntaxList */, nodes.pos, nodes.end, 0, this); list._children = []; var pos = nodes.pos; for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { @@ -53446,16 +52110,13 @@ var ts; scanner.setText((sourceFile || this.getSourceFile()).text); children = []; var pos_3 = this.pos; - var useJSDocScanner_1 = this.kind >= 273 /* FirstJSDocTagNode */ && this.kind <= 285 /* LastJSDocTagNode */; + var useJSDocScanner_1 = this.kind >= 273 /* FirstJSDocTagNode */ && this.kind <= 281 /* LastJSDocTagNode */; var processNode = function (node) { - var isJSDocTagNode = ts.isJSDocTag(node); - if (!isJSDocTagNode && pos_3 < node.pos) { + if (pos_3 < node.pos) { pos_3 = _this.addSyntheticNodes(children, pos_3, node.pos, useJSDocScanner_1); } children.push(node); - if (!isJSDocTagNode) { - pos_3 = node.end; - } + pos_3 = node.end; }; var processNodes = function (nodes) { if (pos_3 < nodes.pos) { @@ -53512,74 +52173,6 @@ var ts; }; return NodeObject; }()); - var TokenOrIdentifierObject = (function () { - function TokenOrIdentifierObject(pos, end) { - // Set properties in same order as NodeObject - this.pos = pos; - this.end = end; - this.flags = 0 /* None */; - this.parent = undefined; - } - TokenOrIdentifierObject.prototype.getSourceFile = function () { - return ts.getSourceFileOfNode(this); - }; - TokenOrIdentifierObject.prototype.getStart = function (sourceFile, includeJsDocComment) { - return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment); - }; - TokenOrIdentifierObject.prototype.getFullStart = function () { - return this.pos; - }; - TokenOrIdentifierObject.prototype.getEnd = function () { - return this.end; - }; - TokenOrIdentifierObject.prototype.getWidth = function (sourceFile) { - return this.getEnd() - this.getStart(sourceFile); - }; - TokenOrIdentifierObject.prototype.getFullWidth = function () { - return this.end - this.pos; - }; - TokenOrIdentifierObject.prototype.getLeadingTriviaWidth = function (sourceFile) { - return this.getStart(sourceFile) - this.pos; - }; - TokenOrIdentifierObject.prototype.getFullText = function (sourceFile) { - return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end); - }; - TokenOrIdentifierObject.prototype.getText = function (sourceFile) { - return (sourceFile || this.getSourceFile()).text.substring(this.getStart(), this.getEnd()); - }; - TokenOrIdentifierObject.prototype.getChildCount = function (sourceFile) { - return 0; - }; - TokenOrIdentifierObject.prototype.getChildAt = function (index, sourceFile) { - return undefined; - }; - TokenOrIdentifierObject.prototype.getChildren = function (sourceFile) { - return emptyArray; - }; - TokenOrIdentifierObject.prototype.getFirstToken = function (sourceFile) { - return undefined; - }; - TokenOrIdentifierObject.prototype.getLastToken = function (sourceFile) { - return undefined; - }; - return TokenOrIdentifierObject; - }()); - var TokenObject = (function (_super) { - __extends(TokenObject, _super); - function TokenObject(kind, pos, end) { - _super.call(this, pos, end); - this.kind = kind; - } - return TokenObject; - }(TokenOrIdentifierObject)); - var IdentifierObject = (function (_super) { - __extends(IdentifierObject, _super); - function IdentifierObject(kind, pos, end) { - _super.call(this, pos, end); - } - return IdentifierObject; - }(TokenOrIdentifierObject)); - IdentifierObject.prototype.kind = 69 /* Identifier */; var SymbolObject = (function () { function SymbolObject(flags, name) { this.flags = flags; @@ -53924,7 +52517,7 @@ var ts; return this.checker.getIndexTypeOfType(this, 1 /* Number */); }; TypeObject.prototype.getBaseTypes = function () { - return this.flags & (32768 /* Class */ | 65536 /* Interface */) + return this.flags & (1024 /* Class */ | 2048 /* Interface */) ? this.checker.getBaseTypes(this) : undefined; }; @@ -53983,7 +52576,7 @@ var ts; return this.namedDeclarations; }; SourceFileObject.prototype.computeNamedDeclarations = function () { - var result = ts.createMap(); + var result = {}; ts.forEachChild(this, visit); return result; function addDeclaration(declaration) { @@ -53994,13 +52587,13 @@ var ts; } } function getDeclarations(name) { - return result[name] || (result[name] = []); + return ts.getProperty(result, name) || (result[name] = []); } function getDeclarationName(declaration) { if (declaration.name) { - var result_3 = getTextOfIdentifierOrLiteral(declaration.name); - if (result_3 !== undefined) { - return result_3; + var result_2 = getTextOfIdentifierOrLiteral(declaration.name); + if (result_2 !== undefined) { + return result_2; } if (declaration.name.kind === 140 /* ComputedPropertyName */) { var expr = declaration.name.expression; @@ -54140,30 +52733,6 @@ var ts; IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; })(ts.IndentStyle || (ts.IndentStyle = {})); var IndentStyle = ts.IndentStyle; - function toEditorSettings(optionsAsMap) { - var allPropertiesAreCamelCased = true; - for (var key in optionsAsMap) { - if (ts.hasProperty(optionsAsMap, key) && !isCamelCase(key)) { - allPropertiesAreCamelCased = false; - break; - } - } - if (allPropertiesAreCamelCased) { - return optionsAsMap; - } - var settings = {}; - for (var key in optionsAsMap) { - if (ts.hasProperty(optionsAsMap, key)) { - var newKey = isCamelCase(key) ? key : key.charAt(0).toLowerCase() + key.substr(1); - settings[newKey] = optionsAsMap[key]; - } - } - return settings; - } - ts.toEditorSettings = toEditorSettings; - function isCamelCase(s) { - return !s.length || s.charAt(0) === s.charAt(0).toLowerCase(); - } (function (SymbolDisplayPartKind) { SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; SymbolDisplayPartKind[SymbolDisplayPartKind["className"] = 1] = "className"; @@ -54238,8 +52807,6 @@ var ts; ScriptElementKind.typeElement = "type"; /** enum E */ ScriptElementKind.enumElement = "enum"; - // TODO: GH#9983 - ScriptElementKind.enumMemberElement = "const"; /** * Inside module and script only * const v = .. @@ -54280,8 +52847,6 @@ var ts; ScriptElementKind.alias = "alias"; ScriptElementKind.constElement = "const"; ScriptElementKind.letElement = "let"; - ScriptElementKind.directory = "directory"; - ScriptElementKind.externalModuleName = "external module name"; })(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {})); var ScriptElementKindModifier; (function (ScriptElementKindModifier) { @@ -54370,9 +52935,9 @@ var ts; return false; } // If the parent is not sourceFile or module block it is local variable - for (var parent_17 = declaration.parent; !ts.isFunctionBlock(parent_17); parent_17 = parent_17.parent) { + for (var parent_16 = declaration.parent; !ts.isFunctionBlock(parent_16); parent_16 = parent_16.parent) { // Reached source file or module block - if (parent_17.kind === 256 /* SourceFile */ || parent_17.kind === 226 /* ModuleBlock */) { + if (parent_16.kind === 256 /* SourceFile */ || parent_16.kind === 226 /* ModuleBlock */) { return false; } } @@ -54388,7 +52953,7 @@ var ts; }; } ts.getDefaultCompilerOptions = getDefaultCompilerOptions; - // Cache host information about script should be refreshed + // Cache host information about scrip Should be refreshed // at each language service public entry point, since we don't know when // set of scripts handled by the host changes. var HostCache = (function () { @@ -54458,24 +53023,49 @@ var ts; }; return HostCache; }()); + var SyntaxTreeCache = (function () { + function SyntaxTreeCache(host) { + this.host = host; + } + SyntaxTreeCache.prototype.getCurrentSourceFile = function (fileName) { + var scriptSnapshot = this.host.getScriptSnapshot(fileName); + if (!scriptSnapshot) { + // The host does not know about this file. + throw new Error("Could not find file: '" + fileName + "'."); + } + var scriptKind = ts.getScriptKind(fileName, this.host); + var version = this.host.getScriptVersion(fileName); + var sourceFile; + if (this.currentFileName !== fileName) { + // This is a new file, just parse it + sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 2 /* Latest */, version, /*setNodeParents*/ true, scriptKind); + } + else if (this.currentFileVersion !== version) { + // This is the same file, just a newer version. Incrementally parse the file. + var editRange = scriptSnapshot.getChangeRange(this.currentFileScriptSnapshot); + sourceFile = updateLanguageServiceSourceFile(this.currentSourceFile, scriptSnapshot, version, editRange); + } + if (sourceFile) { + // All done, ensure state is up to date + this.currentFileVersion = version; + this.currentFileName = fileName; + this.currentFileScriptSnapshot = scriptSnapshot; + this.currentSourceFile = sourceFile; + } + return this.currentSourceFile; + }; + return SyntaxTreeCache; + }()); function setSourceFileFields(sourceFile, scriptSnapshot, version) { sourceFile.version = version; sourceFile.scriptSnapshot = scriptSnapshot; } - /** - * Matches a triple slash reference directive with an incomplete string literal for its path. Used - * to determine if the caret is currently within the string literal and capture the literal fragment - * for completions. - * For example, this matches /// = commentRange.pos && position <= commentRange.end && commentRange; }); - if (!range) { - return undefined; - } - var text = sourceFile.text.substr(range.pos, position - range.pos); - var match = tripleSlashDirectiveFragmentRegex.exec(text); - if (match) { - var prefix = match[1]; - var kind = match[2]; - var toComplete = match[3]; - var scriptPath = ts.getDirectoryPath(sourceFile.path); - var entries_3; - if (kind === "path") { - // Give completions for a relative path - var span = getDirectoryFragmentTextSpan(toComplete, range.pos + prefix.length); - entries_3 = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(program.getCompilerOptions()), /*includeExtensions*/ true, span, sourceFile.path); - } - else { - // Give completions based on the typings available - var span = { start: range.pos + prefix.length, length: match[0].length - prefix.length }; - entries_3 = getCompletionEntriesFromTypings(host, program.getCompilerOptions(), scriptPath, span); - } - return { - isMemberCompletion: false, - isNewIdentifierLocation: true, - entries: entries_3 - }; - } - return undefined; - } - function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { - if (result === void 0) { result = []; } - // Check for typings specified in compiler options - if (options.types) { - for (var _i = 0, _a = options.types; _i < _a.length; _i++) { - var moduleName = _a[_i]; - result.push(createCompletionEntryForModule(moduleName, ScriptElementKind.externalModuleName, span)); - } - } - else if (host.getDirectories) { - var typeRoots = ts.getEffectiveTypeRoots(options, host); - for (var _b = 0, typeRoots_2 = typeRoots; _b < typeRoots_2.length; _b++) { - var root = typeRoots_2[_b]; - getCompletionEntriesFromDirectories(host, options, root, span, result); - } - } - if (host.getDirectories) { - // Also get all @types typings installed in visible node_modules directories - for (var _c = 0, _d = findPackageJsons(scriptPath); _c < _d.length; _c++) { - var package = _d[_c]; - var typesDir = ts.combinePaths(ts.getDirectoryPath(package), "node_modules/@types"); - getCompletionEntriesFromDirectories(host, options, typesDir, span, result); - } - } - return result; - } - function getCompletionEntriesFromDirectories(host, options, directory, span, result) { - if (host.getDirectories && tryDirectoryExists(host, directory)) { - var directories = tryGetDirectories(host, directory); - if (directories) { - for (var _i = 0, directories_3 = directories; _i < directories_3.length; _i++) { - var typeDirectory = directories_3[_i]; - typeDirectory = ts.normalizePath(typeDirectory); - result.push(createCompletionEntryForModule(ts.getBaseFileName(typeDirectory), ScriptElementKind.externalModuleName, span)); - } - } - } - } - function findPackageJsons(currentDir) { - var paths = []; - var currentConfigPath; - while (true) { - currentConfigPath = ts.findConfigFile(currentDir, function (f) { return tryFileExists(host, f); }, "package.json"); - if (currentConfigPath) { - paths.push(currentConfigPath); - currentDir = ts.getDirectoryPath(currentConfigPath); - var parent_21 = ts.getDirectoryPath(currentDir); - if (currentDir === parent_21) { - break; - } - currentDir = parent_21; - } - else { - break; - } - } - return paths; - } - function enumerateNodeModulesVisibleToScript(host, scriptPath) { - var result = []; - if (host.readFile && host.fileExists) { - for (var _i = 0, _a = findPackageJsons(scriptPath); _i < _a.length; _i++) { - var packageJson = _a[_i]; - var package = tryReadingPackageJson(packageJson); - if (!package) { - return; - } - var nodeModulesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules"); - var foundModuleNames = []; - // Provide completions for all non @types dependencies - for (var _b = 0, nodeModulesDependencyKeys_1 = nodeModulesDependencyKeys; _b < nodeModulesDependencyKeys_1.length; _b++) { - var key = nodeModulesDependencyKeys_1[_b]; - addPotentialPackageNames(package[key], foundModuleNames); - } - for (var _c = 0, foundModuleNames_1 = foundModuleNames; _c < foundModuleNames_1.length; _c++) { - var moduleName = foundModuleNames_1[_c]; - var moduleDir = ts.combinePaths(nodeModulesDir, moduleName); - result.push({ - moduleName: moduleName, - moduleDir: moduleDir - }); - } - } - } - return result; - function tryReadingPackageJson(filePath) { - try { - var fileText = tryReadFile(host, filePath); - return fileText ? JSON.parse(fileText) : undefined; - } - catch (e) { - return undefined; - } - } - function addPotentialPackageNames(dependencies, result) { - if (dependencies) { - for (var dep in dependencies) { - if (dependencies.hasOwnProperty(dep) && !ts.startsWith(dep, "@types/")) { - result.push(dep); - } - } - } - } - } - function createCompletionEntryForModule(name, kind, replacementSpan) { - return { name: name, kind: kind, kindModifiers: ScriptElementKindModifier.none, sortText: name, replacementSpan: replacementSpan }; - } - // Replace everything after the last directory seperator that appears - function getDirectoryFragmentTextSpan(text, textStart) { - var index = text.lastIndexOf(ts.directorySeparator); - var offset = index !== -1 ? index + 1 : 0; - return { start: textStart + offset, length: text.length - offset }; - } - // Returns true if the path is explicitly relative to the script (i.e. relative to . or ..) - function isPathRelativeToScript(path) { - if (path && path.length >= 2 && path.charCodeAt(0) === 46 /* dot */) { - var slashIndex = path.length >= 3 && path.charCodeAt(1) === 46 /* dot */ ? 2 : 1; - var slashCharCode = path.charCodeAt(slashIndex); - return slashCharCode === 47 /* slash */ || slashCharCode === 92 /* backslash */; - } - return false; - } - function normalizeAndPreserveTrailingSlash(path) { - return ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(ts.normalizePath(path)) : ts.normalizePath(path); - } - function tryGetDirectories(host, directoryName) { - return tryIOAndConsumeErrors(host, host.getDirectories, directoryName); - } - function tryReadDirectory(host, path, extensions, exclude, include) { - return tryIOAndConsumeErrors(host, host.readDirectory, path, extensions, exclude, include); - } - function tryReadFile(host, path) { - return tryIOAndConsumeErrors(host, host.readFile, path); - } - function tryFileExists(host, path) { - return tryIOAndConsumeErrors(host, host.fileExists, path); - } - function tryDirectoryExists(host, path) { - try { - return ts.directoryProbablyExists(path, host); - } - catch (e) { } - return undefined; - } - function tryIOAndConsumeErrors(host, toApply) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - try { - return toApply && toApply.apply(host, args); - } - catch (e) { } - return undefined; - } } function getCompletionEntryDetails(fileName, position, entryName) { synchronizeHostData(); @@ -57310,7 +55346,7 @@ var ts; displayParts.push(ts.keywordPart(92 /* NewKeyword */)); displayParts.push(ts.spacePart()); } - if (!(type.flags & 2097152 /* Anonymous */) && type.symbol) { + if (!(type.flags & 65536 /* Anonymous */) && type.symbol) { ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */)); } addSignatureDisplayParts(signature, allSignatures, 8 /* WriteArrowStyleSignature */); @@ -57379,7 +55415,7 @@ var ts; displayParts.push(ts.spacePart()); displayParts.push(ts.operatorPart(56 /* EqualsToken */)); displayParts.push(ts.spacePart()); - ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 512 /* InTypeAlias */)); + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration)); } if (symbolFlags & 384 /* Enum */) { addNewLineIfDisplayPartsExist(); @@ -57458,14 +55494,7 @@ var ts; } if (symbolFlags & 8388608 /* Alias */) { addNewLineIfDisplayPartsExist(); - if (symbol.declarations[0].kind === 228 /* NamespaceExportDeclaration */) { - displayParts.push(ts.keywordPart(82 /* ExportKeyword */)); - displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(126 /* NamespaceKeyword */)); - } - else { - displayParts.push(ts.keywordPart(89 /* ImportKeyword */)); - } + displayParts.push(ts.keywordPart(89 /* ImportKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); ts.forEach(symbol.declarations, function (declaration) { @@ -57538,27 +55567,6 @@ var ts; } if (!documentation) { documentation = symbol.getDocumentationComment(); - if (documentation.length === 0 && symbol.flags & 4 /* Property */) { - // For some special property access expressions like `experts.foo = foo` or `module.exports.foo = foo` - // there documentation comments might be attached to the right hand side symbol of their declarations. - // The pattern of such special property access is that the parent symbol is the symbol of the file. - if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 256 /* SourceFile */; })) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (!declaration.parent || declaration.parent.kind !== 187 /* BinaryExpression */) { - continue; - } - var rhsSymbol = program.getTypeChecker().getSymbolAtLocation(declaration.parent.right); - if (!rhsSymbol) { - continue; - } - documentation = rhsSymbol.getDocumentationComment(); - if (documentation.length > 0) { - break; - } - } - } - } } return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind }; function addNewLineIfDisplayPartsExist() { @@ -57765,7 +55773,7 @@ var ts; // Type reference directives var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); if (typeReferenceDirective) { - var referenceFile = program.getResolvedTypeReferenceDirectives()[typeReferenceDirective.fileName]; + var referenceFile = ts.lookUp(program.getResolvedTypeReferenceDirectives(), typeReferenceDirective.fileName); if (referenceFile && referenceFile.resolvedFileName) { return [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)]; } @@ -57840,14 +55848,14 @@ var ts; if (!type) { return undefined; } - if (type.flags & 524288 /* Union */ && !(type.flags & 16 /* Enum */)) { - var result_4 = []; + if (type.flags & 16384 /* Union */) { + var result_3 = []; ts.forEach(type.types, function (t) { if (t.symbol) { - ts.addRange(/*to*/ result_4, /*from*/ getDefinitionFromSymbol(t.symbol, node)); + ts.addRange(/*to*/ result_3, /*from*/ getDefinitionFromSymbol(t.symbol, node)); } }); - return result_4; + return result_3; } if (!type.symbol) { return undefined; @@ -57897,14 +55905,14 @@ var ts; if (!referencedSymbols) { return undefined; } - var fileNameToDocumentHighlights = ts.createMap(); + var fileNameToDocumentHighlights = {}; var result = []; for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) { var referencedSymbol = referencedSymbols_1[_i]; for (var _a = 0, _b = referencedSymbol.references; _a < _b.length; _a++) { var referenceEntry = _b[_a]; var fileName_1 = referenceEntry.fileName; - var documentHighlights = fileNameToDocumentHighlights[fileName_1]; + var documentHighlights = ts.getProperty(fileNameToDocumentHighlights, fileName_1); if (!documentHighlights) { documentHighlights = { fileName: fileName_1, highlightSpans: [] }; fileNameToDocumentHighlights[fileName_1] = documentHighlights; @@ -58053,19 +56061,19 @@ var ts; function getThrowStatementOwner(throwStatement) { var child = throwStatement; while (child.parent) { - var parent_22 = child.parent; - if (ts.isFunctionBlock(parent_22) || parent_22.kind === 256 /* SourceFile */) { - return parent_22; + var parent_20 = child.parent; + if (ts.isFunctionBlock(parent_20) || parent_20.kind === 256 /* SourceFile */) { + return parent_20; } // A throw-statement is only owned by a try-statement if the try-statement has // a catch clause, and if the throw-statement occurs within the try block. - if (parent_22.kind === 216 /* TryStatement */) { - var tryStatement = parent_22; + if (parent_20.kind === 216 /* TryStatement */) { + var tryStatement = parent_20; if (tryStatement.tryBlock === child && tryStatement.catchClause) { return child; } } - child = parent_22; + child = parent_20; } return undefined; } @@ -58527,7 +56535,7 @@ var ts; var sourceFile = sourceFiles_4[_i]; cancellationToken.throwIfCancellationRequested(); var nameTable = getNameTable(sourceFile); - if (nameTable[internedName] !== undefined) { + if (ts.lookUp(nameTable, internedName) !== undefined) { result = result || []; getReferencesInNode(sourceFile, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex); } @@ -58547,8 +56555,7 @@ var ts; name: name, kind: info.symbolKind, fileName: declarations[0].getSourceFile().fileName, - textSpan: ts.createTextSpan(declarations[0].getStart(), 0), - displayParts: info.displayParts + textSpan: ts.createTextSpan(declarations[0].getStart(), 0) }; } function getAliasSymbolForPropertyNameSymbol(symbol, location) { @@ -58717,8 +56724,7 @@ var ts; fileName: targetLabel.getSourceFile().fileName, kind: ScriptElementKind.label, name: labelName, - textSpan: ts.createTextSpanFromBounds(targetLabel.getStart(), targetLabel.getEnd()), - displayParts: [ts.displayPart(labelName, SymbolDisplayPartKind.text)] + textSpan: ts.createTextSpanFromBounds(targetLabel.getStart(), targetLabel.getEnd()) }; return [{ definition: definition, references: references }]; } @@ -58750,6 +56756,7 @@ var ts; */ function getReferencesInNode(container, searchSymbol, searchText, searchLocation, searchMeaning, findInStrings, findInComments, result, symbolToIndex) { var sourceFile = container.getSourceFile(); + var tripleSlashDirectivePrefixRegex = /^\/\/\/\s*= 0 ? s : undefined; }); + var result_4 = []; + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result_4, /*previousIterationSymbolsCache*/ {}); + return ts.forEach(result_4, function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); } return undefined; }); @@ -59193,20 +57203,20 @@ var ts; var contextualType = typeChecker.getContextualType(objectLiteral); var name = getNameFromObjectLiteralElement(node); if (name && contextualType) { - var result_6 = []; - var symbol_2 = contextualType.getProperty(name); - if (symbol_2) { - result_6.push(symbol_2); + var result_5 = []; + var symbol_1 = contextualType.getProperty(name); + if (symbol_1) { + result_5.push(symbol_1); } - if (contextualType.flags & 524288 /* Union */) { + if (contextualType.flags & 16384 /* Union */) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_6.push(symbol); + result_5.push(symbol); } }); } - return result_6; + return result_5; } return undefined; } @@ -59271,12 +57281,12 @@ var ts; return false; } /// NavigateTo - function getNavigateToItems(searchValue, maxResultCount, excludeDts) { + function getNavigateToItems(searchValue, maxResultCount) { synchronizeHostData(); var checker = getProgram().getTypeChecker(); - return ts.NavigateTo.getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount, excludeDts); + return ts.NavigateTo.getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount); } - function getEmitOutput(fileName, emitDeclarationsOnly) { + function getEmitOutput(fileName) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var outputFiles = []; @@ -59287,7 +57297,7 @@ var ts; text: data }); } - var emitOutput = program.emit(sourceFile, writeFile, cancellationToken, emitDeclarationsOnly); + var emitOutput = program.emit(sourceFile, writeFile, cancellationToken); return { outputFiles: outputFiles, emitSkipped: emitOutput.emitSkipped @@ -59445,6 +57455,7 @@ var ts; case 172 /* PropertyAccessExpression */: case 139 /* QualifiedName */: case 9 /* StringLiteral */: + case 166 /* StringLiteralType */: case 84 /* FalseKeyword */: case 99 /* TrueKeyword */: case 93 /* NullKeyword */: @@ -59798,9 +57809,6 @@ var ts; * False will mean that node is not classified and traverse routine should recurse into node contents. */ function tryClassifyNode(node) { - if (ts.isJSDocTag(node)) { - return true; - } if (ts.nodeIsMissing(node)) { return true; } @@ -59883,7 +57891,7 @@ var ts; else if (tokenKind === 8 /* NumericLiteral */) { return 4 /* numericLiteral */; } - else if (tokenKind === 9 /* StringLiteral */) { + else if (tokenKind === 9 /* StringLiteral */ || tokenKind === 166 /* StringLiteralType */) { return token.parent.kind === 246 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; } else if (tokenKind === 10 /* RegularExpressionLiteral */) { @@ -60001,37 +58009,33 @@ var ts; return undefined; } } - function getIndentationAtPosition(fileName, position, optionsOrSettings) { - var start = ts.timestamp(); - var settings = toEditorSettings(optionsOrSettings); + function getIndentationAtPosition(fileName, position, editorOptions) { + var start = new Date().getTime(); var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - log("getIndentationAtPosition: getCurrentSourceFile: " + (ts.timestamp() - start)); - start = ts.timestamp(); - var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, settings); - log("getIndentationAtPosition: computeIndentation : " + (ts.timestamp() - start)); + log("getIndentationAtPosition: getCurrentSourceFile: " + (new Date().getTime() - start)); + start = new Date().getTime(); + var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, editorOptions); + log("getIndentationAtPosition: computeIndentation : " + (new Date().getTime() - start)); return result; } - function getFormattingEditsForRange(fileName, start, end, optionsOrSettings) { - var settings = toEditorSettings(optionsOrSettings); + function getFormattingEditsForRange(fileName, start, end, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(settings), settings); + return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(options), options); } - function getFormattingEditsForDocument(fileName, optionsOrSettings) { - var settings = toEditorSettings(optionsOrSettings); + function getFormattingEditsForDocument(fileName, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.formatting.formatDocument(sourceFile, getRuleProvider(settings), settings); + return ts.formatting.formatDocument(sourceFile, getRuleProvider(options), options); } - function getFormattingEditsAfterKeystroke(fileName, position, key, optionsOrSettings) { - var settings = toEditorSettings(optionsOrSettings); + function getFormattingEditsAfterKeystroke(fileName, position, key, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); if (key === "}") { - return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(settings), settings); + return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(options), options); } else if (key === ";") { - return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(settings), settings); + return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(options), options); } else if (key === "\n") { - return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(settings), settings); + return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(options), options); } return []; } @@ -60311,9 +58315,9 @@ var ts; } } function getStringLiteralTypeForNode(node, typeChecker) { - var searchNode = node.parent.kind === 166 /* LiteralType */ ? node.parent : node; + var searchNode = node.parent.kind === 166 /* StringLiteralType */ ? node.parent : node; var type = typeChecker.getTypeAtLocation(searchNode); - if (type && type.flags & 32 /* StringLiteral */) { + if (type && type.flags & 256 /* StringLiteral */) { return type; } return undefined; @@ -60459,7 +58463,7 @@ var ts; } ts.getNameTable = getNameTable; function initializeNameTable(sourceFile) { - var nameTable = ts.createMap(); + var nameTable = {}; walk(sourceFile); sourceFile.nameTable = nameTable; function walk(node) { @@ -60563,7 +58567,7 @@ var ts; var lastEnd = 0; for (var i = 0, n = dense.length; i < n; i += 3) { var start = dense[i]; - var length_5 = dense[i + 1]; + var length_3 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -60572,8 +58576,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: TokenClass.Whitespace }); } } - entries.push({ length: length_5, classification: convertClassification(type) }); - lastEnd = start + length_5; + entries.push({ length: length_3, classification: convertClassification(type) }); + lastEnd = start + length_3; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -60753,7 +58757,7 @@ var ts; var end = scanner.getTextPos(); addResult(start, end, classFromKind(token)); if (end >= text.length) { - if (token === 9 /* StringLiteral */) { + if (token === 9 /* StringLiteral */ || token === 166 /* StringLiteralType */) { // Check to see if we finished up on a multiline string literal. var tokenText = scanner.getTokenText(); if (scanner.isUnterminated()) { @@ -60892,6 +58896,7 @@ var ts; case 8 /* NumericLiteral */: return 4 /* numericLiteral */; case 9 /* StringLiteral */: + case 166 /* StringLiteralType */: return 6 /* stringLiteral */; case 10 /* RegularExpressionLiteral */: return 7 /* regularExpressionLiteral */; @@ -60932,8 +58937,6 @@ var ts; function initializeServices() { ts.objectAllocator = { getNodeConstructor: function () { return NodeObject; }, - getTokenConstructor: function () { return TokenObject; }, - getIdentifierConstructor: function () { return IdentifierObject; }, getSourceFileConstructor: function () { return SourceFileObject; }, getSymbolConstructor: function () { return SymbolObject; }, getTypeConstructor: function () { return TypeObject; }, @@ -61559,7 +59562,7 @@ var ts; // /// /* @internal */ -var debugObjectHost = new Function("return this")(); +var debugObjectHost = this; // We need to use 'null' to interface with the managed side. /* tslint:disable:no-null-keyword */ /* tslint:disable:no-in-operator */ @@ -61612,7 +59615,7 @@ var ts; this.resolveModuleNames = function (moduleNames, containingFile) { var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile)); return ts.map(moduleNames, function (name) { - var result = ts.getProperty(resolutionsInFile, name); + var result = ts.lookUp(resolutionsInFile, name); return result ? { resolvedFileName: result } : undefined; }); }; @@ -61623,7 +59626,7 @@ var ts; if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) { this.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { var typeDirectivesForFile = JSON.parse(_this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile)); - return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); }); + return ts.map(typeDirectiveNames, function (name) { return ts.lookUp(typeDirectivesForFile, name); }); }; } } @@ -61647,12 +59650,6 @@ var ts; } return this.shimHost.getProjectVersion(); }; - LanguageServiceShimHostAdapter.prototype.getTypeRootsVersion = function () { - if (!this.shimHost.getTypeRootsVersion) { - return 0; - } - return this.shimHost.getTypeRootsVersion(); - }; LanguageServiceShimHostAdapter.prototype.useCaseSensitiveFileNames = function () { return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; }; @@ -61704,21 +59701,11 @@ var ts; return this.shimHost.getCurrentDirectory(); }; LanguageServiceShimHostAdapter.prototype.getDirectories = function (path) { - return JSON.parse(this.shimHost.getDirectories(path)); + return this.shimHost.getDirectories(path); }; LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) { return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); }; - LanguageServiceShimHostAdapter.prototype.readDirectory = function (path, extensions, exclude, include, depth) { - var pattern = ts.getFileMatcherPatterns(path, extensions, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); - return JSON.parse(this.shimHost.readDirectory(path, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); - }; - LanguageServiceShimHostAdapter.prototype.readFile = function (path, encoding) { - return this.shimHost.readFile(path, encoding); - }; - LanguageServiceShimHostAdapter.prototype.fileExists = function (path) { - return this.shimHost.fileExists(path); - }; return LanguageServiceShimHostAdapter; }()); ts.LanguageServiceShimHostAdapter = LanguageServiceShimHostAdapter; @@ -61732,7 +59719,7 @@ var ts; this.lastCancellationCheckTime = 0; } ThrottledCancellationToken.prototype.isCancellationRequested = function () { - var time = ts.timestamp(); + var time = Date.now(); var duration = Math.abs(time - this.lastCancellationCheckTime); if (duration > 10) { // Check no more than once every 10 ms. @@ -61785,9 +59772,6 @@ var ts; CoreServicesShimHostAdapter.prototype.readDirectoryFallback = function (rootDir, extension, exclude) { return JSON.parse(this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude))); }; - CoreServicesShimHostAdapter.prototype.getDirectories = function (path) { - return JSON.parse(this.shimHost.getDirectories(path)); - }; return CoreServicesShimHostAdapter; }()); ts.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter; @@ -61795,11 +59779,11 @@ var ts; var start; if (logPerformance) { logger.log(actionDescription); - start = ts.timestamp(); + start = Date.now(); } var result = action(); if (logPerformance) { - var end = ts.timestamp(); + var end = Date.now(); logger.log(actionDescription + " completed in " + (end - start) + " msec"); if (typeof result === "string") { var str = result; @@ -61838,6 +59822,20 @@ var ts; }; return ShimBase; }()); + function realizeDiagnostics(diagnostics, newLine) { + return diagnostics.map(function (d) { return realizeDiagnostic(d, newLine); }); + } + ts.realizeDiagnostics = realizeDiagnostics; + function realizeDiagnostic(diagnostic, newLine) { + return { + message: ts.flattenDiagnosticMessageText(diagnostic.messageText, newLine), + start: diagnostic.start, + length: diagnostic.length, + /// TODO: no need for the tolowerCase call + category: ts.DiagnosticCategory[diagnostic.category].toLowerCase(), + code: diagnostic.code + }; + } var LanguageServiceShimObject = (function (_super) { __extends(LanguageServiceShimObject, _super); function LanguageServiceShimObject(factory, host, languageService) { @@ -62171,13 +60169,6 @@ var ts; }; }); }; - CoreServicesShimObject.prototype.getAutomaticTypeDirectiveNames = function (compilerOptionsJson) { - var _this = this; - return this.forwardJSONCall("getAutomaticTypeDirectiveNames('" + compilerOptionsJson + "')", function () { - var compilerOptions = JSON.parse(compilerOptionsJson); - return ts.getAutomaticTypeDirectiveNames(compilerOptions, _this.host); - }); - }; CoreServicesShimObject.prototype.convertFileReferences = function (refs) { if (!refs) { return undefined; @@ -62204,7 +60195,7 @@ var ts; typingOptions: {}, files: [], raw: {}, - errors: [ts.realizeDiagnostic(result.error, "\r\n")] + errors: [realizeDiagnostic(result.error, "\r\n")] }; } var normalizedFileName = ts.normalizeSlashes(fileName); @@ -62214,7 +60205,7 @@ var ts; typingOptions: configFile.typingOptions, files: configFile.fileNames, raw: configFile.raw, - errors: ts.realizeDiagnostics(configFile.errors, "\r\n") + errors: realizeDiagnostics(configFile.errors, "\r\n") }; }); }; @@ -62313,5 +60304,5 @@ var TypeScript; // 'toolsVersion' gets consumed by the managed side, so it's not unused. // TODO: it should be moved into a namespace though. /* @internal */ -var toolsVersion = "2.0"; +var toolsVersion = "1.9"; /* tslint:enable:no-unused-variable */ diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index 65cb83be787..fbf9e19d785 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -417,10 +417,7 @@ declare namespace ts { interface ModifiersArray extends NodeArray { flags: NodeFlags; } - interface Token extends Node { - __tokenTag: any; - } - interface Modifier extends Token { + interface Modifier extends Node { } interface Identifier extends PrimaryExpression { text: string; @@ -1738,6 +1735,7 @@ declare namespace ts { getCancellationToken?(): CancellationToken; getDefaultLibFileName(options: CompilerOptions): string; getDefaultLibLocation?(): string; + getDefaultTypeDirectiveNames?(rootPath: string): string[]; writeFile: WriteFileCallback; getCurrentDirectory(): string; getDirectories(path: string): string[]; @@ -1883,6 +1881,8 @@ declare namespace ts { function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange; function getTypeParameterOwner(d: Declaration): Declaration; function isParameterPropertyDeclaration(node: ParameterDeclaration): boolean; + function startsWith(str: string, prefix: string): boolean; + function endsWith(str: string, suffix: string): boolean; } declare namespace ts { function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; @@ -1909,12 +1909,6 @@ declare namespace ts { function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; - interface FormatDiagnosticsHost { - getCurrentDirectory(): string; - getCanonicalFileName(fileName: string): string; - getNewLine(): string; - } - function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; /** * Given a set of options, returns the set of type directive names diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index c131e3b758a..22cbe79129c 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -205,7 +205,7 @@ var ts; SyntaxKind[SyntaxKind["IntersectionType"] = 163] = "IntersectionType"; SyntaxKind[SyntaxKind["ParenthesizedType"] = 164] = "ParenthesizedType"; SyntaxKind[SyntaxKind["ThisType"] = 165] = "ThisType"; - SyntaxKind[SyntaxKind["LiteralType"] = 166] = "LiteralType"; + SyntaxKind[SyntaxKind["StringLiteralType"] = 166] = "StringLiteralType"; // Binding patterns SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 167] = "ObjectBindingPattern"; SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 168] = "ArrayBindingPattern"; @@ -334,14 +334,10 @@ var ts; SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 279] = "JSDocTypedefTag"; SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 280] = "JSDocPropertyTag"; SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 281] = "JSDocTypeLiteral"; - SyntaxKind[SyntaxKind["JSDocLiteralType"] = 282] = "JSDocLiteralType"; - SyntaxKind[SyntaxKind["JSDocNullKeyword"] = 283] = "JSDocNullKeyword"; - SyntaxKind[SyntaxKind["JSDocUndefinedKeyword"] = 284] = "JSDocUndefinedKeyword"; - SyntaxKind[SyntaxKind["JSDocNeverKeyword"] = 285] = "JSDocNeverKeyword"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 286] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 282] = "SyntaxList"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 287] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 283] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 56] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 68] = "LastAssignment"; @@ -367,9 +363,9 @@ var ts; SyntaxKind[SyntaxKind["LastBinaryOperator"] = 68] = "LastBinaryOperator"; SyntaxKind[SyntaxKind["FirstNode"] = 139] = "FirstNode"; SyntaxKind[SyntaxKind["FirstJSDocNode"] = 257] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 282] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 281] = "LastJSDocNode"; SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 273] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 285] = "LastJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 281] = "LastJSDocTagNode"; })(ts.SyntaxKind || (ts.SyntaxKind = {})); var SyntaxKind = ts.SyntaxKind; (function (NodeFlags) { @@ -479,8 +475,6 @@ var ts; TypeFormatFlags[TypeFormatFlags["InElementType"] = 64] = "InElementType"; TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 128] = "UseFullyQualifiedType"; TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 256] = "InFirstTypeArgument"; - TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 512] = "InTypeAlias"; - TypeFormatFlags[TypeFormatFlags["UseTypeAliasValue"] = 1024] = "UseTypeAliasValue"; })(ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var TypeFormatFlags = ts.TypeFormatFlags; (function (SymbolFormatFlags) { @@ -565,8 +559,8 @@ var ts; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; SymbolFlags[SymbolFlags["Value"] = 107455] = "Value"; - SymbolFlags[SymbolFlags["Type"] = 793064] = "Type"; - SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; + SymbolFlags[SymbolFlags["Type"] = 793056] = "Type"; + SymbolFlags[SymbolFlags["Namespace"] = 1536] = "Namespace"; SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; // Variables can be redeclared, but can not redeclare a block-scoped declaration with the @@ -577,10 +571,10 @@ var ts; SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 107455] = "BlockScopedVariableExcludes"; SymbolFlags[SymbolFlags["ParameterExcludes"] = 107455] = "ParameterExcludes"; SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; - SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 900095] = "EnumMemberExcludes"; + SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 107455] = "EnumMemberExcludes"; SymbolFlags[SymbolFlags["FunctionExcludes"] = 106927] = "FunctionExcludes"; SymbolFlags[SymbolFlags["ClassExcludes"] = 899519] = "ClassExcludes"; - SymbolFlags[SymbolFlags["InterfaceExcludes"] = 792968] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 792960] = "InterfaceExcludes"; SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 899327] = "RegularEnumExcludes"; SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 899967] = "ConstEnumExcludes"; SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 106639] = "ValueModuleExcludes"; @@ -588,8 +582,8 @@ var ts; SymbolFlags[SymbolFlags["MethodExcludes"] = 99263] = "MethodExcludes"; SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 41919] = "GetAccessorExcludes"; SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 74687] = "SetAccessorExcludes"; - SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 530920] = "TypeParameterExcludes"; - SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 793064] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 530912] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 793056] = "TypeAliasExcludes"; SymbolFlags[SymbolFlags["AliasExcludes"] = 8388608] = "AliasExcludes"; SymbolFlags[SymbolFlags["ModuleMember"] = 8914931] = "ModuleMember"; SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; @@ -624,7 +618,6 @@ var ts; NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding"; NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding"; NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter"; - NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 4194304] = "AssignmentsMarked"; })(ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); var NodeCheckFlags = ts.NodeCheckFlags; (function (TypeFlags) { @@ -632,63 +625,55 @@ var ts; TypeFlags[TypeFlags["String"] = 2] = "String"; TypeFlags[TypeFlags["Number"] = 4] = "Number"; TypeFlags[TypeFlags["Boolean"] = 8] = "Boolean"; - TypeFlags[TypeFlags["Enum"] = 16] = "Enum"; - TypeFlags[TypeFlags["StringLiteral"] = 32] = "StringLiteral"; - TypeFlags[TypeFlags["NumberLiteral"] = 64] = "NumberLiteral"; - TypeFlags[TypeFlags["BooleanLiteral"] = 128] = "BooleanLiteral"; - TypeFlags[TypeFlags["EnumLiteral"] = 256] = "EnumLiteral"; - TypeFlags[TypeFlags["ESSymbol"] = 512] = "ESSymbol"; - TypeFlags[TypeFlags["Void"] = 1024] = "Void"; - TypeFlags[TypeFlags["Undefined"] = 2048] = "Undefined"; - TypeFlags[TypeFlags["Null"] = 4096] = "Null"; - TypeFlags[TypeFlags["Never"] = 8192] = "Never"; - TypeFlags[TypeFlags["TypeParameter"] = 16384] = "TypeParameter"; - TypeFlags[TypeFlags["Class"] = 32768] = "Class"; - TypeFlags[TypeFlags["Interface"] = 65536] = "Interface"; - TypeFlags[TypeFlags["Reference"] = 131072] = "Reference"; - TypeFlags[TypeFlags["Tuple"] = 262144] = "Tuple"; - TypeFlags[TypeFlags["Union"] = 524288] = "Union"; - TypeFlags[TypeFlags["Intersection"] = 1048576] = "Intersection"; - TypeFlags[TypeFlags["Anonymous"] = 2097152] = "Anonymous"; - TypeFlags[TypeFlags["Instantiated"] = 4194304] = "Instantiated"; + TypeFlags[TypeFlags["Void"] = 16] = "Void"; + TypeFlags[TypeFlags["Undefined"] = 32] = "Undefined"; + TypeFlags[TypeFlags["Null"] = 64] = "Null"; + TypeFlags[TypeFlags["Enum"] = 128] = "Enum"; + TypeFlags[TypeFlags["StringLiteral"] = 256] = "StringLiteral"; + TypeFlags[TypeFlags["TypeParameter"] = 512] = "TypeParameter"; + TypeFlags[TypeFlags["Class"] = 1024] = "Class"; + TypeFlags[TypeFlags["Interface"] = 2048] = "Interface"; + TypeFlags[TypeFlags["Reference"] = 4096] = "Reference"; + TypeFlags[TypeFlags["Tuple"] = 8192] = "Tuple"; + TypeFlags[TypeFlags["Union"] = 16384] = "Union"; + TypeFlags[TypeFlags["Intersection"] = 32768] = "Intersection"; + TypeFlags[TypeFlags["Anonymous"] = 65536] = "Anonymous"; + TypeFlags[TypeFlags["Instantiated"] = 131072] = "Instantiated"; /* @internal */ - TypeFlags[TypeFlags["ObjectLiteral"] = 8388608] = "ObjectLiteral"; + TypeFlags[TypeFlags["FromSignature"] = 262144] = "FromSignature"; + TypeFlags[TypeFlags["ObjectLiteral"] = 524288] = "ObjectLiteral"; /* @internal */ - TypeFlags[TypeFlags["FreshObjectLiteral"] = 16777216] = "FreshObjectLiteral"; + TypeFlags[TypeFlags["FreshObjectLiteral"] = 1048576] = "FreshObjectLiteral"; /* @internal */ - TypeFlags[TypeFlags["ContainsWideningType"] = 33554432] = "ContainsWideningType"; + TypeFlags[TypeFlags["ContainsWideningType"] = 2097152] = "ContainsWideningType"; /* @internal */ - TypeFlags[TypeFlags["ContainsObjectLiteral"] = 67108864] = "ContainsObjectLiteral"; + TypeFlags[TypeFlags["ContainsObjectLiteral"] = 4194304] = "ContainsObjectLiteral"; /* @internal */ - TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 134217728] = "ContainsAnyFunctionType"; - TypeFlags[TypeFlags["ThisType"] = 268435456] = "ThisType"; - TypeFlags[TypeFlags["ObjectLiteralPatternWithComputedProperties"] = 536870912] = "ObjectLiteralPatternWithComputedProperties"; + TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 8388608] = "ContainsAnyFunctionType"; + TypeFlags[TypeFlags["ESSymbol"] = 16777216] = "ESSymbol"; + TypeFlags[TypeFlags["ThisType"] = 33554432] = "ThisType"; + TypeFlags[TypeFlags["ObjectLiteralPatternWithComputedProperties"] = 67108864] = "ObjectLiteralPatternWithComputedProperties"; + TypeFlags[TypeFlags["Never"] = 134217728] = "Never"; /* @internal */ - TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; - TypeFlags[TypeFlags["Literal"] = 480] = "Literal"; + TypeFlags[TypeFlags["Nullable"] = 96] = "Nullable"; /* @internal */ - TypeFlags[TypeFlags["DefinitelyFalsy"] = 7392] = "DefinitelyFalsy"; - TypeFlags[TypeFlags["PossiblyFalsy"] = 7406] = "PossiblyFalsy"; + TypeFlags[TypeFlags["Falsy"] = 112] = "Falsy"; /* @internal */ - TypeFlags[TypeFlags["Intrinsic"] = 16015] = "Intrinsic"; + TypeFlags[TypeFlags["Intrinsic"] = 150995071] = "Intrinsic"; /* @internal */ - TypeFlags[TypeFlags["Primitive"] = 8190] = "Primitive"; - TypeFlags[TypeFlags["StringLike"] = 34] = "StringLike"; - TypeFlags[TypeFlags["NumberLike"] = 340] = "NumberLike"; - TypeFlags[TypeFlags["BooleanLike"] = 136] = "BooleanLike"; - TypeFlags[TypeFlags["EnumLike"] = 272] = "EnumLike"; - TypeFlags[TypeFlags["ObjectType"] = 2588672] = "ObjectType"; - TypeFlags[TypeFlags["UnionOrIntersection"] = 1572864] = "UnionOrIntersection"; - TypeFlags[TypeFlags["StructuredType"] = 4161536] = "StructuredType"; - TypeFlags[TypeFlags["StructuredOrTypeParameter"] = 4177920] = "StructuredOrTypeParameter"; + TypeFlags[TypeFlags["Primitive"] = 16777726] = "Primitive"; + TypeFlags[TypeFlags["StringLike"] = 258] = "StringLike"; + TypeFlags[TypeFlags["NumberLike"] = 132] = "NumberLike"; + TypeFlags[TypeFlags["ObjectType"] = 80896] = "ObjectType"; + TypeFlags[TypeFlags["UnionOrIntersection"] = 49152] = "UnionOrIntersection"; + TypeFlags[TypeFlags["StructuredType"] = 130048] = "StructuredType"; // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never - TypeFlags[TypeFlags["Narrowable"] = 4178943] = "Narrowable"; - TypeFlags[TypeFlags["NotUnionOrUnit"] = 2589191] = "NotUnionOrUnit"; + TypeFlags[TypeFlags["Narrowable"] = 16908175] = "Narrowable"; /* @internal */ - TypeFlags[TypeFlags["RequiresWidening"] = 100663296] = "RequiresWidening"; + TypeFlags[TypeFlags["RequiresWidening"] = 6291456] = "RequiresWidening"; /* @internal */ - TypeFlags[TypeFlags["PropagatingFlags"] = 234881024] = "PropagatingFlags"; + TypeFlags[TypeFlags["PropagatingFlags"] = 14680064] = "PropagatingFlags"; })(ts.TypeFlags || (ts.TypeFlags = {})); var TypeFlags = ts.TypeFlags; (function (SignatureKind) { @@ -908,103 +893,7 @@ var ts; })(ts.CharacterCodes || (ts.CharacterCodes = {})); var CharacterCodes = ts.CharacterCodes; })(ts || (ts = {})); -/*@internal*/ -var ts; -(function (ts) { - /** Gets a timestamp with (at least) ms resolution */ - ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); }; -})(ts || (ts = {})); -/*@internal*/ -/** Performance measurements for the compiler. */ -var ts; -(function (ts) { - var performance; - (function (performance) { - var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true - ? onProfilerEvent - : function (markName) { }; - var enabled = false; - var profilerStart = 0; - var counts; - var marks; - var measures; - /** - * Marks a performance event. - * - * @param markName The name of the mark. - */ - function mark(markName) { - if (enabled) { - marks[markName] = ts.timestamp(); - counts[markName] = (counts[markName] || 0) + 1; - profilerEvent(markName); - } - } - performance.mark = mark; - /** - * Adds a performance measurement with the specified name. - * - * @param measureName The name of the performance measurement. - * @param startMarkName The name of the starting mark. If not supplied, the point at which the - * profiler was enabled is used. - * @param endMarkName The name of the ending mark. If not supplied, the current timestamp is - * used. - */ - function measure(measureName, startMarkName, endMarkName) { - if (enabled) { - var end = endMarkName && marks[endMarkName] || ts.timestamp(); - var start = startMarkName && marks[startMarkName] || profilerStart; - measures[measureName] = (measures[measureName] || 0) + (end - start); - } - } - performance.measure = measure; - /** - * Gets the number of times a marker was encountered. - * - * @param markName The name of the mark. - */ - function getCount(markName) { - return counts && counts[markName] || 0; - } - performance.getCount = getCount; - /** - * Gets the total duration of all measurements with the supplied name. - * - * @param measureName The name of the measure whose durations should be accumulated. - */ - function getDuration(measureName) { - return measures && measures[measureName] || 0; - } - performance.getDuration = getDuration; - /** - * Iterate over each measure, performing some action - * - * @param cb The action to perform for each measure - */ - function forEachMeasure(cb) { - for (var key in measures) { - cb(key, measures[key]); - } - } - performance.forEachMeasure = forEachMeasure; - /** Enables (and resets) performance measurements for the compiler. */ - function enable() { - counts = ts.createMap(); - marks = ts.createMap(); - measures = ts.createMap(); - enabled = true; - profilerStart = ts.timestamp(); - } - performance.enable = enable; - /** Disables performance measurements for the compiler. */ - function disable() { - enabled = false; - } - performance.disable = disable; - })(performance = ts.performance || (ts.performance = {})); -})(ts || (ts = {})); /// -/// /* @internal */ var ts; (function (ts) { @@ -1023,32 +912,14 @@ var ts; Ternary[Ternary["True"] = -1] = "True"; })(ts.Ternary || (ts.Ternary = {})); var Ternary = ts.Ternary; - var createObject = Object.create; - function createMap(template) { - var map = createObject(null); // tslint:disable-line:no-null-keyword - // Using 'delete' on an object causes V8 to put the object in dictionary mode. - // This disables creation of hidden classes, which are expensive when an object is - // constantly changing shape. - map["__"] = undefined; - delete map["__"]; - // Copies keys/values from template. Note that for..in will not throw if - // template is undefined, and instead will just exit the loop. - for (var key in template) - if (hasOwnProperty.call(template, key)) { - map[key] = template[key]; - } - return map; - } - ts.createMap = createMap; function createFileMap(keyMapper) { - var files = createMap(); + var files = {}; return { get: get, set: set, contains: contains, remove: remove, forEachValue: forEachValueInMap, - getKeys: getKeys, clear: clear }; function forEachValueInMap(f) { @@ -1056,13 +927,6 @@ var ts; f(key, files[key]); } } - function getKeys() { - var keys = []; - for (var key in files) { - keys.push(key); - } - return keys; - } // path should already be well-formed so it does not need to be normalized function get(path) { return files[toKey(path)]; @@ -1071,14 +935,14 @@ var ts; files[toKey(path)] = value; } function contains(path) { - return toKey(path) in files; + return hasProperty(files, toKey(path)); } function remove(path) { var key = toKey(path); delete files[key]; } function clear() { - files = createMap(); + files = {}; } function toKey(path) { return keyMapper ? keyMapper(path) : path; @@ -1115,36 +979,11 @@ var ts; return undefined; } ts.forEach = forEach; - /** Works like Array.prototype.find, returning `undefined` if no element satisfying the predicate is found. */ - function find(array, predicate) { - for (var i = 0, len = array.length; i < len; i++) { - var value = array[i]; - if (predicate(value, i)) { - return value; - } - } - return undefined; - } - ts.find = find; - /** - * Returns the first truthy result of `callback`, or else fails. - * This is like `forEach`, but never returns undefined. - */ - function findMap(array, callback) { - for (var i = 0, len = array.length; i < len; i++) { - var result = callback(array[i], i); - if (result) { - return result; - } - } - Debug.fail(); - } - ts.findMap = findMap; - function contains(array, value) { + function contains(array, value, areEqual) { if (array) { for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { var v = array_1[_i]; - if (v === value) { + if (areEqual ? areEqual(v, value) : v === value) { return true; } } @@ -1185,48 +1024,20 @@ var ts; return count; } ts.countWhere = countWhere; - /** - * Filters an array by a predicate function. Returns the same array instance if the predicate is - * true for all elements, otherwise returns a new array instance containing the filtered subset. - */ function filter(array, f) { + var result; if (array) { - var len = array.length; - var i = 0; - while (i < len && f(array[i])) - i++; - if (i < len) { - var result = array.slice(0, i); - i++; - while (i < len) { - var item = array[i]; - if (f(item)) { - result.push(item); - } - i++; + result = []; + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var item = array_3[_i]; + if (f(item)) { + result.push(item); } - return result; } } - return array; + return result; } ts.filter = filter; - function removeWhere(array, f) { - var outIndex = 0; - for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { - var item = array_3[_i]; - if (!f(item)) { - array[outIndex] = item; - outIndex++; - } - } - if (outIndex !== array.length) { - array.length = outIndex; - return true; - } - return false; - } - ts.removeWhere = removeWhere; function filterMutate(array, f) { var outIndex = 0; for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { @@ -1259,20 +1070,15 @@ var ts; return array1.concat(array2); } ts.concatenate = concatenate; - // TODO: fixme (N^2) - add optional comparer so collection can be sorted before deduplication. function deduplicate(array, areEqual) { var result; if (array) { result = []; - loop: for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { var item = array_6[_i]; - for (var _a = 0, result_1 = result; _a < result_1.length; _a++) { - var res = result_1[_a]; - if (areEqual ? areEqual(res, item) : res === item) { - continue loop; - } + if (!contains(result, item, areEqual)) { + result.push(item); } - result.push(item); } } return result; @@ -1323,22 +1129,16 @@ var ts; * @param array A sorted array whose first element must be no larger than number * @param number The value to be searched for in the array. */ - function binarySearch(array, value, comparer) { - if (!array || array.length === 0) { - return -1; - } + function binarySearch(array, value) { var low = 0; var high = array.length - 1; - comparer = comparer !== undefined - ? comparer - : function (v1, v2) { return (v1 < v2 ? -1 : (v1 > v2 ? 1 : 0)); }; while (low <= high) { var middle = low + ((high - low) >> 1); var midValue = array[middle]; - if (comparer(midValue, value) === 0) { + if (midValue === value) { return middle; } - else if (comparer(midValue, value) > 0) { + else if (midValue > value) { high = middle - 1; } else { @@ -1394,191 +1194,117 @@ var ts; } ts.reduceRight = reduceRight; var hasOwnProperty = Object.prototype.hasOwnProperty; - /** - * Indicates whether a map-like contains an own property with the specified key. - * - * NOTE: This is intended for use only with MapLike objects. For Map objects, use - * the 'in' operator. - * - * @param map A map-like. - * @param key A property key. - */ function hasProperty(map, key) { return hasOwnProperty.call(map, key); } ts.hasProperty = hasProperty; - /** - * Gets the value of an owned property in a map-like. - * - * NOTE: This is intended for use only with MapLike objects. For Map objects, use - * an indexer. - * - * @param map A map-like. - * @param key A property key. - */ + function getKeys(map) { + var keys = []; + for (var key in map) { + keys.push(key); + } + return keys; + } + ts.getKeys = getKeys; function getProperty(map, key) { return hasOwnProperty.call(map, key) ? map[key] : undefined; } ts.getProperty = getProperty; - /** - * Gets the owned, enumerable property keys of a map-like. - * - * NOTE: This is intended for use with MapLike objects. For Map objects, use - * Object.keys instead as it offers better performance. - * - * @param map A map-like. - */ - function getOwnKeys(map) { - var keys = []; - for (var key in map) - if (hasOwnProperty.call(map, key)) { - keys.push(key); + function isEmpty(map) { + for (var id in map) { + if (hasProperty(map, id)) { + return false; } - return keys; + } + return true; } - ts.getOwnKeys = getOwnKeys; - /** - * Enumerates the properties of a Map, invoking a callback and returning the first truthy result. - * - * @param map A map for which properties should be enumerated. - * @param callback A callback to invoke for each property. - */ - function forEachProperty(map, callback) { + ts.isEmpty = isEmpty; + function clone(object) { + var result = {}; + for (var id in object) { + result[id] = object[id]; + } + return result; + } + ts.clone = clone; + function extend(first, second) { + var result = {}; + for (var id in first) { + result[id] = first[id]; + } + for (var id in second) { + if (!hasProperty(result, id)) { + result[id] = second[id]; + } + } + return result; + } + ts.extend = extend; + function forEachValue(map, callback) { var result; - for (var key in map) { - if (result = callback(map[key], key)) + for (var id in map) { + if (result = callback(map[id])) break; } return result; } - ts.forEachProperty = forEachProperty; - /** - * Returns true if a Map has some matching property. - * - * @param map A map whose properties should be tested. - * @param predicate An optional callback used to test each property. - */ - function someProperties(map, predicate) { - for (var key in map) { - if (!predicate || predicate(map[key], key)) - return true; + ts.forEachValue = forEachValue; + function forEachKey(map, callback) { + var result; + for (var id in map) { + if (result = callback(id)) + break; } - return false; + return result; } - ts.someProperties = someProperties; - /** - * Performs a shallow copy of the properties from a source Map to a target MapLike - * - * @param source A map from which properties should be copied. - * @param target A map to which properties should be copied. - */ - function copyProperties(source, target) { - for (var key in source) { - target[key] = source[key]; + ts.forEachKey = forEachKey; + function lookUp(map, key) { + return hasProperty(map, key) ? map[key] : undefined; + } + ts.lookUp = lookUp; + function copyMap(source, target) { + for (var p in source) { + target[p] = source[p]; } } - ts.copyProperties = copyProperties; + ts.copyMap = copyMap; + /** + * Creates a map from the elements of an array. + * + * @param array the array of input elements. + * @param makeKey a function that produces a key for a given element. + * + * This function makes no effort to avoid collisions; if any two elements produce + * the same key with the given 'makeKey' function, then the element with the higher + * index in the array will be the one associated with the produced key. + */ + function arrayToMap(array, makeKey) { + var result = {}; + forEach(array, function (value) { + result[makeKey(value)] = value; + }); + return result; + } + ts.arrayToMap = arrayToMap; /** * Reduce the properties of a map. * - * NOTE: This is intended for use with Map objects. For MapLike objects, use - * reduceOwnProperties instead as it offers better runtime safety. - * * @param map The map to reduce * @param callback An aggregation function that is called for each entry in the map * @param initial The initial value for the reduction. */ function reduceProperties(map, callback, initial) { var result = initial; - for (var key in map) { - result = callback(result, map[key], String(key)); + if (map) { + for (var key in map) { + if (hasProperty(map, key)) { + result = callback(result, map[key], String(key)); + } + } } return result; } ts.reduceProperties = reduceProperties; - /** - * Reduce the properties defined on a map-like (but not from its prototype chain). - * - * NOTE: This is intended for use with MapLike objects. For Map objects, use - * reduceProperties instead as it offers better performance. - * - * @param map The map-like to reduce - * @param callback An aggregation function that is called for each entry in the map - * @param initial The initial value for the reduction. - */ - function reduceOwnProperties(map, callback, initial) { - var result = initial; - for (var key in map) - if (hasOwnProperty.call(map, key)) { - result = callback(result, map[key], String(key)); - } - return result; - } - ts.reduceOwnProperties = reduceOwnProperties; - /** - * Performs a shallow equality comparison of the contents of two map-likes. - * - * @param left A map-like whose properties should be compared. - * @param right A map-like whose properties should be compared. - */ - function equalOwnProperties(left, right, equalityComparer) { - if (left === right) - return true; - if (!left || !right) - return false; - for (var key in left) - if (hasOwnProperty.call(left, key)) { - if (!hasOwnProperty.call(right, key) === undefined) - return false; - if (equalityComparer ? !equalityComparer(left[key], right[key]) : left[key] !== right[key]) - return false; - } - for (var key in right) - if (hasOwnProperty.call(right, key)) { - if (!hasOwnProperty.call(left, key)) - return false; - } - return true; - } - ts.equalOwnProperties = equalOwnProperties; - function arrayToMap(array, makeKey, makeValue) { - var result = createMap(); - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var value = array_8[_i]; - result[makeKey(value)] = makeValue ? makeValue(value) : value; - } - return result; - } - ts.arrayToMap = arrayToMap; - function cloneMap(map) { - var clone = createMap(); - copyProperties(map, clone); - return clone; - } - ts.cloneMap = cloneMap; - function clone(object) { - var result = {}; - for (var id in object) { - if (hasOwnProperty.call(object, id)) { - result[id] = object[id]; - } - } - return result; - } - ts.clone = clone; - function extend(first, second) { - var result = {}; - for (var id in second) - if (hasOwnProperty.call(second, id)) { - result[id] = second[id]; - } - for (var id in first) - if (hasOwnProperty.call(first, id)) { - result[id] = first[id]; - } - return result; - } - ts.extend = extend; /** * Tests whether a value is an array. */ @@ -1603,7 +1329,9 @@ var ts; } ts.localizedDiagnosticMessages = undefined; function getLocaleSpecificMessage(message) { - return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message; + return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] + ? ts.localizedDiagnosticMessages[message.key] + : message.message; } ts.getLocaleSpecificMessage = getLocaleSpecificMessage; function createFileDiagnostic(file, start, length, message) { @@ -2028,19 +1756,10 @@ var ts; return true; } ts.containsPath = containsPath; - /* @internal */ - function startsWith(str, prefix) { - return str.lastIndexOf(prefix, 0) === 0; - } - ts.startsWith = startsWith; - /* @internal */ - function endsWith(str, suffix) { - var expectedPos = str.length - suffix.length; - return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; - } - ts.endsWith = endsWith; function fileExtensionIs(path, extension) { - return path.length > extension.length && endsWith(path, extension); + var pathLen = path.length; + var extLen = extension.length; + return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension; } ts.fileExtensionIs = fileExtensionIs; function fileExtensionIsAny(path, extensions) { @@ -2058,25 +1777,10 @@ var ts; // proof. var reservedCharacterPattern = /[^\w\s\/]/g; var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; - /** - * Matches any single directory segment unless it is the last segment and a .min.js file - * Breakdown: - * [^./] # matches everything up to the first . character (excluding directory seperators) - * (\\.(?!min\\.js$))? # matches . characters but not if they are part of the .min.js file extension - */ - var singleAsteriskRegexFragmentFiles = "([^./]|(\\.(?!min\\.js$))?)*"; - var singleAsteriskRegexFragmentOther = "[^/]*"; function getRegularExpressionForWildcard(specs, basePath, usage) { if (specs === undefined || specs.length === 0) { return undefined; } - var replaceWildcardCharacter = usage === "files" ? replaceWildCardCharacterFiles : replaceWildCardCharacterOther; - var singleAsteriskRegexFragment = usage === "files" ? singleAsteriskRegexFragmentFiles : singleAsteriskRegexFragmentOther; - /** - * Regex for the ** wildcard. Matches any number of subdirectories. When used for including - * files or directories, does not match subdirectories that start with a . character - */ - var doubleAsteriskRegexFragment = usage === "exclude" ? "(/.+?)?" : "(/[^/.][^/]*)*?"; var pattern = ""; var hasWrittenSubpattern = false; spec: for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { @@ -2101,7 +1805,7 @@ var ts; if (hasRecursiveDirectoryWildcard) { continue spec; } - subpattern += doubleAsteriskRegexFragment; + subpattern += "(/.+?)?"; hasRecursiveDirectoryWildcard = true; hasWrittenComponent = true; } @@ -2113,19 +1817,6 @@ var ts; if (hasWrittenComponent) { subpattern += ts.directorySeparator; } - if (usage !== "exclude") { - // The * and ? wildcards should not match directories or files that start with . if they - // appear first in a component. Dotted directories and files can be included explicitly - // like so: **/.*/.* - if (component.charCodeAt(0) === 42 /* asterisk */) { - subpattern += "([^./]" + singleAsteriskRegexFragment + ")?"; - component = component.substr(1); - } - else if (component.charCodeAt(0) === 63 /* question */) { - subpattern += "[^./]"; - component = component.substr(1); - } - } subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); hasWrittenComponent = true; } @@ -2146,14 +1837,8 @@ var ts; return "^(" + pattern + (usage === "exclude" ? ")($|/)" : ")$"); } ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; - function replaceWildCardCharacterFiles(match) { - return replaceWildcardCharacter(match, singleAsteriskRegexFragmentFiles); - } - function replaceWildCardCharacterOther(match) { - return replaceWildcardCharacter(match, singleAsteriskRegexFragmentOther); - } - function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { - return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; + function replaceWildcardCharacter(match) { + return match === "*" ? "[^/]*" : match === "?" ? "[^/]" : "\\" + match; } function getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { path = normalizePath(path); @@ -2272,22 +1957,12 @@ var ts; * List of supported extensions in order of file resolution precedence. */ ts.supportedTypeScriptExtensions = [".ts", ".tsx", ".d.ts"]; - /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ - ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"]; ts.supportedJavascriptExtensions = [".js", ".jsx"]; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); function getSupportedExtensions(options) { return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } ts.getSupportedExtensions = getSupportedExtensions; - function hasJavaScriptFileExtension(fileName) { - return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); - } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); - } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; function isSupportedSourceFileName(fileName, compilerOptions) { if (!fileName) { return false; @@ -2365,13 +2040,9 @@ var ts; } ts.removeFileExtension = removeFileExtension; function tryRemoveExtension(path, extension) { - return fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined; + return fileExtensionIs(path, extension) ? path.substring(0, path.length - extension.length) : undefined; } ts.tryRemoveExtension = tryRemoveExtension; - function removeExtension(path, extension) { - return path.substring(0, path.length - extension.length); - } - ts.removeExtension = removeExtension; function isJsxOrTsxExtension(ext) { return ext === ".jsx" || ext === ".tsx"; } @@ -2399,8 +2070,6 @@ var ts; } ts.objectAllocator = { getNodeConstructor: function () { return Node; }, - getTokenConstructor: function () { return Node; }, - getIdentifierConstructor: function () { return Node; }, getSourceFileConstructor: function () { return Node; }, getSymbolConstructor: function () { return Symbol; }, getTypeConstructor: function () { return Type; }, @@ -2453,68 +2122,6 @@ var ts; : (function (fileName) { return fileName.toLowerCase(); }); } ts.createGetCanonicalFileName = createGetCanonicalFileName; - function trace(host, message) { - host.trace(formatMessage.apply(undefined, arguments)); - } - ts.trace = trace; - /* @internal */ - function isTraceEnabled(compilerOptions, host) { - return compilerOptions.traceResolution && host.trace !== undefined; - } - ts.isTraceEnabled = isTraceEnabled; - /* @internal */ - function hasZeroOrOneAsteriskCharacter(str) { - var seenAsterisk = false; - for (var i = 0; i < str.length; i++) { - if (str.charCodeAt(i) === 42 /* asterisk */) { - if (!seenAsterisk) { - seenAsterisk = true; - } - else { - // have already seen asterisk - return false; - } - } - } - return true; - } - ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - /* @internal */ - function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; - } - ts.createResolvedModule = createResolvedModule; - /* @internal */ - function isExternalModuleNameRelative(moduleName) { - // TypeScript 1.0 spec (April 2014): 11.2.1 - // An external module name is "relative" if the first term is "." or "..". - return /^\.\.?($|[\\/])/.test(moduleName); - } - ts.isExternalModuleNameRelative = isExternalModuleNameRelative; - /* @internal */ - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - return jsonText ? JSON.parse(jsonText) : {}; - } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - return {}; - } - } - ts.readJson = readJson; - /* @internal */ - function getEmitModuleKind(compilerOptions) { - return typeof compilerOptions.module === "number" ? - compilerOptions.module : - getEmitScriptTarget(compilerOptions) === 2 /* ES6 */ ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; - } - ts.getEmitModuleKind = getEmitModuleKind; - /* @internal */ - function getEmitScriptTarget(compilerOptions) { - return compilerOptions.target || 0 /* ES3 */; - } - ts.getEmitScriptTarget = getEmitScriptTarget; })(ts || (ts = {})); /// var ts; @@ -2609,7 +2216,7 @@ var ts; function readDirectory(path, extensions, excludes, includes) { return ts.matchFiles(path, extensions, excludes, includes, /*useCaseSensitiveFileNames*/ false, shell.CurrentDirectory, getAccessibleFileSystemEntries); } - var wscriptSystem = { + return { args: args, newLine: "\r\n", useCaseSensitiveFileNames: false, @@ -2628,7 +2235,7 @@ var ts; return fso.FolderExists(path); }, createDirectory: function (directoryName) { - if (!wscriptSystem.directoryExists(directoryName)) { + if (!this.directoryExists(directoryName)) { fso.CreateFolder(directoryName); } }, @@ -2648,7 +2255,6 @@ var ts; } } }; - return wscriptSystem; } function getNodeSystem() { var _fs = require("fs"); @@ -2657,14 +2263,14 @@ var ts; var _crypto = require("crypto"); var useNonPollingWatchers = process.env["TSC_NONPOLLING_WATCHER"]; function createWatchedFileSet() { - var dirWatchers = ts.createMap(); + var dirWatchers = {}; // One file can have multiple watchers - var fileWatcherCallbacks = ts.createMap(); + var fileWatcherCallbacks = {}; return { addFile: addFile, removeFile: removeFile }; function reduceDirWatcherRefCountForFile(fileName) { var dirName = ts.getDirectoryPath(fileName); - var watcher = dirWatchers[dirName]; - if (watcher) { + if (ts.hasProperty(dirWatchers, dirName)) { + var watcher = dirWatchers[dirName]; watcher.referenceCount -= 1; if (watcher.referenceCount <= 0) { watcher.close(); @@ -2673,18 +2279,23 @@ var ts; } } function addDirWatcher(dirPath) { - var watcher = dirWatchers[dirPath]; - if (watcher) { - watcher.referenceCount += 1; + if (ts.hasProperty(dirWatchers, dirPath)) { + var watcher_1 = dirWatchers[dirPath]; + watcher_1.referenceCount += 1; return; } - watcher = _fs.watch(dirPath, { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); + var watcher = _fs.watch(dirPath, { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); watcher.referenceCount = 1; dirWatchers[dirPath] = watcher; return; } function addFileWatcherCallback(filePath, callback) { - (fileWatcherCallbacks[filePath] || (fileWatcherCallbacks[filePath] = [])).push(callback); + if (ts.hasProperty(fileWatcherCallbacks, filePath)) { + fileWatcherCallbacks[filePath].push(callback); + } + else { + fileWatcherCallbacks[filePath] = [callback]; + } } function addFile(fileName, callback) { addFileWatcherCallback(fileName, callback); @@ -2696,9 +2307,8 @@ var ts; reduceDirWatcherRefCountForFile(watchedFile.fileName); } function removeFileWatcherCallback(filePath, callback) { - var callbacks = fileWatcherCallbacks[filePath]; - if (callbacks) { - var newCallbacks = ts.copyListRemovingItem(callback, callbacks); + if (ts.hasProperty(fileWatcherCallbacks, filePath)) { + var newCallbacks = ts.copyListRemovingItem(callback, fileWatcherCallbacks[filePath]); if (newCallbacks.length === 0) { delete fileWatcherCallbacks[filePath]; } @@ -2713,7 +2323,7 @@ var ts; ? undefined : ts.getNormalizedAbsolutePath(relativeFileName, baseDirPath); // Some applications save a working file via rename operations - if ((eventName === "change" || eventName === "rename") && fileWatcherCallbacks[fileName]) { + if ((eventName === "change" || eventName === "rename") && ts.hasProperty(fileWatcherCallbacks, fileName)) { for (var _i = 0, _a = fileWatcherCallbacks[fileName]; _i < _a.length; _i++) { var fileCallback = _a[_i]; fileCallback(fileName); @@ -2834,7 +2444,7 @@ var ts; function getDirectories(path) { return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1 /* Directory */); }); } - var nodeSystem = { + return { args: process.argv.slice(2), newLine: _os.EOL, useCaseSensitiveFileNames: useCaseSensitiveFileNames, @@ -2890,7 +2500,7 @@ var ts; fileExists: fileExists, directoryExists: directoryExists, createDirectory: function (directoryName) { - if (!nodeSystem.directoryExists(directoryName)) { + if (!this.directoryExists(directoryName)) { _fs.mkdirSync(directoryName); } }, @@ -2938,7 +2548,6 @@ var ts; return _fs.realpathSync(path); } }; - return nodeSystem; } function getChakraSystem() { var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); }); @@ -2973,40 +2582,20 @@ var ts; realpath: realpath }; } - function recursiveCreateDirectory(directoryPath, sys) { - var basePath = ts.getDirectoryPath(directoryPath); - var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath); - if (shouldCreateParent) { - recursiveCreateDirectory(basePath, sys); - } - if (shouldCreateParent || !sys.directoryExists(directoryPath)) { - sys.createDirectory(directoryPath); - } - } - var sys; if (typeof ChakraHost !== "undefined") { - sys = getChakraSystem(); + return getChakraSystem(); } else if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { - sys = getWScriptSystem(); + return getWScriptSystem(); } else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") { // process and process.nextTick checks if current environment is node-like // process.browser check excludes webpack and browserify - sys = getNodeSystem(); + return getNodeSystem(); } - if (sys) { - // patch writefile to create folder before writing the file - var originalWriteFile_1 = sys.writeFile; - sys.writeFile = function (path, data, writeBom) { - var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path)); - if (directoryPath && !sys.directoryExists(directoryPath)) { - recursiveCreateDirectory(directoryPath, sys); - } - originalWriteFile_1.call(sys, path, data, writeBom); - }; + else { + return undefined; // Unsupported host } - return sys; })(); })(ts || (ts = {})); // @@ -3454,7 +3043,6 @@ var ts; Object_is_possibly_undefined: { code: 2532, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_undefined_2532", message: "Object is possibly 'undefined'." }, Object_is_possibly_null_or_undefined: { code: 2533, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_null_or_undefined_2533", message: "Object is possibly 'null' or 'undefined'." }, A_function_returning_never_cannot_have_a_reachable_end_point: { code: 2534, category: ts.DiagnosticCategory.Error, key: "A_function_returning_never_cannot_have_a_reachable_end_point_2534", message: "A function returning 'never' cannot have a reachable end point." }, - Enum_type_0_has_members_with_initializers_that_are_not_literals: { code: 2535, category: ts.DiagnosticCategory.Error, key: "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", message: "Enum type '{0}' has members with initializers that are not literals." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "The return type of a JSX element constructor must return an object type." }, JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -3502,9 +3090,6 @@ var ts; All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, - A_class_must_be_declared_after_its_base_class: { code: 2690, category: ts.DiagnosticCategory.Error, key: "A_class_must_be_declared_after_its_base_class_2690", message: "A class must be declared after its base class." }, - An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: { code: 2691, category: ts.DiagnosticCategory.Error, key: "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691", message: "An import path cannot end with a '{0}' extension. Consider importing '{1}' instead." }, - _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: { code: 2692, category: ts.DiagnosticCategory.Error, key: "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", message: "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible." }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -3575,7 +3160,7 @@ var ts; Parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4078, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", message: "Parameter '{0}' of exported function has or is using private name '{1}'." }, Exported_type_alias_0_has_or_is_using_private_name_1: { code: 4081, category: ts.DiagnosticCategory.Error, key: "Exported_type_alias_0_has_or_is_using_private_name_1_4081", message: "Exported type alias '{0}' has or is using private name '{1}'." }, Default_export_of_the_module_has_or_is_using_private_name_0: { code: 4082, category: ts.DiagnosticCategory.Error, key: "Default_export_of_the_module_has_or_is_using_private_name_0_4082", message: "Default export of the module has or is using private name '{0}'." }, - Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", message: "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict." }, + Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_to_resolve_this_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_t_4090", message: "Conflicting library definitions for '{0}' found at '{1}' and '{2}'. Copy the correct file to the 'typings' folder to resolve this conflict." }, The_current_host_does_not_support_the_0_option: { code: 5001, category: ts.DiagnosticCategory.Error, key: "The_current_host_does_not_support_the_0_option_5001", message: "The current host does not support the '{0}' option." }, Cannot_find_the_common_subdirectory_path_for_the_input_files: { code: 5009, category: ts.DiagnosticCategory.Error, key: "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", message: "Cannot find the common subdirectory path for the input files." }, File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5010, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", message: "File specification cannot end in a recursive directory wildcard ('**'): '{0}'." }, @@ -3603,7 +3188,6 @@ var ts; Substitutions_for_pattern_0_should_be_an_array: { code: 5063, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_should_be_an_array_5063", message: "Substitutions for pattern '{0}' should be an array." }, Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: { code: 5064, category: ts.DiagnosticCategory.Error, key: "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", message: "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'." }, File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5065, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", message: "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'." }, - Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: { code: 5066, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", message: "Substitutions for pattern '{0}' shouldn't be an empty array." }, Concatenate_and_emit_output_to_single_file: { code: 6001, category: ts.DiagnosticCategory.Message, key: "Concatenate_and_emit_output_to_single_file_6001", message: "Concatenate and emit output to single file." }, Generates_corresponding_d_ts_file: { code: 6002, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_d_ts_file_6002", message: "Generates corresponding '.d.ts' file." }, Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: ts.DiagnosticCategory.Message, key: "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", message: "Specify the location where debugger should locate map files instead of generated locations." }, @@ -3720,12 +3304,10 @@ var ts; Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." }, File_name_0_has_a_1_extension_stripping_it: { code: 6132, category: ts.DiagnosticCategory.Message, key: "File_name_0_has_a_1_extension_stripping_it_6132", message: "File name '{0}' has a '{1}' extension - stripping it" }, _0_is_declared_but_never_used: { code: 6133, category: ts.DiagnosticCategory.Error, key: "_0_is_declared_but_never_used_6133", message: "'{0}' is declared but never used." }, - Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, - Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, + Report_Errors_on_Unused_Locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Locals_6134", message: "Report Errors on Unused Locals." }, + Report_Errors_on_Unused_Parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Parameters_6135", message: "Report Errors on Unused Parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" }, No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" }, - Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, - Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6139, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6139", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -3734,6 +3316,7 @@ var ts; Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: { code: 7011, category: ts.DiagnosticCategory.Error, key: "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", message: "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type." }, Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7013, category: ts.DiagnosticCategory.Error, key: "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", message: "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type." }, Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: { code: 7015, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", message: "Element implicitly has an 'any' type because index expression is not of type 'number'." }, + Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation: { code: 7016, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation_7016", message: "Property '{0}' implicitly has type 'any', because its 'set' accessor lacks a type annotation." }, Index_signature_of_object_type_implicitly_has_an_any_type: { code: 7017, category: ts.DiagnosticCategory.Error, key: "Index_signature_of_object_type_implicitly_has_an_any_type_7017", message: "Index signature of object type implicitly has an 'any' type." }, Object_literal_s_property_0_implicitly_has_an_1_type: { code: 7018, category: ts.DiagnosticCategory.Error, key: "Object_literal_s_property_0_implicitly_has_an_1_type_7018", message: "Object literal's property '{0}' implicitly has an '{1}' type." }, Rest_parameter_0_implicitly_has_an_any_type: { code: 7019, category: ts.DiagnosticCategory.Error, key: "Rest_parameter_0_implicitly_has_an_any_type_7019", message: "Rest parameter '{0}' implicitly has an 'any[]' type." }, @@ -3748,8 +3331,6 @@ var ts; Fallthrough_case_in_switch: { code: 7029, category: ts.DiagnosticCategory.Error, key: "Fallthrough_case_in_switch_7029", message: "Fallthrough case in switch." }, Not_all_code_paths_return_a_value: { code: 7030, category: ts.DiagnosticCategory.Error, key: "Not_all_code_paths_return_a_value_7030", message: "Not all code paths return a value." }, Binding_element_0_implicitly_has_an_1_type: { code: 7031, category: ts.DiagnosticCategory.Error, key: "Binding_element_0_implicitly_has_an_1_type_7031", message: "Binding element '{0}' implicitly has an '{1}' type." }, - Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { code: 7032, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", message: "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation." }, - Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { code: 7033, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", message: "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation." }, You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, @@ -3789,7 +3370,7 @@ var ts; return token >= 69 /* Identifier */; } ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; - var textToToken = ts.createMap({ + var textToToken = { "abstract": 115 /* AbstractKeyword */, "any": 117 /* AnyKeyword */, "as": 116 /* AsKeyword */, @@ -3913,7 +3494,7 @@ var ts; "|=": 67 /* BarEqualsToken */, "^=": 68 /* CaretEqualsToken */, "@": 55 /* AtToken */ - }); + }; /* As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers IdentifierStart :: @@ -3999,7 +3580,9 @@ var ts; function makeReverseMap(source) { var result = []; for (var name_4 in source) { - result[source[name_4]] = name_4; + if (source.hasOwnProperty(name_4)) { + result[source[name_4]] = name_4; + } } return result; } @@ -5487,6 +5070,24 @@ var ts; return node.end - node.pos; } ts.getFullWidth = getFullWidth; + function mapIsEqualTo(map1, map2) { + if (!map1 || !map2) { + return map1 === map2; + } + return containsAll(map1, map2) && containsAll(map2, map1); + } + ts.mapIsEqualTo = mapIsEqualTo; + function containsAll(map, other) { + for (var key in map) { + if (!ts.hasProperty(map, key)) { + continue; + } + if (!ts.hasProperty(other, key) || map[key] !== other[key]) { + return false; + } + } + return true; + } function arrayIsEqualTo(array1, array2, equaler) { if (!array1 || !array2) { return array1 === array2; @@ -5504,7 +5105,7 @@ var ts; } ts.arrayIsEqualTo = arrayIsEqualTo; function hasResolvedModule(sourceFile, moduleNameText) { - return !!(sourceFile.resolvedModules && sourceFile.resolvedModules[moduleNameText]); + return sourceFile.resolvedModules && ts.hasProperty(sourceFile.resolvedModules, moduleNameText); } ts.hasResolvedModule = hasResolvedModule; function getResolvedModule(sourceFile, moduleNameText) { @@ -5513,14 +5114,14 @@ var ts; ts.getResolvedModule = getResolvedModule; function setResolvedModule(sourceFile, moduleNameText, resolvedModule) { if (!sourceFile.resolvedModules) { - sourceFile.resolvedModules = ts.createMap(); + sourceFile.resolvedModules = {}; } sourceFile.resolvedModules[moduleNameText] = resolvedModule; } ts.setResolvedModule = setResolvedModule; function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) { if (!sourceFile.resolvedTypeReferenceDirectiveNames) { - sourceFile.resolvedTypeReferenceDirectiveNames = ts.createMap(); + sourceFile.resolvedTypeReferenceDirectiveNames = {}; } sourceFile.resolvedTypeReferenceDirectiveNames[typeReferenceDirectiveName] = resolvedTypeReferenceDirective; } @@ -5542,7 +5143,7 @@ var ts; } for (var i = 0; i < names.length; i++) { var newResolution = newResolutions[i]; - var oldResolution = oldResolutions && oldResolutions[names[i]]; + var oldResolution = oldResolutions && ts.hasProperty(oldResolutions, names[i]) ? oldResolutions[names[i]] : undefined; var changed = oldResolution ? !newResolution || !comparer(oldResolution, newResolution) : newResolution; @@ -5676,20 +5277,16 @@ var ts; // the syntax list itself considers them as normal trivia. Therefore if we simply skip // trivia for the list, we may have skipped the JSDocComment as well. So we should process its // first child to determine the actual position of its first token. - if (node.kind === 286 /* SyntaxList */ && node._children.length > 0) { + if (node.kind === 282 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDocComment); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); } ts.getTokenPosOfNode = getTokenPosOfNode; function isJSDocNode(node) { - return node.kind >= 257 /* FirstJSDocNode */ && node.kind <= 282 /* LastJSDocNode */; + return node.kind >= 257 /* FirstJSDocNode */ && node.kind <= 281 /* LastJSDocNode */; } ts.isJSDocNode = isJSDocNode; - function isJSDocTag(node) { - return node.kind >= 273 /* FirstJSDocTagNode */ && node.kind <= 285 /* LastJSDocTagNode */; - } - ts.isJSDocTag = isJSDocTag; function getNonDecoratorTokenPosOfNode(node, sourceFile) { if (nodeIsMissing(node) || !node.decorators) { return getTokenPosOfNode(node, sourceFile); @@ -5744,14 +5341,11 @@ var ts; (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; - function isShorthandAmbientModuleSymbol(moduleSymbol) { - return isShorthandAmbientModule(moduleSymbol.valueDeclaration); - } - ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; function isShorthandAmbientModule(node) { // The only kind of module that can be missing a body is a shorthand ambient module. return node.kind === 225 /* ModuleDeclaration */ && (!node.body); } + ts.isShorthandAmbientModule = isShorthandAmbientModule; function isBlockScopedContainerTopLevel(node) { return node.kind === 256 /* SourceFile */ || node.kind === 225 /* ModuleDeclaration */ || @@ -6387,7 +5981,6 @@ var ts; case 155 /* TypeReference */: return node.typeName; case 194 /* ExpressionWithTypeArguments */: - ts.Debug.assert(isEntityNameExpression(node.expression)); return node.expression; case 69 /* Identifier */: case 139 /* QualifiedName */: @@ -6557,6 +6150,12 @@ var ts; return false; } ts.isExpression = isExpression; + function isExternalModuleNameRelative(moduleName) { + // TypeScript 1.0 spec (April 2014): 11.2.1 + // An external module name is "relative" if the first term is "." or "..". + return moduleName.substr(0, 2) === "./" || moduleName.substr(0, 3) === "../" || moduleName.substr(0, 2) === ".\\" || moduleName.substr(0, 3) === "..\\"; + } + ts.isExternalModuleNameRelative = isExternalModuleNameRelative; function isInstantiatedModule(node, preserveConstEnums) { var moduleState = ts.getModuleInstanceState(node); return moduleState === 1 /* Instantiated */ || @@ -6847,7 +6446,7 @@ var ts; continue; } return parent_5.kind === 187 /* BinaryExpression */ && - isAssignmentOperator(parent_5.operatorToken.kind) && + parent_5.operatorToken.kind === 56 /* EqualsToken */ && parent_5.left === node || (parent_5.kind === 207 /* ForInStatement */ || parent_5.kind === 208 /* ForOfStatement */) && parent_5.initializer === node; @@ -6894,7 +6493,6 @@ var ts; case 146 /* MethodSignature */: case 225 /* ModuleDeclaration */: case 232 /* NamespaceImport */: - case 228 /* NamespaceExportDeclaration */: case 142 /* Parameter */: case 253 /* PropertyAssignment */: case 145 /* PropertyDeclaration */: @@ -7016,8 +6614,8 @@ var ts; // import * as from ... // import { x as } from ... // export { x as } from ... - // export = - // export default + // export = ... + // export default ... function isAliasSymbolDeclaration(node) { return node.kind === 229 /* ImportEqualsDeclaration */ || node.kind === 228 /* NamespaceExportDeclaration */ || @@ -7025,13 +6623,9 @@ var ts; node.kind === 232 /* NamespaceImport */ || node.kind === 234 /* ImportSpecifier */ || node.kind === 238 /* ExportSpecifier */ || - node.kind === 235 /* ExportAssignment */ && exportAssignmentIsAlias(node); + node.kind === 235 /* ExportAssignment */ && node.expression.kind === 69 /* Identifier */; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; - function exportAssignmentIsAlias(node) { - return isEntityNameExpression(node.expression); - } - ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getClassExtendsHeritageClauseElement(node) { var heritageClause = getHeritageClause(node.heritageClauses, 83 /* ExtendsKeyword */); return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; @@ -7283,7 +6877,7 @@ var ts; ts.createSynthesizedNodeArray = createSynthesizedNodeArray; function createDiagnosticCollection() { var nonFileDiagnostics = []; - var fileDiagnostics = ts.createMap(); + var fileDiagnostics = {}; var diagnosticsModified = false; var modificationCount = 0; return { @@ -7297,12 +6891,12 @@ var ts; return modificationCount; } function reattachFileDiagnostics(newFile) { - var diagnostics = fileDiagnostics[newFile.fileName]; - if (diagnostics) { - for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { - var diagnostic = diagnostics_1[_i]; - diagnostic.file = newFile; - } + if (!ts.hasProperty(fileDiagnostics, newFile.fileName)) { + return; + } + for (var _i = 0, _a = fileDiagnostics[newFile.fileName]; _i < _a.length; _i++) { + var diagnostic = _a[_i]; + diagnostic.file = newFile; } } function add(diagnostic) { @@ -7336,7 +6930,9 @@ var ts; } ts.forEach(nonFileDiagnostics, pushDiagnostic); for (var key in fileDiagnostics) { - ts.forEach(fileDiagnostics[key], pushDiagnostic); + if (ts.hasProperty(fileDiagnostics, key)) { + ts.forEach(fileDiagnostics[key], pushDiagnostic); + } } return ts.sortAndDeduplicateDiagnostics(allDiagnostics); } @@ -7347,7 +6943,9 @@ var ts; diagnosticsModified = false; nonFileDiagnostics = ts.sortAndDeduplicateDiagnostics(nonFileDiagnostics); for (var key in fileDiagnostics) { - fileDiagnostics[key] = ts.sortAndDeduplicateDiagnostics(fileDiagnostics[key]); + if (ts.hasProperty(fileDiagnostics, key)) { + fileDiagnostics[key] = ts.sortAndDeduplicateDiagnostics(fileDiagnostics[key]); + } } } } @@ -7358,7 +6956,7 @@ var ts; // the map below must be updated. Note that this regexp *does not* include the 'delete' character. // There is no reason for this other than that JSON.stringify does not handle it either. var escapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; - var escapedCharsMap = ts.createMap({ + var escapedCharsMap = { "\0": "\\0", "\t": "\\t", "\v": "\\v", @@ -7371,7 +6969,7 @@ var ts; "\u2028": "\\u2028", "\u2029": "\\u2029", "\u0085": "\\u0085" // nextLine - }); + }; /** * Based heavily on the abstract 'Quote'/'QuoteJSONString' operation from ECMA-262 (24.3.2.2), * but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine) @@ -7511,13 +7109,25 @@ var ts; function getDeclarationEmitOutputFilePath(sourceFile, host) { var options = host.getCompilerOptions(); var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified - var path = outputDir - ? getSourceFilePathInNewDir(sourceFile, host, outputDir) - : sourceFile.fileName; - return ts.removeFileExtension(path) + ".d.ts"; + if (options.declaration) { + var path = outputDir + ? getSourceFilePathInNewDir(sourceFile, host, outputDir) + : sourceFile.fileName; + return ts.removeFileExtension(path) + ".d.ts"; + } } ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; - function forEachExpectedEmitFile(host, action, targetSourceFile, emitOnlyDtsFiles) { + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0 /* ES3 */; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return typeof compilerOptions.module === "number" ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) === 2 /* ES6 */ ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; + } + ts.getEmitModuleKind = getEmitModuleKind; + function forEachExpectedEmitFile(host, action, targetSourceFile) { var options = host.getCompilerOptions(); // Emit on each source file if (options.outFile || options.out) { @@ -7550,13 +7160,12 @@ var ts; } } var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); - var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; var emitFileNames = { jsFilePath: jsFilePath, sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), - declarationFilePath: declarationFilePath + declarationFilePath: !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined }; - action(emitFileNames, [sourceFile], /*isBundledEmit*/ false, emitOnlyDtsFiles); + action(emitFileNames, [sourceFile], /*isBundledEmit*/ false); } function onBundledEmit(host) { // Can emit only sources that are not declaration file and are either non module code or module with @@ -7564,7 +7173,7 @@ var ts; var bundledSources = ts.filter(host.getSourceFiles(), function (sourceFile) { return !isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile) && (!ts.isExternalModule(sourceFile) || - !!ts.getEmitModuleKind(options)); }); + !!getEmitModuleKind(options)); }); if (bundledSources.length) { var jsFilePath = options.outFile || options.out; var emitFileNames = { @@ -7572,7 +7181,7 @@ var ts; sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), declarationFilePath: options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined }; - action(emitFileNames, bundledSources, /*isBundledEmit*/ true, emitOnlyDtsFiles); + action(emitFileNames, bundledSources, /*isBundledEmit*/ true); } } function getSourceMapFilePath(jsFilePath, options) { @@ -7903,11 +7512,23 @@ var ts; isClassLike(node.parent.parent); } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; - function isEntityNameExpression(node) { - return node.kind === 69 /* Identifier */ || - node.kind === 172 /* PropertyAccessExpression */ && isEntityNameExpression(node.expression); + // Returns false if this heritage clause element's expression contains something unsupported + // (i.e. not a name or dotted name). + function isSupportedExpressionWithTypeArguments(node) { + return isSupportedExpressionWithTypeArgumentsRest(node.expression); + } + ts.isSupportedExpressionWithTypeArguments = isSupportedExpressionWithTypeArguments; + function isSupportedExpressionWithTypeArgumentsRest(node) { + if (node.kind === 69 /* Identifier */) { + return true; + } + else if (isPropertyAccessExpression(node)) { + return isSupportedExpressionWithTypeArgumentsRest(node.expression); + } + else { + return false; + } } - ts.isEntityNameExpression = isEntityNameExpression; function isRightSideOfQualifiedNameOrPropertyAccess(node) { return (node.parent.kind === 139 /* QualifiedName */ && node.parent.right === node) || (node.parent.kind === 172 /* PropertyAccessExpression */ && node.parent.name === node); @@ -7928,11 +7549,14 @@ var ts; return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & 512 /* Default */) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; - /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ - function tryExtractTypeScriptExtension(fileName) { - return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function hasJavaScriptFileExtension(fileName) { + return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; + ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; + function hasTypeScriptFileExtension(fileName) { + return ts.forEach(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; /** * Replace each instance of non-ascii characters by one, two, three, or four escape sequences * representing the UTF-8 encoding of the character, and return the expanded char code list. @@ -8002,7 +7626,7 @@ var ts; return (memo ? memo + "," : memo) + stringifyValue(value); } function stringifyObject(value) { - return "{" + ts.reduceOwnProperties(value, stringifyProperty, "") + "}"; + return "{" + ts.reduceProperties(value, stringifyProperty, "") + "}"; } function stringifyProperty(memo, value, key) { return value === undefined || typeof value === "function" || key === "__cycle" ? memo @@ -8292,25 +7916,27 @@ var ts; return node.flags & 92 /* ParameterPropertyModifier */ && node.parent.kind === 148 /* Constructor */ && ts.isClassLike(node.parent.parent); } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; + function startsWith(str, prefix) { + return str.lastIndexOf(prefix, 0) === 0; + } + ts.startsWith = startsWith; + function endsWith(str, suffix) { + var expectedPos = str.length - suffix.length; + return str.indexOf(suffix, expectedPos) === expectedPos; + } + ts.endsWith = endsWith; })(ts || (ts = {})); /// /// var ts; (function (ts) { + /* @internal */ ts.parseTime = 0; var NodeConstructor; - var TokenConstructor; - var IdentifierConstructor; var SourceFileConstructor; function createNode(kind, pos, end) { if (kind === 256 /* SourceFile */) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); } - else if (kind === 69 /* Identifier */) { - return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); - } - else if (kind < 139 /* FirstNode */) { - return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end); - } else { return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end); } @@ -8426,8 +8052,6 @@ var ts; return visitNodes(cbNodes, node.types); case 164 /* ParenthesizedType */: return visitNode(cbNode, node.type); - case 166 /* LiteralType */: - return visitNode(cbNode, node.literal); case 167 /* ObjectBindingPattern */: case 168 /* ArrayBindingPattern */: return visitNodes(cbNodes, node.elements); @@ -8706,17 +8330,14 @@ var ts; case 280 /* JSDocPropertyTag */: return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); - case 282 /* JSDocLiteralType */: - return visitNode(cbNode, node.literal); } } ts.forEachChild = forEachChild; function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { if (setParentNodes === void 0) { setParentNodes = false; } - ts.performance.mark("beforeParse"); + var start = new Date().getTime(); var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); - ts.performance.mark("afterParse"); - ts.performance.measure("Parse", "beforeParse", "afterParse"); + ts.parseTime += new Date().getTime() - start; return result; } ts.createSourceFile = createSourceFile; @@ -8743,7 +8364,7 @@ var ts; if (result && result.jsDocComment) { // because the jsDocComment was parsed out of the source file, it might // not be covered by the fixupParentReferences. - fixupParentReferences(result.jsDocComment); + Parser.fixupParentReferences(result.jsDocComment); } return result; } @@ -8754,37 +8375,6 @@ var ts; return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length); } ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; - /* @internal */ - function fixupParentReferences(rootNode) { - // normally parent references are set during binding. However, for clients that only need - // a syntax tree, and no semantic features, then the binding process is an unnecessary - // overhead. This functions allows us to set all the parents, without all the expense of - // binding. - var parent = rootNode; - forEachChild(rootNode, visitNode); - return; - function visitNode(n) { - // walk down setting parents that differ from the parent we think it should be. This - // allows us to quickly bail out of setting parents for subtrees during incremental - // parsing - if (n.parent !== parent) { - n.parent = parent; - var saveParent = parent; - parent = n; - forEachChild(n, visitNode); - if (n.jsDocComments) { - for (var _i = 0, _a = n.jsDocComments; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - jsDocComment.parent = n; - parent = jsDocComment; - forEachChild(jsDocComment, visitNode); - } - } - parent = saveParent; - } - } - } - ts.fixupParentReferences = fixupParentReferences; // Implement the parser as a singleton module. We do this for perf reasons because creating // parser instances can actually be expensive enough to impact us on projects with many source // files. @@ -8796,13 +8386,11 @@ var ts; var disallowInAndDecoratorContext = 4194304 /* DisallowInContext */ | 16777216 /* DecoratorContext */; // capture constructors in 'initializeState' to avoid null checks var NodeConstructor; - var TokenConstructor; - var IdentifierConstructor; var SourceFileConstructor; var sourceFile; var parseDiagnostics; var syntaxCursor; - var currentToken; + var token; var sourceText; var nodeCount; var identifiers; @@ -8897,14 +8485,12 @@ var ts; } function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind) { NodeConstructor = ts.objectAllocator.getNodeConstructor(); - TokenConstructor = ts.objectAllocator.getTokenConstructor(); - IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor(); SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor(); sourceText = _sourceText; syntaxCursor = _syntaxCursor; parseDiagnostics = []; parsingContext = 0; - identifiers = ts.createMap(); + identifiers = {}; identifierCount = 0; nodeCount = 0; contextFlags = scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */ ? 134217728 /* JavaScriptFile */ : 0 /* None */; @@ -8930,10 +8516,10 @@ var ts; sourceFile = createSourceFile(fileName, languageVersion, scriptKind); sourceFile.flags = contextFlags; // Prime the scanner. - nextToken(); + token = nextToken(); processReferenceComments(sourceFile); sourceFile.statements = parseList(0 /* SourceElements */, parseStatement); - ts.Debug.assert(token() === 1 /* EndOfFileToken */); + ts.Debug.assert(token === 1 /* EndOfFileToken */); sourceFile.endOfFileToken = parseTokenNode(); setExternalModuleIndicator(sourceFile); sourceFile.nodeCount = nodeCount; @@ -8964,6 +8550,36 @@ var ts; } return node; } + function fixupParentReferences(rootNode) { + // normally parent references are set during binding. However, for clients that only need + // a syntax tree, and no semantic features, then the binding process is an unnecessary + // overhead. This functions allows us to set all the parents, without all the expense of + // binding. + var parent = rootNode; + forEachChild(rootNode, visitNode); + return; + function visitNode(n) { + // walk down setting parents that differ from the parent we think it should be. This + // allows us to quickly bail out of setting parents for subtrees during incremental + // parsing + if (n.parent !== parent) { + n.parent = parent; + var saveParent = parent; + parent = n; + forEachChild(n, visitNode); + if (n.jsDocComments) { + for (var _i = 0, _a = n.jsDocComments; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + jsDocComment.parent = n; + parent = jsDocComment; + forEachChild(jsDocComment, visitNode); + } + } + parent = saveParent; + } + } + } + Parser.fixupParentReferences = fixupParentReferences; function createSourceFile(fileName, languageVersion, scriptKind) { // code from createNode is inlined here so createNode won't have to deal with special case of creating source files // this is quite rare comparing to other nodes and createNode should be as fast as possible @@ -9097,43 +8713,34 @@ var ts; function getNodeEnd() { return scanner.getStartPos(); } - // Use this function to access the current token instead of reading the currentToken - // variable. Since function results aren't narrowed in control flow analysis, this ensures - // that the type checker doesn't make wrong assumptions about the type of the current - // token (e.g. a call to nextToken() changes the current token but the checker doesn't - // reason about this side effect). Mainstream VMs inline simple functions like this, so - // there is no performance penalty. - function token() { - return currentToken; - } function nextToken() { - return currentToken = scanner.scan(); + return token = scanner.scan(); } function reScanGreaterToken() { - return currentToken = scanner.reScanGreaterToken(); + return token = scanner.reScanGreaterToken(); } function reScanSlashToken() { - return currentToken = scanner.reScanSlashToken(); + return token = scanner.reScanSlashToken(); } function reScanTemplateToken() { - return currentToken = scanner.reScanTemplateToken(); + return token = scanner.reScanTemplateToken(); } function scanJsxIdentifier() { - return currentToken = scanner.scanJsxIdentifier(); + return token = scanner.scanJsxIdentifier(); } function scanJsxText() { - return currentToken = scanner.scanJsxToken(); + return token = scanner.scanJsxToken(); } function speculationHelper(callback, isLookAhead) { // Keep track of the state we'll need to rollback to if lookahead fails (or if the // caller asked us to always reset our state). - var saveToken = currentToken; + var saveToken = token; var saveParseDiagnosticsLength = parseDiagnostics.length; var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; // Note: it is not actually necessary to save/restore the context flags here. That's // because the saving/restoring of these flags happens naturally through the recursive // descent nature of our parser. However, we still store this here just so we can - // assert that invariant holds. + // assert that that invariant holds. var saveContextFlags = contextFlags; // If we're only looking ahead, then tell the scanner to only lookahead as well. // Otherwise, if we're actually speculatively parsing, then tell the scanner to do the @@ -9145,7 +8752,7 @@ var ts; // If our callback returned something 'falsy' or we're just looking ahead, // then unconditionally restore us to where we were. if (!result || isLookAhead) { - currentToken = saveToken; + token = saveToken; parseDiagnostics.length = saveParseDiagnosticsLength; parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; } @@ -9168,24 +8775,24 @@ var ts; } // Ignore strict mode flag because we will report an error in type checker instead. function isIdentifier() { - if (token() === 69 /* Identifier */) { + if (token === 69 /* Identifier */) { return true; } // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is // considered a keyword and is not an identifier. - if (token() === 114 /* YieldKeyword */ && inYieldContext()) { + if (token === 114 /* YieldKeyword */ && inYieldContext()) { return false; } // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is // considered a keyword and is not an identifier. - if (token() === 119 /* AwaitKeyword */ && inAwaitContext()) { + if (token === 119 /* AwaitKeyword */ && inAwaitContext()) { return false; } - return token() > 105 /* LastReservedWord */; + return token > 105 /* LastReservedWord */; } function parseExpected(kind, diagnosticMessage, shouldAdvance) { if (shouldAdvance === void 0) { shouldAdvance = true; } - if (token() === kind) { + if (token === kind) { if (shouldAdvance) { nextToken(); } @@ -9201,14 +8808,14 @@ var ts; return false; } function parseOptional(t) { - if (token() === t) { + if (token === t) { nextToken(); return true; } return false; } function parseOptionalToken(t) { - if (token() === t) { + if (token === t) { return parseTokenNode(); } return undefined; @@ -9218,21 +8825,21 @@ var ts; createMissingNode(t, reportAtCurrentPosition, diagnosticMessage, arg0); } function parseTokenNode() { - var node = createNode(token()); + var node = createNode(token); nextToken(); return finishNode(node); } function canParseSemicolon() { // If there's a real semicolon, then we can always parse it out. - if (token() === 23 /* SemicolonToken */) { + if (token === 23 /* SemicolonToken */) { return true; } // We can parse out an optional semicolon in ASI cases in the following cases. - return token() === 16 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); + return token === 16 /* CloseBraceToken */ || token === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); } function parseSemicolon() { if (canParseSemicolon()) { - if (token() === 23 /* SemicolonToken */) { + if (token === 23 /* SemicolonToken */) { // consume the semicolon if it was explicitly provided. nextToken(); } @@ -9248,9 +8855,7 @@ var ts; if (!(pos >= 0)) { pos = scanner.getStartPos(); } - return kind >= 139 /* FirstNode */ ? new NodeConstructor(kind, pos, pos) : - kind === 69 /* Identifier */ ? new IdentifierConstructor(kind, pos, pos) : - new TokenConstructor(kind, pos, pos); + return new NodeConstructor(kind, pos, pos); } function finishNode(node, end) { node.end = end === undefined ? scanner.getStartPos() : end; @@ -9279,7 +8884,7 @@ var ts; } function internIdentifier(text) { text = ts.escapeIdentifier(text); - return identifiers[text] || (identifiers[text] = text); + return ts.hasProperty(identifiers, text) ? identifiers[text] : (identifiers[text] = text); } // An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for @@ -9289,8 +8894,8 @@ var ts; if (isIdentifier) { var node = createNode(69 /* Identifier */); // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker - if (token() !== 69 /* Identifier */) { - node.originalKeywordKind = token(); + if (token !== 69 /* Identifier */) { + node.originalKeywordKind = token; } node.text = internIdentifier(scanner.getTokenValue()); nextToken(); @@ -9302,18 +8907,18 @@ var ts; return createIdentifier(isIdentifier(), diagnosticMessage); } function parseIdentifierName() { - return createIdentifier(ts.tokenIsIdentifierOrKeyword(token())); + return createIdentifier(ts.tokenIsIdentifierOrKeyword(token)); } function isLiteralPropertyName() { - return ts.tokenIsIdentifierOrKeyword(token()) || - token() === 9 /* StringLiteral */ || - token() === 8 /* NumericLiteral */; + return ts.tokenIsIdentifierOrKeyword(token) || + token === 9 /* StringLiteral */ || + token === 8 /* NumericLiteral */; } function parsePropertyNameWorker(allowComputedPropertyNames) { - if (token() === 9 /* StringLiteral */ || token() === 8 /* NumericLiteral */) { + if (token === 9 /* StringLiteral */ || token === 8 /* NumericLiteral */) { return parseLiteralNode(/*internName*/ true); } - if (allowComputedPropertyNames && token() === 19 /* OpenBracketToken */) { + if (allowComputedPropertyNames && token === 19 /* OpenBracketToken */) { return parseComputedPropertyName(); } return parseIdentifierName(); @@ -9325,7 +8930,7 @@ var ts; return parsePropertyNameWorker(/*allowComputedPropertyNames*/ false); } function isSimplePropertyName() { - return token() === 9 /* StringLiteral */ || token() === 8 /* NumericLiteral */ || ts.tokenIsIdentifierOrKeyword(token()); + return token === 9 /* StringLiteral */ || token === 8 /* NumericLiteral */ || ts.tokenIsIdentifierOrKeyword(token); } function parseComputedPropertyName() { // PropertyName [Yield]: @@ -9341,7 +8946,7 @@ var ts; return finishNode(node); } function parseContextualModifier(t) { - return token() === t && tryParse(nextTokenCanFollowModifier); + return token === t && tryParse(nextTokenCanFollowModifier); } function nextTokenIsOnSameLineAndCanFollowModifier() { nextToken(); @@ -9351,40 +8956,40 @@ var ts; return canFollowModifier(); } function nextTokenCanFollowModifier() { - if (token() === 74 /* ConstKeyword */) { + if (token === 74 /* ConstKeyword */) { // 'const' is only a modifier if followed by 'enum'. return nextToken() === 81 /* EnumKeyword */; } - if (token() === 82 /* ExportKeyword */) { + if (token === 82 /* ExportKeyword */) { nextToken(); - if (token() === 77 /* DefaultKeyword */) { + if (token === 77 /* DefaultKeyword */) { return lookAhead(nextTokenIsClassOrFunctionOrAsync); } - return token() !== 37 /* AsteriskToken */ && token() !== 116 /* AsKeyword */ && token() !== 15 /* OpenBraceToken */ && canFollowModifier(); + return token !== 37 /* AsteriskToken */ && token !== 116 /* AsKeyword */ && token !== 15 /* OpenBraceToken */ && canFollowModifier(); } - if (token() === 77 /* DefaultKeyword */) { + if (token === 77 /* DefaultKeyword */) { return nextTokenIsClassOrFunctionOrAsync(); } - if (token() === 113 /* StaticKeyword */) { + if (token === 113 /* StaticKeyword */) { nextToken(); return canFollowModifier(); } return nextTokenIsOnSameLineAndCanFollowModifier(); } function parseAnyContextualModifier() { - return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); + return ts.isModifierKind(token) && tryParse(nextTokenCanFollowModifier); } function canFollowModifier() { - return token() === 19 /* OpenBracketToken */ - || token() === 15 /* OpenBraceToken */ - || token() === 37 /* AsteriskToken */ - || token() === 22 /* DotDotDotToken */ + return token === 19 /* OpenBracketToken */ + || token === 15 /* OpenBraceToken */ + || token === 37 /* AsteriskToken */ + || token === 22 /* DotDotDotToken */ || isLiteralPropertyName(); } function nextTokenIsClassOrFunctionOrAsync() { nextToken(); - return token() === 73 /* ClassKeyword */ || token() === 87 /* FunctionKeyword */ || - (token() === 118 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); + return token === 73 /* ClassKeyword */ || token === 87 /* FunctionKeyword */ || + (token === 118 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); } // True if positioned at the start of a list element function isListElement(parsingContext, inErrorRecovery) { @@ -9402,9 +9007,9 @@ var ts; // we're parsing. For example, if we have a semicolon in the middle of a class, then // we really don't want to assume the class is over and we're on a statement in the // outer module. We just want to consume and move on. - return !(token() === 23 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); + return !(token === 23 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); case 2 /* SwitchClauses */: - return token() === 71 /* CaseKeyword */ || token() === 77 /* DefaultKeyword */; + return token === 71 /* CaseKeyword */ || token === 77 /* DefaultKeyword */; case 4 /* TypeMembers */: return lookAhead(isTypeMemberStart); case 5 /* ClassMembers */: @@ -9412,19 +9017,19 @@ var ts; // not in error recovery. If we're in error recovery, we don't want an errant // semicolon to be treated as a class member (since they're almost always used // for statements. - return lookAhead(isClassMemberStart) || (token() === 23 /* SemicolonToken */ && !inErrorRecovery); + return lookAhead(isClassMemberStart) || (token === 23 /* SemicolonToken */ && !inErrorRecovery); case 6 /* EnumMembers */: // Include open bracket computed properties. This technically also lets in indexers, // which would be a candidate for improved error reporting. - return token() === 19 /* OpenBracketToken */ || isLiteralPropertyName(); + return token === 19 /* OpenBracketToken */ || isLiteralPropertyName(); case 12 /* ObjectLiteralMembers */: - return token() === 19 /* OpenBracketToken */ || token() === 37 /* AsteriskToken */ || isLiteralPropertyName(); + return token === 19 /* OpenBracketToken */ || token === 37 /* AsteriskToken */ || isLiteralPropertyName(); case 9 /* ObjectBindingElements */: - return token() === 19 /* OpenBracketToken */ || isLiteralPropertyName(); + return token === 19 /* OpenBracketToken */ || isLiteralPropertyName(); case 7 /* HeritageClauseElement */: // If we see { } then only consume it as an expression if it is followed by , or { // That way we won't consume the body of a class in its heritage clause. - if (token() === 15 /* OpenBraceToken */) { + if (token === 15 /* OpenBraceToken */) { return lookAhead(isValidHeritageClauseObjectLiteral); } if (!inErrorRecovery) { @@ -9439,23 +9044,23 @@ var ts; case 8 /* VariableDeclarations */: return isIdentifierOrPattern(); case 10 /* ArrayBindingElements */: - return token() === 24 /* CommaToken */ || token() === 22 /* DotDotDotToken */ || isIdentifierOrPattern(); + return token === 24 /* CommaToken */ || token === 22 /* DotDotDotToken */ || isIdentifierOrPattern(); case 17 /* TypeParameters */: return isIdentifier(); case 11 /* ArgumentExpressions */: case 15 /* ArrayLiteralMembers */: - return token() === 24 /* CommaToken */ || token() === 22 /* DotDotDotToken */ || isStartOfExpression(); + return token === 24 /* CommaToken */ || token === 22 /* DotDotDotToken */ || isStartOfExpression(); case 16 /* Parameters */: return isStartOfParameter(); case 18 /* TypeArguments */: case 19 /* TupleElementTypes */: - return token() === 24 /* CommaToken */ || isStartOfType(); + return token === 24 /* CommaToken */ || isStartOfType(); case 20 /* HeritageClauses */: return isHeritageClause(); case 21 /* ImportOrExportSpecifiers */: - return ts.tokenIsIdentifierOrKeyword(token()); + return ts.tokenIsIdentifierOrKeyword(token); case 13 /* JsxAttributes */: - return ts.tokenIsIdentifierOrKeyword(token()) || token() === 15 /* OpenBraceToken */; + return ts.tokenIsIdentifierOrKeyword(token) || token === 15 /* OpenBraceToken */; case 14 /* JsxChildren */: return true; case 22 /* JSDocFunctionParameters */: @@ -9468,7 +9073,7 @@ var ts; ts.Debug.fail("Non-exhaustive case in 'isListElement'."); } function isValidHeritageClauseObjectLiteral() { - ts.Debug.assert(token() === 15 /* OpenBraceToken */); + ts.Debug.assert(token === 15 /* OpenBraceToken */); if (nextToken() === 16 /* CloseBraceToken */) { // if we see "extends {}" then only treat the {} as what we're extending (and not // the class body) if we have: @@ -9488,11 +9093,11 @@ var ts; } function nextTokenIsIdentifierOrKeyword() { nextToken(); - return ts.tokenIsIdentifierOrKeyword(token()); + return ts.tokenIsIdentifierOrKeyword(token); } function isHeritageClauseExtendsOrImplementsKeyword() { - if (token() === 106 /* ImplementsKeyword */ || - token() === 83 /* ExtendsKeyword */) { + if (token === 106 /* ImplementsKeyword */ || + token === 83 /* ExtendsKeyword */) { return lookAhead(nextTokenIsStartOfExpression); } return false; @@ -9503,7 +9108,7 @@ var ts; } // True if positioned at a list terminator function isListTerminator(kind) { - if (token() === 1 /* EndOfFileToken */) { + if (token === 1 /* EndOfFileToken */) { // Being at the end of the file ends all lists. return true; } @@ -9516,43 +9121,43 @@ var ts; case 12 /* ObjectLiteralMembers */: case 9 /* ObjectBindingElements */: case 21 /* ImportOrExportSpecifiers */: - return token() === 16 /* CloseBraceToken */; + return token === 16 /* CloseBraceToken */; case 3 /* SwitchClauseStatements */: - return token() === 16 /* CloseBraceToken */ || token() === 71 /* CaseKeyword */ || token() === 77 /* DefaultKeyword */; + return token === 16 /* CloseBraceToken */ || token === 71 /* CaseKeyword */ || token === 77 /* DefaultKeyword */; case 7 /* HeritageClauseElement */: - return token() === 15 /* OpenBraceToken */ || token() === 83 /* ExtendsKeyword */ || token() === 106 /* ImplementsKeyword */; + return token === 15 /* OpenBraceToken */ || token === 83 /* ExtendsKeyword */ || token === 106 /* ImplementsKeyword */; case 8 /* VariableDeclarations */: return isVariableDeclaratorListTerminator(); case 17 /* TypeParameters */: // Tokens other than '>' are here for better error recovery - return token() === 27 /* GreaterThanToken */ || token() === 17 /* OpenParenToken */ || token() === 15 /* OpenBraceToken */ || token() === 83 /* ExtendsKeyword */ || token() === 106 /* ImplementsKeyword */; + return token === 27 /* GreaterThanToken */ || token === 17 /* OpenParenToken */ || token === 15 /* OpenBraceToken */ || token === 83 /* ExtendsKeyword */ || token === 106 /* ImplementsKeyword */; case 11 /* ArgumentExpressions */: // Tokens other than ')' are here for better error recovery - return token() === 18 /* CloseParenToken */ || token() === 23 /* SemicolonToken */; + return token === 18 /* CloseParenToken */ || token === 23 /* SemicolonToken */; case 15 /* ArrayLiteralMembers */: case 19 /* TupleElementTypes */: case 10 /* ArrayBindingElements */: - return token() === 20 /* CloseBracketToken */; + return token === 20 /* CloseBracketToken */; case 16 /* Parameters */: // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery - return token() === 18 /* CloseParenToken */ || token() === 20 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; + return token === 18 /* CloseParenToken */ || token === 20 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; case 18 /* TypeArguments */: // Tokens other than '>' are here for better error recovery - return token() === 27 /* GreaterThanToken */ || token() === 17 /* OpenParenToken */; + return token === 27 /* GreaterThanToken */ || token === 17 /* OpenParenToken */; case 20 /* HeritageClauses */: - return token() === 15 /* OpenBraceToken */ || token() === 16 /* CloseBraceToken */; + return token === 15 /* OpenBraceToken */ || token === 16 /* CloseBraceToken */; case 13 /* JsxAttributes */: - return token() === 27 /* GreaterThanToken */ || token() === 39 /* SlashToken */; + return token === 27 /* GreaterThanToken */ || token === 39 /* SlashToken */; case 14 /* JsxChildren */: - return token() === 25 /* LessThanToken */ && lookAhead(nextTokenIsSlash); + return token === 25 /* LessThanToken */ && lookAhead(nextTokenIsSlash); case 22 /* JSDocFunctionParameters */: - return token() === 18 /* CloseParenToken */ || token() === 54 /* ColonToken */ || token() === 16 /* CloseBraceToken */; + return token === 18 /* CloseParenToken */ || token === 54 /* ColonToken */ || token === 16 /* CloseBraceToken */; case 23 /* JSDocTypeArguments */: - return token() === 27 /* GreaterThanToken */ || token() === 16 /* CloseBraceToken */; + return token === 27 /* GreaterThanToken */ || token === 16 /* CloseBraceToken */; case 25 /* JSDocTupleTypes */: - return token() === 20 /* CloseBracketToken */ || token() === 16 /* CloseBraceToken */; + return token === 20 /* CloseBracketToken */ || token === 16 /* CloseBraceToken */; case 24 /* JSDocRecordMembers */: - return token() === 16 /* CloseBraceToken */; + return token === 16 /* CloseBraceToken */; } } function isVariableDeclaratorListTerminator() { @@ -9563,14 +9168,14 @@ var ts; } // in the case where we're parsing the variable declarator of a 'for-in' statement, we // are done if we see an 'in' keyword in front of us. Same with for-of - if (isInOrOfKeyword(token())) { + if (isInOrOfKeyword(token)) { return true; } // ERROR RECOVERY TWEAK: // For better error recovery, if we see an '=>' then we just stop immediately. We've got an // arrow function here and it's going to be very unlikely that we'll resynchronize and get // another variable declaration. - if (token() === 34 /* EqualsGreaterThanToken */) { + if (token === 34 /* EqualsGreaterThanToken */) { return true; } // Keep trying to parse out variable declarators. @@ -9911,7 +9516,7 @@ var ts; // parse errors. For example, this can happen when people do things like use // a semicolon to delimit object literal members. Note: we'll have already // reported an error when we called parseExpected above. - if (considerSemicolonAsDelimiter && token() === 23 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) { + if (considerSemicolonAsDelimiter && token === 23 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) { nextToken(); } continue; @@ -9982,7 +9587,7 @@ var ts; // the code would be implicitly: "name.identifierOrKeyword; identifierNameOrKeyword". // In the first case though, ASI will not take effect because there is not a // line terminator after the identifier or keyword. - if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) { + if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token)) { var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); if (matchesPattern) { // Report that we need an identifier. However, report it right after the dot, @@ -10010,7 +9615,7 @@ var ts; var span = createNode(197 /* TemplateSpan */); span.expression = allowInAnd(parseExpression); var literal; - if (token() === 16 /* CloseBraceToken */) { + if (token === 16 /* CloseBraceToken */) { reScanTemplateToken(); literal = parseTemplateLiteralFragment(); } @@ -10020,11 +9625,14 @@ var ts; span.literal = literal; return finishNode(span); } + function parseStringLiteralTypeNode() { + return parseLiteralLikeNode(166 /* StringLiteralType */, /*internName*/ true); + } function parseLiteralNode(internName) { - return parseLiteralLikeNode(token(), internName); + return parseLiteralLikeNode(token, internName); } function parseTemplateLiteralFragment() { - return parseLiteralLikeNode(token(), /*internName*/ false); + return parseLiteralLikeNode(token, /*internName*/ false); } function parseLiteralLikeNode(kind, internName) { var node = createNode(kind); @@ -10057,7 +9665,7 @@ var ts; var typeName = parseEntityName(/*allowReservedWords*/ false, ts.Diagnostics.Type_expected); var node = createNode(155 /* TypeReference */, typeName.pos); node.typeName = typeName; - if (!scanner.hasPrecedingLineBreak() && token() === 25 /* LessThanToken */) { + if (!scanner.hasPrecedingLineBreak() && token === 25 /* LessThanToken */) { node.typeArguments = parseBracketedList(18 /* TypeArguments */, parseType, 25 /* LessThanToken */, 27 /* GreaterThanToken */); } return finishNode(node); @@ -10105,7 +9713,7 @@ var ts; return finishNode(node); } function parseTypeParameters() { - if (token() === 25 /* LessThanToken */) { + if (token === 25 /* LessThanToken */) { return parseBracketedList(17 /* TypeParameters */, parseTypeParameter, 25 /* LessThanToken */, 27 /* GreaterThanToken */); } } @@ -10116,7 +9724,7 @@ var ts; return undefined; } function isStartOfParameter() { - return token() === 22 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 55 /* AtToken */ || token() === 97 /* ThisKeyword */; + return token === 22 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token) || token === 55 /* AtToken */ || token === 97 /* ThisKeyword */; } function setModifiers(node, modifiers) { if (modifiers) { @@ -10126,7 +9734,7 @@ var ts; } function parseParameter() { var node = createNode(142 /* Parameter */); - if (token() === 97 /* ThisKeyword */) { + if (token === 97 /* ThisKeyword */) { node.name = createIdentifier(/*isIdentifier*/ true, undefined); node.type = parseParameterType(); return finishNode(node); @@ -10137,7 +9745,7 @@ var ts; // FormalParameter [Yield,Await]: // BindingElement[?Yield,?Await] node.name = parseIdentifierOrPattern(); - if (ts.getFullWidth(node.name) === 0 && node.flags === 0 && ts.isModifierKind(token())) { + if (ts.getFullWidth(node.name) === 0 && node.flags === 0 && ts.isModifierKind(token)) { // in cases like // 'use strict' // function foo(static) @@ -10232,7 +9840,7 @@ var ts; return finishNode(node); } function isIndexSignature() { - if (token() !== 19 /* OpenBracketToken */) { + if (token !== 19 /* OpenBracketToken */) { return false; } return lookAhead(isUnambiguouslyIndexSignature); @@ -10255,10 +9863,10 @@ var ts; // [] // nextToken(); - if (token() === 22 /* DotDotDotToken */ || token() === 20 /* CloseBracketToken */) { + if (token === 22 /* DotDotDotToken */ || token === 20 /* CloseBracketToken */) { return true; } - if (ts.isModifierKind(token())) { + if (ts.isModifierKind(token)) { nextToken(); if (isIdentifier()) { return true; @@ -10274,18 +9882,18 @@ var ts; // A colon signifies a well formed indexer // A comma should be a badly formed indexer because comma expressions are not allowed // in computed properties. - if (token() === 54 /* ColonToken */ || token() === 24 /* CommaToken */) { + if (token === 54 /* ColonToken */ || token === 24 /* CommaToken */) { return true; } // Question mark could be an indexer with an optional property, // or it could be a conditional expression in a computed property. - if (token() !== 53 /* QuestionToken */) { + if (token !== 53 /* QuestionToken */) { return false; } // If any of the following tokens are after the question mark, it cannot // be a conditional expression, so treat it as an indexer. nextToken(); - return token() === 54 /* ColonToken */ || token() === 24 /* CommaToken */ || token() === 20 /* CloseBracketToken */; + return token === 54 /* ColonToken */ || token === 24 /* CommaToken */ || token === 20 /* CloseBracketToken */; } function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { var node = createNode(153 /* IndexSignature */, fullStart); @@ -10299,7 +9907,7 @@ var ts; function parsePropertyOrMethodSignature(fullStart, modifiers) { var name = parsePropertyName(); var questionToken = parseOptionalToken(53 /* QuestionToken */); - if (token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */) { + if (token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */) { var method = createNode(146 /* MethodSignature */, fullStart); setModifiers(method, modifiers); method.name = name; @@ -10316,7 +9924,7 @@ var ts; property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); - if (token() === 56 /* EqualsToken */) { + if (token === 56 /* EqualsToken */) { // Although type literal properties cannot not have initializers, we attempt // to parse an initializer so we can report in the checker that an interface // property or type literal property cannot have an initializer. @@ -10329,40 +9937,39 @@ var ts; function isTypeMemberStart() { var idToken; // Return true if we have the start of a signature member - if (token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */) { + if (token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */) { return true; } // Eat up all modifiers, but hold on to the last one in case it is actually an identifier - while (ts.isModifierKind(token())) { - idToken = token(); + while (ts.isModifierKind(token)) { + idToken = token; nextToken(); } // Index signatures and computed property names are type members - if (token() === 19 /* OpenBracketToken */) { + if (token === 19 /* OpenBracketToken */) { return true; } // Try to get the first property-like token following all modifiers if (isLiteralPropertyName()) { - idToken = token(); + idToken = token; nextToken(); } // If we were able to get any potential identifier, check that it is // the start of a member declaration if (idToken) { - return token() === 17 /* OpenParenToken */ || - token() === 25 /* LessThanToken */ || - token() === 53 /* QuestionToken */ || - token() === 54 /* ColonToken */ || - token() === 24 /* CommaToken */ || + return token === 17 /* OpenParenToken */ || + token === 25 /* LessThanToken */ || + token === 53 /* QuestionToken */ || + token === 54 /* ColonToken */ || canParseSemicolon(); } return false; } function parseTypeMember() { - if (token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */) { + if (token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */) { return parseSignatureMember(151 /* CallSignature */); } - if (token() === 92 /* NewKeyword */ && lookAhead(isStartOfConstructSignature)) { + if (token === 92 /* NewKeyword */ && lookAhead(isStartOfConstructSignature)) { return parseSignatureMember(152 /* ConstructSignature */); } var fullStart = getNodePos(); @@ -10374,7 +9981,7 @@ var ts; } function isStartOfConstructSignature() { nextToken(); - return token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */; + return token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */; } function parseTypeLiteral() { var node = createNode(159 /* TypeLiteral */); @@ -10414,19 +10021,10 @@ var ts; } function parseKeywordAndNoDot() { var node = parseTokenNode(); - return token() === 21 /* DotToken */ ? undefined : node; - } - function parseLiteralTypeNode() { - var node = createNode(166 /* LiteralType */); - node.literal = parseSimpleUnaryExpression(); - finishNode(node); - return node; - } - function nextTokenIsNumericLiteral() { - return nextToken() === 8 /* NumericLiteral */; + return token === 21 /* DotToken */ ? undefined : node; } function parseNonArrayType() { - switch (token()) { + switch (token) { case 117 /* AnyKeyword */: case 132 /* StringKeyword */: case 130 /* NumberKeyword */: @@ -10438,18 +10036,13 @@ var ts; var node = tryParse(parseKeywordAndNoDot); return node || parseTypeReference(); case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: - case 99 /* TrueKeyword */: - case 84 /* FalseKeyword */: - return parseLiteralTypeNode(); - case 36 /* MinusToken */: - return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode() : parseTypeReference(); + return parseStringLiteralTypeNode(); case 103 /* VoidKeyword */: case 93 /* NullKeyword */: return parseTokenNode(); case 97 /* ThisKeyword */: { var thisKeyword = parseThisTypeNode(); - if (token() === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + if (token === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { return parseThisTypePredicate(thisKeyword); } else { @@ -10469,7 +10062,7 @@ var ts; } } function isStartOfType() { - switch (token()) { + switch (token) { case 117 /* AnyKeyword */: case 132 /* StringKeyword */: case 130 /* NumberKeyword */: @@ -10486,12 +10079,7 @@ var ts; case 25 /* LessThanToken */: case 92 /* NewKeyword */: case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: - case 99 /* TrueKeyword */: - case 84 /* FalseKeyword */: return true; - case 36 /* MinusToken */: - return lookAhead(nextTokenIsNumericLiteral); case 17 /* OpenParenToken */: // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier, // or something that starts a type. We don't want to consider things like '(1)' a type. @@ -10502,7 +10090,7 @@ var ts; } function isStartOfParenthesizedOrFunctionType() { nextToken(); - return token() === 18 /* CloseParenToken */ || isStartOfParameter() || isStartOfType(); + return token === 18 /* CloseParenToken */ || isStartOfParameter() || isStartOfType(); } function parseArrayTypeOrHigher() { var type = parseNonArrayType(); @@ -10516,7 +10104,7 @@ var ts; } function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { var type = parseConstituentType(); - if (token() === operator) { + if (token === operator) { var types = [type]; types.pos = type.pos; while (parseOptional(operator)) { @@ -10536,21 +10124,21 @@ var ts; return parseUnionOrIntersectionType(162 /* UnionType */, parseIntersectionTypeOrHigher, 47 /* BarToken */); } function isStartOfFunctionType() { - if (token() === 25 /* LessThanToken */) { + if (token === 25 /* LessThanToken */) { return true; } - return token() === 17 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType); + return token === 17 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType); } function skipParameterStart() { - if (ts.isModifierKind(token())) { + if (ts.isModifierKind(token)) { // Skip modifiers parseModifiers(); } - if (isIdentifier() || token() === 97 /* ThisKeyword */) { + if (isIdentifier() || token === 97 /* ThisKeyword */) { nextToken(); return true; } - if (token() === 19 /* OpenBracketToken */ || token() === 15 /* OpenBraceToken */) { + if (token === 19 /* OpenBracketToken */ || token === 15 /* OpenBraceToken */) { // Return true if we can parse an array or object binding pattern with no errors var previousErrorCount = parseDiagnostics.length; parseIdentifierOrPattern(); @@ -10560,7 +10148,7 @@ var ts; } function isUnambiguouslyStartOfFunctionType() { nextToken(); - if (token() === 18 /* CloseParenToken */ || token() === 22 /* DotDotDotToken */) { + if (token === 18 /* CloseParenToken */ || token === 22 /* DotDotDotToken */) { // ( ) // ( ... return true; @@ -10568,17 +10156,17 @@ var ts; if (skipParameterStart()) { // We successfully skipped modifiers (if any) and an identifier or binding pattern, // now see if we have something that indicates a parameter declaration - if (token() === 54 /* ColonToken */ || token() === 24 /* CommaToken */ || - token() === 53 /* QuestionToken */ || token() === 56 /* EqualsToken */) { + if (token === 54 /* ColonToken */ || token === 24 /* CommaToken */ || + token === 53 /* QuestionToken */ || token === 56 /* EqualsToken */) { // ( xxx : // ( xxx , // ( xxx ? // ( xxx = return true; } - if (token() === 18 /* CloseParenToken */) { + if (token === 18 /* CloseParenToken */) { nextToken(); - if (token() === 34 /* EqualsGreaterThanToken */) { + if (token === 34 /* EqualsGreaterThanToken */) { // ( xxx ) => return true; } @@ -10601,7 +10189,7 @@ var ts; } function parseTypePredicatePrefix() { var id = parseIdentifier(); - if (token() === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + if (token === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { nextToken(); return id; } @@ -10615,7 +10203,7 @@ var ts; if (isStartOfFunctionType()) { return parseFunctionOrConstructorType(156 /* FunctionType */); } - if (token() === 92 /* NewKeyword */) { + if (token === 92 /* NewKeyword */) { return parseFunctionOrConstructorType(157 /* ConstructorType */); } return parseUnionTypeOrHigher(); @@ -10625,7 +10213,7 @@ var ts; } // EXPRESSIONS function isStartOfLeftHandSideExpression() { - switch (token()) { + switch (token) { case 97 /* ThisKeyword */: case 95 /* SuperKeyword */: case 93 /* NullKeyword */: @@ -10653,7 +10241,7 @@ var ts; if (isStartOfLeftHandSideExpression()) { return true; } - switch (token()) { + switch (token) { case 35 /* PlusToken */: case 36 /* MinusToken */: case 50 /* TildeToken */: @@ -10683,10 +10271,10 @@ var ts; } function isStartOfExpressionStatement() { // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement. - return token() !== 15 /* OpenBraceToken */ && - token() !== 87 /* FunctionKeyword */ && - token() !== 73 /* ClassKeyword */ && - token() !== 55 /* AtToken */ && + return token !== 15 /* OpenBraceToken */ && + token !== 87 /* FunctionKeyword */ && + token !== 73 /* ClassKeyword */ && + token !== 55 /* AtToken */ && isStartOfExpression(); } function parseExpression() { @@ -10709,7 +10297,7 @@ var ts; return expr; } function parseInitializer(inParameter) { - if (token() !== 56 /* EqualsToken */) { + if (token !== 56 /* EqualsToken */) { // It's not uncommon during typing for the user to miss writing the '=' token. Check if // there is no newline after the last token and if we're on an expression. If so, parse // this as an equals-value clause with a missing equals. @@ -10718,7 +10306,7 @@ var ts; // it's more likely that a { would be a allowed (as an object literal). While this // is also allowed for parameters, the risk is that we consume the { as an object // literal when it really will be for the block following the parameter. - if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 15 /* OpenBraceToken */) || !isStartOfExpression()) { + if (scanner.hasPrecedingLineBreak() || (inParameter && token === 15 /* OpenBraceToken */) || !isStartOfExpression()) { // preceding line break, open brace in a parameter (likely a function body) or current token is not an expression - // do not try to parse initializer return undefined; @@ -10740,7 +10328,7 @@ var ts; // // Note: for ease of implementation we treat productions '2' and '3' as the same thing. // (i.e. they're both BinaryExpressions with an assignment operator in it). - // First, do the simple check if we have a YieldExpression (production '6'). + // First, do the simple check if we have a YieldExpression (production '5'). if (isYieldExpression()) { return parseYieldExpression(); } @@ -10772,7 +10360,7 @@ var ts; // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single // identifier and the current token is an arrow. - if (expr.kind === 69 /* Identifier */ && token() === 34 /* EqualsGreaterThanToken */) { + if (expr.kind === 69 /* Identifier */ && token === 34 /* EqualsGreaterThanToken */) { return parseSimpleArrowFunctionExpression(expr); } // Now see if we might be in cases '2' or '3'. @@ -10788,7 +10376,7 @@ var ts; return parseConditionalExpressionRest(expr); } function isYieldExpression() { - if (token() === 114 /* YieldKeyword */) { + if (token === 114 /* YieldKeyword */) { // If we have a 'yield' keyword, and this is a context where yield expressions are // allowed, then definitely parse out a yield expression. if (inYieldContext()) { @@ -10824,7 +10412,7 @@ var ts; // yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] nextToken(); if (!scanner.hasPrecedingLineBreak() && - (token() === 37 /* AsteriskToken */ || isStartOfExpression())) { + (token === 37 /* AsteriskToken */ || isStartOfExpression())) { node.asteriskToken = parseOptionalToken(37 /* AsteriskToken */); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); @@ -10836,7 +10424,7 @@ var ts; } } function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { - ts.Debug.assert(token() === 34 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + ts.Debug.assert(token === 34 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); var node; if (asyncModifier) { node = createNode(180 /* ArrowFunction */, asyncModifier.pos); @@ -10875,7 +10463,7 @@ var ts; var isAsync = !!(arrowFunction.flags & 256 /* Async */); // If we have an arrow, then try to parse the body. Even if not, try to parse if we // have an opening brace, just in case we're in an error state. - var lastToken = token(); + var lastToken = token; arrowFunction.equalsGreaterThanToken = parseExpectedToken(34 /* EqualsGreaterThanToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, "=>"); arrowFunction.body = (lastToken === 34 /* EqualsGreaterThanToken */ || lastToken === 15 /* OpenBraceToken */) ? parseArrowFunctionExpressionBody(isAsync) @@ -10887,10 +10475,10 @@ var ts; // Unknown -> There *might* be a parenthesized arrow function here. // Speculatively look ahead to be sure, and rollback if not. function isParenthesizedArrowFunctionExpression() { - if (token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */ || token() === 118 /* AsyncKeyword */) { + if (token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */ || token === 118 /* AsyncKeyword */) { return lookAhead(isParenthesizedArrowFunctionExpressionWorker); } - if (token() === 34 /* EqualsGreaterThanToken */) { + if (token === 34 /* EqualsGreaterThanToken */) { // ERROR RECOVERY TWEAK: // If we see a standalone => try to parse it as an arrow function expression as that's // likely what the user intended to write. @@ -10900,16 +10488,16 @@ var ts; return 0 /* False */; } function isParenthesizedArrowFunctionExpressionWorker() { - if (token() === 118 /* AsyncKeyword */) { + if (token === 118 /* AsyncKeyword */) { nextToken(); if (scanner.hasPrecedingLineBreak()) { return 0 /* False */; } - if (token() !== 17 /* OpenParenToken */ && token() !== 25 /* LessThanToken */) { + if (token !== 17 /* OpenParenToken */ && token !== 25 /* LessThanToken */) { return 0 /* False */; } } - var first = token(); + var first = token; var second = nextToken(); if (first === 17 /* OpenParenToken */) { if (second === 18 /* CloseParenToken */) { @@ -10998,7 +10586,7 @@ var ts; } function tryParseAsyncSimpleArrowFunctionExpression() { // We do a check here so that we won't be doing unnecessarily call to "lookAhead" - if (token() === 118 /* AsyncKeyword */) { + if (token === 118 /* AsyncKeyword */) { var isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker); if (isUnParenthesizedAsyncArrowFunction === 1 /* True */) { var asyncModifier = parseModifiersForArrowFunction(); @@ -11012,16 +10600,16 @@ var ts; // AsyncArrowFunctionExpression: // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In] // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] - if (token() === 118 /* AsyncKeyword */) { + if (token === 118 /* AsyncKeyword */) { nextToken(); // If the "async" is followed by "=>" token then it is not a begining of an async arrow-function // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher" - if (scanner.hasPrecedingLineBreak() || token() === 34 /* EqualsGreaterThanToken */) { + if (scanner.hasPrecedingLineBreak() || token === 34 /* EqualsGreaterThanToken */) { return 0 /* False */; } // Check for un-parenthesized AsyncArrowFunction var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); - if (!scanner.hasPrecedingLineBreak() && expr.kind === 69 /* Identifier */ && token() === 34 /* EqualsGreaterThanToken */) { + if (!scanner.hasPrecedingLineBreak() && expr.kind === 69 /* Identifier */ && token === 34 /* EqualsGreaterThanToken */) { return 1 /* True */; } } @@ -11051,19 +10639,19 @@ var ts; // - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation. // // So we need just a bit of lookahead to ensure that it can only be a signature. - if (!allowAmbiguity && token() !== 34 /* EqualsGreaterThanToken */ && token() !== 15 /* OpenBraceToken */) { + if (!allowAmbiguity && token !== 34 /* EqualsGreaterThanToken */ && token !== 15 /* OpenBraceToken */) { // Returning undefined here will cause our caller to rewind to where we started from. return undefined; } return node; } function parseArrowFunctionExpressionBody(isAsync) { - if (token() === 15 /* OpenBraceToken */) { + if (token === 15 /* OpenBraceToken */) { return parseFunctionBlock(/*allowYield*/ false, /*allowAwait*/ isAsync, /*ignoreMissingOpenBrace*/ false); } - if (token() !== 23 /* SemicolonToken */ && - token() !== 87 /* FunctionKeyword */ && - token() !== 73 /* ClassKeyword */ && + if (token !== 23 /* SemicolonToken */ && + token !== 87 /* FunctionKeyword */ && + token !== 73 /* ClassKeyword */ && isStartOfStatement() && !isStartOfExpressionStatement()) { // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations) @@ -11136,16 +10724,16 @@ var ts; // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand // a ** b - c // ^token; leftOperand = b. Return b to the caller as a rightOperand - var consumeCurrentOperator = token() === 38 /* AsteriskAsteriskToken */ ? + var consumeCurrentOperator = token === 38 /* AsteriskAsteriskToken */ ? newPrecedence >= precedence : newPrecedence > precedence; if (!consumeCurrentOperator) { break; } - if (token() === 90 /* InKeyword */ && inDisallowInContext()) { + if (token === 90 /* InKeyword */ && inDisallowInContext()) { break; } - if (token() === 116 /* AsKeyword */) { + if (token === 116 /* AsKeyword */) { // Make sure we *do* perform ASI for constructs like this: // var x = foo // as (Bar) @@ -11166,13 +10754,13 @@ var ts; return leftOperand; } function isBinaryOperator() { - if (inDisallowInContext() && token() === 90 /* InKeyword */) { + if (inDisallowInContext() && token === 90 /* InKeyword */) { return false; } return getBinaryOperatorPrecedence() > 0; } function getBinaryOperatorPrecedence() { - switch (token()) { + switch (token) { case 52 /* BarBarToken */: return 1; case 51 /* AmpersandAmpersandToken */: @@ -11229,7 +10817,7 @@ var ts; } function parsePrefixUnaryExpression() { var node = createNode(185 /* PrefixUnaryExpression */); - node.operator = token(); + node.operator = token; nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); @@ -11253,7 +10841,7 @@ var ts; return finishNode(node); } function isAwaitExpression() { - if (token() === 119 /* AwaitKeyword */) { + if (token === 119 /* AwaitKeyword */) { if (inAwaitContext()) { return true; } @@ -11269,42 +10857,25 @@ var ts; return finishNode(node); } /** - * Parse ES7 exponential expression and await expression - * - * ES7 ExponentiationExpression: - * 1) UnaryExpression[?Yield] - * 2) UpdateExpression[?Yield] ** ExponentiationExpression[?Yield] + * Parse ES7 unary expression and await expression * + * ES7 UnaryExpression: + * 1) SimpleUnaryExpression[?yield] + * 2) IncrementExpression[?yield] ** UnaryExpression[?yield] */ function parseUnaryExpressionOrHigher() { - /** - * ES7 UpdateExpression: - * 1) LeftHandSideExpression[?Yield] - * 2) LeftHandSideExpression[?Yield][no LineTerminator here]++ - * 3) LeftHandSideExpression[?Yield][no LineTerminator here]-- - * 4) ++UnaryExpression[?Yield] - * 5) --UnaryExpression[?Yield] - */ - if (isUpdateExpression()) { + if (isAwaitExpression()) { + return parseAwaitExpression(); + } + if (isIncrementExpression()) { var incrementExpression = parseIncrementExpression(); - return token() === 38 /* AsteriskAsteriskToken */ ? + return token === 38 /* AsteriskAsteriskToken */ ? parseBinaryExpressionRest(getBinaryOperatorPrecedence(), incrementExpression) : incrementExpression; } - /** - * ES7 UnaryExpression: - * 1) UpdateExpression[?yield] - * 2) delete UpdateExpression[?yield] - * 3) void UpdateExpression[?yield] - * 4) typeof UpdateExpression[?yield] - * 5) + UpdateExpression[?yield] - * 6) - UpdateExpression[?yield] - * 7) ~ UpdateExpression[?yield] - * 8) ! UpdateExpression[?yield] - */ - var unaryOperator = token(); + var unaryOperator = token; var simpleUnaryExpression = parseSimpleUnaryExpression(); - if (token() === 38 /* AsteriskAsteriskToken */) { + if (token === 38 /* AsteriskAsteriskToken */) { var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); if (simpleUnaryExpression.kind === 177 /* TypeAssertionExpression */) { parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); @@ -11318,8 +10889,8 @@ var ts; /** * Parse ES7 simple-unary expression or higher: * - * ES7 UnaryExpression: - * 1) UpdateExpression[?yield] + * ES7 SimpleUnaryExpression: + * 1) IncrementExpression[?yield] * 2) delete UnaryExpression[?yield] * 3) void UnaryExpression[?yield] * 4) typeof UnaryExpression[?yield] @@ -11327,10 +10898,9 @@ var ts; * 6) - UnaryExpression[?yield] * 7) ~ UnaryExpression[?yield] * 8) ! UnaryExpression[?yield] - * 9) [+Await] await UnaryExpression[?yield] */ function parseSimpleUnaryExpression() { - switch (token()) { + switch (token) { case 35 /* PlusToken */: case 36 /* MinusToken */: case 50 /* TildeToken */: @@ -11347,10 +10917,6 @@ var ts; // UnaryExpression (modified): // < type > UnaryExpression return parseTypeAssertion(); - case 119 /* AwaitKeyword */: - if (isAwaitExpression()) { - return parseAwaitExpression(); - } default: return parseIncrementExpression(); } @@ -11358,17 +10924,17 @@ var ts; /** * Check if the current token can possibly be an ES7 increment expression. * - * ES7 UpdateExpression: + * ES7 IncrementExpression: * LeftHandSideExpression[?Yield] * LeftHandSideExpression[?Yield][no LineTerminator here]++ * LeftHandSideExpression[?Yield][no LineTerminator here]-- * ++LeftHandSideExpression[?Yield] * --LeftHandSideExpression[?Yield] */ - function isUpdateExpression() { + function isIncrementExpression() { // This function is called inside parseUnaryExpression to decide // whether to call parseSimpleUnaryExpression or call parseIncrementExpression directly - switch (token()) { + switch (token) { case 35 /* PlusToken */: case 36 /* MinusToken */: case 50 /* TildeToken */: @@ -11376,7 +10942,6 @@ var ts; case 78 /* DeleteKeyword */: case 101 /* TypeOfKeyword */: case 103 /* VoidKeyword */: - case 119 /* AwaitKeyword */: return false; case 25 /* LessThanToken */: // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression @@ -11401,23 +10966,23 @@ var ts; * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression */ function parseIncrementExpression() { - if (token() === 41 /* PlusPlusToken */ || token() === 42 /* MinusMinusToken */) { + if (token === 41 /* PlusPlusToken */ || token === 42 /* MinusMinusToken */) { var node = createNode(185 /* PrefixUnaryExpression */); - node.operator = token(); + node.operator = token; nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); return finishNode(node); } - else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 25 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeyword)) { + else if (sourceFile.languageVariant === 1 /* JSX */ && token === 25 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeyword)) { // JSXElement is part of primaryExpression return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); } var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); - if ((token() === 41 /* PlusPlusToken */ || token() === 42 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { + if ((token === 41 /* PlusPlusToken */ || token === 42 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { var node = createNode(186 /* PostfixUnaryExpression */, expression.pos); node.operand = expression; - node.operator = token(); + node.operator = token; nextToken(); return finishNode(node); } @@ -11454,7 +11019,7 @@ var ts; // the last two CallExpression productions. Or we have a MemberExpression which either // completes the LeftHandSideExpression, or starts the beginning of the first four // CallExpression productions. - var expression = token() === 95 /* SuperKeyword */ + var expression = token === 95 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher(); // Now, we *may* be complete. However, we might have consumed the start of a @@ -11514,7 +11079,7 @@ var ts; } function parseSuperExpression() { var expression = parseTokenNode(); - if (token() === 17 /* OpenParenToken */ || token() === 21 /* DotToken */ || token() === 19 /* OpenBracketToken */) { + if (token === 17 /* OpenParenToken */ || token === 21 /* DotToken */ || token === 19 /* OpenBracketToken */) { return expression; } // If we have seen "super" it must be followed by '(' or '.'. @@ -11566,7 +11131,7 @@ var ts; // does less damage and we can report a better error. // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios // of one sort or another. - if (inExpressionContext && token() === 25 /* LessThanToken */) { + if (inExpressionContext && token === 25 /* LessThanToken */) { var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); @@ -11583,11 +11148,11 @@ var ts; } function parseJsxText() { var node = createNode(244 /* JsxText */, scanner.getStartPos()); - currentToken = scanner.scanJsxToken(); + token = scanner.scanJsxToken(); return finishNode(node); } function parseJsxChild() { - switch (token()) { + switch (token) { case 244 /* JsxText */: return parseJsxText(); case 15 /* OpenBraceToken */: @@ -11595,7 +11160,7 @@ var ts; case 25 /* LessThanToken */: return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ false); } - ts.Debug.fail("Unknown JSX child kind " + token()); + ts.Debug.fail("Unknown JSX child kind " + token); } function parseJsxChildren(openingTagName) { var result = []; @@ -11603,12 +11168,12 @@ var ts; var saveParsingContext = parsingContext; parsingContext |= 1 << 14 /* JsxChildren */; while (true) { - currentToken = scanner.reScanJsxToken(); - if (token() === 26 /* LessThanSlashToken */) { + token = scanner.reScanJsxToken(); + if (token === 26 /* LessThanSlashToken */) { // Closing tag break; } - else if (token() === 1 /* EndOfFileToken */) { + else if (token === 1 /* EndOfFileToken */) { // If we hit EOF, issue the error at the tag that lacks the closing element // rather than at the end of the file (which is useless) parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); @@ -11626,7 +11191,7 @@ var ts; var tagName = parseJsxElementName(); var attributes = parseList(13 /* JsxAttributes */, parseJsxAttribute); var node; - if (token() === 27 /* GreaterThanToken */) { + if (token === 27 /* GreaterThanToken */) { // Closing tag, so scan the immediately-following text with the JSX scanning instead // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate // scanning errors @@ -11655,7 +11220,7 @@ var ts; // primaryExpression in the form of an identifier and "this" keyword // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword // We only want to consider "this" as a primaryExpression - var expression = token() === 97 /* ThisKeyword */ ? + var expression = token === 97 /* ThisKeyword */ ? parseTokenNode() : parseIdentifierName(); while (parseOptional(21 /* DotToken */)) { var propertyAccess = createNode(172 /* PropertyAccessExpression */, expression.pos); @@ -11668,7 +11233,7 @@ var ts; function parseJsxExpression(inExpressionContext) { var node = createNode(248 /* JsxExpression */); parseExpected(15 /* OpenBraceToken */); - if (token() !== 16 /* CloseBraceToken */) { + if (token !== 16 /* CloseBraceToken */) { node.expression = parseAssignmentExpressionOrHigher(); } if (inExpressionContext) { @@ -11681,14 +11246,14 @@ var ts; return finishNode(node); } function parseJsxAttribute() { - if (token() === 15 /* OpenBraceToken */) { + if (token === 15 /* OpenBraceToken */) { return parseJsxSpreadAttribute(); } scanJsxIdentifier(); var node = createNode(246 /* JsxAttribute */); node.name = parseIdentifierName(); if (parseOptional(56 /* EqualsToken */)) { - switch (token()) { + switch (token) { case 9 /* StringLiteral */: node.initializer = parseLiteralNode(); break; @@ -11738,7 +11303,7 @@ var ts; expression = finishNode(propertyAccess); continue; } - if (token() === 49 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + if (token === 49 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { nextToken(); var nonNullExpression = createNode(196 /* NonNullExpression */, expression.pos); nonNullExpression.expression = expression; @@ -11751,7 +11316,7 @@ var ts; indexedAccess.expression = expression; // It's not uncommon for a user to write: "new Type[]". // Check for that common pattern and report a better error message. - if (token() !== 20 /* CloseBracketToken */) { + if (token !== 20 /* CloseBracketToken */) { indexedAccess.argumentExpression = allowInAnd(parseExpression); if (indexedAccess.argumentExpression.kind === 9 /* StringLiteral */ || indexedAccess.argumentExpression.kind === 8 /* NumericLiteral */) { var literal = indexedAccess.argumentExpression; @@ -11762,10 +11327,10 @@ var ts; expression = finishNode(indexedAccess); continue; } - if (token() === 11 /* NoSubstitutionTemplateLiteral */ || token() === 12 /* TemplateHead */) { + if (token === 11 /* NoSubstitutionTemplateLiteral */ || token === 12 /* TemplateHead */) { var tagExpression = createNode(176 /* TaggedTemplateExpression */, expression.pos); tagExpression.tag = expression; - tagExpression.template = token() === 11 /* NoSubstitutionTemplateLiteral */ + tagExpression.template = token === 11 /* NoSubstitutionTemplateLiteral */ ? parseLiteralNode() : parseTemplateExpression(); expression = finishNode(tagExpression); @@ -11777,7 +11342,7 @@ var ts; function parseCallExpressionRest(expression) { while (true) { expression = parseMemberExpressionRest(expression); - if (token() === 25 /* LessThanToken */) { + if (token === 25 /* LessThanToken */) { // See if this is the start of a generic invocation. If so, consume it and // keep checking for postfix expressions. Otherwise, it's just a '<' that's // part of an arithmetic expression. Break out so we consume it higher in the @@ -11793,7 +11358,7 @@ var ts; expression = finishNode(callExpr); continue; } - else if (token() === 17 /* OpenParenToken */) { + else if (token === 17 /* OpenParenToken */) { var callExpr = createNode(174 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); @@ -11825,7 +11390,7 @@ var ts; : undefined; } function canFollowTypeArgumentsInExpression() { - switch (token()) { + switch (token) { case 17 /* OpenParenToken */: // foo( // this case are the only case where this token can legally follow a type argument // list. So we definitely want to treat this as a type arg list. @@ -11861,7 +11426,7 @@ var ts; } } function parsePrimaryExpression() { - switch (token()) { + switch (token) { case 8 /* NumericLiteral */: case 9 /* StringLiteral */: case 11 /* NoSubstitutionTemplateLiteral */: @@ -11917,8 +11482,8 @@ var ts; return finishNode(node); } function parseArgumentOrArrayLiteralElement() { - return token() === 22 /* DotDotDotToken */ ? parseSpreadElement() : - token() === 24 /* CommaToken */ ? createNode(193 /* OmittedExpression */) : + return token === 22 /* DotDotDotToken */ ? parseSpreadElement() : + token === 24 /* CommaToken */ ? createNode(193 /* OmittedExpression */) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { @@ -11956,7 +11521,7 @@ var ts; var propertyName = parsePropertyName(); // Disallowing of optional property assignments happens in the grammar checker. var questionToken = parseOptionalToken(53 /* QuestionToken */); - if (asteriskToken || token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */) { + if (asteriskToken || token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */) { return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); } // check if it is short-hand property assignment or normal property assignment @@ -11964,7 +11529,7 @@ var ts; // CoverInitializedName[Yield] : // IdentifierReference[?Yield] Initializer[In, ?Yield] // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern - var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 24 /* CommaToken */ || token() === 16 /* CloseBraceToken */ || token() === 56 /* EqualsToken */); + var isShorthandPropertyAssignment = tokenIsIdentifier && (token === 24 /* CommaToken */ || token === 16 /* CloseBraceToken */ || token === 56 /* EqualsToken */); if (isShorthandPropertyAssignment) { var shorthandDeclaration = createNode(254 /* ShorthandPropertyAssignment */, fullStart); shorthandDeclaration.name = propertyName; @@ -12032,7 +11597,7 @@ var ts; parseExpected(92 /* NewKeyword */); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); - if (node.typeArguments || token() === 17 /* OpenParenToken */) { + if (node.typeArguments || token === 17 /* OpenParenToken */) { node.arguments = parseArgumentList(); } return finishNode(node); @@ -12112,8 +11677,8 @@ var ts; parseExpected(86 /* ForKeyword */); parseExpected(17 /* OpenParenToken */); var initializer = undefined; - if (token() !== 23 /* SemicolonToken */) { - if (token() === 102 /* VarKeyword */ || token() === 108 /* LetKeyword */ || token() === 74 /* ConstKeyword */) { + if (token !== 23 /* SemicolonToken */) { + if (token === 102 /* VarKeyword */ || token === 108 /* LetKeyword */ || token === 74 /* ConstKeyword */) { initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true); } else { @@ -12139,11 +11704,11 @@ var ts; var forStatement = createNode(206 /* ForStatement */, pos); forStatement.initializer = initializer; parseExpected(23 /* SemicolonToken */); - if (token() !== 23 /* SemicolonToken */ && token() !== 18 /* CloseParenToken */) { + if (token !== 23 /* SemicolonToken */ && token !== 18 /* CloseParenToken */) { forStatement.condition = allowInAnd(parseExpression); } parseExpected(23 /* SemicolonToken */); - if (token() !== 18 /* CloseParenToken */) { + if (token !== 18 /* CloseParenToken */) { forStatement.incrementor = allowInAnd(parseExpression); } parseExpected(18 /* CloseParenToken */); @@ -12195,7 +11760,7 @@ var ts; return finishNode(node); } function parseCaseOrDefaultClause() { - return token() === 71 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); + return token === 71 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { var node = createNode(213 /* SwitchStatement */); @@ -12229,10 +11794,10 @@ var ts; var node = createNode(216 /* TryStatement */); parseExpected(100 /* TryKeyword */); node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); - node.catchClause = token() === 72 /* CatchKeyword */ ? parseCatchClause() : undefined; + node.catchClause = token === 72 /* CatchKeyword */ ? parseCatchClause() : undefined; // If we don't have a catch clause, then we must have a finally clause. Try to parse // one out no matter what. - if (!node.catchClause || token() === 85 /* FinallyKeyword */) { + if (!node.catchClause || token === 85 /* FinallyKeyword */) { parseExpected(85 /* FinallyKeyword */); node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); } @@ -12275,19 +11840,19 @@ var ts; } function nextTokenIsIdentifierOrKeywordOnSameLine() { nextToken(); - return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak(); + return ts.tokenIsIdentifierOrKeyword(token) && !scanner.hasPrecedingLineBreak(); } function nextTokenIsFunctionKeywordOnSameLine() { nextToken(); - return token() === 87 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak(); + return token === 87 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak(); } function nextTokenIsIdentifierOrKeywordOrNumberOnSameLine() { nextToken(); - return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */) && !scanner.hasPrecedingLineBreak(); + return (ts.tokenIsIdentifierOrKeyword(token) || token === 8 /* NumericLiteral */) && !scanner.hasPrecedingLineBreak(); } function isDeclaration() { while (true) { - switch (token()) { + switch (token) { case 102 /* VarKeyword */: case 108 /* LetKeyword */: case 74 /* ConstKeyword */: @@ -12337,16 +11902,16 @@ var ts; continue; case 137 /* GlobalKeyword */: nextToken(); - return token() === 15 /* OpenBraceToken */ || token() === 69 /* Identifier */ || token() === 82 /* ExportKeyword */; + return token === 15 /* OpenBraceToken */ || token === 69 /* Identifier */ || token === 82 /* ExportKeyword */; case 89 /* ImportKeyword */: nextToken(); - return token() === 9 /* StringLiteral */ || token() === 37 /* AsteriskToken */ || - token() === 15 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token()); + return token === 9 /* StringLiteral */ || token === 37 /* AsteriskToken */ || + token === 15 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token); case 82 /* ExportKeyword */: nextToken(); - if (token() === 56 /* EqualsToken */ || token() === 37 /* AsteriskToken */ || - token() === 15 /* OpenBraceToken */ || token() === 77 /* DefaultKeyword */ || - token() === 116 /* AsKeyword */) { + if (token === 56 /* EqualsToken */ || token === 37 /* AsteriskToken */ || + token === 15 /* OpenBraceToken */ || token === 77 /* DefaultKeyword */ || + token === 116 /* AsKeyword */) { return true; } continue; @@ -12362,7 +11927,7 @@ var ts; return lookAhead(isDeclaration); } function isStartOfStatement() { - switch (token()) { + switch (token) { case 55 /* AtToken */: case 23 /* SemicolonToken */: case 15 /* OpenBraceToken */: @@ -12415,7 +11980,7 @@ var ts; } function nextTokenIsIdentifierOrStartOfDestructuring() { nextToken(); - return isIdentifier() || token() === 15 /* OpenBraceToken */ || token() === 19 /* OpenBracketToken */; + return isIdentifier() || token === 15 /* OpenBraceToken */ || token === 19 /* OpenBracketToken */; } function isLetDeclaration() { // In ES6 'let' always starts a lexical declaration if followed by an identifier or { @@ -12423,7 +11988,7 @@ var ts; return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); } function parseStatement() { - switch (token()) { + switch (token) { case 23 /* SemicolonToken */: return parseEmptyStatement(); case 15 /* OpenBraceToken */: @@ -12496,7 +12061,7 @@ var ts; var fullStart = getNodePos(); var decorators = parseDecorators(); var modifiers = parseModifiers(); - switch (token()) { + switch (token) { case 102 /* VarKeyword */: case 108 /* LetKeyword */: case 74 /* ConstKeyword */: @@ -12519,7 +12084,7 @@ var ts; return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); case 82 /* ExportKeyword */: nextToken(); - switch (token()) { + switch (token) { case 77 /* DefaultKeyword */: case 56 /* EqualsToken */: return parseExportAssignment(fullStart, decorators, modifiers); @@ -12542,10 +12107,10 @@ var ts; } function nextTokenIsIdentifierOrStringLiteralOnSameLine() { nextToken(); - return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9 /* StringLiteral */); + return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token === 9 /* StringLiteral */); } function parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage) { - if (token() !== 15 /* OpenBraceToken */ && canParseSemicolon()) { + if (token !== 15 /* OpenBraceToken */ && canParseSemicolon()) { parseSemicolon(); return; } @@ -12553,7 +12118,7 @@ var ts; } // DECLARATIONS function parseArrayBindingElement() { - if (token() === 24 /* CommaToken */) { + if (token === 24 /* CommaToken */) { return createNode(193 /* OmittedExpression */); } var node = createNode(169 /* BindingElement */); @@ -12566,7 +12131,7 @@ var ts; var node = createNode(169 /* BindingElement */); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); - if (tokenIsIdentifier && token() !== 54 /* ColonToken */) { + if (tokenIsIdentifier && token !== 54 /* ColonToken */) { node.name = propertyName; } else { @@ -12592,13 +12157,13 @@ var ts; return finishNode(node); } function isIdentifierOrPattern() { - return token() === 15 /* OpenBraceToken */ || token() === 19 /* OpenBracketToken */ || isIdentifier(); + return token === 15 /* OpenBraceToken */ || token === 19 /* OpenBracketToken */ || isIdentifier(); } function parseIdentifierOrPattern() { - if (token() === 19 /* OpenBracketToken */) { + if (token === 19 /* OpenBracketToken */) { return parseArrayBindingPattern(); } - if (token() === 15 /* OpenBraceToken */) { + if (token === 15 /* OpenBraceToken */) { return parseObjectBindingPattern(); } return parseIdentifier(); @@ -12607,14 +12172,14 @@ var ts; var node = createNode(218 /* VariableDeclaration */); node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); - if (!isInOrOfKeyword(token())) { + if (!isInOrOfKeyword(token)) { node.initializer = parseInitializer(/*inParameter*/ false); } return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { var node = createNode(219 /* VariableDeclarationList */); - switch (token()) { + switch (token) { case 102 /* VarKeyword */: break; case 108 /* LetKeyword */: @@ -12636,7 +12201,7 @@ var ts; // So we need to look ahead to determine if 'of' should be treated as a keyword in // this context. // The checker will then give an error that there is an empty declaration list. - if (token() === 138 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { + if (token === 138 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { @@ -12721,7 +12286,7 @@ var ts; // Note: this is not legal as per the grammar. But we allow it in the parser and // report an error in the grammar checker. var questionToken = parseOptionalToken(53 /* QuestionToken */); - if (asteriskToken || token() === 17 /* OpenParenToken */ || token() === 25 /* LessThanToken */) { + if (asteriskToken || token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */) { return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, ts.Diagnostics.or_expected); } else { @@ -12754,12 +12319,12 @@ var ts; } function isClassMemberStart() { var idToken; - if (token() === 55 /* AtToken */) { + if (token === 55 /* AtToken */) { return true; } // Eat up all modifiers, but hold on to the last one in case it is actually an identifier. - while (ts.isModifierKind(token())) { - idToken = token(); + while (ts.isModifierKind(token)) { + idToken = token; // If the idToken is a class modifier (protected, private, public, and static), it is // certain that we are starting to parse class member. This allows better error recovery // Example: @@ -12771,17 +12336,17 @@ var ts; } nextToken(); } - if (token() === 37 /* AsteriskToken */) { + if (token === 37 /* AsteriskToken */) { return true; } // Try to get the first property-like token following all modifiers. // This can either be an identifier or the 'get' or 'set' keywords. if (isLiteralPropertyName()) { - idToken = token(); + idToken = token; nextToken(); } // Index signatures and computed properties are class members; we can parse. - if (token() === 19 /* OpenBracketToken */) { + if (token === 19 /* OpenBracketToken */) { return true; } // If we were able to get any potential identifier... @@ -12792,7 +12357,7 @@ var ts; } // If it *is* a keyword, but not an accessor, check a little farther along // to see if it should actually be parsed as a class member. - switch (token()) { + switch (token) { case 17 /* OpenParenToken */: // Method declaration case 25 /* LessThanToken */: // Generic Method declaration case 54 /* ColonToken */: // Type Annotation for declaration @@ -12842,8 +12407,8 @@ var ts; var modifiers; while (true) { var modifierStart = scanner.getStartPos(); - var modifierKind = token(); - if (token() === 74 /* ConstKeyword */ && permitInvalidConstAsModifier) { + var modifierKind = token; + if (token === 74 /* ConstKeyword */ && permitInvalidConstAsModifier) { // We need to ensure that any subsequent modifiers appear on the same line // so that when 'const' is a standalone declaration, we don't issue an error. if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { @@ -12871,9 +12436,9 @@ var ts; function parseModifiersForArrowFunction() { var flags = 0; var modifiers; - if (token() === 118 /* AsyncKeyword */) { + if (token === 118 /* AsyncKeyword */) { var modifierStart = scanner.getStartPos(); - var modifierKind = token(); + var modifierKind = token; nextToken(); modifiers = []; modifiers.pos = modifierStart; @@ -12885,7 +12450,7 @@ var ts; return modifiers; } function parseClassElement() { - if (token() === 23 /* SemicolonToken */) { + if (token === 23 /* SemicolonToken */) { var result = createNode(198 /* SemicolonClassElement */); nextToken(); return finishNode(result); @@ -12897,7 +12462,7 @@ var ts; if (accessor) { return accessor; } - if (token() === 121 /* ConstructorKeyword */) { + if (token === 121 /* ConstructorKeyword */) { return parseConstructorDeclaration(fullStart, decorators, modifiers); } if (isIndexSignature()) { @@ -12905,11 +12470,11 @@ var ts; } // It is very important that we check this *after* checking indexers because // the [ token can start an index signature or a computed property name - if (ts.tokenIsIdentifierOrKeyword(token()) || - token() === 9 /* StringLiteral */ || - token() === 8 /* NumericLiteral */ || - token() === 37 /* AsteriskToken */ || - token() === 19 /* OpenBracketToken */) { + if (ts.tokenIsIdentifierOrKeyword(token) || + token === 9 /* StringLiteral */ || + token === 8 /* NumericLiteral */ || + token === 37 /* AsteriskToken */ || + token === 19 /* OpenBracketToken */) { return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); } if (decorators || modifiers) { @@ -12959,7 +12524,7 @@ var ts; : undefined; } function isImplementsClause() { - return token() === 106 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword); + return token === 106 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword); } function parseHeritageClauses(isClassHeritageClause) { // ClassTail[Yield,Await] : (Modified) See 14.5 @@ -12970,9 +12535,9 @@ var ts; return undefined; } function parseHeritageClause() { - if (token() === 83 /* ExtendsKeyword */ || token() === 106 /* ImplementsKeyword */) { + if (token === 83 /* ExtendsKeyword */ || token === 106 /* ImplementsKeyword */) { var node = createNode(251 /* HeritageClause */); - node.token = token(); + node.token = token; nextToken(); node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); return finishNode(node); @@ -12982,13 +12547,13 @@ var ts; function parseExpressionWithTypeArguments() { var node = createNode(194 /* ExpressionWithTypeArguments */); node.expression = parseLeftHandSideExpressionOrHigher(); - if (token() === 25 /* LessThanToken */) { + if (token === 25 /* LessThanToken */) { node.typeArguments = parseBracketedList(18 /* TypeArguments */, parseType, 25 /* LessThanToken */, 27 /* GreaterThanToken */); } return finishNode(node); } function isHeritageClause() { - return token() === 83 /* ExtendsKeyword */ || token() === 106 /* ImplementsKeyword */; + return token === 83 /* ExtendsKeyword */ || token === 106 /* ImplementsKeyword */; } function parseClassMembers() { return parseList(5 /* ClassMembers */, parseClassElement); @@ -13070,7 +12635,7 @@ var ts; var node = createNode(225 /* ModuleDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); - if (token() === 137 /* GlobalKeyword */) { + if (token === 137 /* GlobalKeyword */) { // parse 'global' as name of global scope augmentation node.name = parseIdentifier(); node.flags |= 131072 /* GlobalAugmentation */; @@ -13078,7 +12643,7 @@ var ts; else { node.name = parseLiteralNode(/*internName*/ true); } - if (token() === 15 /* OpenBraceToken */) { + if (token === 15 /* OpenBraceToken */) { node.body = parseModuleBlock(); } else { @@ -13088,7 +12653,7 @@ var ts; } function parseModuleDeclaration(fullStart, decorators, modifiers) { var flags = modifiers ? modifiers.flags : 0; - if (token() === 137 /* GlobalKeyword */) { + if (token === 137 /* GlobalKeyword */) { // global augmentation return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } @@ -13097,14 +12662,14 @@ var ts; } else { parseExpected(125 /* ModuleKeyword */); - if (token() === 9 /* StringLiteral */) { + if (token === 9 /* StringLiteral */) { return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } } return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); } function isExternalModuleReference() { - return token() === 129 /* RequireKeyword */ && + return token === 129 /* RequireKeyword */ && lookAhead(nextTokenIsOpenParen); } function nextTokenIsOpenParen() { @@ -13129,7 +12694,7 @@ var ts; var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token() !== 24 /* CommaToken */ && token() !== 136 /* FromKeyword */) { + if (token !== 24 /* CommaToken */ && token !== 136 /* FromKeyword */) { // ImportEquals declaration of type: // import x = require("mod"); or // import x = M.x; @@ -13151,8 +12716,8 @@ var ts; // import ImportClause from ModuleSpecifier ; // import ModuleSpecifier; if (identifier || - token() === 37 /* AsteriskToken */ || - token() === 15 /* OpenBraceToken */) { + token === 37 /* AsteriskToken */ || + token === 15 /* OpenBraceToken */) { importDeclaration.importClause = parseImportClause(identifier, afterImportPos); parseExpected(136 /* FromKeyword */); } @@ -13177,7 +12742,7 @@ var ts; // parse namespace or named imports if (!importClause.name || parseOptional(24 /* CommaToken */)) { - importClause.namedBindings = token() === 37 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(233 /* NamedImports */); + importClause.namedBindings = token === 37 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(233 /* NamedImports */); } return finishNode(importClause); } @@ -13195,7 +12760,7 @@ var ts; return finishNode(node); } function parseModuleSpecifier() { - if (token() === 9 /* StringLiteral */) { + if (token === 9 /* StringLiteral */) { var result = parseLiteralNode(); internIdentifier(result.text); return result; @@ -13242,14 +12807,14 @@ var ts; // ExportSpecifier: // IdentifierName // IdentifierName as IdentifierName - var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); + var checkIdentifierIsKeyword = ts.isKeyword(token) && !isIdentifier(); var checkIdentifierStart = scanner.getTokenPos(); var checkIdentifierEnd = scanner.getTextPos(); var identifierName = parseIdentifierName(); - if (token() === 116 /* AsKeyword */) { + if (token === 116 /* AsKeyword */) { node.propertyName = identifierName; parseExpected(116 /* AsKeyword */); - checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); + checkIdentifierIsKeyword = ts.isKeyword(token) && !isIdentifier(); checkIdentifierStart = scanner.getTokenPos(); checkIdentifierEnd = scanner.getTextPos(); node.name = parseIdentifierName(); @@ -13276,7 +12841,7 @@ var ts; // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios, // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`) // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect. - if (token() === 136 /* FromKeyword */ || (token() === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { + if (token === 136 /* FromKeyword */ || (token === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { parseExpected(136 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } @@ -13414,7 +12979,7 @@ var ts; var JSDocParser; (function (JSDocParser) { function isJSDocType() { - switch (token()) { + switch (token) { case 37 /* AsteriskToken */: case 53 /* QuestionToken */: case 17 /* OpenParenToken */: @@ -13427,13 +12992,13 @@ var ts; case 97 /* ThisKeyword */: return true; } - return ts.tokenIsIdentifierOrKeyword(token()); + return ts.tokenIsIdentifierOrKeyword(token); } JSDocParser.isJSDocType = isJSDocType; function parseJSDocTypeExpressionForTests(content, start, length) { initializeState("file.js", content, 2 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); scanner.setText(content, start, length); - currentToken = scanner.scan(); + token = scanner.scan(); var jsDocTypeExpression = parseJSDocTypeExpression(); var diagnostics = parseDiagnostics; clearState(); @@ -13453,12 +13018,12 @@ var ts; JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression; function parseJSDocTopLevelType() { var type = parseJSDocType(); - if (token() === 47 /* BarToken */) { + if (token === 47 /* BarToken */) { var unionType = createNode(261 /* JSDocUnionType */, type.pos); unionType.types = parseJSDocTypeList(type); type = finishNode(unionType); } - if (token() === 56 /* EqualsToken */) { + if (token === 56 /* EqualsToken */) { var optionalType = createNode(268 /* JSDocOptionalType */, type.pos); nextToken(); optionalType.type = type; @@ -13469,20 +13034,20 @@ var ts; function parseJSDocType() { var type = parseBasicTypeExpression(); while (true) { - if (token() === 19 /* OpenBracketToken */) { + if (token === 19 /* OpenBracketToken */) { var arrayType = createNode(260 /* JSDocArrayType */, type.pos); arrayType.elementType = type; nextToken(); parseExpected(20 /* CloseBracketToken */); type = finishNode(arrayType); } - else if (token() === 53 /* QuestionToken */) { + else if (token === 53 /* QuestionToken */) { var nullableType = createNode(263 /* JSDocNullableType */, type.pos); nullableType.type = type; nextToken(); type = finishNode(nullableType); } - else if (token() === 49 /* ExclamationToken */) { + else if (token === 49 /* ExclamationToken */) { var nonNullableType = createNode(264 /* JSDocNonNullableType */, type.pos); nonNullableType.type = type; nextToken(); @@ -13495,7 +13060,7 @@ var ts; return type; } function parseBasicTypeExpression() { - switch (token()) { + switch (token) { case 37 /* AsteriskToken */: return parseJSDocAllType(); case 53 /* QuestionToken */: @@ -13522,16 +13087,9 @@ var ts; case 120 /* BooleanKeyword */: case 133 /* SymbolKeyword */: case 103 /* VoidKeyword */: - case 93 /* NullKeyword */: - case 135 /* UndefinedKeyword */: - case 127 /* NeverKeyword */: return parseTokenNode(); - case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: - case 99 /* TrueKeyword */: - case 84 /* FalseKeyword */: - return parseJSDocLiteralType(); } + // TODO (drosen): Parse string literal types in JSDoc as well. return parseJSDocTypeReference(); } function parseJSDocThisType() { @@ -13561,7 +13119,7 @@ var ts; result.parameters = parseDelimitedList(22 /* JSDocFunctionParameters */, parseJSDocParameter); checkForTrailingComma(result.parameters); parseExpected(18 /* CloseParenToken */); - if (token() === 54 /* ColonToken */) { + if (token === 54 /* ColonToken */) { nextToken(); result.type = parseJSDocType(); } @@ -13578,12 +13136,12 @@ var ts; function parseJSDocTypeReference() { var result = createNode(267 /* JSDocTypeReference */); result.name = parseSimplePropertyName(); - if (token() === 25 /* LessThanToken */) { + if (token === 25 /* LessThanToken */) { result.typeArguments = parseTypeArguments(); } else { while (parseOptional(21 /* DotToken */)) { - if (token() === 25 /* LessThanToken */) { + if (token === 25 /* LessThanToken */) { result.typeArguments = parseTypeArguments(); break; } @@ -13627,7 +13185,7 @@ var ts; function parseJSDocRecordMember() { var result = createNode(266 /* JSDocRecordMember */); result.name = parseSimplePropertyName(); - if (token() === 54 /* ColonToken */) { + if (token === 54 /* ColonToken */) { nextToken(); result.type = parseJSDocType(); } @@ -13676,11 +13234,6 @@ var ts; nextToken(); return finishNode(result); } - function parseJSDocLiteralType() { - var result = createNode(282 /* JSDocLiteralType */); - result.literal = parseLiteralTypeNode(); - return finishNode(result); - } function parseJSDocUnknownOrNullableType() { var pos = scanner.getStartPos(); // skip the ? @@ -13694,12 +13247,12 @@ var ts; // Foo // Foo(?= // (?| - if (token() === 24 /* CommaToken */ || - token() === 16 /* CloseBraceToken */ || - token() === 18 /* CloseParenToken */ || - token() === 27 /* GreaterThanToken */ || - token() === 56 /* EqualsToken */ || - token() === 47 /* BarToken */) { + if (token === 24 /* CommaToken */ || + token === 16 /* CloseBraceToken */ || + token === 18 /* CloseParenToken */ || + token === 27 /* GreaterThanToken */ || + token === 56 /* EqualsToken */ || + token === 47 /* BarToken */) { var result = createNode(259 /* JSDocUnknownType */, pos); return finishNode(result); } @@ -13719,14 +13272,14 @@ var ts; } JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; function parseJSDocComment(parent, start, length) { - var saveToken = currentToken; + var saveToken = token; var saveParseDiagnosticsLength = parseDiagnostics.length; var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; var comment = parseJSDocCommentWorker(start, length); if (comment) { comment.parent = parent; } - currentToken = saveToken; + token = saveToken; parseDiagnostics.length = saveParseDiagnosticsLength; parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; return comment; @@ -13754,8 +13307,8 @@ var ts; var canParseTag = true; var seenAsterisk = true; nextJSDocToken(); - while (token() !== 1 /* EndOfFileToken */) { - switch (token()) { + while (token !== 1 /* EndOfFileToken */) { + switch (token) { case 55 /* AtToken */: if (canParseTag) { parseTag(); @@ -13800,12 +13353,12 @@ var ts; return finishNode(result, end); } function skipWhitespace() { - while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + while (token === 5 /* WhitespaceTrivia */ || token === 4 /* NewLineTrivia */) { nextJSDocToken(); } } function parseTag() { - ts.Debug.assert(token() === 55 /* AtToken */); + ts.Debug.assert(token === 55 /* AtToken */); var atToken = createNode(55 /* AtToken */, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); @@ -13851,7 +13404,7 @@ var ts; } } function tryParseTypeExpression() { - if (token() !== 15 /* OpenBraceToken */) { + if (token !== 15 /* OpenBraceToken */) { return undefined; } var typeExpression = parseJSDocTypeExpression(); @@ -13872,7 +13425,7 @@ var ts; } parseExpected(20 /* CloseBracketToken */); } - else if (ts.tokenIsIdentifierOrKeyword(token())) { + else if (ts.tokenIsIdentifierOrKeyword(token)) { name = parseJSDocIdentifierName(); } if (!name) { @@ -13965,15 +13518,12 @@ var ts; var canParseTag = true; var seenAsterisk = false; var parentTagTerminated = false; - while (token() !== 1 /* EndOfFileToken */ && !parentTagTerminated) { + while (token !== 1 /* EndOfFileToken */ && !parentTagTerminated) { nextJSDocToken(); - switch (token()) { + switch (token) { case 55 /* AtToken */: if (canParseTag) { parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral); - if (!parentTagTerminated) { - resumePos = scanner.getStartPos(); - } } seenAsterisk = false; break; @@ -13999,7 +13549,7 @@ var ts; } } function tryParseChildTag(parentTag) { - ts.Debug.assert(token() === 55 /* AtToken */); + ts.Debug.assert(token === 55 /* AtToken */); var atToken = createNode(55 /* AtToken */, scanner.getStartPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); @@ -14043,7 +13593,7 @@ var ts; typeParameter.name = name_9; finishNode(typeParameter); typeParameters.push(typeParameter); - if (token() === 24 /* CommaToken */) { + if (token === 24 /* CommaToken */) { nextJSDocToken(); } else { @@ -14059,10 +13609,10 @@ var ts; return result; } function nextJSDocToken() { - return currentToken = scanner.scanJSDocToken(); + return token = scanner.scanJSDocToken(); } function parseJSDocIdentifierName() { - return createJSDocIdentifier(ts.tokenIsIdentifierOrKeyword(token())); + return createJSDocIdentifier(ts.tokenIsIdentifierOrKeyword(token)); } function createJSDocIdentifier(isIdentifier) { if (!isIdentifier) { @@ -14189,8 +13739,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { - var node = array_9[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } } @@ -14327,8 +13877,8 @@ var ts; array._children = undefined; // Adjust the pos or end (or both) of the intersecting array accordingly. adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_10 = array; _i < array_10.length; _i++) { - var node = array_10[_i]; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; visitNode(node); } return; @@ -14556,545 +14106,12 @@ var ts; })(InvalidPosition || (InvalidPosition = {})); })(IncrementalParser || (IncrementalParser = {})); })(ts || (ts = {})); -/// -/// -var ts; -(function (ts) { - function tryReadTypesSection(packageJsonPath, baseDirectory, state) { - var jsonContent = ts.readJson(packageJsonPath, state.host); - function tryReadFromField(fieldName) { - if (ts.hasProperty(jsonContent, fieldName)) { - var typesFile = jsonContent[fieldName]; - if (typeof typesFile === "string") { - var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1); - } - return typesFilePath_1; - } - else { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); - } - } - } - } - var typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); - if (typesFilePath) { - return typesFilePath; - } - // Use the main module for inferring types if no types package specified and the allowJs is set - if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); - } - var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); - return mainFilePath; - } - return undefined; - } - /** Return the file if it exists. */ - function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures && state.host.fileExists(fileName)) { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); - } - return fileName; - } - else { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); - } - failedLookupLocation.push(fileName); - return undefined; - } - } - /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ - function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures) { - // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing - var directory = ts.getDirectoryPath(candidate); - if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); - } - } - return ts.forEach(extensions, function (ext) { - return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); - }); - } - /** - * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary - * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. - */ - function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); - if (resolvedByAddingExtension) { - return resolvedByAddingExtension; - } - // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; - // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" - if (ts.hasJavaScriptFileExtension(candidate)) { - var extensionless = ts.removeFileExtension(candidate); - if (state.traceEnabled) { - var extension = candidate.substring(extensionless.length); - ts.trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); - } - return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); - } - } - /* @internal */ - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { - var packageJsonPath = pathToPackageJson(candidate); - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - if (directoryExists && state.host.fileExists(packageJsonPath)) { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); - if (typesFile) { - var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); - // A package.json "typings" may specify an exact filename, or may choose to omit an extension. - var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) || - tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state); - if (result) { - return result; - } - } - else { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field); - } - } - } - else { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); - } - // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results - failedLookupLocation.push(packageJsonPath); - } - return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); - } - ts.loadNodeModuleFromDirectory = loadNodeModuleFromDirectory; - function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { - var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions); - var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - } - /* @internal */ - function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state, checkOneLevel) { - directory = ts.normalizeSlashes(directory); - while (true) { - var baseName = ts.getBaseFileName(directory); - if (baseName !== "node_modules") { - // Try to load source from the package - var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); - if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { - // Always prefer a TypeScript (.ts, .tsx, .d.ts) file shipped with the package - return packageResult; - } - else { - // Else prefer a types package over non-TypeScript results (e.g. JavaScript files) - var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); - if (typesResult || packageResult) { - return typesResult || packageResult; - } - } - } - var parentPath = ts.getDirectoryPath(directory); - if (parentPath === directory || checkOneLevel) { - break; - } - directory = parentPath; - } - return undefined; - } - ts.loadModuleFromNodeModules = loadModuleFromNodeModules; - function moduleHasNonRelativeName(moduleName) { - return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); - } - function classicNameResolver(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = ts.isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; - var failedLookupLocations = []; - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var containingDirectory = ts.getDirectoryPath(containingFile); - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); - if (resolvedFileName) { - return ts.createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/ false, failedLookupLocations); - } - var referencedSourceFile; - if (moduleHasNonRelativeName(moduleName)) { - while (true) { - var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); - if (referencedSourceFile) { - break; - } - var parentPath = ts.getDirectoryPath(containingDirectory); - if (parentPath === containingDirectory) { - break; - } - containingDirectory = parentPath; - } - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); - } - return referencedSourceFile - ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } - : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; - } - ts.classicNameResolver = classicNameResolver; - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { - var containingDirectory = ts.getDirectoryPath(containingFile); - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var traceEnabled = ts.isTraceEnabled(compilerOptions, host); - var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); - var isExternalLibraryImport = false; - if (!resolvedFileName) { - if (moduleHasNonRelativeName(moduleName)) { - if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); - } - resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state, /*checkOneLevel*/ false); - isExternalLibraryImport = resolvedFileName !== undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); - } - } - if (resolvedFileName && host.realpath) { - var originalFileName = resolvedFileName; - resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName)); - if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); - } - } - return ts.createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; - function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); - } - var resolvedFileName = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); - return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); - } - function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.rootDirs) { - return undefined; - } - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); - } - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var matchedRootDir; - var matchedNormalizedPrefix; - for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { - var rootDir = _a[_i]; - // rootDirs are expected to be absolute - // in case of tsconfig.json this will happen automatically - compiler will expand relative names - // using location of tsconfig.json as base location - var normalizedRoot = ts.normalizePath(rootDir); - if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { - normalizedRoot += ts.directorySeparator; - } - var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && - (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); - } - if (isLongestMatchingPrefix) { - matchedNormalizedPrefix = normalizedRoot; - matchedRootDir = rootDir; - } - } - if (matchedNormalizedPrefix) { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); - } - var suffix = candidate.substr(matchedNormalizedPrefix.length); - // first - try to load from a initial location - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); - } - // then try to resolve using remaining entries in rootDirs - for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { - var rootDir = _c[_b]; - if (rootDir === matchedRootDir) { - // skip the initially matched entry - continue; - } - var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); - } - var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); - if (resolvedFileName_1) { - return resolvedFileName_1; - } - } - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); - } - } - return undefined; - } - function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.baseUrl) { - return undefined; - } - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); - } - // string is for exact match - var matchedPattern = undefined; - if (state.compilerOptions.paths) { - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); - } - matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName); - var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern); - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); - } - for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) { - var subst = _a[_i]; - var path = matchedStar ? subst.replace("*", matchedStar) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - } - return undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - ts.trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - } - } - /** - * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to - * mitigate differences between design time structure of the project and its runtime counterpart so the same import name - * can be resolved successfully by TypeScript compiler and runtime module loader. - * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will - * fallback to standard resolution routine. - * - * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative - * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will - * be '/a/b/c/d' - * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names - * will be resolved based on the content of the module name. - * Structure of 'paths' compiler options - * 'paths': { - * pattern-1: [...substitutions], - * pattern-2: [...substitutions], - * ... - * pattern-n: [...substitutions] - * } - * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against - * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case. - * If pattern contains '*' then to match pattern "*" module name must start with the and end with . - * denotes part of the module name between and . - * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked. - * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module - * from the candidate location. - * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every - * substitution in the list and replace '*' with string. If candidate location is not rooted it - * will be converted to absolute using baseUrl. - * For example: - * baseUrl: /a/b/c - * "paths": { - * // match all module names - * "*": [ - * "*", // use matched name as is, - * // will be looked as /a/b/c/ - * - * "folder1/*" // substitution will convert matched name to 'folder1/', - * // since it is not rooted then final candidate location will be /a/b/c/folder1/ - * ], - * // match module names that start with 'components/' - * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/ to '/root/components/folder1/', - * // it is rooted so it will be final candidate location - * } - * - * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if - * they were in the same location. For example lets say there are two files - * '/local/src/content/file1.ts' - * '/shared/components/contracts/src/content/protocols/file2.ts' - * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so - * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime. - * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all - * root dirs were merged together. - * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ]. - * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file: - * '/local/src/content/protocols/file2' and try to load it - failure. - * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will - * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining - * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. - */ - function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (moduleHasNonRelativeName(moduleName)) { - return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); - } - else { - return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); - } - } - function resolveModuleName(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = ts.isTraceEnabled(compilerOptions, host); - if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); - } - var moduleResolution = compilerOptions.moduleResolution; - if (moduleResolution === undefined) { - moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; - if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - else { - if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - var result; - switch (moduleResolution) { - case ts.ModuleResolutionKind.NodeJs: - result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); - break; - case ts.ModuleResolutionKind.Classic: - result = classicNameResolver(moduleName, containingFile, compilerOptions, host); - break; - } - if (traceEnabled) { - if (result.resolvedModule) { - ts.trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); - } - else { - ts.trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); - } - } - return result; - } - ts.resolveModuleName = resolveModuleName; - /** - * patternStrings contains both pattern strings (containing "*") and regular strings. - * Return an exact match if possible, or a pattern match, or undefined. - * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.) - */ - function matchPatternOrExact(patternStrings, candidate) { - var patterns = []; - for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { - var patternString = patternStrings_1[_i]; - var pattern = tryParsePattern(patternString); - if (pattern) { - patterns.push(pattern); - } - else if (patternString === candidate) { - // pattern was matched as is - no need to search further - return patternString; - } - } - return findBestPatternMatch(patterns, function (_) { return _; }, candidate); - } - function patternText(_a) { - var prefix = _a.prefix, suffix = _a.suffix; - return prefix + "*" + suffix; - } - /** - * Given that candidate matches pattern, returns the text matching the '*'. - * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar" - */ - function matchedText(pattern, candidate) { - ts.Debug.assert(isPatternMatch(pattern, candidate)); - return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); - } - /** Return the object corresponding to the best pattern to match `candidate`. */ - /* @internal */ - function findBestPatternMatch(values, getPattern, candidate) { - var matchedValue = undefined; - // use length of prefix as betterness criteria - var longestMatchPrefixLength = -1; - for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { - var v = values_1[_i]; - var pattern = getPattern(v); - if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { - longestMatchPrefixLength = pattern.prefix.length; - matchedValue = v; - } - } - return matchedValue; - } - ts.findBestPatternMatch = findBestPatternMatch; - function isPatternMatch(_a, candidate) { - var prefix = _a.prefix, suffix = _a.suffix; - return candidate.length >= prefix.length + suffix.length && - ts.startsWith(candidate, prefix) && - ts.endsWith(candidate, suffix); - } - /* @internal */ - function tryParsePattern(pattern) { - // This should be verified outside of here and a proper error thrown. - ts.Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern)); - var indexOfStar = pattern.indexOf("*"); - return indexOfStar === -1 ? undefined : { - prefix: pattern.substr(0, indexOfStar), - suffix: pattern.substr(indexOfStar + 1) - }; - } - ts.tryParsePattern = tryParsePattern; - /* @internal */ - function directoryProbablyExists(directoryName, host) { - // if host does not support 'directoryExists' assume that directory will exist - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - /* @internal */ - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - ts.pathToPackageJson = pathToPackageJson; -})(ts || (ts = {})); /// -/// /// /* @internal */ var ts; (function (ts) { + ts.bindTime = 0; (function (ModuleInstanceState) { ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated"; ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated"; @@ -15166,10 +14183,9 @@ var ts; })(ContainerFlags || (ContainerFlags = {})); var binder = createBinder(); function bindSourceFile(file, options) { - ts.performance.mark("beforeBind"); + var start = new Date().getTime(); binder(file, options); - ts.performance.mark("afterBind"); - ts.performance.measure("Bind", "beforeBind", "afterBind"); + ts.bindTime += new Date().getTime() - start; } ts.bindSourceFile = bindSourceFile; function createBinder() { @@ -15207,7 +14223,7 @@ var ts; options = opts; languageVersion = ts.getEmitScriptTarget(options); inStrictMode = !!file.externalModuleIndicator; - classifiableNames = ts.createMap(); + classifiableNames = {}; symbolCount = 0; Symbol = ts.objectAllocator.getSymbolConstructor(); if (!file.locals) { @@ -15246,10 +14262,10 @@ var ts; } symbol.declarations.push(node); if (symbolFlags & 1952 /* HasExports */ && !symbol.exports) { - symbol.exports = ts.createMap(); + symbol.exports = {}; } if (symbolFlags & 6240 /* HasMembers */ && !symbol.members) { - symbol.members = ts.createMap(); + symbol.members = {}; } if (symbolFlags & 107455 /* Value */) { var valueDeclaration = symbol.valueDeclaration; @@ -15351,10 +14367,7 @@ var ts; // The exported symbol for an export default function/class node is always named "default" var name = isDefaultExport && parent ? "default" : getDeclarationName(node); var symbol; - if (name === undefined) { - symbol = createSymbol(0 /* None */, "__missing"); - } - else { + if (name !== undefined) { // Check and see if the symbol table already has a symbol with this name. If not, // create a new symbol with this name and add it to the table. Note that we don't // give the new symbol any flags *yet*. This ensures that it will not conflict @@ -15366,11 +14379,6 @@ var ts; // declaration we have for this symbol, and then create a new symbol for this // declaration. // - // Note that when properties declared in Javascript constructors - // (marked by isReplaceableByMethod) conflict with another symbol, the property loses. - // Always. This allows the common Javascript pattern of overwriting a prototype method - // with an bound instance method of the same type: `this.method = this.method.bind(this)` - // // If we created a new symbol, either because we didn't have a symbol with this name // in the symbol table, or we conflicted with an existing symbol, then just add this // node as the sole declaration of the new symbol. @@ -15378,38 +14386,36 @@ var ts; // Otherwise, we'll be merging into a compatible existing symbol (for example when // you have multiple 'vars' with the same name in the same container). In this case // just add this node into the declarations list of the symbol. - symbol = symbolTable[name] || (symbolTable[name] = createSymbol(0 /* None */, name)); + symbol = ts.hasProperty(symbolTable, name) + ? symbolTable[name] + : (symbolTable[name] = createSymbol(0 /* None */, name)); if (name && (includes & 788448 /* Classifiable */)) { classifiableNames[name] = name; } if (symbol.flags & excludes) { - if (symbol.isReplaceableByMethod) { - // Javascript constructor-declared symbols can be discarded in favor of - // prototype symbols like methods. - symbol = symbolTable[name] = createSymbol(0 /* None */, name); + if (node.name) { + node.name.parent = node; } - else { - if (node.name) { - node.name.parent = node; + // Report errors every position with duplicate declaration + // Report errors on previous encountered declarations + var message_1 = symbol.flags & 2 /* BlockScopedVariable */ + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + : ts.Diagnostics.Duplicate_identifier_0; + ts.forEach(symbol.declarations, function (declaration) { + if (declaration.flags & 512 /* Default */) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; } - // Report errors every position with duplicate declaration - // Report errors on previous encountered declarations - var message_1 = symbol.flags & 2 /* BlockScopedVariable */ - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - ts.forEach(symbol.declarations, function (declaration) { - if (declaration.flags & 512 /* Default */) { - message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; - } - }); - ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); - }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); - symbol = createSymbol(0 /* None */, name); - } + }); + ts.forEach(symbol.declarations, function (declaration) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); + }); + file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); + symbol = createSymbol(0 /* None */, name); } } + else { + symbol = createSymbol(0 /* None */, "__missing"); + } addDeclarationToSymbol(symbol, node, includes); symbol.parent = parent; return symbol; @@ -15442,8 +14448,8 @@ var ts; // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. if (!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 8192 /* ExportContext */)) { var exportKind = (symbolFlags & 107455 /* Value */ ? 1048576 /* ExportValue */ : 0) | - (symbolFlags & 793064 /* Type */ ? 2097152 /* ExportType */ : 0) | - (symbolFlags & 1920 /* Namespace */ ? 4194304 /* ExportNamespace */ : 0); + (symbolFlags & 793056 /* Type */ ? 2097152 /* ExportType */ : 0) | + (symbolFlags & 1536 /* Namespace */ ? 4194304 /* ExportNamespace */ : 0); var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; @@ -15483,7 +14489,7 @@ var ts; if (containerFlags & 1 /* IsContainer */) { container = blockScopeContainer = node; if (containerFlags & 32 /* HasLocals */) { - container.locals = ts.createMap(); + container.locals = {}; } addToContainerChain(container); } @@ -15665,9 +14671,15 @@ var ts; } return false; } + function isNarrowingNullCheckOperands(expr1, expr2) { + return (expr1.kind === 93 /* NullKeyword */ || expr1.kind === 69 /* Identifier */ && expr1.text === "undefined") && isNarrowableOperand(expr2); + } function isNarrowingTypeofOperands(expr1, expr2) { return expr1.kind === 182 /* TypeOfExpression */ && isNarrowableOperand(expr1.expression) && expr2.kind === 9 /* StringLiteral */; } + function isNarrowingDiscriminant(expr) { + return expr.kind === 172 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); + } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { case 56 /* EqualsToken */: @@ -15676,8 +14688,9 @@ var ts; case 31 /* ExclamationEqualsToken */: case 32 /* EqualsEqualsEqualsToken */: case 33 /* ExclamationEqualsEqualsToken */: - return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || - isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); + return isNarrowingNullCheckOperands(expr.right, expr.left) || isNarrowingNullCheckOperands(expr.left, expr.right) || + isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right) || + isNarrowingDiscriminant(expr.left) || isNarrowingDiscriminant(expr.right); case 91 /* InstanceOfKeyword */: return isNarrowableOperand(expr.left); case 24 /* CommaToken */: @@ -15699,6 +14712,10 @@ var ts; } return isNarrowableReference(expr); } + function isNarrowingSwitchStatement(switchStatement) { + var expr = switchStatement.expression; + return expr.kind === 172 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); + } function createBranchLabel() { return { flags: 4 /* BranchLabel */, @@ -15743,7 +14760,7 @@ var ts; }; } function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { - if (!isNarrowingExpression(switchStatement.expression)) { + if (!isNarrowingSwitchStatement(switchStatement)) { return antecedent; } setFlowNodeReferenced(antecedent); @@ -16381,8 +15398,8 @@ var ts; addDeclarationToSymbol(symbol, node, 131072 /* Signature */); var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type"); addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */); - typeLiteralSymbol.members = ts.createMap(); - typeLiteralSymbol.members[symbol.name] = symbol; + typeLiteralSymbol.members = (_a = {}, _a[symbol.name] = symbol, _a); + var _a; } function bindObjectLiteralExpression(node) { var ElementKind; @@ -16391,7 +15408,7 @@ var ts; ElementKind[ElementKind["Accessor"] = 2] = "Accessor"; })(ElementKind || (ElementKind = {})); if (inStrictMode) { - var seen = ts.createMap(); + var seen = {}; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; if (prop.name.kind !== 69 /* Identifier */) { @@ -16439,7 +15456,7 @@ var ts; // fall through. default: if (!blockScopeContainer.locals) { - blockScopeContainer.locals = ts.createMap(); + blockScopeContainer.locals = {}; addToContainerChain(blockScopeContainer); } declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); @@ -16700,7 +15717,7 @@ var ts; case 154 /* TypePredicate */: return checkTypePredicate(node); case 141 /* TypeParameter */: - return declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 530920 /* TypeParameterExcludes */); + return declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 530912 /* TypeParameterExcludes */); case 142 /* Parameter */: return bindParameter(node); case 218 /* VariableDeclaration */: @@ -16716,7 +15733,7 @@ var ts; case 254 /* ShorthandPropertyAssignment */: return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); case 255 /* EnumMember */: - return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */); + return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 107455 /* EnumMemberExcludes */); case 247 /* JsxSpreadAttribute */: emitFlags |= 1073741824 /* HasJsxSpreadAttribute */; return; @@ -16764,10 +15781,10 @@ var ts; inStrictMode = true; return bindClassLikeDeclaration(node); case 222 /* InterfaceDeclaration */: - return bindBlockScopedDeclaration(node, 64 /* Interface */, 792968 /* InterfaceExcludes */); + return bindBlockScopedDeclaration(node, 64 /* Interface */, 792960 /* InterfaceExcludes */); case 279 /* JSDocTypedefTag */: case 223 /* TypeAliasDeclaration */: - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793056 /* TypeAliasExcludes */); case 224 /* EnumDeclaration */: return bindEnumDeclaration(node); case 225 /* ModuleDeclaration */: @@ -16818,15 +15835,18 @@ var ts; bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\""); } function bindExportAssignment(node) { + var boundExpression = node.kind === 235 /* ExportAssignment */ ? node.expression : node.right; if (!container.symbol || !container.symbol.exports) { // Export assignment in some sort of block construct bindAnonymousDeclaration(node, 8388608 /* Alias */, getDeclarationName(node)); } + else if (boundExpression.kind === 69 /* Identifier */ && node.kind === 235 /* ExportAssignment */) { + // An export default clause with an identifier exports all meanings of that identifier + declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* Alias */, 0 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); + } else { - var flags = node.kind === 235 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) - ? 8388608 /* Alias */ - : 4 /* Property */; - declareSymbol(container.symbol.exports, container.symbol, node, flags, 0 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); + // An export default clause with an expression exports a value + declareSymbol(container.symbol.exports, container.symbol, node, 4 /* Property */, 0 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); } } function bindNamespaceExportDeclaration(node) { @@ -16848,7 +15868,7 @@ var ts; return; } } - file.symbol.globalExports = file.symbol.globalExports || ts.createMap(); + file.symbol.globalExports = file.symbol.globalExports || {}; declareSymbol(file.symbol.globalExports, file.symbol, node, 8388608 /* Alias */, 8388608 /* AliasExcludes */); } function bindExportDeclaration(node) { @@ -16884,25 +15904,20 @@ var ts; declareSymbol(file.symbol.exports, file.symbol, node, 4 /* Property */ | 7340032 /* Export */ | 512 /* ValueModule */, 0 /* None */); } function bindThisPropertyAssignment(node) { - ts.Debug.assert(ts.isInJavaScriptFile(node)); - // Declare a 'member' if the container is an ES5 class or ES6 constructor - if (container.kind === 220 /* FunctionDeclaration */ || container.kind === 179 /* FunctionExpression */) { - container.symbol.members = container.symbol.members || ts.createMap(); - // It's acceptable for multiple 'this' assignments of the same identifier to occur - declareSymbol(container.symbol.members, container.symbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */); + // Declare a 'member' in case it turns out the container was an ES5 class or ES6 constructor + var assignee; + if (container.kind === 220 /* FunctionDeclaration */ || container.kind === 220 /* FunctionDeclaration */) { + assignee = container; } else if (container.kind === 148 /* Constructor */) { - // this.foo assignment in a JavaScript class - // Bind this property to the containing class - var saveContainer = container; - container = container.parent; - var symbol = bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* None */); - if (symbol) { - // constructor-declared symbols can be overwritten by subsequent method declarations - symbol.isReplaceableByMethod = true; - } - container = saveContainer; + assignee = container.parent; } + else { + return; + } + assignee.symbol.members = assignee.symbol.members || {}; + // It's acceptable for multiple 'this' assignments of the same identifier to occur + declareSymbol(assignee.symbol.members, assignee.symbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */); } function bindPrototypePropertyAssignment(node) { // We saw a node of the form 'x.prototype.y = z'. Declare a 'member' y on x if x was a function. @@ -16921,7 +15936,7 @@ var ts; } // Set up the members collection if it doesn't exist already if (!funcSymbol.members) { - funcSymbol.members = ts.createMap(); + funcSymbol.members = {}; } // Declare the method/property declareSymbol(funcSymbol.members, funcSymbol, leftSideOfAssignment, 4 /* Property */, 0 /* PropertyExcludes */); @@ -16964,7 +15979,7 @@ var ts; // module might have an exported variable called 'prototype'. We can't allow that as // that would clash with the built-in 'prototype' for the class. var prototypeSymbol = createSymbol(4 /* Property */ | 134217728 /* Prototype */, "prototype"); - if (symbol.exports[prototypeSymbol.name]) { + if (ts.hasProperty(symbol.exports, prototypeSymbol.name)) { if (node.name) { node.name.parent = node; } @@ -17119,7 +16134,6 @@ var ts; /* @internal */ var ts; (function (ts) { - var ambientModuleSymbolRegex = /^".+"$/; var nextSymbolId = 1; var nextNodeId = 1; var nextMergeId = 1; @@ -17132,6 +16146,7 @@ var ts; return node.id; } ts.getNodeId = getNodeId; + ts.checkTime = 0; function getSymbolId(symbol) { if (!symbol.id) { symbol.id = nextSymbolId; @@ -17157,7 +16172,7 @@ var ts; var typeCount = 0; var symbolCount = 0; var emptyArray = []; - var emptySymbols = ts.createMap(); + var emptySymbols = {}; var compilerOptions = host.getCompilerOptions(); var languageVersion = compilerOptions.target || 0 /* ES3 */; var modulekind = ts.getEmitModuleKind(compilerOptions); @@ -17209,45 +16224,36 @@ var ts; getAliasedSymbol: resolveAlias, getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, - getAmbientModules: getAmbientModules, getJsxElementAttributesType: getJsxElementAttributesType, getJsxIntrinsicTagNames: getJsxIntrinsicTagNames, isOptionalParameter: isOptionalParameter }; - var tupleTypes = []; - var unionTypes = ts.createMap(); - var intersectionTypes = ts.createMap(); - var stringLiteralTypes = ts.createMap(); - var numericLiteralTypes = ts.createMap(); var unknownSymbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "unknown"); var resolvingSymbol = createSymbol(67108864 /* Transient */, "__resolving__"); var anyType = createIntrinsicType(1 /* Any */, "any"); - var unknownType = createIntrinsicType(1 /* Any */, "unknown"); - var undefinedType = createIntrinsicType(2048 /* Undefined */, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 /* Undefined */ | 33554432 /* ContainsWideningType */, "undefined"); - var nullType = createIntrinsicType(4096 /* Null */, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(4096 /* Null */ | 33554432 /* ContainsWideningType */, "null"); var stringType = createIntrinsicType(2 /* String */, "string"); var numberType = createIntrinsicType(4 /* Number */, "number"); - var trueType = createIntrinsicType(128 /* BooleanLiteral */, "true"); - var falseType = createIntrinsicType(128 /* BooleanLiteral */, "false"); - var booleanType = createBooleanType([trueType, falseType]); - var esSymbolType = createIntrinsicType(512 /* ESSymbol */, "symbol"); - var voidType = createIntrinsicType(1024 /* Void */, "void"); - var neverType = createIntrinsicType(8192 /* Never */, "never"); + var booleanType = createIntrinsicType(8 /* Boolean */, "boolean"); + var esSymbolType = createIntrinsicType(16777216 /* ESSymbol */, "symbol"); + var voidType = createIntrinsicType(16 /* Void */, "void"); + var undefinedType = createIntrinsicType(32 /* Undefined */, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32 /* Undefined */ | 2097152 /* ContainsWideningType */, "undefined"); + var nullType = createIntrinsicType(64 /* Null */, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(64 /* Null */ | 2097152 /* ContainsWideningType */, "null"); + var unknownType = createIntrinsicType(1 /* Any */, "unknown"); + var neverType = createIntrinsicType(134217728 /* Never */, "never"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - emptyGenericType.instantiations = ts.createMap(); + emptyGenericType.instantiations = {}; var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. - anyFunctionType.flags |= 134217728 /* ContainsAnyFunctionType */; + anyFunctionType.flags |= 8388608 /* ContainsAnyFunctionType */; var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var anySignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var unknownSignature = createSignature(undefined, undefined, undefined, emptyArray, unknownType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var resolvingSignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var anySignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false); + var unknownSignature = createSignature(undefined, undefined, undefined, emptyArray, unknownType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false); var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); - var globals = ts.createMap(); + var globals = {}; /** * List of every ambient module with a "*" wildcard. * Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches. @@ -17291,8 +16297,10 @@ var ts; var flowLoopStart = 0; var flowLoopCount = 0; var visitedFlowCount = 0; - var emptyStringType = getLiteralTypeForText(32 /* StringLiteral */, ""); - var zeroType = getLiteralTypeForText(64 /* NumberLiteral */, "0"); + var tupleTypes = {}; + var unionTypes = {}; + var intersectionTypes = {}; + var stringLiteralTypes = {}; var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; @@ -17333,45 +16341,26 @@ var ts; TypeFacts[TypeFacts["NEUndefinedOrNull"] = 524288] = "NEUndefinedOrNull"; TypeFacts[TypeFacts["Truthy"] = 1048576] = "Truthy"; TypeFacts[TypeFacts["Falsy"] = 2097152] = "Falsy"; - TypeFacts[TypeFacts["Discriminatable"] = 4194304] = "Discriminatable"; - TypeFacts[TypeFacts["All"] = 8388607] = "All"; + TypeFacts[TypeFacts["All"] = 4194303] = "All"; // The following members encode facts about particular kinds of types for use in the getTypeFacts function. // The presence of a particular fact means that the given test is true for some (and possibly all) values // of that kind of type. - TypeFacts[TypeFacts["BaseStringStrictFacts"] = 933633] = "BaseStringStrictFacts"; - TypeFacts[TypeFacts["BaseStringFacts"] = 3145473] = "BaseStringFacts"; TypeFacts[TypeFacts["StringStrictFacts"] = 4079361] = "StringStrictFacts"; TypeFacts[TypeFacts["StringFacts"] = 4194049] = "StringFacts"; - TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 3030785] = "EmptyStringStrictFacts"; - TypeFacts[TypeFacts["EmptyStringFacts"] = 3145473] = "EmptyStringFacts"; - TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 1982209] = "NonEmptyStringStrictFacts"; - TypeFacts[TypeFacts["NonEmptyStringFacts"] = 4194049] = "NonEmptyStringFacts"; - TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 933506] = "BaseNumberStrictFacts"; - TypeFacts[TypeFacts["BaseNumberFacts"] = 3145346] = "BaseNumberFacts"; TypeFacts[TypeFacts["NumberStrictFacts"] = 4079234] = "NumberStrictFacts"; TypeFacts[TypeFacts["NumberFacts"] = 4193922] = "NumberFacts"; - TypeFacts[TypeFacts["ZeroStrictFacts"] = 3030658] = "ZeroStrictFacts"; - TypeFacts[TypeFacts["ZeroFacts"] = 3145346] = "ZeroFacts"; - TypeFacts[TypeFacts["NonZeroStrictFacts"] = 1982082] = "NonZeroStrictFacts"; - TypeFacts[TypeFacts["NonZeroFacts"] = 4193922] = "NonZeroFacts"; - TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 933252] = "BaseBooleanStrictFacts"; - TypeFacts[TypeFacts["BaseBooleanFacts"] = 3145092] = "BaseBooleanFacts"; TypeFacts[TypeFacts["BooleanStrictFacts"] = 4078980] = "BooleanStrictFacts"; TypeFacts[TypeFacts["BooleanFacts"] = 4193668] = "BooleanFacts"; - TypeFacts[TypeFacts["FalseStrictFacts"] = 3030404] = "FalseStrictFacts"; - TypeFacts[TypeFacts["FalseFacts"] = 3145092] = "FalseFacts"; - TypeFacts[TypeFacts["TrueStrictFacts"] = 1981828] = "TrueStrictFacts"; - TypeFacts[TypeFacts["TrueFacts"] = 4193668] = "TrueFacts"; TypeFacts[TypeFacts["SymbolStrictFacts"] = 1981320] = "SymbolStrictFacts"; TypeFacts[TypeFacts["SymbolFacts"] = 4193160] = "SymbolFacts"; - TypeFacts[TypeFacts["ObjectStrictFacts"] = 6166480] = "ObjectStrictFacts"; - TypeFacts[TypeFacts["ObjectFacts"] = 8378320] = "ObjectFacts"; - TypeFacts[TypeFacts["FunctionStrictFacts"] = 6164448] = "FunctionStrictFacts"; - TypeFacts[TypeFacts["FunctionFacts"] = 8376288] = "FunctionFacts"; + TypeFacts[TypeFacts["ObjectStrictFacts"] = 1972176] = "ObjectStrictFacts"; + TypeFacts[TypeFacts["ObjectFacts"] = 4184016] = "ObjectFacts"; + TypeFacts[TypeFacts["FunctionStrictFacts"] = 1970144] = "FunctionStrictFacts"; + TypeFacts[TypeFacts["FunctionFacts"] = 4181984] = "FunctionFacts"; TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts"; TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts"; })(TypeFacts || (TypeFacts = {})); - var typeofEQFacts = ts.createMap({ + var typeofEQFacts = { "string": 1 /* TypeofEQString */, "number": 2 /* TypeofEQNumber */, "boolean": 4 /* TypeofEQBoolean */, @@ -17379,8 +16368,8 @@ var ts; "undefined": 16384 /* EQUndefined */, "object": 16 /* TypeofEQObject */, "function": 32 /* TypeofEQFunction */ - }); - var typeofNEFacts = ts.createMap({ + }; + var typeofNEFacts = { "string": 128 /* TypeofNEString */, "number": 256 /* TypeofNENumber */, "boolean": 512 /* TypeofNEBoolean */, @@ -17388,17 +16377,17 @@ var ts; "undefined": 131072 /* NEUndefined */, "object": 2048 /* TypeofNEObject */, "function": 4096 /* TypeofNEFunction */ - }); - var typeofTypesByName = ts.createMap({ + }; + var typeofTypesByName = { "string": stringType, "number": numberType, "boolean": booleanType, "symbol": esSymbolType, "undefined": undefinedType - }); + }; var jsxElementType; /** Things we lazy load from the JSX namespace */ - var jsxTypes = ts.createMap(); + var jsxTypes = {}; var JsxNames = { JSX: "JSX", IntrinsicElements: "IntrinsicElements", @@ -17408,11 +16397,10 @@ var ts; IntrinsicAttributes: "IntrinsicAttributes", IntrinsicClassAttributes: "IntrinsicClassAttributes" }; - var subtypeRelation = ts.createMap(); - var assignableRelation = ts.createMap(); - var comparableRelation = ts.createMap(); - var identityRelation = ts.createMap(); - var enumRelation = ts.createMap(); + var subtypeRelation = {}; + var assignableRelation = {}; + var comparableRelation = {}; + var identityRelation = {}; // This is for caching the result of getSymbolDisplayBuilder. Do not access directly. var _displayBuilder; var TypeSystemPropertyName; @@ -17422,8 +16410,10 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); - var builtinGlobals = ts.createMap(); - builtinGlobals[undefinedSymbol.name] = undefinedSymbol; + var builtinGlobals = (_a = {}, + _a[undefinedSymbol.name] = undefinedSymbol, + _a + ); initializeTypeChecker(); return checker; function getEmitResolver(sourceFile, cancellationToken) { @@ -17451,13 +16441,13 @@ var ts; if (flags & 4 /* Property */) result |= 0 /* PropertyExcludes */; if (flags & 8 /* EnumMember */) - result |= 900095 /* EnumMemberExcludes */; + result |= 107455 /* EnumMemberExcludes */; if (flags & 16 /* Function */) result |= 106927 /* FunctionExcludes */; if (flags & 32 /* Class */) result |= 899519 /* ClassExcludes */; if (flags & 64 /* Interface */) - result |= 792968 /* InterfaceExcludes */; + result |= 792960 /* InterfaceExcludes */; if (flags & 256 /* RegularEnum */) result |= 899327 /* RegularEnumExcludes */; if (flags & 128 /* ConstEnum */) @@ -17471,9 +16461,9 @@ var ts; if (flags & 65536 /* SetAccessor */) result |= 74687 /* SetAccessorExcludes */; if (flags & 262144 /* TypeParameter */) - result |= 530920 /* TypeParameterExcludes */; + result |= 530912 /* TypeParameterExcludes */; if (flags & 524288 /* TypeAlias */) - result |= 793064 /* TypeAliasExcludes */; + result |= 793056 /* TypeAliasExcludes */; if (flags & 8388608 /* Alias */) result |= 8388608 /* AliasExcludes */; return result; @@ -17494,9 +16484,9 @@ var ts; if (symbol.constEnumOnlyModule) result.constEnumOnlyModule = true; if (symbol.members) - result.members = ts.cloneMap(symbol.members); + result.members = cloneSymbolTable(symbol.members); if (symbol.exports) - result.exports = ts.cloneMap(symbol.exports); + result.exports = cloneSymbolTable(symbol.exports); recordMergedSymbol(result, symbol); return result; } @@ -17518,12 +16508,12 @@ var ts; }); if (source.members) { if (!target.members) - target.members = ts.createMap(); + target.members = {}; mergeSymbolTable(target.members, source.members); } if (source.exports) { if (!target.exports) - target.exports = ts.createMap(); + target.exports = {}; mergeSymbolTable(target.exports, source.exports); } recordMergedSymbol(target, source); @@ -17539,17 +16529,28 @@ var ts; }); } } + function cloneSymbolTable(symbolTable) { + var result = {}; + for (var id in symbolTable) { + if (ts.hasProperty(symbolTable, id)) { + result[id] = symbolTable[id]; + } + } + return result; + } function mergeSymbolTable(target, source) { for (var id in source) { - var targetSymbol = target[id]; - if (!targetSymbol) { - target[id] = source[id]; - } - else { - if (!(targetSymbol.flags & 33554432 /* Merged */)) { - target[id] = targetSymbol = cloneSymbol(targetSymbol); + if (ts.hasProperty(source, id)) { + if (!ts.hasProperty(target, id)) { + target[id] = source[id]; + } + else { + var symbol = target[id]; + if (!(symbol.flags & 33554432 /* Merged */)) { + target[id] = symbol = cloneSymbol(symbol); + } + mergeSymbol(symbol, source[id]); } - mergeSymbol(targetSymbol, source[id]); } } } @@ -17577,7 +16578,7 @@ var ts; } // obtain item referenced by 'export=' mainModule = resolveExternalModuleSymbol(mainModule); - if (mainModule.flags & 1920 /* Namespace */) { + if (mainModule.flags & 1536 /* Namespace */) { // if module symbol has already been merged - it is safe to use it. // otherwise clone it mainModule = mainModule.flags & 33554432 /* Merged */ ? mainModule : cloneSymbol(mainModule); @@ -17590,12 +16591,14 @@ var ts; } function addToSymbolTable(target, source, message) { for (var id in source) { - if (target[id]) { - // Error on redeclarations - ts.forEach(target[id].declarations, addDeclarationDiagnostic(id, message)); - } - else { - target[id] = source[id]; + if (ts.hasProperty(source, id)) { + if (ts.hasProperty(target, id)) { + // Error on redeclarations + ts.forEach(target[id].declarations, addDeclarationDiagnostic(id, message)); + } + else { + target[id] = source[id]; + } } } function addDeclarationDiagnostic(id, message) { @@ -17610,26 +16613,24 @@ var ts; } function getNodeLinks(node) { var nodeId = getNodeId(node); - return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); + return nodeLinks[nodeId] || (nodeLinks[nodeId] = {}); } function isGlobalSourceFile(node) { return node.kind === 256 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { - if (meaning) { + if (meaning && ts.hasProperty(symbols, name)) { var symbol = symbols[name]; - if (symbol) { - ts.Debug.assert((symbol.flags & 16777216 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); - if (symbol.flags & meaning) { + ts.Debug.assert((symbol.flags & 16777216 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); + if (symbol.flags & meaning) { + return symbol; + } + if (symbol.flags & 8388608 /* Alias */) { + var target = resolveAlias(symbol); + // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors + if (target === unknownSymbol || target.flags & meaning) { return symbol; } - if (symbol.flags & 8388608 /* Alias */) { - var target = resolveAlias(symbol); - // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors - if (target === unknownSymbol || target.flags & meaning) { - return symbol; - } - } } } // return undefined if we can't find a symbol. @@ -17738,7 +16739,7 @@ var ts; // - parameters are only in the scope of function body // This restriction does not apply to JSDoc comment types because they are parented // at a higher level than type parameters would normally be - if (meaning & result.flags & 793064 /* Type */ && lastLocation.kind !== 273 /* JSDocComment */) { + if (meaning & result.flags & 793056 /* Type */ && lastLocation.kind !== 273 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ ? lastLocation === location.type || lastLocation.kind === 142 /* Parameter */ || @@ -17792,7 +16793,7 @@ var ts; // 2. We check === SymbolFlags.Alias in order to check that the symbol is *purely* // an alias. If we used &, we'd be throwing out symbols that have non alias aspects, // which is not the desired behavior. - if (moduleExports[name] && + if (ts.hasProperty(moduleExports, name) && moduleExports[name].flags === 8388608 /* Alias */ && ts.getDeclarationOfKind(moduleExports[name], 238 /* ExportSpecifier */)) { break; @@ -17828,7 +16829,7 @@ var ts; case 221 /* ClassDeclaration */: case 192 /* ClassExpression */: case 222 /* InterfaceDeclaration */: - if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064 /* Type */)) { + if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056 /* Type */)) { if (lastLocation && lastLocation.flags & 32 /* Static */) { // TypeScript 1.0 spec (April 2014): 3.4.1 // The scope of a type parameter extends over the entire declaration with which the type @@ -17858,7 +16859,7 @@ var ts; grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 222 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error - if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793064 /* Type */)) { + if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793056 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -17923,9 +16924,8 @@ var ts; } if (!result) { if (nameNotFoundMessage) { - if (!errorLocation || - !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && - !checkAndReportErrorForExtendingInterface(errorLocation)) { + if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForExtendingInterface(errorLocation)) { error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); } } @@ -17957,8 +16957,8 @@ var ts; checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } - // If we're in an external module, we can't reference value symbols created from UMD export declarations - if (result && isInExternalModule && (meaning & 107455 /* Value */) === 107455 /* Value */) { + // If we're in an external module, we can't reference symbols created from UMD export declarations + if (result && isInExternalModule) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 228 /* NamespaceExportDeclaration */) { error(errorLocation, ts.Diagnostics.Identifier_0_must_be_imported_from_a_module, name); @@ -17968,7 +16968,7 @@ var ts; return result; } function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { - if ((errorLocation.kind === 69 /* Identifier */ && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { + if (!errorLocation || (errorLocation.kind === 69 /* Identifier */ && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { return false; } var container = ts.getThisContainer(errorLocation, /* includeArrowFunctions */ true); @@ -18000,35 +17000,34 @@ var ts; return false; } function checkAndReportErrorForExtendingInterface(errorLocation) { - var expression = getEntityNameForExtendingInterface(errorLocation); - var isError = !!(expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)); - if (isError) { + var parentClassExpression = errorLocation; + while (parentClassExpression) { + var kind = parentClassExpression.kind; + if (kind === 69 /* Identifier */ || kind === 172 /* PropertyAccessExpression */) { + parentClassExpression = parentClassExpression.parent; + continue; + } + if (kind === 194 /* ExpressionWithTypeArguments */) { + break; + } + return false; + } + if (!parentClassExpression) { + return false; + } + var expression = parentClassExpression.expression; + if (resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)) { error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); + return true; } - return isError; - } - /** - * Climbs up parents to an ExpressionWithTypeArguments, and returns its expression, - * but returns undefined if that expression is not an EntityNameExpression. - */ - function getEntityNameForExtendingInterface(node) { - switch (node.kind) { - case 69 /* Identifier */: - case 172 /* PropertyAccessExpression */: - return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; - case 194 /* ExpressionWithTypeArguments */: - ts.Debug.assert(ts.isEntityNameExpression(node.expression)); - return node.expression; - default: - return undefined; - } + return false; } function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert((result.flags & 2 /* BlockScopedVariable */) !== 0); // Block-scoped variables cannot be used before their definition var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) ? d : undefined; }); ts.Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined"); - if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 218 /* VariableDeclaration */), errorLocation)) { + if (!isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 218 /* VariableDeclaration */), errorLocation)) { error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); } } @@ -18070,7 +17069,7 @@ var ts; function getTargetOfImportClause(node) { var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { - var exportDefaultSymbol = ts.isShorthandAmbientModuleSymbol(moduleSymbol) ? + var exportDefaultSymbol = ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration) ? moduleSymbol : moduleSymbol.exports["export="] ? getPropertyOfType(getTypeOfSymbol(moduleSymbol.exports["export="]), "default") : @@ -18107,7 +17106,7 @@ var ts; // An 'import { Point } from "graphics"' needs to create a symbol that combines the value side 'Point' // property with the type/namespace side interface 'Point'. function combineValueAndTypeSymbols(valueSymbol, typeSymbol) { - if (valueSymbol.flags & (793064 /* Type */ | 1920 /* Namespace */)) { + if (valueSymbol.flags & (793056 /* Type */ | 1536 /* Namespace */)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.name); @@ -18123,9 +17122,9 @@ var ts; } function getExportOfModule(symbol, name) { if (symbol.flags & 1536 /* Module */) { - var exportedSymbol = getExportsOfSymbol(symbol)[name]; - if (exportedSymbol) { - return resolveSymbol(exportedSymbol); + var exports = getExportsOfSymbol(symbol); + if (ts.hasProperty(exports, name)) { + return resolveSymbol(exports[name]); } } } @@ -18143,7 +17142,7 @@ var ts; if (targetSymbol) { var name_10 = specifier.propertyName || specifier.name; if (name_10.text) { - if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + if (ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration)) { return moduleSymbol; } var symbolFromVariable = void 0; @@ -18157,10 +17156,6 @@ var ts; // if symbolFromVariable is export - get its final target symbolFromVariable = resolveSymbol(symbolFromVariable); var symbolFromModule = getExportOfModule(targetSymbol, name_10.text); - // If the export member we're looking for is default, and there is no real default but allowSyntheticDefaultImports is on, return the entire module as the default - if (!symbolFromModule && allowSyntheticDefaultImports && name_10.text === "default") { - symbolFromModule = resolveExternalModuleSymbol(moduleSymbol) || resolveSymbol(moduleSymbol); - } var symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; @@ -18180,10 +17175,10 @@ var ts; function getTargetOfExportSpecifier(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */); + resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */); } function getTargetOfExportAssignment(node) { - return resolveEntityName(node.expression, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */); + return resolveEntityName(node.expression, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */); } function getTargetOfAliasDeclaration(node) { switch (node.kind) { @@ -18204,7 +17199,7 @@ var ts; } } function resolveSymbol(symbol) { - return symbol && symbol.flags & 8388608 /* Alias */ && !(symbol.flags & (107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */)) ? resolveAlias(symbol) : symbol; + return symbol && symbol.flags & 8388608 /* Alias */ && !(symbol.flags & (107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */)) ? resolveAlias(symbol) : symbol; } function resolveAlias(symbol) { ts.Debug.assert((symbol.flags & 8388608 /* Alias */) !== 0, "Should only get Alias here."); @@ -18212,7 +17207,6 @@ var ts; if (!links.target) { links.target = resolvingSymbol; var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); var target = getTargetOfAliasDeclaration(node); if (links.target === resolvingSymbol) { links.target = target || unknownSymbol; @@ -18245,7 +17239,6 @@ var ts; if (!links.referenced) { links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); if (node.kind === 235 /* ExportAssignment */) { // export default checkExpressionCached(node.expression); @@ -18273,13 +17266,13 @@ var ts; } // Check for case 1 and 3 in the above example if (entityName.kind === 69 /* Identifier */ || entityName.parent.kind === 139 /* QualifiedName */) { - return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + return resolveEntityName(entityName, 1536 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } else { // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier ts.Debug.assert(entityName.parent.kind === 229 /* ImportEqualsDeclaration */); - return resolveEntityName(entityName, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + return resolveEntityName(entityName, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } function getFullyQualifiedName(symbol) { @@ -18292,7 +17285,7 @@ var ts; } var symbol; if (name.kind === 69 /* Identifier */) { - var message = meaning === 1920 /* Namespace */ ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; + var message = meaning === 1536 /* Namespace */ ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; symbol = resolveName(name, name.text, meaning, ignoreErrors ? undefined : message, name); if (!symbol) { return undefined; @@ -18301,7 +17294,7 @@ var ts; else if (name.kind === 139 /* QualifiedName */ || name.kind === 172 /* PropertyAccessExpression */) { var left = name.kind === 139 /* QualifiedName */ ? name.left : name.expression; var right = name.kind === 139 /* QualifiedName */ ? name.right : name.name; - var namespace = resolveEntityName(left, 1920 /* Namespace */, ignoreErrors); + var namespace = resolveEntityName(left, 1536 /* Namespace */, ignoreErrors); if (!namespace || ts.nodeIsMissing(right)) { return undefined; } @@ -18365,14 +17358,7 @@ var ts; } if (moduleNotFoundError) { // report errors only if it was requested - var tsExtension = ts.tryExtractTypeScriptExtension(moduleName); - if (tsExtension) { - var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; - error(moduleReferenceLiteral, diag, tsExtension, ts.removeExtension(moduleName, tsExtension)); - } - else { - error(moduleReferenceLiteral, moduleNotFoundError, moduleName); - } + error(moduleReferenceLiteral, moduleNotFoundError, moduleName); } return undefined; } @@ -18411,7 +17397,7 @@ var ts; */ function extendExportSymbols(target, source, lookupTable, exportNode) { for (var id in source) { - if (id !== "default" && !target[id]) { + if (id !== "default" && !ts.hasProperty(target, id)) { target[id] = source[id]; if (lookupTable && exportNode) { lookupTable[id] = { @@ -18419,7 +17405,7 @@ var ts; }; } } - else if (lookupTable && exportNode && id !== "default" && target[id] && resolveSymbol(target[id]) !== resolveSymbol(source[id])) { + else if (lookupTable && exportNode && id !== "default" && ts.hasProperty(target, id) && resolveSymbol(target[id]) !== resolveSymbol(source[id])) { if (!lookupTable[id].exportsWithDuplicate) { lookupTable[id].exportsWithDuplicate = [exportNode]; } @@ -18439,12 +17425,12 @@ var ts; return; } visitedSymbols.push(symbol); - var symbols = ts.cloneMap(symbol.exports); + var symbols = cloneSymbolTable(symbol.exports); // All export * declarations are collected in an __export symbol by the binder var exportStars = symbol.exports["__export"]; if (exportStars) { - var nestedSymbols = ts.createMap(); - var lookupTable = ts.createMap(); + var nestedSymbols = {}; + var lookupTable = {}; for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { var node = _a[_i]; var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); @@ -18454,7 +17440,7 @@ var ts; for (var id in lookupTable) { var exportsWithDuplicate = lookupTable[id].exportsWithDuplicate; // It's not an error if the file with multiple `export *`s with duplicate names exports a member with that name itself - if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols[id]) { + if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || ts.hasProperty(symbols, id)) { continue; } for (var _b = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _b < exportsWithDuplicate_1.length; _b++) { @@ -18509,8 +17495,8 @@ var ts; } function createType(flags) { var result = new Type(checker, flags); - typeCount++; result.id = typeCount; + typeCount++; return result; } function createIntrinsicType(kind, intrinsicName) { @@ -18518,12 +17504,6 @@ var ts; type.intrinsicName = intrinsicName; return type; } - function createBooleanType(trueFalseTypes) { - var type = getUnionType(trueFalseTypes); - type.flags |= 8 /* Boolean */; - type.intrinsicName = "boolean"; - return type; - } function createObjectType(kind, symbol) { var type = createType(kind); type.symbol = symbol; @@ -18542,12 +17522,14 @@ var ts; function getNamedMembers(members) { var result; for (var id in members) { - if (!isReservedMemberName(id)) { - if (!result) - result = []; - var symbol = members[id]; - if (symbolIsValue(symbol)) { - result.push(symbol); + if (ts.hasProperty(members, id)) { + if (!isReservedMemberName(id)) { + if (!result) + result = []; + var symbol = members[id]; + if (symbolIsValue(symbol)) { + result.push(symbol); + } } } } @@ -18565,7 +17547,7 @@ var ts; return type; } function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { - return setObjectTypeMembers(createObjectType(2097152 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + return setObjectTypeMembers(createObjectType(65536 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function forEachSymbolTableInScope(enclosingDeclaration, callback) { var result; @@ -18592,7 +17574,7 @@ var ts; } function getQualifiedLeftMeaning(rightMeaning) { // If we are looking in value space, the parent meaning is value, other wise it is namespace - return rightMeaning === 107455 /* Value */ ? 107455 /* Value */ : 1920 /* Namespace */; + return rightMeaning === 107455 /* Value */ ? 107455 /* Value */ : 1536 /* Namespace */; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { function getAccessibleSymbolChainFromSymbolTable(symbols) { @@ -18615,11 +17597,11 @@ var ts; } } // If symbol is directly available by its name in the symbol table - if (isAccessible(symbols[symbol.name])) { + if (isAccessible(ts.lookUp(symbols, symbol.name))) { return [symbol]; } // Check if symbol is any of the alias - return ts.forEachProperty(symbols, function (symbolFromSymbolTable) { + return ts.forEachValue(symbols, function (symbolFromSymbolTable) { if (symbolFromSymbolTable.flags & 8388608 /* Alias */ && symbolFromSymbolTable.name !== "export=" && !ts.getDeclarationOfKind(symbolFromSymbolTable, 238 /* ExportSpecifier */)) { @@ -18650,12 +17632,12 @@ var ts; var qualify = false; forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { // If symbol of this name is not available in the symbol table we are ok - var symbolFromSymbolTable = symbolTable[symbol.name]; - if (!symbolFromSymbolTable) { + if (!ts.hasProperty(symbolTable, symbol.name)) { // Continue to the next symbol table return false; } // If the symbol with this name is present it should refer to the symbol + var symbolFromSymbolTable = symbolTable[symbol.name]; if (symbolFromSymbolTable === symbol) { // No need to qualify return true; @@ -18702,7 +17684,7 @@ var ts; return { accessibility: 1 /* NotAccessible */, errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920 /* Namespace */) : undefined + errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1536 /* Namespace */) : undefined }; } return hasAccessibleDeclarations; @@ -18796,11 +17778,11 @@ var ts; entityName.parent.kind === 229 /* ImportEqualsDeclaration */) { // Left identifier from type reference or TypeAlias // Entity name of the import declaration - meaning = 1920 /* Namespace */; + meaning = 1536 /* Namespace */; } else { // Type Reference or TypeAlias entity = Identifier - meaning = 793064 /* Type */; + meaning = 793056 /* Type */; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.text, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); @@ -18852,31 +17834,6 @@ var ts; ts.releaseStringWriter(writer); return result; } - function formatUnionTypes(types) { - var result = []; - var flags = 0; - for (var i = 0; i < types.length; i++) { - var t = types[i]; - flags |= t.flags; - if (!(t.flags & 6144 /* Nullable */)) { - if (t.flags & (128 /* BooleanLiteral */ | 256 /* EnumLiteral */)) { - var baseType = t.flags & 128 /* BooleanLiteral */ ? booleanType : t.baseType; - var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { - result.push(baseType); - i += count - 1; - continue; - } - } - result.push(t); - } - } - if (flags & 4096 /* Null */) - result.push(nullType); - if (flags & 2048 /* Undefined */) - result.push(undefinedType); - return result || types; - } function visibilityToString(flags) { if (flags === 8 /* Private */) { return "private"; @@ -19026,53 +17983,38 @@ var ts; var inObjectTypeLiteral = false; return writeType(type, globalFlags); function writeType(type, flags) { - var nextFlags = flags & ~512 /* InTypeAlias */; // Write undefined/null type as any - if (type.flags & 16015 /* Intrinsic */) { + if (type.flags & 150995071 /* Intrinsic */) { // Special handling for unknown / resolving types, they should show up as any and not unknown or __resolving writer.writeKeyword(!(globalFlags & 16 /* WriteOwnNameForAnyLike */) && isTypeAny(type) ? "any" : type.intrinsicName); } - else if (type.flags & 268435456 /* ThisType */) { + else if (type.flags & 33554432 /* ThisType */) { if (inObjectTypeLiteral) { writer.reportInaccessibleThisError(); } writer.writeKeyword("this"); } - else if (type.flags & 131072 /* Reference */) { - writeTypeReference(type, nextFlags); + else if (type.flags & 4096 /* Reference */) { + writeTypeReference(type, flags); } - else if (type.flags & 256 /* EnumLiteral */) { - buildSymbolDisplay(getParentOfSymbol(type.symbol), writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); - writePunctuation(writer, 21 /* DotToken */); - appendSymbolNameOnly(type.symbol, writer); - } - else if (type.flags & (32768 /* Class */ | 65536 /* Interface */ | 16 /* Enum */ | 16384 /* TypeParameter */)) { + else if (type.flags & (1024 /* Class */ | 2048 /* Interface */ | 128 /* Enum */ | 512 /* TypeParameter */)) { // The specified symbol flags need to be reinterpreted as type flags - buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); + buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793056 /* Type */, 0 /* None */, flags); } - else if (!(flags & 512 /* InTypeAlias */) && type.flags & (2097152 /* Anonymous */ | 1572864 /* UnionOrIntersection */) && type.aliasSymbol) { - if (type.flags & 2097152 /* Anonymous */ || !(flags & 1024 /* UseTypeAliasValue */)) { - var typeArguments = type.aliasTypeArguments; - writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); - } - else { - writeUnionOrIntersectionType(type, nextFlags); - } + else if (type.flags & 8192 /* Tuple */) { + writeTupleType(type); } - else if (type.flags & 1572864 /* UnionOrIntersection */) { - writeUnionOrIntersectionType(type, nextFlags); + else if (type.flags & 49152 /* UnionOrIntersection */) { + writeUnionOrIntersectionType(type, flags); } - else if (type.flags & 2097152 /* Anonymous */) { - writeAnonymousType(type, nextFlags); + else if (type.flags & 65536 /* Anonymous */) { + writeAnonymousType(type, flags); } - else if (type.flags & 32 /* StringLiteral */) { + else if (type.flags & 256 /* StringLiteral */) { writer.writeStringLiteral("\"" + ts.escapeString(type.text) + "\""); } - else if (type.flags & 64 /* NumberLiteral */) { - writer.writeStringLiteral(type.text); - } else { // Should never get here // { ... } @@ -19098,7 +18040,7 @@ var ts; function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { // Unnamed function expressions and arrow functions have reserved names that we don't want to display if (symbol.flags & 32 /* Class */ || !isReservedMemberName(symbol.name)) { - buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, flags); + buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793056 /* Type */, 0 /* None */, flags); } if (pos < end) { writePunctuation(writer, 25 /* LessThanToken */); @@ -19120,11 +18062,6 @@ var ts; writePunctuation(writer, 19 /* OpenBracketToken */); writePunctuation(writer, 20 /* CloseBracketToken */); } - else if (type.target.flags & 262144 /* Tuple */) { - writePunctuation(writer, 19 /* OpenBracketToken */); - writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 24 /* CommaToken */); - writePunctuation(writer, 20 /* CloseBracketToken */); - } else { // Write the type reference in the format f.g.C where A and B are type arguments // for outer type parameters, and f and g are the respective declaring containers of those @@ -19152,16 +18089,16 @@ var ts; writeSymbolTypeReference(type.symbol, typeArguments, i, typeParameterCount, flags); } } + function writeTupleType(type) { + writePunctuation(writer, 19 /* OpenBracketToken */); + writeTypeList(type.elementTypes, 24 /* CommaToken */); + writePunctuation(writer, 20 /* CloseBracketToken */); + } function writeUnionOrIntersectionType(type, flags) { if (flags & 64 /* InElementType */) { writePunctuation(writer, 17 /* OpenParenToken */); } - if (type.flags & 524288 /* Union */) { - writeTypeList(formatUnionTypes(type.types), 47 /* BarToken */); - } - else { - writeTypeList(type.types, 46 /* AmpersandToken */); - } + writeTypeList(type.types, type.flags & 16384 /* Union */ ? 47 /* BarToken */ : 46 /* AmpersandToken */); if (flags & 64 /* InElementType */) { writePunctuation(writer, 18 /* CloseParenToken */); } @@ -19181,7 +18118,7 @@ var ts; var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, flags); + buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793056 /* Type */, 0 /* None */, flags); } else { // Recursive usage, use any @@ -19604,13 +18541,13 @@ var ts; function collectLinkedAliases(node) { var exportSymbol; if (node.parent && node.parent.kind === 235 /* ExportAssignment */) { - exportSymbol = resolveName(node.parent, node.text, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */, ts.Diagnostics.Cannot_find_name_0, node); + exportSymbol = resolveName(node.parent, node.text, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */, ts.Diagnostics.Cannot_find_name_0, node); } else if (node.parent.kind === 238 /* ExportSpecifier */) { var exportSpecifier = node.parent; exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : - resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */); + resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */); } var result = []; if (exportSymbol) { @@ -19628,7 +18565,7 @@ var ts; // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.text, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, undefined, undefined); + var importSymbol = resolveName(declaration, firstIdentifier.text, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */, undefined, undefined); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -19681,7 +18618,7 @@ var ts; return getSymbolLinks(target).declaredType; } if (propertyName === 1 /* ResolvedBaseConstructorType */) { - ts.Debug.assert(!!(target.flags & 32768 /* Class */)); + ts.Debug.assert(!!(target.flags & 1024 /* Class */)); return target.resolvedBaseConstructorType; } if (propertyName === 3 /* ResolvedReturnType */) { @@ -19730,7 +18667,7 @@ var ts; return type && (type.flags & 1 /* Any */) !== 0; } function isTypeNever(type) { - return type && (type.flags & 8192 /* Never */) !== 0; + return type && (type.flags & 134217728 /* Never */) !== 0; } // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been // assigned by contextual typing. @@ -19807,7 +18744,7 @@ var ts; : elementType; if (!type) { if (isTupleType(parentType)) { - error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); + error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), parentType.elementTypes.length, pattern.elements.length); } else { error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), propName); @@ -19822,12 +18759,10 @@ var ts; } // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 2048 /* Undefined */)) { + if (strictNullChecks && declaration.initializer && !(getCombinedTypeFlags(checkExpressionCached(declaration.initializer)) & 32 /* Undefined */)) { type = getTypeWithFacts(type, 131072 /* NEUndefined */); } - return declaration.initializer ? - getUnionType([type, checkExpressionCached(declaration.initializer)], /*subtypeReduction*/ true) : - type; + return type; } function getTypeForVariableLikeDeclarationFromJSDocComment(declaration) { var jsDocType = getJSDocTypeForVariableLikeDeclarationFromJSDocComment(declaration); @@ -19861,7 +18796,7 @@ var ts; return undefined; } function addOptionality(type, optional) { - return strictNullChecks && optional ? includeFalsyTypes(type, 2048 /* Undefined */) : type; + return strictNullChecks && optional ? addTypeKind(type, 32 /* Undefined */) : type; } // Return the inferred type for a variable, parameter, or property declaration function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { @@ -19909,14 +18844,9 @@ var ts; } } // Use contextual parameter type if one is available - var type = void 0; - if (declaration.symbol.name === "this") { - var thisParameter = getContextualThisParameter(func); - type = thisParameter ? getTypeOfSymbol(thisParameter) : undefined; - } - else { - type = getContextuallyTypedParameterType(declaration); - } + var type = declaration.symbol.name === "this" + ? getContextuallyTypedThisType(func) + : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, /*optional*/ declaration.questionToken && includeOptionality); } @@ -19931,7 +18861,7 @@ var ts; } // If the declaration specifies a binding pattern, use the type implied by the binding pattern if (ts.isBindingPattern(declaration.name)) { - return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true); + return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false); } // No type specified and nothing can be inferred return undefined; @@ -19939,21 +18869,23 @@ var ts; // Return the type implied by a binding pattern element. This is the type of the initializer of the element if // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding // pattern. Otherwise, it is the type any. - function getTypeFromBindingElement(element, includePatternInType, reportErrors) { + function getTypeFromBindingElement(element, includePatternInType) { if (element.initializer) { - return checkExpressionCached(element.initializer); + var type = checkExpressionCached(element.initializer); + reportErrorsFromWidening(element, type); + return getWidenedType(type); } if (ts.isBindingPattern(element.name)) { - return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); + return getTypeFromBindingPattern(element.name, includePatternInType); } - if (reportErrors && compilerOptions.noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { + if (compilerOptions.noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { reportImplicitAnyError(element, anyType); } return anyType; } // Return the type implied by an object binding pattern - function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { - var members = ts.createMap(); + function getTypeFromObjectBindingPattern(pattern, includePatternInType) { + var members = {}; var hasComputedProperties = false; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; @@ -19965,7 +18897,7 @@ var ts; var text = getTextOfPropertyName(name); var flags = 4 /* Property */ | 67108864 /* Transient */ | (e.initializer ? 536870912 /* Optional */ : 0); var symbol = createSymbol(flags, text); - symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); + symbol.type = getTypeFromBindingElement(e, includePatternInType); symbol.bindingElement = e; members[symbol.name] = symbol; }); @@ -19974,24 +18906,24 @@ var ts; result.pattern = pattern; } if (hasComputedProperties) { - result.flags |= 536870912 /* ObjectLiteralPatternWithComputedProperties */; + result.flags |= 67108864 /* ObjectLiteralPatternWithComputedProperties */; } return result; } // Return the type implied by an array binding pattern - function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { + function getTypeFromArrayBindingPattern(pattern, includePatternInType) { var elements = pattern.elements; if (elements.length === 0 || elements[elements.length - 1].dotDotDotToken) { return languageVersion >= 2 /* ES6 */ ? createIterableType(anyType) : anyArrayType; } // If the pattern has at least one element, and no rest element, then it should imply a tuple type. - var elementTypes = ts.map(elements, function (e) { return e.kind === 193 /* OmittedExpression */ ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); }); - var result = createTupleType(elementTypes); + var elementTypes = ts.map(elements, function (e) { return e.kind === 193 /* OmittedExpression */ ? anyType : getTypeFromBindingElement(e, includePatternInType); }); if (includePatternInType) { - result = cloneTypeReference(result); + var result = createNewTupleType(elementTypes); result.pattern = pattern; + return result; } - return result; + return createTupleType(elementTypes); } // Return the type implied by a binding pattern. This is the type implied purely by the binding pattern itself // and without regard to its context (i.e. without regard any type annotation or initializer associated with the @@ -20000,10 +18932,10 @@ var ts; // used as the contextual type of an initializer associated with the binding pattern. Also, for a destructuring // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of // the parameter. - function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { + function getTypeFromBindingPattern(pattern, includePatternInType) { return pattern.kind === 167 /* ObjectBindingPattern */ - ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) - : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); + ? getTypeFromObjectBindingPattern(pattern, includePatternInType) + : getTypeFromArrayBindingPattern(pattern, includePatternInType); } // Return the type associated with a variable, parameter, or property declaration. In the simple case this is the type // specified in a type annotation or inferred from an initializer. However, in the case of a destructuring declaration it @@ -20059,34 +18991,24 @@ var ts; if (declaration.kind === 235 /* ExportAssignment */) { return links.type = checkExpression(declaration.expression); } - if (declaration.flags & 134217728 /* JavaScriptFile */ && declaration.kind === 280 /* JSDocPropertyTag */ && declaration.typeExpression) { - return links.type = getTypeFromTypeNode(declaration.typeExpression.type); - } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { return unknownType; } - var type = void 0; - // Handle certain special assignment kinds, which happen to union across multiple declarations: - // * module.exports = expr - // * exports.p = expr - // * this.p = expr - // * className.prototype.method = expr - if (declaration.kind === 187 /* BinaryExpression */ || - declaration.kind === 172 /* PropertyAccessExpression */ && declaration.parent.kind === 187 /* BinaryExpression */) { - // Use JS Doc type if present on parent expression statement - if (declaration.flags & 134217728 /* JavaScriptFile */) { - var typeTag = ts.getJSDocTypeTag(declaration.parent); - if (typeTag && typeTag.typeExpression) { - return links.type = getTypeFromTypeNode(typeTag.typeExpression.type); - } - } - var declaredTypes = ts.map(symbol.declarations, function (decl) { return decl.kind === 187 /* BinaryExpression */ ? - checkExpressionCached(decl.right) : - checkExpressionCached(decl.parent.right); }); - type = getUnionType(declaredTypes, /*subtypeReduction*/ true); + var type = undefined; + // Handle module.exports = expr or this.p = expr + if (declaration.kind === 187 /* BinaryExpression */) { + type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); })); } - else { + else if (declaration.kind === 172 /* PropertyAccessExpression */) { + // Declarations only exist for property access expressions for certain + // special assignment kinds + if (declaration.parent.kind === 187 /* BinaryExpression */) { + // Handle exports.p = expr or className.prototype.method = expr + type = checkExpressionCached(declaration.parent.right); + } + } + if (type === undefined) { type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); } if (!popTypeResolution()) { @@ -20159,13 +19081,7 @@ var ts; } else { if (compilerOptions.noImplicitAny) { - if (setter) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } + error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation, symbolToString(symbol)); } type = anyType; } @@ -20185,13 +19101,13 @@ var ts; function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbol.valueDeclaration.kind === 225 /* ModuleDeclaration */ && ts.isShorthandAmbientModuleSymbol(symbol)) { + if (symbol.valueDeclaration.kind === 225 /* ModuleDeclaration */ && ts.isShorthandAmbientModule(symbol.valueDeclaration)) { links.type = anyType; } else { - var type = createObjectType(2097152 /* Anonymous */, symbol); + var type = createObjectType(65536 /* Anonymous */, symbol); links.type = strictNullChecks && symbol.flags & 536870912 /* Optional */ ? - includeFalsyTypes(type, 2048 /* Undefined */) : type; + addTypeKind(type, 32 /* Undefined */) : type; } } return links.type; @@ -20247,7 +19163,7 @@ var ts; return unknownType; } function getTargetType(type) { - return type.flags & 131072 /* Reference */ ? type.target : type; + return type.flags & 4096 /* Reference */ ? type.target : type; } function hasBaseType(type, checkBase) { return check(type); @@ -20318,7 +19234,7 @@ var ts; return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); } function isConstructorType(type) { - return type.flags & 2588672 /* ObjectType */ && getSignaturesOfType(type, 1 /* Construct */).length > 0; + return type.flags & 80896 /* ObjectType */ && getSignaturesOfType(type, 1 /* Construct */).length > 0; } function getBaseTypeNodeOfClass(type) { return ts.getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); @@ -20350,7 +19266,7 @@ var ts; return unknownType; } var baseConstructorType = checkExpression(baseTypeNode.expression); - if (baseConstructorType.flags & 2588672 /* ObjectType */) { + if (baseConstructorType.flags & 80896 /* ObjectType */) { // Resolving the members of a class requires us to resolve the base class of that class. // We force resolution here such that we catch circularities now. resolveStructuredTypeMembers(baseConstructorType); @@ -20368,28 +19284,25 @@ var ts; return type.resolvedBaseConstructorType; } function getBaseTypes(type) { + var isClass = type.symbol.flags & 32 /* Class */; + var isInterface = type.symbol.flags & 64 /* Interface */; if (!type.resolvedBaseTypes) { - if (type.flags & 262144 /* Tuple */) { - type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters))]; - } - else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) { - if (type.symbol.flags & 32 /* Class */) { - resolveBaseTypesOfClass(type); - } - if (type.symbol.flags & 64 /* Interface */) { - resolveBaseTypesOfInterface(type); - } - } - else { + if (!isClass && !isInterface) { ts.Debug.fail("type must be class or interface"); } + if (isClass) { + resolveBaseTypesOfClass(type); + } + if (isInterface) { + resolveBaseTypesOfInterface(type); + } } return type.resolvedBaseTypes; } function resolveBaseTypesOfClass(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; var baseConstructorType = getBaseConstructorTypeOfClass(type); - if (!(baseConstructorType.flags & 2588672 /* ObjectType */)) { + if (!(baseConstructorType.flags & 80896 /* ObjectType */)) { return; } var baseTypeNode = getBaseTypeNodeOfClass(type); @@ -20416,7 +19329,7 @@ var ts; if (baseType === unknownType) { return; } - if (!(getTargetType(baseType).flags & (32768 /* Class */ | 65536 /* Interface */))) { + if (!(getTargetType(baseType).flags & (1024 /* Class */ | 2048 /* Interface */))) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); return; } @@ -20451,7 +19364,7 @@ var ts; var node = _c[_b]; var baseType = getTypeFromTypeNode(node); if (baseType !== unknownType) { - if (getTargetType(baseType).flags & (32768 /* Class */ | 65536 /* Interface */)) { + if (getTargetType(baseType).flags & (1024 /* Class */ | 2048 /* Interface */)) { if (type !== baseType && !hasBaseType(baseType, type)) { if (type.resolvedBaseTypes === emptyArray) { type.resolvedBaseTypes = [baseType]; @@ -20486,8 +19399,8 @@ var ts; if (baseTypeNodes) { for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { var node = baseTypeNodes_1[_b]; - if (ts.isEntityNameExpression(node.expression)) { - var baseSymbol = resolveEntityName(node.expression, 793064 /* Type */, /*ignoreErrors*/ true); + if (ts.isSupportedExpressionWithTypeArguments(node)) { + var baseSymbol = resolveEntityName(node.expression, 793056 /* Type */, /*ignoreErrors*/ true); if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -20501,7 +19414,7 @@ var ts; function getDeclaredTypeOfClassOrInterface(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var kind = symbol.flags & 32 /* Class */ ? 32768 /* Class */ : 65536 /* Interface */; + var kind = symbol.flags & 32 /* Class */ ? 1024 /* Class */ : 2048 /* Interface */; var type = links.declaredType = createObjectType(kind, symbol); var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); @@ -20510,16 +19423,16 @@ var ts; // property types inferred from initializers and method return types inferred from return statements are very hard // to exhaustively analyze). We give interfaces a "this" type if we can't definitely determine that they are free of // "this" references. - if (outerTypeParameters || localTypeParameters || kind === 32768 /* Class */ || !isIndependentInterface(symbol)) { - type.flags |= 131072 /* Reference */; + if (outerTypeParameters || localTypeParameters || kind === 1024 /* Class */ || !isIndependentInterface(symbol)) { + type.flags |= 4096 /* Reference */; type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); type.outerTypeParameters = outerTypeParameters; type.localTypeParameters = localTypeParameters; - type.instantiations = ts.createMap(); + type.instantiations = {}; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 /* TypeParameter */ | 268435456 /* ThisType */); + type.thisType = createType(512 /* TypeParameter */ | 33554432 /* ThisType */); type.thisType.symbol = symbol; type.thisType.constraint = type; } @@ -20534,9 +19447,8 @@ var ts; if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) { return unknownType; } - var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - var declaration = ts.getDeclarationOfKind(symbol, 279 /* JSDocTypedefTag */); var type = void 0; + var declaration = ts.getDeclarationOfKind(symbol, 279 /* JSDocTypedefTag */); if (declaration) { if (declaration.jsDocTypeLiteral) { type = getTypeFromTypeNode(declaration.jsDocTypeLiteral); @@ -20547,14 +19459,14 @@ var ts; } else { declaration = ts.getDeclarationOfKind(symbol, 223 /* TypeAliasDeclaration */); - type = getTypeFromTypeNode(declaration.type, symbol, typeParameters); + type = getTypeFromTypeNode(declaration.type); } if (popTypeResolution()) { - links.typeParameters = typeParameters; - if (typeParameters) { + links.typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (links.typeParameters) { // Initialize the instantiation cache for generic type aliases. The declared type corresponds to // an instantiation of the type alias with the type parameters supplied as type arguments. - links.instantiations = ts.createMap(); + links.instantiations = {}; links.instantiations[getTypeListId(links.typeParameters)] = type; } } @@ -20566,80 +19478,19 @@ var ts; } return links.declaredType; } - function isLiteralEnumMember(symbol, member) { - var expr = member.initializer; - if (!expr) { - return !ts.isInAmbientContext(member); - } - return expr.kind === 8 /* NumericLiteral */ || - expr.kind === 185 /* PrefixUnaryExpression */ && expr.operator === 36 /* MinusToken */ && - expr.operand.kind === 8 /* NumericLiteral */ || - expr.kind === 69 /* Identifier */ && !!symbol.exports[expr.text]; - } - function enumHasLiteralMembers(symbol) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 224 /* EnumDeclaration */) { - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - if (!isLiteralEnumMember(symbol, member)) { - return false; - } - } - } - } - return true; - } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var enumType = links.declaredType = createType(16 /* Enum */); - enumType.symbol = symbol; - if (enumHasLiteralMembers(symbol)) { - var memberTypeList = []; - var memberTypes = ts.createMap(); - for (var _i = 0, _a = enumType.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 224 /* EnumDeclaration */) { - computeEnumMemberValues(declaration); - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - var memberSymbol = getSymbolOfNode(member); - var value = getEnumMemberValue(member); - if (!memberTypes[value]) { - var memberType = memberTypes[value] = createType(256 /* EnumLiteral */); - memberType.symbol = memberSymbol; - memberType.baseType = enumType; - memberType.text = "" + value; - memberTypeList.push(memberType); - } - } - } - } - enumType.memberTypes = memberTypes; - if (memberTypeList.length > 1) { - enumType.flags |= 524288 /* Union */; - enumType.types = memberTypeList; - unionTypes[getTypeListId(memberTypeList)] = enumType; - } - } - } - return links.declaredType; - } - function getDeclaredTypeOfEnumMember(symbol) { - var links = getSymbolLinks(symbol); - if (!links.declaredType) { - var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); - links.declaredType = enumType.flags & 524288 /* Union */ ? - enumType.memberTypes[getEnumMemberValue(symbol.valueDeclaration)] : - enumType; + var type = createType(128 /* Enum */); + type.symbol = symbol; + links.declaredType = type; } return links.declaredType; } function getDeclaredTypeOfTypeParameter(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var type = createType(16384 /* TypeParameter */); + var type = createType(512 /* TypeParameter */); type.symbol = symbol; if (!ts.getDeclarationOfKind(symbol, 141 /* TypeParameter */).constraint) { type.constraint = noConstraintType; @@ -20663,14 +19514,11 @@ var ts; if (symbol.flags & 524288 /* TypeAlias */) { return getDeclaredTypeOfTypeAlias(symbol); } - if (symbol.flags & 262144 /* TypeParameter */) { - return getDeclaredTypeOfTypeParameter(symbol); - } if (symbol.flags & 384 /* Enum */) { return getDeclaredTypeOfEnum(symbol); } - if (symbol.flags & 8 /* EnumMember */) { - return getDeclaredTypeOfEnumMember(symbol); + if (symbol.flags & 262144 /* TypeParameter */) { + return getDeclaredTypeOfTypeParameter(symbol); } if (symbol.flags & 8388608 /* Alias */) { return getDeclaredTypeOfAlias(symbol); @@ -20703,7 +19551,7 @@ var ts; case 135 /* UndefinedKeyword */: case 93 /* NullKeyword */: case 127 /* NeverKeyword */: - case 166 /* LiteralType */: + case 166 /* StringLiteralType */: return true; case 160 /* ArrayType */: return isIndependentType(node.elementType); @@ -20754,7 +19602,7 @@ var ts; return false; } function createSymbolTable(symbols) { - var result = ts.createMap(); + var result = {}; for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { var symbol = symbols_1[_i]; result[symbol.name] = symbol; @@ -20764,7 +19612,7 @@ var ts; // The mappingThisOnly flag indicates that the only type parameter being mapped is "this". When the flag is true, // we check symbols to see if we can quickly conclude they are free of "this" references, thus needing no instantiation. function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) { - var result = ts.createMap(); + var result = {}; for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { var symbol = symbols_2[_i]; result[symbol.name] = mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper); @@ -20774,7 +19622,7 @@ var ts; function addInheritedMembers(symbols, baseSymbols) { for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) { var s = baseSymbols_1[_i]; - if (!symbols[s.name]) { + if (!ts.hasProperty(symbols, s.name)) { symbols[s.name] = s; } } @@ -20791,27 +19639,19 @@ var ts; return type; } function getTypeWithThisArgument(type, thisArgument) { - if (type.flags & 131072 /* Reference */) { + if (type.flags & 4096 /* Reference */) { return createTypeReference(type.target, ts.concatenate(type.typeArguments, [thisArgument || type.target.thisType])); } return type; } function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { - var mapper; - var members; - var callSignatures; - var constructSignatures; - var stringIndexInfo; - var numberIndexInfo; - if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { - mapper = identityMapper; - members = source.symbol ? source.symbol.members : createSymbolTable(source.declaredProperties); - callSignatures = source.declaredCallSignatures; - constructSignatures = source.declaredConstructSignatures; - stringIndexInfo = source.declaredStringIndexInfo; - numberIndexInfo = source.declaredNumberIndexInfo; - } - else { + var mapper = identityMapper; + var members = source.symbol.members; + var callSignatures = source.declaredCallSignatures; + var constructSignatures = source.declaredConstructSignatures; + var stringIndexInfo = source.declaredStringIndexInfo; + var numberIndexInfo = source.declaredNumberIndexInfo; + if (!ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { mapper = createTypeMapper(typeParameters, typeArguments); members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1); callSignatures = instantiateList(source.declaredCallSignatures, mapper, instantiateSignature); @@ -20821,7 +19661,7 @@ var ts; } var baseTypes = getBaseTypes(source); if (baseTypes.length) { - if (source.symbol && members === source.symbol.members) { + if (members === source.symbol.members) { members = createSymbolTable(source.declaredProperties); } var thisArgument = ts.lastOrUndefined(typeArguments); @@ -20847,7 +19687,7 @@ var ts; type.typeArguments : ts.concatenate(type.typeArguments, [type]); resolveObjectTypeMembers(type, source, typeParameters, typeArguments); } - function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasStringLiterals) { var sig = new Signature(checker); sig.declaration = declaration; sig.typeParameters = typeParameters; @@ -20857,17 +19697,17 @@ var ts; sig.typePredicate = typePredicate; sig.minArgumentCount = minArgumentCount; sig.hasRestParameter = hasRestParameter; - sig.hasLiteralTypes = hasLiteralTypes; + sig.hasStringLiterals = hasStringLiterals; return sig; } function cloneSignature(sig) { - return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); + return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); } function getDefaultConstructSignatures(classType) { var baseConstructorType = getBaseConstructorTypeOfClass(classType); var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); if (baseSignatures.length === 0) { - return [createSignature(undefined, classType.localTypeParameters, undefined, emptyArray, classType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; + return [createSignature(undefined, classType.localTypeParameters, undefined, emptyArray, classType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false)]; } var baseTypeNode = getBaseTypeNodeOfClass(classType); var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); @@ -20885,6 +19725,23 @@ var ts; } return result; } + function createTupleTypeMemberSymbols(memberTypes) { + var members = {}; + for (var i = 0; i < memberTypes.length; i++) { + var symbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "" + i); + symbol.type = memberTypes[i]; + members[i] = symbol; + } + return members; + } + function resolveTupleTypeMembers(type) { + var arrayElementType = getUnionType(type.elementTypes, /*noSubtypeReduction*/ true); + // Make the tuple type itself the 'this' type by including an extra type argument + var arrayType = resolveStructuredTypeMembers(createTypeFromGenericGlobalType(globalArrayType, [arrayElementType, type])); + var members = createTupleTypeMemberSymbols(type.elementTypes); + addInheritedMembers(members, arrayType.properties); + setObjectTypeMembers(type, members, arrayType.callSignatures, arrayType.constructSignatures, arrayType.stringIndexInfo, arrayType.numberIndexInfo); + } function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) { for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { var s = signatureList_1[_i]; @@ -20939,7 +19796,7 @@ var ts; if (unionSignatures.length > 1) { s = cloneSignature(signature); if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { - var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; }), /*subtypeReduction*/ true); + var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; })); s.thisParameter = createTransientSymbol(signature.thisParameter, thisType); } // Clear resolved return type we possibly got from cloneSignature @@ -20965,7 +19822,7 @@ var ts; indexTypes.push(indexInfo.type); isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; } - return createIndexInfo(getUnionType(indexTypes, /*subtypeReduction*/ true), isAnyReadonly); + return createIndexInfo(getUnionType(indexTypes), isAnyReadonly); } function resolveUnionTypeMembers(type) { // The members and properties collections are empty for union types. To get all properties of a union @@ -21030,7 +19887,7 @@ var ts; constructSignatures = getDefaultConstructSignatures(classType); } var baseConstructorType = getBaseConstructorTypeOfClass(classType); - if (baseConstructorType.flags & 2588672 /* ObjectType */) { + if (baseConstructorType.flags & 80896 /* ObjectType */) { members = createSymbolTable(getNamedMembers(members)); addInheritedMembers(members, getPropertiesOfObjectType(baseConstructorType)); } @@ -21048,19 +19905,22 @@ var ts; } function resolveStructuredTypeMembers(type) { if (!type.members) { - if (type.flags & 131072 /* Reference */) { + if (type.flags & 4096 /* Reference */) { resolveTypeReferenceMembers(type); } - else if (type.flags & (32768 /* Class */ | 65536 /* Interface */)) { + else if (type.flags & (1024 /* Class */ | 2048 /* Interface */)) { resolveClassOrInterfaceMembers(type); } - else if (type.flags & 2097152 /* Anonymous */) { + else if (type.flags & 65536 /* Anonymous */) { resolveAnonymousTypeMembers(type); } - else if (type.flags & 524288 /* Union */) { + else if (type.flags & 8192 /* Tuple */) { + resolveTupleTypeMembers(type); + } + else if (type.flags & 16384 /* Union */) { resolveUnionTypeMembers(type); } - else if (type.flags & 1048576 /* Intersection */) { + else if (type.flags & 32768 /* Intersection */) { resolveIntersectionTypeMembers(type); } } @@ -21068,7 +19928,7 @@ var ts; } /** Return properties of an object type or an empty array for other types */ function getPropertiesOfObjectType(type) { - if (type.flags & 2588672 /* ObjectType */) { + if (type.flags & 80896 /* ObjectType */) { return resolveStructuredTypeMembers(type).properties; } return emptyArray; @@ -21076,11 +19936,13 @@ var ts; /** If the given type is an object type and that type has a property by the given name, * return the symbol for that property. Otherwise return undefined. */ function getPropertyOfObjectType(type, name) { - if (type.flags & 2588672 /* ObjectType */) { + if (type.flags & 80896 /* ObjectType */) { var resolved = resolveStructuredTypeMembers(type); - var symbol = resolved.members[name]; - if (symbol && symbolIsValue(symbol)) { - return symbol; + if (ts.hasProperty(resolved.members, name)) { + var symbol = resolved.members[name]; + if (symbolIsValue(symbol)) { + return symbol; + } } } } @@ -21093,7 +19955,7 @@ var ts; } // The properties of a union type are those that are present in all constituent types, so // we only need to check the properties of the first type - if (type.flags & 524288 /* Union */) { + if (type.flags & 16384 /* Union */) { break; } } @@ -21101,7 +19963,7 @@ var ts; } function getPropertiesOfType(type) { type = getApparentType(type); - return type.flags & 1572864 /* UnionOrIntersection */ ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); + return type.flags & 49152 /* UnionOrIntersection */ ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } /** * The apparent type of a type parameter is the base constraint instantiated with the type parameter @@ -21110,7 +19972,7 @@ var ts; function getApparentTypeOfTypeParameter(type) { if (!type.resolvedApparentType) { var constraintType = getConstraintOfTypeParameter(type); - while (constraintType && constraintType.flags & 16384 /* TypeParameter */) { + while (constraintType && constraintType.flags & 512 /* TypeParameter */) { constraintType = getConstraintOfTypeParameter(constraintType); } type.resolvedApparentType = getTypeWithThisArgument(constraintType || emptyObjectType, type); @@ -21123,19 +19985,19 @@ var ts; * type itself. Note that the apparent type of a union type is the union type itself. */ function getApparentType(type) { - if (type.flags & 16384 /* TypeParameter */) { + if (type.flags & 512 /* TypeParameter */) { type = getApparentTypeOfTypeParameter(type); } - if (type.flags & 34 /* StringLike */) { + if (type.flags & 258 /* StringLike */) { type = globalStringType; } - else if (type.flags & 340 /* NumberLike */) { + else if (type.flags & 132 /* NumberLike */) { type = globalNumberType; } - else if (type.flags & 136 /* BooleanLike */) { + else if (type.flags & 8 /* Boolean */) { type = globalBooleanType; } - else if (type.flags & 512 /* ESSymbol */) { + else if (type.flags & 16777216 /* ESSymbol */) { type = getGlobalESSymbolType(); } return type; @@ -21144,7 +20006,7 @@ var ts; var types = containingType.types; var props; // Flags we want to propagate to the result if they exist in all source symbols - var commonFlags = (containingType.flags & 1048576 /* Intersection */) ? 536870912 /* Optional */ : 0 /* None */; + var commonFlags = (containingType.flags & 32768 /* Intersection */) ? 536870912 /* Optional */ : 0 /* None */; var isReadonly = false; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var current = types_2[_i]; @@ -21163,7 +20025,7 @@ var ts; isReadonly = true; } } - else if (containingType.flags & 524288 /* Union */) { + else if (containingType.flags & 16384 /* Union */) { // A union type requires the property to be present in all constituent types return undefined; } @@ -21177,20 +20039,11 @@ var ts; } var propTypes = []; var declarations = []; - var commonType = undefined; - var hasCommonType = true; for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { var prop = props_1[_a]; if (prop.declarations) { ts.addRange(declarations, prop.declarations); } - var type = getTypeOfSymbol(prop); - if (!commonType) { - commonType = type; - } - else if (type !== commonType) { - hasCommonType = false; - } propTypes.push(getTypeOfSymbol(prop)); } var result = createSymbol(4 /* Property */ | @@ -21198,54 +20051,50 @@ var ts; 268435456 /* SyntheticProperty */ | commonFlags, name); result.containingType = containingType; - result.hasCommonType = hasCommonType; result.declarations = declarations; result.isReadonly = isReadonly; - result.type = containingType.flags & 524288 /* Union */ ? getUnionType(propTypes) : getIntersectionType(propTypes); + result.type = containingType.flags & 16384 /* Union */ ? getUnionType(propTypes) : getIntersectionType(propTypes); return result; } function getPropertyOfUnionOrIntersectionType(type, name) { - var properties = type.resolvedProperties || (type.resolvedProperties = ts.createMap()); - var property = properties[name]; - if (!property) { - property = createUnionOrIntersectionProperty(type, name); - if (property) { - properties[name] = property; - } + var properties = type.resolvedProperties || (type.resolvedProperties = {}); + if (ts.hasProperty(properties, name)) { + return properties[name]; + } + var property = createUnionOrIntersectionProperty(type, name); + if (property) { + properties[name] = property; } return property; } - /** - * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when - * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from - * Object and Function as appropriate. - * - * @param type a type to look up property from - * @param name a name of property to look up in a given type - */ + // Return the symbol for the property with the given name in the given type. Creates synthetic union properties when + // necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from + // Object and Function as appropriate. function getPropertyOfType(type, name) { type = getApparentType(type); - if (type.flags & 2588672 /* ObjectType */) { + if (type.flags & 80896 /* ObjectType */) { var resolved = resolveStructuredTypeMembers(type); - var symbol = resolved.members[name]; - if (symbol && symbolIsValue(symbol)) { - return symbol; + if (ts.hasProperty(resolved.members, name)) { + var symbol = resolved.members[name]; + if (symbolIsValue(symbol)) { + return symbol; + } } if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); - if (symbol_1) { - return symbol_1; + var symbol = getPropertyOfObjectType(globalFunctionType, name); + if (symbol) { + return symbol; } } return getPropertyOfObjectType(globalObjectType, name); } - if (type.flags & 1572864 /* UnionOrIntersection */) { + if (type.flags & 49152 /* UnionOrIntersection */) { return getPropertyOfUnionOrIntersectionType(type, name); } return undefined; } function getSignaturesOfStructuredType(type, kind) { - if (type.flags & 4161536 /* StructuredType */) { + if (type.flags & 130048 /* StructuredType */) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures; } @@ -21259,7 +20108,7 @@ var ts; return getSignaturesOfStructuredType(getApparentType(type), kind); } function getIndexInfoOfStructuredType(type, kind) { - if (type.flags & 4161536 /* StructuredType */) { + if (type.flags & 130048 /* StructuredType */) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo; } @@ -21288,7 +20137,7 @@ var ts; } } if (propTypes.length) { - return getUnionType(propTypes, /*subtypeReduction*/ true); + return getUnionType(propTypes); } } return undefined; @@ -21373,7 +20222,7 @@ var ts; var links = getNodeLinks(declaration); if (!links.resolvedSignature) { var parameters = []; - var hasLiteralTypes = false; + var hasStringLiterals = false; var minArgumentCount = -1; var thisParameter = undefined; var hasThisParameter = void 0; @@ -21396,8 +20245,8 @@ var ts; else { parameters.push(paramSymbol); } - if (param.type && param.type.kind === 166 /* LiteralType */) { - hasLiteralTypes = true; + if (param.type && param.type.kind === 166 /* StringLiteralType */) { + hasStringLiterals = true; } if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { if (minArgumentCount < 0) { @@ -21425,9 +20274,6 @@ var ts; if (isJSConstructSignature) { minArgumentCount--; } - if (!thisParameter && ts.isObjectLiteralMethod(declaration)) { - thisParameter = getContextualThisParameter(declaration); - } var classType = declaration.kind === 148 /* Constructor */ ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; @@ -21438,7 +20284,7 @@ var ts; var typePredicate = declaration.type && declaration.type.kind === 154 /* TypePredicate */ ? createTypePredicateFromTypePredicateNode(declaration.type) : undefined; - links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasLiteralTypes); + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasStringLiterals); } return links.resolvedSignature; } @@ -21528,7 +20374,7 @@ var ts; type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); } else if (signature.unionSignatures) { - type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); + type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature)); } else { type = getReturnTypeFromBody(signature.declaration); @@ -21552,7 +20398,7 @@ var ts; function getRestTypeOfSignature(signature) { if (signature.hasRestParameter) { var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); - if (type.flags & 131072 /* Reference */ && type.target === globalArrayType) { + if (type.flags & 4096 /* Reference */ && type.target === globalArrayType) { return type.typeArguments[0]; } } @@ -21576,7 +20422,7 @@ var ts; // will result in a different declaration kind. if (!signature.isolatedSignatureType) { var isConstructor = signature.declaration.kind === 148 /* Constructor */ || signature.declaration.kind === 152 /* ConstructSignature */; - var type = createObjectType(2097152 /* Anonymous */); + var type = createObjectType(65536 /* Anonymous */ | 262144 /* FromSignature */); type.members = emptySymbols; type.properties = emptyArray; type.callSignatures = !isConstructor ? [signature] : emptyArray; @@ -21620,7 +20466,7 @@ var ts; } function hasConstraintReferenceTo(type, target) { var checked; - while (type && !(type.flags & 268435456 /* ThisType */) && type.flags & 16384 /* TypeParameter */ && !ts.contains(checked, type)) { + while (type && !(type.flags & 33554432 /* ThisType */) && type.flags & 512 /* TypeParameter */ && !ts.contains(checked, type)) { if (type === target) { return true; } @@ -21652,27 +20498,24 @@ var ts; return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 141 /* TypeParameter */).parent); } function getTypeListId(types) { - var result = ""; if (types) { - var length_3 = types.length; - var i = 0; - while (i < length_3) { - var startId = types[i].id; - var count = 1; - while (i + count < length_3 && types[i + count].id === startId + count) { - count++; - } - if (result.length) { - result += ","; - } - result += startId; - if (count > 1) { - result += ":" + count; - } - i += count; + switch (types.length) { + case 1: + return "" + types[0].id; + case 2: + return types[0].id + "," + types[1].id; + default: + var result = ""; + for (var i = 0; i < types.length; i++) { + if (i > 0) { + result += ","; + } + result += types[i].id; + } + return result; } } - return result; + return ""; } // This function is used to propagate certain flags when creating new object type references and union types. // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type @@ -21686,29 +20529,20 @@ var ts; result |= type.flags; } } - return result & 234881024 /* PropagatingFlags */; + return result & 14680064 /* PropagatingFlags */; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); var type = target.instantiations[id]; if (!type) { var propagatedFlags = typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0; - var flags = 131072 /* Reference */ | propagatedFlags; + var flags = 4096 /* Reference */ | propagatedFlags; type = target.instantiations[id] = createObjectType(flags, target.symbol); type.target = target; type.typeArguments = typeArguments; } return type; } - function cloneTypeReference(source) { - var type = createObjectType(source.flags, source.symbol); - type.target = source.target; - type.typeArguments = source.typeArguments; - return type; - } - function getTypeReferenceArity(type) { - return type.target.typeParameters ? type.target.typeParameters.length : 0; - } // Get type from reference to class or interface function getTypeFromClassOrInterfaceReference(node, symbol) { var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); @@ -21768,9 +20602,8 @@ var ts; case 194 /* ExpressionWithTypeArguments */: // We only support expressions that are simple qualified names. For other // expressions this produces undefined. - var expr = node.expression; - if (ts.isEntityNameExpression(expr)) { - return expr; + if (ts.isSupportedExpressionWithTypeArguments(node)) { + return node.expression; } } return undefined; @@ -21779,7 +20612,7 @@ var ts; if (!typeReferenceName) { return unknownSymbol; } - return resolveEntityName(typeReferenceName, 793064 /* Type */) || unknownSymbol; + return resolveEntityName(typeReferenceName, 793056 /* Type */) || unknownSymbol; } function getTypeReferenceType(node, symbol) { if (symbol === unknownSymbol) { @@ -21808,15 +20641,15 @@ var ts; var typeReferenceName = getTypeReferenceName(node); symbol = resolveTypeReferenceName(node, typeReferenceName); type = getTypeReferenceType(node, symbol); + links.resolvedSymbol = symbol; + links.resolvedType = type; } else { // We only support expressions that are simple qualified names. For other expressions this produces undefined. - var typeNameOrExpression = node.kind === 155 /* TypeReference */ - ? node.typeName - : ts.isEntityNameExpression(node.expression) - ? node.expression - : undefined; - symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793064 /* Type */) || unknownSymbol; + var typeNameOrExpression = node.kind === 155 /* TypeReference */ ? node.typeName : + ts.isSupportedExpressionWithTypeArguments(node) ? node.expression : + undefined; + symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793056 /* Type */) || unknownSymbol; type = symbol === unknownSymbol ? unknownType : symbol.flags & (32 /* Class */ | 64 /* Interface */) ? getTypeFromClassOrInterfaceReference(node, symbol) : symbol.flags & 524288 /* TypeAlias */ ? getTypeFromTypeAliasReference(node, symbol) : @@ -21857,7 +20690,7 @@ var ts; return arity ? emptyGenericType : emptyObjectType; } var type = getDeclaredTypeOfSymbol(symbol); - if (!(type.flags & 2588672 /* ObjectType */)) { + if (!(type.flags & 80896 /* ObjectType */)) { error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbol.name); return arity ? emptyGenericType : emptyObjectType; } @@ -21871,7 +20704,7 @@ var ts; return getGlobalSymbol(name, 107455 /* Value */, ts.Diagnostics.Cannot_find_global_value_0); } function getGlobalTypeSymbol(name) { - return getGlobalSymbol(name, 793064 /* Type */, ts.Diagnostics.Cannot_find_global_type_0); + return getGlobalSymbol(name, 793056 /* Type */, ts.Diagnostics.Cannot_find_global_type_0); } function getGlobalSymbol(name, meaning, diagnostic) { return resolveName(undefined, name, meaning, diagnostic, name); @@ -21885,8 +20718,8 @@ var ts; * getExportedTypeFromNamespace('JSX', 'Element') returns the JSX.Element type */ function getExportedTypeFromNamespace(namespace, name) { - var namespaceSymbol = getGlobalSymbol(namespace, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); - var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793064 /* Type */); + var namespaceSymbol = getGlobalSymbol(namespace, 1536 /* Namespace */, /*diagnosticMessage*/ undefined); + var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793056 /* Type */); return typeSymbol && getDeclaredTypeOfSymbol(typeSymbol); } /** @@ -21920,45 +20753,15 @@ var ts; } return links.resolvedType; } - // We represent tuple types as type references to synthesized generic interface types created by - // this function. The types are of the form: - // - // interface Tuple extends Array { 0: T0, 1: T1, 2: T2, ... } - // - // Note that the generic type created by this function has no symbol associated with it. The same - // is true for each of the synthesized type parameters. - function createTupleTypeOfArity(arity) { - var typeParameters = []; - var properties = []; - for (var i = 0; i < arity; i++) { - var typeParameter = createType(16384 /* TypeParameter */); - typeParameters.push(typeParameter); - var property = createSymbol(4 /* Property */ | 67108864 /* Transient */, "" + i); - property.type = typeParameter; - properties.push(property); - } - var type = createObjectType(262144 /* Tuple */ | 131072 /* Reference */); - type.typeParameters = typeParameters; - type.outerTypeParameters = undefined; - type.localTypeParameters = typeParameters; - type.instantiations = ts.createMap(); - type.instantiations[getTypeListId(type.typeParameters)] = type; - type.target = type; - type.typeArguments = type.typeParameters; - type.thisType = createType(16384 /* TypeParameter */ | 268435456 /* ThisType */); - type.thisType.constraint = type; - type.declaredProperties = properties; - type.declaredCallSignatures = emptyArray; - type.declaredConstructSignatures = emptyArray; - type.declaredStringIndexInfo = undefined; - type.declaredNumberIndexInfo = undefined; - return type; - } - function getTupleTypeOfArity(arity) { - return tupleTypes[arity] || (tupleTypes[arity] = createTupleTypeOfArity(arity)); - } function createTupleType(elementTypes) { - return createTypeReference(getTupleTypeOfArity(elementTypes.length), elementTypes); + var id = getTypeListId(elementTypes); + return tupleTypes[id] || (tupleTypes[id] = createNewTupleType(elementTypes)); + } + function createNewTupleType(elementTypes) { + var propagatedFlags = getPropagatingFlagsOfTypes(elementTypes, /*excludeKinds*/ 0); + var type = createObjectType(8192 /* Tuple */ | propagatedFlags); + type.elementTypes = elementTypes; + return type; } function getTypeFromTupleTypeNode(node) { var links = getNodeLinks(node); @@ -21967,70 +20770,32 @@ var ts; } return links.resolvedType; } - function binarySearchTypes(types, type) { - var low = 0; - var high = types.length - 1; - var typeId = type.id; - while (low <= high) { - var middle = low + ((high - low) >> 1); - var id = types[middle].id; - if (id === typeId) { - return middle; - } - else if (id > typeId) { - high = middle - 1; - } - else { - low = middle + 1; - } + function addTypeToSet(typeSet, type, typeSetKind) { + if (type.flags & typeSetKind) { + addTypesToSet(typeSet, type.types, typeSetKind); } - return ~low; - } - function containsType(types, type) { - return binarySearchTypes(types, type) >= 0; - } - function addTypeToUnion(typeSet, type) { - if (type.flags & 524288 /* Union */) { - addTypesToUnion(typeSet, type.types); - } - else if (type.flags & 1 /* Any */) { - typeSet.containsAny = true; - } - else if (!strictNullChecks && type.flags & 6144 /* Nullable */) { - if (type.flags & 2048 /* Undefined */) + else if (type.flags & (1 /* Any */ | 32 /* Undefined */ | 64 /* Null */)) { + if (type.flags & 1 /* Any */) + typeSet.containsAny = true; + if (type.flags & 32 /* Undefined */) typeSet.containsUndefined = true; - if (type.flags & 4096 /* Null */) + if (type.flags & 64 /* Null */) typeSet.containsNull = true; - if (!(type.flags & 33554432 /* ContainsWideningType */)) + if (!(type.flags & 2097152 /* ContainsWideningType */)) typeSet.containsNonWideningType = true; } - else if (!(type.flags & 8192 /* Never */)) { - var len = typeSet.length; - var index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type); - if (index < 0) { - if (!(type.flags & 2097152 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); - } - } + else if (type !== neverType && !ts.contains(typeSet, type)) { + typeSet.push(type); } } // Add the given types to the given type set. Order is preserved, duplicates are removed, // and nested types of the given kind are flattened into the set. - function addTypesToUnion(typeSet, types) { + function addTypesToSet(typeSet, types, typeSetKind) { for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { var type = types_4[_i]; - addTypeToUnion(typeSet, type); + addTypeToSet(typeSet, type, typeSetKind); } } - function containsIdenticalType(types, type) { - for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { - var t = types_5[_i]; - if (isTypeIdenticalTo(t, type)) { - return true; - } - } - return false; - } function isSubtypeOfAny(candidate, types) { for (var i = 0, len = types.length; i < len; i++) { if (candidate !== types[i] && isTypeSubtypeOf(candidate, types[i])) { @@ -22048,14 +20813,14 @@ var ts; } } } - // We sort and deduplicate the constituent types based on object identity. If the subtypeReduction - // flag is specified we also reduce the constituent type set to only include types that aren't subtypes - // of other types. Subtype reduction is expensive for large union types and is possible only when union - // types are known not to circularly reference themselves (as is the case with union types created by - // expression constructs such as array literals and the || and ?: operators). Named types can - // circularly reference themselves and therefore cannot be subtype reduced during their declaration. - // For example, "type Item = string | (() => Item" is a named type that circularly references itself. - function getUnionType(types, subtypeReduction, aliasSymbol, aliasTypeArguments) { + // We reduce the constituent type set to only include types that aren't subtypes of other types, unless + // the noSubtypeReduction flag is specified, in which case we perform a simple deduplication based on + // object identity. Subtype reduction is possible only when union types are known not to circularly + // reference themselves (as is the case with union types created by expression constructs such as array + // literals and the || and ?: operators). Named types can circularly reference themselves and therefore + // cannot be deduplicated during their declaration. For example, "type Item = string | (() => Item" is + // a named type that circularly references itself. + function getUnionType(types, noSubtypeReduction) { if (types.length === 0) { return neverType; } @@ -22063,11 +20828,17 @@ var ts; return types[0]; } var typeSet = []; - addTypesToUnion(typeSet, types); + addTypesToSet(typeSet, types, 16384 /* Union */); if (typeSet.containsAny) { return anyType; } - if (subtypeReduction) { + if (strictNullChecks) { + if (typeSet.containsNull) + typeSet.push(nullType); + if (typeSet.containsUndefined) + typeSet.push(undefinedType); + } + if (!noSubtypeReduction) { removeSubtypes(typeSet); } if (typeSet.length === 0) { @@ -22075,112 +20846,84 @@ var ts; typeSet.containsUndefined ? typeSet.containsNonWideningType ? undefinedType : undefinedWideningType : neverType; } - return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments); - } - // This function assumes the constituent type list is sorted and deduplicated. - function getUnionTypeFromSortedList(types, aliasSymbol, aliasTypeArguments) { - if (types.length === 0) { - return neverType; + else if (typeSet.length === 1) { + return typeSet[0]; } - if (types.length === 1) { - return types[0]; - } - var id = getTypeListId(types); + var id = getTypeListId(typeSet); var type = unionTypes[id]; if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 6144 /* Nullable */); - type = unionTypes[id] = createObjectType(524288 /* Union */ | propagatedFlags); - type.types = types; - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = aliasTypeArguments; + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 96 /* Nullable */); + type = unionTypes[id] = createObjectType(16384 /* Union */ | propagatedFlags); + type.types = typeSet; } return type; } - function getTypeFromUnionTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getTypeFromUnionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), /*subtypeReduction*/ false, aliasSymbol, aliasTypeArguments); + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), /*noSubtypeReduction*/ true); } return links.resolvedType; } - function addTypeToIntersection(typeSet, type) { - if (type.flags & 1048576 /* Intersection */) { - addTypesToIntersection(typeSet, type.types); - } - else if (type.flags & 1 /* Any */) { - typeSet.containsAny = true; - } - else if (!(type.flags & 8192 /* Never */) && (strictNullChecks || !(type.flags & 6144 /* Nullable */)) && !ts.contains(typeSet, type)) { - typeSet.push(type); - } - } - // Add the given types to the given type set. Order is preserved, duplicates are removed, - // and nested types of the given kind are flattened into the set. - function addTypesToIntersection(typeSet, types) { - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type = types_6[_i]; - addTypeToIntersection(typeSet, type); - } - } // We do not perform structural deduplication on intersection types. Intersection types are created only by the & // type operator and we can't reduce those because we want to support recursive intersection types. For example, // a type alias of the form "type List = T & { next: List }" cannot be reduced during its declaration. // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution // for intersections of types with signatures can be deterministic. - function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { + function getIntersectionType(types) { if (types.length === 0) { return emptyObjectType; } var typeSet = []; - addTypesToIntersection(typeSet, types); + addTypesToSet(typeSet, types, 32768 /* Intersection */); if (typeSet.containsAny) { return anyType; } + if (strictNullChecks) { + if (typeSet.containsNull) + typeSet.push(nullType); + if (typeSet.containsUndefined) + typeSet.push(undefinedType); + } if (typeSet.length === 1) { return typeSet[0]; } var id = getTypeListId(typeSet); var type = intersectionTypes[id]; if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 6144 /* Nullable */); - type = intersectionTypes[id] = createObjectType(1048576 /* Intersection */ | propagatedFlags); + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 96 /* Nullable */); + type = intersectionTypes[id] = createObjectType(32768 /* Intersection */ | propagatedFlags); type.types = typeSet; - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = aliasTypeArguments; } return type; } - function getTypeFromIntersectionTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getTypeFromIntersectionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, aliasTypeArguments); + links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode)); } return links.resolvedType; } - function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { // Deferred resolution of members is handled by resolveObjectTypeMembers - var type = createObjectType(2097152 /* Anonymous */, node.symbol); - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = aliasTypeArguments; - links.resolvedType = type; + links.resolvedType = createObjectType(65536 /* Anonymous */, node.symbol); } return links.resolvedType; } - function createLiteralType(flags, text) { - var type = createType(flags); + function getStringLiteralTypeForText(text) { + if (ts.hasProperty(stringLiteralTypes, text)) { + return stringLiteralTypes[text]; + } + var type = stringLiteralTypes[text] = createType(256 /* StringLiteral */); type.text = text; return type; } - function getLiteralTypeForText(flags, text) { - var map = flags & 32 /* StringLiteral */ ? stringLiteralTypes : numericLiteralTypes; - return map[text] || (map[text] = createLiteralType(flags, text)); - } - function getTypeFromLiteralTypeNode(node) { + function getTypeFromStringLiteralTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = checkExpression(node.literal); + links.resolvedType = getStringLiteralTypeForText(ts.unescapeIdentifier(node.text)); } return links.resolvedType; } @@ -22219,7 +20962,7 @@ var ts; } return links.resolvedType; } - function getTypeFromTypeNode(node, aliasSymbol, aliasTypeArguments) { + function getTypeFromTypeNode(node) { switch (node.kind) { case 117 /* AnyKeyword */: case 258 /* JSDocAllType */: @@ -22241,19 +20984,11 @@ var ts; return nullType; case 127 /* NeverKeyword */: return neverType; - case 283 /* JSDocNullKeyword */: - return nullType; - case 284 /* JSDocUndefinedKeyword */: - return undefinedType; - case 285 /* JSDocNeverKeyword */: - return neverType; case 165 /* ThisType */: case 97 /* ThisKeyword */: return getTypeFromThisTypeNode(node); - case 166 /* LiteralType */: - return getTypeFromLiteralTypeNode(node); - case 282 /* JSDocLiteralType */: - return getTypeFromLiteralTypeNode(node.literal); + case 166 /* StringLiteralType */: + return getTypeFromStringLiteralTypeNode(node); case 155 /* TypeReference */: case 267 /* JSDocTypeReference */: return getTypeFromTypeReference(node); @@ -22270,9 +21005,9 @@ var ts; return getTypeFromTupleTypeNode(node); case 162 /* UnionType */: case 261 /* JSDocUnionType */: - return getTypeFromUnionTypeNode(node, aliasSymbol, aliasTypeArguments); + return getTypeFromUnionTypeNode(node); case 163 /* IntersectionType */: - return getTypeFromIntersectionTypeNode(node, aliasSymbol, aliasTypeArguments); + return getTypeFromIntersectionTypeNode(node); case 164 /* ParenthesizedType */: case 263 /* JSDocNullableType */: case 264 /* JSDocNonNullableType */: @@ -22286,7 +21021,7 @@ var ts; case 281 /* JSDocTypeLiteral */: case 269 /* JSDocFunctionType */: case 265 /* JSDocRecordType */: - return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node, aliasSymbol, aliasTypeArguments); + return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); // This function assumes that an identifier or qualified name is a type expression // Callers should first ensure this by calling isTypeNode case 69 /* Identifier */: @@ -22334,7 +21069,6 @@ var ts; count == 2 ? createBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : createArrayTypeMapper(sources, targets); mapper.mappedTypes = sources; - mapper.targetTypes = targets; return mapper; } function createTypeEraser(sources) { @@ -22367,7 +21101,7 @@ var ts; return mapper; } function cloneTypeParameter(typeParameter) { - var result = createType(16384 /* TypeParameter */); + var result = createType(512 /* TypeParameter */); result.symbol = typeParameter.symbol; result.target = typeParameter; return result; @@ -22405,7 +21139,7 @@ var ts; if (signature.typePredicate) { freshTypePredicate = cloneTypePredicate(signature.typePredicate, mapper); } - var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); + var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasStringLiterals); result.target = signature; result.mapper = mapper; return result; @@ -22442,11 +21176,9 @@ var ts; mapper.instantiations = []; } // Mark the anonymous type as instantiated such that our infinite instantiation detection logic can recognize it - var result = createObjectType(2097152 /* Anonymous */ | 4194304 /* Instantiated */, type.symbol); + var result = createObjectType(65536 /* Anonymous */ | 131072 /* Instantiated */, type.symbol); result.target = type; result.mapper = mapper; - result.aliasSymbol = type.aliasSymbol; - result.aliasTypeArguments = mapper.targetTypes; mapper.instantiations[type.id] = result; return result; } @@ -22501,10 +21233,10 @@ var ts; } function instantiateType(type, mapper) { if (type && mapper !== identityMapper) { - if (type.flags & 16384 /* TypeParameter */) { + if (type.flags & 512 /* TypeParameter */) { return mapper(type); } - if (type.flags & 2097152 /* Anonymous */) { + if (type.flags & 65536 /* Anonymous */) { // If the anonymous type originates in a declaration of a function, method, class, or // interface, in an object type literal, or in an object literal expression, we may need // to instantiate the type because it might reference a type parameter. We skip instantiation @@ -22513,17 +21245,20 @@ var ts; // instantiation. return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && - (type.flags & 4194304 /* Instantiated */ || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? + (type.flags & 131072 /* Instantiated */ || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? instantiateAnonymousType(type, mapper) : type; } - if (type.flags & 131072 /* Reference */) { + if (type.flags & 4096 /* Reference */) { return createTypeReference(type.target, instantiateList(type.typeArguments, mapper, instantiateType)); } - if (type.flags & 524288 /* Union */ && !(type.flags & 8190 /* Primitive */)) { - return getUnionType(instantiateList(type.types, mapper, instantiateType), /*subtypeReduction*/ false, type.aliasSymbol, mapper.targetTypes); + if (type.flags & 8192 /* Tuple */) { + return createTupleType(instantiateList(type.elementTypes, mapper, instantiateType)); } - if (type.flags & 1048576 /* Intersection */) { - return getIntersectionType(instantiateList(type.types, mapper, instantiateType), type.aliasSymbol, mapper.targetTypes); + if (type.flags & 16384 /* Union */) { + return getUnionType(instantiateList(type.types, mapper, instantiateType), /*noSubtypeReduction*/ true); + } + if (type.flags & 32768 /* Intersection */) { + return getIntersectionType(instantiateList(type.types, mapper, instantiateType)); } } return type; @@ -22568,10 +21303,10 @@ var ts; return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { - if (type.flags & 2588672 /* ObjectType */) { + if (type.flags & 80896 /* ObjectType */) { var resolved = resolveStructuredTypeMembers(type); if (resolved.constructSignatures.length) { - var result = createObjectType(2097152 /* Anonymous */, type.symbol); + var result = createObjectType(65536 /* Anonymous */, type.symbol); result.members = resolved.members; result.properties = resolved.properties; result.callSignatures = emptyArray; @@ -22583,32 +21318,26 @@ var ts; } // TYPE CHECKING function isTypeIdenticalTo(source, target) { - return isTypeRelatedTo(source, target, identityRelation); + return checkTypeRelatedTo(source, target, identityRelation, /*errorNode*/ undefined); } function compareTypesIdentical(source, target) { - return isTypeRelatedTo(source, target, identityRelation) ? -1 /* True */ : 0 /* False */; + return checkTypeRelatedTo(source, target, identityRelation, /*errorNode*/ undefined) ? -1 /* True */ : 0 /* False */; } function compareTypesAssignable(source, target) { - return isTypeRelatedTo(source, target, assignableRelation) ? -1 /* True */ : 0 /* False */; + return checkTypeRelatedTo(source, target, assignableRelation, /*errorNode*/ undefined) ? -1 /* True */ : 0 /* False */; } function isTypeSubtypeOf(source, target) { - return isTypeRelatedTo(source, target, subtypeRelation); + return checkTypeSubtypeOf(source, target, /*errorNode*/ undefined); } function isTypeAssignableTo(source, target) { - return isTypeRelatedTo(source, target, assignableRelation); - } - // A type S is considered to be an instance of a type T if S and T are the same type or if S is a - // subtype of T but not structurally identical to T. This specifically means that two distinct but - // structurally identical types (such as two classes) are not considered instances of each other. - function isTypeInstanceOf(source, target) { - return source === target || isTypeSubtypeOf(source, target) && !isTypeIdenticalTo(source, target); + return checkTypeAssignableTo(source, target, /*errorNode*/ undefined); } /** * This is *not* a bi-directional relationship. * If one needs to check both directions for comparability, use a second call to this function or 'checkTypeComparableTo'. */ function isTypeComparableTo(source, target) { - return isTypeRelatedTo(source, target, comparableRelation); + return checkTypeComparableTo(source, target, /*errorNode*/ undefined); } function areTypesComparable(type1, type2) { return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); @@ -22734,8 +21463,8 @@ var ts; var sourceReturnType = getReturnTypeOfSignature(erasedSource); var targetReturnType = getReturnTypeOfSignature(erasedTarget); if (targetReturnType === voidType - || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation) - || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) { + || checkTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation, /*errorNode*/ undefined) + || checkTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation, /*errorNode*/ undefined)) { return isSignatureAssignableTo(erasedSource, erasedTarget, /*ignoreReturnTypes*/ true); } return false; @@ -22764,88 +21493,6 @@ var ts; sourceNonRestParamCount; } } - function isEnumTypeRelatedTo(source, target, errorReporter) { - if (source === target) { - return true; - } - var id = source.id + "," + target.id; - if (enumRelation[id] !== undefined) { - return enumRelation[id]; - } - if (source.symbol.name !== target.symbol.name || - !(source.symbol.flags & 256 /* RegularEnum */) || !(target.symbol.flags & 256 /* RegularEnum */) || - (source.flags & 524288 /* Union */) !== (target.flags & 524288 /* Union */)) { - return enumRelation[id] = false; - } - var targetEnumType = getTypeOfSymbol(target.symbol); - for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { - var property = _a[_i]; - if (property.flags & 8 /* EnumMember */) { - var targetProperty = getPropertyOfType(targetEnumType, property.name); - if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { - if (errorReporter) { - errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */)); - } - return enumRelation[id] = false; - } - } - } - return enumRelation[id] = true; - } - function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { - if (target.flags & 8192 /* Never */) - return false; - if (target.flags & 1 /* Any */ || source.flags & 8192 /* Never */) - return true; - if (source.flags & 34 /* StringLike */ && target.flags & 2 /* String */) - return true; - if (source.flags & 340 /* NumberLike */ && target.flags & 4 /* Number */) - return true; - if (source.flags & 136 /* BooleanLike */ && target.flags & 8 /* Boolean */) - return true; - if (source.flags & 256 /* EnumLiteral */ && target.flags & 16 /* Enum */ && source.baseType === target) - return true; - if (source.flags & 16 /* Enum */ && target.flags & 16 /* Enum */ && isEnumTypeRelatedTo(source, target, errorReporter)) - return true; - if (source.flags & 2048 /* Undefined */ && (!strictNullChecks || target.flags & (2048 /* Undefined */ | 1024 /* Void */))) - return true; - if (source.flags & 4096 /* Null */ && (!strictNullChecks || target.flags & 4096 /* Null */)) - return true; - if (relation === assignableRelation || relation === comparableRelation) { - if (source.flags & 1 /* Any */) - return true; - if ((source.flags & 4 /* Number */ | source.flags & 64 /* NumberLiteral */) && target.flags & 272 /* EnumLike */) - return true; - if (source.flags & 256 /* EnumLiteral */ && - target.flags & 256 /* EnumLiteral */ && - source.text === target.text && - isEnumTypeRelatedTo(source.baseType, target.baseType, errorReporter)) { - return true; - } - if (source.flags & 256 /* EnumLiteral */ && - target.flags & 16 /* Enum */ && - isEnumTypeRelatedTo(target, source.baseType, errorReporter)) { - return true; - } - } - return false; - } - function isTypeRelatedTo(source, target, relation) { - if (source === target || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { - return true; - } - if (source.flags & 2588672 /* ObjectType */ && target.flags & 2588672 /* ObjectType */) { - var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; - var related = relation[id]; - if (related !== undefined) { - return related === 1 /* Succeeded */; - } - } - if (source.flags & 4177920 /* StructuredOrTypeParameter */ || target.flags & 4177920 /* StructuredOrTypeParameter */) { - return checkTypeRelatedTo(source, target, relation, undefined, undefined, undefined); - } - return false; - } /** * Checks if 'source' is related to 'target' (e.g.: is a assignable to). * @param source The left-hand-side of the relation. @@ -22894,16 +21541,6 @@ var ts; } reportError(message, sourceType, targetType); } - function tryElaborateErrorsForPrimitivesAndObjects(source, target) { - var sourceType = typeToString(source); - var targetType = typeToString(target); - if ((globalStringType === source && stringType === target) || - (globalNumberType === source && numberType === target) || - (globalBooleanType === source && booleanType === target) || - (getGlobalESSymbolType() === source && esSymbolType === target)) { - reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); - } - } // Compare two types and return // Ternary.True if they are related with no assumptions, // Ternary.Maybe if they are related with assumptions of other relationships, or @@ -22916,9 +21553,37 @@ var ts; if (relation === identityRelation) { return isIdenticalTo(source, target); } - if (isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) - return -1 /* True */; - if (source.flags & 16777216 /* FreshObjectLiteral */) { + if (!(target.flags & 134217728 /* Never */)) { + if (target.flags & 1 /* Any */ || source.flags & 134217728 /* Never */) + return -1 /* True */; + if (source.flags & 32 /* Undefined */) { + if (!strictNullChecks || target.flags & (32 /* Undefined */ | 16 /* Void */)) + return -1 /* True */; + } + if (source.flags & 64 /* Null */) { + if (!strictNullChecks || target.flags & 64 /* Null */) + return -1 /* True */; + } + if (source.flags & 128 /* Enum */ && target === numberType) + return -1 /* True */; + if (source.flags & 128 /* Enum */ && target.flags & 128 /* Enum */) { + if (result = enumRelatedTo(source, target, reportErrors)) { + return result; + } + } + if (source.flags & 256 /* StringLiteral */ && target === stringType) + return -1 /* True */; + if (relation === assignableRelation || relation === comparableRelation) { + if (source.flags & 1 /* Any */) + return -1 /* True */; + if (source === numberType && target.flags & 128 /* Enum */) + return -1 /* True */; + } + if (source.flags & 8 /* Boolean */ && target.flags & 8 /* Boolean */) { + return -1 /* True */; + } + } + if (source.flags & 1048576 /* FreshObjectLiteral */) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { reportRelationError(headMessage, source, target); @@ -22929,24 +21594,24 @@ var ts; // and intersection types are further deconstructed on the target side, we don't want to // make the check again (as it might fail for a partial target type). Therefore we obtain // the regular source type and proceed with that. - if (target.flags & 1572864 /* UnionOrIntersection */) { + if (target.flags & 49152 /* UnionOrIntersection */) { source = getRegularTypeOfObjectLiteral(source); } } var saveErrorInfo = errorInfo; // Note that these checks are specifically ordered to produce correct results. - if (source.flags & 524288 /* Union */) { + if (source.flags & 16384 /* Union */) { if (relation === comparableRelation) { - result = someTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */)); + result = someTypeRelatedToType(source, target, reportErrors); } else { - result = eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */)); + result = eachTypeRelatedToType(source, target, reportErrors); } if (result) { return result; } } - else if (target.flags & 1048576 /* Intersection */) { + else if (target.flags & 32768 /* Intersection */) { result = typeRelatedToEachType(source, target, reportErrors); if (result) { return result; @@ -22956,7 +21621,7 @@ var ts; // It is necessary to try these "some" checks on both sides because there may be nested "each" checks // on either side that need to be prioritized. For example, A | B = (A | B) & (C | D) or // A & B = (A & B) | (C & D). - if (source.flags & 1048576 /* Intersection */) { + if (source.flags & 32768 /* Intersection */) { // Check to see if any constituents of the intersection are immediately related to the target. // // Don't report errors though. Checking whether a constituent is related to the source is not actually @@ -22974,13 +21639,13 @@ var ts; return result; } } - if (target.flags & 524288 /* Union */) { - if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */) && !(target.flags & 8190 /* Primitive */))) { + if (target.flags & 16384 /* Union */) { + if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 16777726 /* Primitive */))) { return result; } } } - if (source.flags & 16384 /* TypeParameter */) { + if (source.flags & 512 /* TypeParameter */) { var constraint = getConstraintOfTypeParameter(source); if (!constraint || constraint.flags & 1 /* Any */) { constraint = emptyObjectType; @@ -22995,7 +21660,7 @@ var ts; } } else { - if (source.flags & 131072 /* Reference */ && target.flags & 131072 /* Reference */ && source.target === target.target) { + if (source.flags & 4096 /* Reference */ && target.flags & 4096 /* Reference */ && source.target === target.target) { // We have type references to same target type, see if relationship holds for all type arguments if (result = typeArgumentsRelatedTo(source, target, reportErrors)) { return result; @@ -23007,9 +21672,9 @@ var ts; // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. - if (apparentSource.flags & (2588672 /* ObjectType */ | 1048576 /* Intersection */) && target.flags & 2588672 /* ObjectType */) { + if (apparentSource.flags & (80896 /* ObjectType */ | 32768 /* Intersection */) && target.flags & 80896 /* ObjectType */) { // Report structural errors only if we haven't reported any errors yet - var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !(source.flags & 8190 /* Primitive */); + var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !(source.flags & 16777726 /* Primitive */); if (result = objectTypeRelatedTo(apparentSource, source, target, reportStructuralErrors)) { errorInfo = saveErrorInfo; return result; @@ -23017,17 +21682,14 @@ var ts; } } if (reportErrors) { - if (source.flags & 2588672 /* ObjectType */ && target.flags & 8190 /* Primitive */) { - tryElaborateErrorsForPrimitivesAndObjects(source, target); - } reportRelationError(headMessage, source, target); } return 0 /* False */; } function isIdenticalTo(source, target) { var result; - if (source.flags & 2588672 /* ObjectType */ && target.flags & 2588672 /* ObjectType */) { - if (source.flags & 131072 /* Reference */ && target.flags & 131072 /* Reference */ && source.target === target.target) { + if (source.flags & 80896 /* ObjectType */ && target.flags & 80896 /* ObjectType */) { + if (source.flags & 4096 /* Reference */ && target.flags & 4096 /* Reference */ && source.target === target.target) { // We have type references to same target type, see if all type arguments are identical if (result = typeArgumentsRelatedTo(source, target, /*reportErrors*/ false)) { return result; @@ -23035,8 +21697,8 @@ var ts; } return objectTypeRelatedTo(source, source, target, /*reportErrors*/ false); } - if (source.flags & 524288 /* Union */ && target.flags & 524288 /* Union */ || - source.flags & 1048576 /* Intersection */ && target.flags & 1048576 /* Intersection */) { + if (source.flags & 16384 /* Union */ && target.flags & 16384 /* Union */ || + source.flags & 32768 /* Intersection */ && target.flags & 32768 /* Intersection */) { if (result = eachTypeRelatedToSomeType(source, target, /*reportErrors*/ false)) { if (result &= eachTypeRelatedToSomeType(target, source, /*reportErrors*/ false)) { return result; @@ -23050,7 +21712,7 @@ var ts; // index signatures, or if the property is actually declared in the object type. In a union or intersection // type, a property is considered known if it is known in any constituent type. function isKnownProperty(type, name) { - if (type.flags & 2588672 /* ObjectType */) { + if (type.flags & 80896 /* ObjectType */) { var resolved = resolveStructuredTypeMembers(type); if ((relation === assignableRelation || relation === comparableRelation) && (type === globalObjectType || isEmptyObjectType(resolved)) || resolved.stringIndexInfo || @@ -23059,7 +21721,7 @@ var ts; return true; } } - else if (type.flags & 1572864 /* UnionOrIntersection */) { + else if (type.flags & 49152 /* UnionOrIntersection */) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; if (isKnownProperty(t, name)) { @@ -23077,7 +21739,7 @@ var ts; !t.numberIndexInfo; } function hasExcessProperties(source, target, reportErrors) { - if (!(target.flags & 536870912 /* ObjectLiteralPatternWithComputedProperties */) && maybeTypeOfKind(target, 2588672 /* ObjectType */)) { + if (!(target.flags & 67108864 /* ObjectLiteralPatternWithComputedProperties */) && maybeTypeOfKind(target, 80896 /* ObjectType */)) { for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; if (!isKnownProperty(target, prop.name)) { @@ -23110,10 +21772,18 @@ var ts; } function typeRelatedToSomeType(source, target, reportErrors) { var targetTypes = target.types; - if (target.flags & 524288 /* Union */ && containsType(targetTypes, source)) { - return -1 /* True */; - } var len = targetTypes.length; + // The null and undefined types are guaranteed to be at the end of the constituent type list. In order + // to produce the best possible errors we first check the nullable types, such that the last type we + // check and report errors from is a non-nullable type if one is present. + while (len >= 2 && targetTypes[len - 1].flags & 96 /* Nullable */) { + var related = isRelatedTo(source, targetTypes[len - 1], /*reportErrors*/ false); + if (related) { + return related; + } + len--; + } + // Now check the non-nullable types and report errors on the last one. for (var i = 0; i < len; i++) { var related = isRelatedTo(source, targetTypes[i], reportErrors && i === len - 1); if (related) { @@ -23137,10 +21807,18 @@ var ts; } function someTypeRelatedToType(source, target, reportErrors) { var sourceTypes = source.types; - if (source.flags & 524288 /* Union */ && containsType(sourceTypes, target)) { - return -1 /* True */; - } var len = sourceTypes.length; + // The null and undefined types are guaranteed to be at the end of the constituent type list. In order + // to produce the best possible errors we first check the nullable types, such that the last type we + // check and report errors from is a non-nullable type if one is present. + while (len >= 2 && sourceTypes[len - 1].flags & 96 /* Nullable */) { + var related = isRelatedTo(sourceTypes[len - 1], target, /*reportErrors*/ false); + if (related) { + return related; + } + len--; + } + // Now check the non-nullable types and report errors on the last one. for (var i = 0; i < len; i++) { var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); if (related) { @@ -23220,7 +21898,7 @@ var ts; } sourceStack[depth] = source; targetStack[depth] = target; - maybeStack[depth] = ts.createMap(); + maybeStack[depth] = {}; maybeStack[depth][id] = 1 /* Succeeded */; depth++; var saveExpandingFlags = expandingFlags; @@ -23253,7 +21931,7 @@ var ts; var maybeCache = maybeStack[depth]; // If result is definitely true, copy assumptions to global cache, else copy to next level up var destinationCache = (result === -1 /* True */ || depth === 0) ? relation : maybeStack[depth - 1]; - ts.copyProperties(maybeCache, destinationCache); + ts.copyMap(maybeCache, destinationCache); } else { // A false result goes straight into global cache (when something is false under assumptions it @@ -23268,7 +21946,7 @@ var ts; } var result = -1 /* True */; var properties = getPropertiesOfObjectType(target); - var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 8388608 /* ObjectLiteral */); + var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 524288 /* ObjectLiteral */); for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) { var targetProp = properties_1[_i]; var sourceProp = getPropertyOfType(source, targetProp.name); @@ -23341,7 +22019,7 @@ var ts; return result; } function propertiesIdenticalTo(source, target) { - if (!(source.flags & 2588672 /* ObjectType */ && target.flags & 2588672 /* ObjectType */)) { + if (!(source.flags & 80896 /* ObjectType */ && target.flags & 80896 /* ObjectType */)) { return 0 /* False */; } var sourceProperties = getPropertiesOfObjectType(source); @@ -23462,7 +22140,7 @@ var ts; return indexTypesIdenticalTo(source, target, kind); } var targetInfo = getIndexInfoOfType(target, kind); - if (!targetInfo || ((targetInfo.type.flags & 1 /* Any */) && !(originalSource.flags & 8190 /* Primitive */))) { + if (!targetInfo || ((targetInfo.type.flags & 1 /* Any */) && !(originalSource.flags & 16777726 /* Primitive */))) { // Index signature of type any permits assignment from everything but primitives return -1 /* True */; } @@ -23500,6 +22178,27 @@ var ts; } return 0 /* False */; } + function enumRelatedTo(source, target, reportErrors) { + if (source.symbol.name !== target.symbol.name || + source.symbol.flags & 128 /* ConstEnum */ || + target.symbol.flags & 128 /* ConstEnum */) { + return 0 /* False */; + } + var targetEnumType = getTypeOfSymbol(target.symbol); + for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { + var property = _a[_i]; + if (property.flags & 8 /* EnumMember */) { + var targetProperty = getPropertyOfType(targetEnumType, property.name); + if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */)); + } + return 0 /* False */; + } + } + } + return -1 /* True */; + } function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) { if (!sourceSignature.declaration || !targetSignature.declaration) { return true; @@ -23526,7 +22225,7 @@ var ts; } // Return true if the given type is the constructor type for an abstract class function isAbstractConstructorType(type) { - if (type.flags & 2097152 /* Anonymous */) { + if (type.flags & 65536 /* Anonymous */) { var symbol = type.symbol; if (symbol && symbol.flags & 32 /* Class */) { var declaration = getClassLikeDeclarationOfSymbol(symbol); @@ -23544,12 +22243,12 @@ var ts; // some level beyond that. function isDeeplyNestedGeneric(type, stack, depth) { // We track type references (created by createTypeReference) and instantiated types (created by instantiateType) - if (type.flags & (131072 /* Reference */ | 4194304 /* Instantiated */) && depth >= 5) { + if (type.flags & (4096 /* Reference */ | 131072 /* Instantiated */) && depth >= 5) { var symbol = type.symbol; var count = 0; for (var i = 0; i < depth; i++) { var t = stack[i]; - if (t.flags & (131072 /* Reference */ | 4194304 /* Instantiated */) && t.symbol === symbol) { + if (t.flags & (4096 /* Reference */ | 131072 /* Instantiated */) && t.symbol === symbol) { count++; if (count >= 5) return true; @@ -23599,10 +22298,8 @@ var ts; // A source signature partially matches a target signature if the target signature has no fewer required // parameters and no more overall parameters than the source signature (where a signature with a rest // parameter is always considered to have more overall parameters than one without). - var sourceRestCount = source.hasRestParameter ? 1 : 0; - var targetRestCount = target.hasRestParameter ? 1 : 0; - if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (sourceRestCount > targetRestCount || - sourceRestCount === targetRestCount && source.parameters.length >= target.parameters.length)) { + if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (source.hasRestParameter && !target.hasRestParameter || + source.hasRestParameter === target.hasRestParameter && source.parameters.length >= target.parameters.length)) { return true; } return false; @@ -23663,23 +22360,31 @@ var ts; return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } function isSupertypeOfEach(candidate, types) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var t = types_5[_i]; if (candidate !== t && !isTypeSubtypeOf(t, candidate)) return false; } return true; } + function getCombinedFlagsOfTypes(types) { + var flags = 0; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var t = types_6[_i]; + flags |= t.flags; + } + return flags; + } function getCommonSupertype(types) { if (!strictNullChecks) { return ts.forEach(types, function (t) { return isSupertypeOfEach(t, types) ? t : undefined; }); } - var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 6144 /* Nullable */); }); + var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 96 /* Nullable */); }); if (!primaryTypes.length) { - return getUnionType(types, /*subtypeReduction*/ true); + return getUnionType(types); } var supertype = ts.forEach(primaryTypes, function (t) { return isSupertypeOfEach(t, primaryTypes) ? t : undefined; }); - return supertype && includeFalsyTypes(supertype, getFalsyFlagsOfTypes(types) & 6144 /* Nullable */); + return supertype && addTypeKind(supertype, getCombinedFlagsOfTypes(types) & 96 /* Nullable */); } function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { // The downfallType/bestSupertypeDownfallType is the first type that caused a particular candidate @@ -23715,81 +22420,50 @@ var ts; checkTypeSubtypeOf(bestSupertypeDownfallType, bestSupertype, errorLocation, ts.Diagnostics.Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0, errorMessageChainHead); } function isArrayType(type) { - return type.flags & 131072 /* Reference */ && type.target === globalArrayType; + return type.flags & 4096 /* Reference */ && type.target === globalArrayType; } function isArrayLikeType(type) { // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, // or if it is not the undefined or null type and if it is assignable to ReadonlyArray - return type.flags & 131072 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || - !(type.flags & 6144 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); + return type.flags & 4096 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || + !(type.flags & 96 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); } function isTupleLikeType(type) { return !!getPropertyOfType(type, "0"); } - function isUnitType(type) { - return (type.flags & (480 /* Literal */ | 2048 /* Undefined */ | 4096 /* Null */)) !== 0; - } - function isUnitUnionType(type) { - return type.flags & 8 /* Boolean */ ? true : - type.flags & 524288 /* Union */ ? type.flags & 16 /* Enum */ ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : - isUnitType(type); - } - function getBaseTypeOfUnitType(type) { - return type.flags & 32 /* StringLiteral */ ? stringType : - type.flags & 64 /* NumberLiteral */ ? numberType : - type.flags & 128 /* BooleanLiteral */ ? booleanType : - type.flags & 256 /* EnumLiteral */ ? type.baseType : - type.flags & 524288 /* Union */ && !(type.flags & 16 /* Enum */) ? getUnionType(ts.map(type.types, getBaseTypeOfUnitType)) : - type; + function isStringLiteralUnionType(type) { + return type.flags & 256 /* StringLiteral */ ? true : + type.flags & 16384 /* Union */ ? ts.forEach(type.types, isStringLiteralUnionType) : + false; } /** * Check if a Type was written as a tuple type literal. * Prefer using isTupleLikeType() unless the use of `elementTypes` is required. */ function isTupleType(type) { - return !!(type.flags & 131072 /* Reference */ && type.target.flags & 262144 /* Tuple */); + return !!(type.flags & 8192 /* Tuple */); } - function getFalsyFlagsOfTypes(types) { - var result = 0; - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var t = types_8[_i]; - result |= getFalsyFlags(t); - } - return result; + function getCombinedTypeFlags(type) { + return type.flags & 16384 /* Union */ ? getCombinedFlagsOfTypes(type.types) : type.flags; } - // Returns the String, Number, Boolean, StringLiteral, NumberLiteral, BooleanLiteral, Void, Undefined, or Null - // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns - // no flags for all other types (including non-falsy literal types). - function getFalsyFlags(type) { - return type.flags & 524288 /* Union */ ? getFalsyFlagsOfTypes(type.types) : - type.flags & 32 /* StringLiteral */ ? type === emptyStringType ? 32 /* StringLiteral */ : 0 : - type.flags & 64 /* NumberLiteral */ ? type === zeroType ? 64 /* NumberLiteral */ : 0 : - type.flags & 128 /* BooleanLiteral */ ? type === falseType ? 128 /* BooleanLiteral */ : 0 : - type.flags & 7406 /* PossiblyFalsy */; - } - function includeFalsyTypes(type, flags) { - if ((getFalsyFlags(type) & flags) === flags) { + function addTypeKind(type, kind) { + if ((getCombinedTypeFlags(type) & kind) === kind) { return type; } var types = [type]; - if (flags & 34 /* StringLike */) - types.push(emptyStringType); - if (flags & 340 /* NumberLike */) - types.push(zeroType); - if (flags & 136 /* BooleanLike */) - types.push(falseType); - if (flags & 1024 /* Void */) + if (kind & 2 /* String */) + types.push(stringType); + if (kind & 4 /* Number */) + types.push(numberType); + if (kind & 8 /* Boolean */) + types.push(booleanType); + if (kind & 16 /* Void */) types.push(voidType); - if (flags & 2048 /* Undefined */) + if (kind & 32 /* Undefined */) types.push(undefinedType); - if (flags & 4096 /* Null */) + if (kind & 64 /* Null */) types.push(nullType); - return getUnionType(types, /*subtypeReduction*/ true); - } - function removeDefinitelyFalsyTypes(type) { - return getFalsyFlags(type) & 7392 /* DefinitelyFalsy */ ? - filterType(type, function (t) { return !(getFalsyFlags(t) & 7392 /* DefinitelyFalsy */); }) : - type; + return getUnionType(types); } function getNonNullableType(type) { return strictNullChecks ? getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */) : type; @@ -23815,7 +22489,7 @@ var ts; return symbol; } function transformTypeOfMembers(type, f) { - var members = ts.createMap(); + var members = {}; for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { var property = _a[_i]; var original = getTypeOfSymbol(property); @@ -23831,7 +22505,7 @@ var ts; * Leave signatures alone since they are not subject to the check. */ function getRegularTypeOfObjectLiteral(type) { - if (!(type.flags & 16777216 /* FreshObjectLiteral */)) { + if (!(type.flags & 1048576 /* FreshObjectLiteral */)) { return type; } var regularType = type.regularType; @@ -23841,7 +22515,7 @@ var ts; var resolved = type; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); - regularNew.flags = resolved.flags & ~16777216 /* FreshObjectLiteral */; + regularNew.flags = resolved.flags & ~1048576 /* FreshObjectLiteral */; type.regularType = regularNew; return regularNew; } @@ -23855,21 +22529,24 @@ var ts; return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); } function getWidenedConstituentType(type) { - return type.flags & 6144 /* Nullable */ ? type : getWidenedType(type); + return type.flags & 96 /* Nullable */ ? type : getWidenedType(type); } function getWidenedType(type) { - if (type.flags & 100663296 /* RequiresWidening */) { - if (type.flags & 6144 /* Nullable */) { + if (type.flags & 6291456 /* RequiresWidening */) { + if (type.flags & 96 /* Nullable */) { return anyType; } - if (type.flags & 8388608 /* ObjectLiteral */) { + if (type.flags & 524288 /* ObjectLiteral */) { return getWidenedTypeOfObjectLiteral(type); } - if (type.flags & 524288 /* Union */) { - return getUnionType(ts.map(type.types, getWidenedConstituentType)); + if (type.flags & 16384 /* Union */) { + return getUnionType(ts.map(type.types, getWidenedConstituentType), /*noSubtypeReduction*/ true); } - if (isArrayType(type) || isTupleType(type)) { - return createTypeReference(type.target, ts.map(type.typeArguments, getWidenedType)); + if (isArrayType(type)) { + return createArrayType(getWidenedType(type.typeArguments[0])); + } + if (isTupleType(type)) { + return createTupleType(ts.map(type.elementTypes, getWidenedType)); } } return type; @@ -23887,7 +22564,7 @@ var ts; */ function reportWideningErrorsInType(type) { var errorReported = false; - if (type.flags & 524288 /* Union */) { + if (type.flags & 16384 /* Union */) { for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; if (reportWideningErrorsInType(t)) { @@ -23895,19 +22572,22 @@ var ts; } } } - if (isArrayType(type) || isTupleType(type)) { - for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) { + if (isArrayType(type)) { + return reportWideningErrorsInType(type.typeArguments[0]); + } + if (isTupleType(type)) { + for (var _b = 0, _c = type.elementTypes; _b < _c.length; _b++) { var t = _c[_b]; if (reportWideningErrorsInType(t)) { errorReported = true; } } } - if (type.flags & 8388608 /* ObjectLiteral */) { + if (type.flags & 524288 /* ObjectLiteral */) { for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); - if (t.flags & 33554432 /* ContainsWideningType */) { + if (t.flags & 2097152 /* ContainsWideningType */) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, p.name, typeToString(getWidenedType(t))); } @@ -23952,7 +22632,7 @@ var ts; error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); } function reportErrorsFromWidening(declaration, type) { - if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 33554432 /* ContainsWideningType */) { + if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 2097152 /* ContainsWideningType */) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAnyError(declaration, type); @@ -23995,27 +22675,12 @@ var ts; isFixed: false }; } - // Return true if the given type could possibly reference a type parameter for which - // we perform type inference (i.e. a type parameter of a generic function). We cache - // results for union and intersection types for performance reasons. - function couldContainTypeParameters(type) { - return !!(type.flags & 16384 /* TypeParameter */ || - type.flags & 131072 /* Reference */ && ts.forEach(type.typeArguments, couldContainTypeParameters) || - type.flags & 2097152 /* Anonymous */ && type.symbol && type.symbol.flags & (8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */) || - type.flags & 1572864 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeParameters(type)); - } - function couldUnionOrIntersectionContainTypeParameters(type) { - if (type.couldContainTypeParameters === undefined) { - type.couldContainTypeParameters = ts.forEach(type.types, couldContainTypeParameters); - } - return type.couldContainTypeParameters; - } function inferTypes(context, source, target) { var sourceStack; var targetStack; var depth = 0; var inferiority = 0; - var visited = ts.createMap(); + var visited = {}; inferFromTypes(source, target); function isInProcess(source, target) { for (var i = 0; i < depth; i++) { @@ -24026,27 +22691,16 @@ var ts; return false; } function inferFromTypes(source, target) { - if (!couldContainTypeParameters(target)) { - return; - } - if (source.flags & 524288 /* Union */ && target.flags & 524288 /* Union */ && !(source.flags & 16 /* Enum */ && target.flags & 16 /* Enum */) || - source.flags & 1048576 /* Intersection */ && target.flags & 1048576 /* Intersection */) { - // Source and target are both unions or both intersections. If source and target - // are the same type, just relate each constituent type to itself. - if (source === target) { - for (var _i = 0, _a = source.types; _i < _a.length; _i++) { - var t = _a[_i]; - inferFromTypes(t, t); - } - return; - } - // Find each target constituent type that has an identically matching source - // constituent type, and for each such target constituent type infer from the type to - // itself. When inferring from a type to itself we effectively find all type parameter + if (source.flags & 16384 /* Union */ && target.flags & 16384 /* Union */ || + source.flags & 32768 /* Intersection */ && target.flags & 32768 /* Intersection */) { + // Source and target are both unions or both intersections. First, find each + // target constituent type that has an identically matching source constituent + // type, and for each such target constituent type infer from the type to itself. + // When inferring from a type to itself we effectively find all type parameter // occurrences within that type and infer themselves as their type arguments. var matchingTypes = void 0; - for (var _b = 0, _c = target.types; _b < _c.length; _b++) { - var t = _c[_b]; + for (var _i = 0, _a = target.types; _i < _a.length; _i++) { + var t = _a[_i]; if (typeIdenticalToSomeType(t, source.types)) { (matchingTypes || (matchingTypes = [])).push(t); inferFromTypes(t, t); @@ -24060,14 +22714,14 @@ var ts; target = removeTypesFromUnionOrIntersection(target, matchingTypes); } } - if (target.flags & 16384 /* TypeParameter */) { + if (target.flags & 512 /* TypeParameter */) { // If target is a type parameter, make an inference, unless the source type contains // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). // Because the anyFunctionType is internal, it should not be exposed to the user by adding // it as an inference candidate. Hopefully, a better candidate will come along that does // not contain anyFunctionType when we come back to this argument for its second round // of inference. - if (source.flags & 134217728 /* ContainsAnyFunctionType */) { + if (source.flags & 8388608 /* ContainsAnyFunctionType */) { return; } var typeParameters = context.typeParameters; @@ -24092,7 +22746,7 @@ var ts; } } } - else if (source.flags & 131072 /* Reference */ && target.flags & 131072 /* Reference */ && source.target === target.target) { + else if (source.flags & 4096 /* Reference */ && target.flags & 4096 /* Reference */ && source.target === target.target) { // If source and target are references to the same generic type, infer from type arguments var sourceTypes = source.typeArguments || emptyArray; var targetTypes = target.typeArguments || emptyArray; @@ -24101,14 +22755,22 @@ var ts; inferFromTypes(sourceTypes[i], targetTypes[i]); } } - else if (target.flags & 1572864 /* UnionOrIntersection */) { + else if (source.flags & 8192 /* Tuple */ && target.flags & 8192 /* Tuple */ && source.elementTypes.length === target.elementTypes.length) { + // If source and target are tuples of the same size, infer from element types + var sourceTypes = source.elementTypes; + var targetTypes = target.elementTypes; + for (var i = 0; i < sourceTypes.length; i++) { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } + } + else if (target.flags & 49152 /* UnionOrIntersection */) { var targetTypes = target.types; var typeParameterCount = 0; var typeParameter = void 0; // First infer to each type in union or intersection that isn't a type parameter - for (var _d = 0, targetTypes_2 = targetTypes; _d < targetTypes_2.length; _d++) { - var t = targetTypes_2[_d]; - if (t.flags & 16384 /* TypeParameter */ && ts.contains(context.typeParameters, t)) { + for (var _b = 0, targetTypes_2 = targetTypes; _b < targetTypes_2.length; _b++) { + var t = targetTypes_2[_b]; + if (t.flags & 512 /* TypeParameter */ && ts.contains(context.typeParameters, t)) { typeParameter = t; typeParameterCount++; } @@ -24125,17 +22787,21 @@ var ts; inferiority--; } } - else if (source.flags & 1572864 /* UnionOrIntersection */) { + else if (source.flags & 49152 /* UnionOrIntersection */) { // Source is a union or intersection type, infer from each constituent type var sourceTypes = source.types; - for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { - var sourceType = sourceTypes_3[_e]; + for (var _c = 0, sourceTypes_3 = sourceTypes; _c < sourceTypes_3.length; _c++) { + var sourceType = sourceTypes_3[_c]; inferFromTypes(sourceType, target); } } else { source = getApparentType(source); - if (source.flags & 2588672 /* ObjectType */) { + if (source.flags & 80896 /* ObjectType */ && (target.flags & 4096 /* Reference */ && target.typeArguments || + target.flags & 8192 /* Tuple */ || + target.flags & 65536 /* Anonymous */ && target.symbol && target.symbol.flags & (8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */))) { + // If source is an object type, and target is a type reference with type arguments, a tuple type, + // the type of a method, or a type literal, infer from members if (isInProcess(source, target)) { return; } @@ -24143,7 +22809,7 @@ var ts; return; } var key = source.id + "," + target.id; - if (visited[key]) { + if (ts.hasProperty(visited, key)) { return; } visited[key] = true; @@ -24212,8 +22878,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var t = types_7[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -24232,7 +22898,7 @@ var ts; reducedTypes.push(t); } } - return type.flags & 524288 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); + return type.flags & 16384 /* Union */ ? getUnionType(reducedTypes, /*noSubtypeReduction*/ true) : getIntersectionType(reducedTypes); } function getInferenceCandidates(context, index) { var inferences = context.inferences[index]; @@ -24245,7 +22911,7 @@ var ts; var inferences = getInferenceCandidates(context, index); if (inferences.length) { // Infer widened union or supertype, or the unknown type for no common supertype - var unionOrSuperType = context.inferUnionTypes ? getUnionType(inferences, /*subtypeReduction*/ true) : getCommonSupertype(inferences); + var unionOrSuperType = context.inferUnionTypes ? getUnionType(inferences) : getCommonSupertype(inferences); inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType; inferenceSucceeded = !!unionOrSuperType; } @@ -24327,6 +22993,10 @@ var ts; } return undefined; } + function isNullOrUndefinedLiteral(node) { + return node.kind === 93 /* NullKeyword */ || + node.kind === 69 /* Identifier */ && getResolvedSymbol(node) === undefinedSymbol; + } function getLeftmostIdentifierOrThis(node) { switch (node.kind) { case 69 /* Identifier */: @@ -24338,17 +23008,16 @@ var ts; return undefined; } function isMatchingReference(source, target) { - switch (source.kind) { - case 69 /* Identifier */: - return target.kind === 69 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || - (target.kind === 218 /* VariableDeclaration */ || target.kind === 169 /* BindingElement */) && - getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); - case 97 /* ThisKeyword */: - return target.kind === 97 /* ThisKeyword */; - case 172 /* PropertyAccessExpression */: - return target.kind === 172 /* PropertyAccessExpression */ && - source.name.text === target.name.text && - isMatchingReference(source.expression, target.expression); + if (source.kind === target.kind) { + switch (source.kind) { + case 69 /* Identifier */: + return getResolvedSymbol(source) === getResolvedSymbol(target); + case 97 /* ThisKeyword */: + return true; + case 172 /* PropertyAccessExpression */: + return source.name.text === target.name.text && + isMatchingReference(source.expression, target.expression); + } } return false; } @@ -24361,48 +23030,6 @@ var ts; } return false; } - // Return true if target is a property access xxx.yyy, source is a property access xxx.zzz, the declared - // type of xxx is a union type, and yyy is a property that is possibly a discriminant. We consider a property - // a possible discriminant if its type differs in the constituents of containing union type, and if every - // choice is a unit type or a union of unit types. - function containsMatchingReferenceDiscriminant(source, target) { - return target.kind === 172 /* PropertyAccessExpression */ && - containsMatchingReference(source, target.expression) && - isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.text); - } - function getDeclaredTypeOfReference(expr) { - if (expr.kind === 69 /* Identifier */) { - return getTypeOfSymbol(getResolvedSymbol(expr)); - } - if (expr.kind === 172 /* PropertyAccessExpression */) { - var type = getDeclaredTypeOfReference(expr.expression); - return type && getTypeOfPropertyOfType(type, expr.name.text); - } - return undefined; - } - function isDiscriminantProperty(type, name) { - if (type && type.flags & 524288 /* Union */) { - var prop = getPropertyOfType(type, name); - if (!prop) { - // The type may be a union that includes nullable or primitive types. If filtering - // those out produces a different type, get the property from that type instead. - // Effectively, we're checking if this *could* be a discriminant property once nullable - // and primitive types are removed by other type guards. - var filteredType = getTypeWithFacts(type, 4194304 /* Discriminatable */); - if (filteredType !== type && filteredType.flags & 524288 /* Union */) { - prop = getPropertyOfType(filteredType, name); - } - } - if (prop && prop.flags & 268435456 /* SyntheticProperty */) { - if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !prop.hasCommonType && - isUnitUnionType(getTypeOfSymbol(prop)); - } - return prop.isDiscriminantProperty; - } - } - return false; - } function isOrContainsMatchingReference(source, target) { return isMatchingReference(source, target) || containsMatchingReference(source, target); } @@ -24429,7 +23056,7 @@ var ts; return flow.id; } function typeMaybeAssignableTo(source, target) { - if (!(source.flags & 524288 /* Union */)) { + if (!(source.flags & 16384 /* Union */)) { return isTypeAssignableTo(source, target); } for (var _i = 0, _a = source.types; _i < _a.length; _i++) { @@ -24444,81 +23071,70 @@ var ts; // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, // we remove type string. function getAssignmentReducedType(declaredType, assignedType) { - if (declaredType !== assignedType) { - var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); - if (reducedType !== neverType) { - return reducedType; + if (declaredType !== assignedType && declaredType.flags & 16384 /* Union */) { + var reducedTypes = ts.filter(declaredType.types, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (reducedTypes.length) { + return reducedTypes.length === 1 ? reducedTypes[0] : getUnionType(reducedTypes); } } return declaredType; } - function getTypeFactsOfTypes(types) { - var result = 0 /* None */; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; - result |= getTypeFacts(t); - } - return result; - } - function isFunctionObjectType(type) { - // We do a quick check for a "bind" property before performing the more expensive subtype - // check. This gives us a quicker out in the common case where an object type is not a function. - var resolved = resolveStructuredTypeMembers(type); - return !!(resolved.callSignatures.length || resolved.constructSignatures.length || - resolved.members["bind"] && isTypeSubtypeOf(type, globalFunctionType)); - } function getTypeFacts(type) { var flags = type.flags; - if (flags & 2 /* String */) { + if (flags & 258 /* StringLike */) { return strictNullChecks ? 4079361 /* StringStrictFacts */ : 4194049 /* StringFacts */; } - if (flags & 32 /* StringLiteral */) { - return strictNullChecks ? - type === emptyStringType ? 3030785 /* EmptyStringStrictFacts */ : 1982209 /* NonEmptyStringStrictFacts */ : - type === emptyStringType ? 3145473 /* EmptyStringFacts */ : 4194049 /* NonEmptyStringFacts */; - } - if (flags & (4 /* Number */ | 16 /* Enum */)) { + if (flags & 132 /* NumberLike */) { return strictNullChecks ? 4079234 /* NumberStrictFacts */ : 4193922 /* NumberFacts */; } - if (flags & (64 /* NumberLiteral */ | 256 /* EnumLiteral */)) { - var isZero = type === zeroType || type.flags & 256 /* EnumLiteral */ && type.text === "0"; - return strictNullChecks ? - isZero ? 3030658 /* ZeroStrictFacts */ : 1982082 /* NonZeroStrictFacts */ : - isZero ? 3145346 /* ZeroFacts */ : 4193922 /* NonZeroFacts */; - } if (flags & 8 /* Boolean */) { return strictNullChecks ? 4078980 /* BooleanStrictFacts */ : 4193668 /* BooleanFacts */; } - if (flags & 136 /* BooleanLike */) { - return strictNullChecks ? - type === falseType ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : - type === falseType ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; + if (flags & 80896 /* ObjectType */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length || resolved.constructSignatures.length || isTypeSubtypeOf(type, globalFunctionType) ? + strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : + strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; } - if (flags & 2588672 /* ObjectType */) { - return isFunctionObjectType(type) ? - strictNullChecks ? 6164448 /* FunctionStrictFacts */ : 8376288 /* FunctionFacts */ : - strictNullChecks ? 6166480 /* ObjectStrictFacts */ : 8378320 /* ObjectFacts */; - } - if (flags & (1024 /* Void */ | 2048 /* Undefined */)) { + if (flags & (16 /* Void */ | 32 /* Undefined */)) { return 2457472 /* UndefinedFacts */; } - if (flags & 4096 /* Null */) { + if (flags & 64 /* Null */) { return 2340752 /* NullFacts */; } - if (flags & 512 /* ESSymbol */) { + if (flags & 16777216 /* ESSymbol */) { return strictNullChecks ? 1981320 /* SymbolStrictFacts */ : 4193160 /* SymbolFacts */; } - if (flags & 16384 /* TypeParameter */) { + if (flags & 512 /* TypeParameter */) { var constraint = getConstraintOfTypeParameter(type); - return getTypeFacts(constraint || emptyObjectType); + return constraint ? getTypeFacts(constraint) : 4194303 /* All */; } - if (flags & 1572864 /* UnionOrIntersection */) { - return getTypeFactsOfTypes(type.types); + if (flags & 32768 /* Intersection */) { + return ts.reduceLeft(type.types, function (flags, type) { return flags |= getTypeFacts(type); }, 0 /* None */); } - return 8388607 /* All */; + return 4194303 /* All */; } function getTypeWithFacts(type, include) { - return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); + if (!(type.flags & 16384 /* Union */)) { + return getTypeFacts(type) & include ? type : neverType; + } + var firstType; + var types; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (getTypeFacts(t) & include) { + if (!firstType) { + firstType = t; + } + else { + if (!types) { + types = [firstType]; + } + types.push(t); + } + } + } + return firstType ? types ? getUnionType(types, /*noSubtypeReduction*/ true) : firstType : neverType; } function getTypeWithDefault(type, defaultExpression) { if (defaultExpression) { @@ -24615,31 +23231,26 @@ var ts; getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } - function getInitialOrAssignedType(node) { - return node.kind === 218 /* VariableDeclaration */ || node.kind === 169 /* BindingElement */ ? - getInitialType(node) : - getAssignedType(node); - } - function getReferenceCandidate(node) { + function getReferenceFromExpression(node) { switch (node.kind) { case 178 /* ParenthesizedExpression */: - return getReferenceCandidate(node.expression); + return getReferenceFromExpression(node.expression); case 187 /* BinaryExpression */: switch (node.operatorToken.kind) { case 56 /* EqualsToken */: - return getReferenceCandidate(node.left); + return getReferenceFromExpression(node.left); case 24 /* CommaToken */: - return getReferenceCandidate(node.right); + return getReferenceFromExpression(node.right); } } return node; } function getTypeOfSwitchClause(clause) { if (clause.kind === 249 /* CaseClause */) { - var caseType = checkExpression(clause.expression); - return isUnitType(caseType) ? caseType : undefined; + var expr = clause.expression; + return expr.kind === 9 /* StringLiteral */ ? getStringLiteralTypeForText(expr.text) : checkExpression(expr); } - return neverType; + return undefined; } function getSwitchClauseTypes(switchStatement) { var links = getNodeLinks(switchStatement); @@ -24647,56 +23258,26 @@ var ts; // If all case clauses specify expressions that have unit types, we return an array // of those unit types. Otherwise we return an empty array. var types = ts.map(switchStatement.caseBlock.clauses, getTypeOfSwitchClause); - links.switchTypes = !ts.contains(types, undefined) ? types : emptyArray; + links.switchTypes = ts.forEach(types, function (t) { return !t || t.flags & 256 /* StringLiteral */; }) ? types : emptyArray; } return links.switchTypes; } function eachTypeContainedIn(source, types) { - return source.flags & 524288 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); - } - function isTypeSubsetOf(source, target) { - return source === target || target.flags & 524288 /* Union */ && isTypeSubsetOfUnion(source, target); - } - function isTypeSubsetOfUnion(source, target) { - if (source.flags & 524288 /* Union */) { - for (var _i = 0, _a = source.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (!containsType(target.types, t)) { - return false; - } - } - return true; - } - if (source.flags & 256 /* EnumLiteral */ && target.flags & 16 /* Enum */ && source.baseType === target) { - return true; - } - return containsType(target.types, source); + return source.flags & 16384 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } function filterType(type, f) { - if (type.flags & 524288 /* Union */) { - var types = type.types; - var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered); - } - return f(type) ? type : neverType; + return type.flags & 16384 /* Union */ ? + getUnionType(ts.filter(type.types, f)) : + f(type) ? type : neverType; } - function isIncomplete(flowType) { - return flowType.flags === 0; - } - function getTypeFromFlowType(flowType) { - return flowType.flags === 0 ? flowType.type : flowType; - } - function createFlowType(type, incomplete) { - return incomplete ? { flags: 0, type: type } : type; - } - function getFlowTypeOfReference(reference, declaredType, assumeInitialized, flowContainer) { + function getFlowTypeOfReference(reference, declaredType, assumeInitialized, includeOuterFunctions) { var key; - if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 4178943 /* Narrowable */)) { + if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 16908175 /* Narrowable */)) { return declaredType; } - var initialType = assumeInitialized ? declaredType : includeFalsyTypes(declaredType, 2048 /* Undefined */); + var initialType = assumeInitialized ? declaredType : addTypeKind(declaredType, 32 /* Undefined */); var visitedFlowStart = visitedFlowCount; - var result = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); + var result = getTypeAtFlowNode(reference.flowNode); visitedFlowCount = visitedFlowStart; if (reference.parent.kind === 196 /* NonNullExpression */ && getTypeWithFacts(result, 524288 /* NEUndefinedOrNull */) === neverType) { return declaredType; @@ -24740,7 +23321,7 @@ var ts; else if (flow.flags & 2 /* Start */) { // Check if we should continue with the control flow of the containing function. var container = flow.container; - if (container && container !== flowContainer && reference.kind !== 172 /* PropertyAccessExpression */) { + if (container && includeOuterFunctions) { flow = container.flowNode; continue; } @@ -24765,9 +23346,19 @@ var ts; var node = flow.node; // Assignments only narrow the computed type if the declared type is a union type. Thus, we // only need to evaluate the assigned type if the declared type is a union type. + if ((node.kind === 218 /* VariableDeclaration */ || node.kind === 169 /* BindingElement */) && + reference.kind === 69 /* Identifier */ && + getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(reference)) === getSymbolOfNode(node)) { + return declaredType.flags & 16384 /* Union */ ? + getAssignmentReducedType(declaredType, getInitialType(node)) : + declaredType; + } + // If the node is not a variable declaration or binding element, it is an identifier + // or a dotted name that is the target of an assignment. If we have a match, reduce + // the declared type by the assigned type. if (isMatchingReference(reference, node)) { - return declaredType.flags & 524288 /* Union */ ? - getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : + return declaredType.flags & 16384 /* Union */ ? + getAssignmentReducedType(declaredType, getAssignedType(node)) : declaredType; } // We didn't have a direct match. However, if the reference is a dotted name, this @@ -24781,43 +23372,32 @@ var ts; return undefined; } function getTypeAtFlowCondition(flow) { - var flowType = getTypeAtFlowNode(flow.antecedent); - var type = getTypeFromFlowType(flowType); + var type = getTypeAtFlowNode(flow.antecedent); if (type !== neverType) { // If we have an antecedent type (meaning we're reachable in some way), we first - // attempt to narrow the antecedent type. If that produces the never type, and if - // the antecedent type is incomplete (i.e. a transient type in a loop), then we - // take the type guard as an indication that control *could* reach here once we - // have the complete type. We proceed by reverting to the declared type and then + // attempt to narrow the antecedent type. If that produces the nothing type, then + // we take the type guard as an indication that control could reach here in a + // manner not understood by the control flow analyzer (e.g. a function argument + // has an invalid type, or a nested function has possibly made an assignment to a + // captured variable). We proceed by reverting to the declared type and then // narrow that. var assumeTrue = (flow.flags & 32 /* TrueCondition */) !== 0; type = narrowType(type, flow.expression, assumeTrue); - if (type === neverType && isIncomplete(flowType)) { + if (type === neverType) { type = narrowType(declaredType, flow.expression, assumeTrue); } } - return createFlowType(type, isIncomplete(flowType)); + return type; } function getTypeAtSwitchClause(flow) { - var flowType = getTypeAtFlowNode(flow.antecedent); - var type = getTypeFromFlowType(flowType); - var expr = flow.switchStatement.expression; - if (isMatchingReference(reference, expr)) { - type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); - } - else if (isMatchingReferenceDiscriminant(expr)) { - type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); - } - return createFlowType(type, isIncomplete(flowType)); + var type = getTypeAtFlowNode(flow.antecedent); + return narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } function getTypeAtFlowBranchLabel(flow) { var antecedentTypes = []; - var subtypeReduction = false; - var seenIncomplete = false; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { var antecedent = _a[_i]; - var flowType = getTypeAtFlowNode(antecedent); - var type = getTypeFromFlowType(flowType); + var type = getTypeAtFlowNode(antecedent); // If the type at a particular antecedent path is the declared type and the // reference is known to always be assigned (i.e. when declared and initial types // are the same), there is no reason to process more antecedents since the only @@ -24828,23 +23408,14 @@ var ts; if (!ts.contains(antecedentTypes, type)) { antecedentTypes.push(type); } - // If an antecedent type is not a subset of the declared type, we need to perform - // subtype reduction. This happens when a "foreign" type is injected into the control - // flow using the instanceof operator or a user defined type predicate. - if (!isTypeSubsetOf(type, declaredType)) { - subtypeReduction = true; - } - if (isIncomplete(flowType)) { - seenIncomplete = true; - } } - return createFlowType(getUnionType(antecedentTypes, subtypeReduction), seenIncomplete); + return getUnionType(antecedentTypes); } function getTypeAtFlowLoopLabel(flow) { // If we have previously computed the control flow type for the reference at // this flow loop junction, return the cached type. var id = getFlowNodeId(flow); - var cache = flowLoopCaches[id] || (flowLoopCaches[id] = ts.createMap()); + var cache = flowLoopCaches[id] || (flowLoopCaches[id] = {}); if (!key) { key = getFlowCacheKey(reference); } @@ -24852,31 +23423,25 @@ var ts; return cache[key]; } // If this flow loop junction and reference are already being processed, return - // the union of the types computed for each branch so far, marked as incomplete. - // We should never see an empty array here because the first antecedent of a loop - // junction is always the non-looping control flow path that leads to the top. + // the union of the types computed for each branch so far. We should never see + // an empty array here because the first antecedent of a loop junction is always + // the non-looping control flow path that leads to the top. for (var i = flowLoopStart; i < flowLoopCount; i++) { if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key) { - return createFlowType(getUnionType(flowLoopTypes[i]), /*incomplete*/ true); + return getUnionType(flowLoopTypes[i]); } } // Add the flow loop junction and reference to the in-process stack and analyze // each antecedent code path. var antecedentTypes = []; - var subtypeReduction = false; - var firstAntecedentType; flowLoopNodes[flowLoopCount] = flow; flowLoopKeys[flowLoopCount] = key; flowLoopTypes[flowLoopCount] = antecedentTypes; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { var antecedent = _a[_i]; flowLoopCount++; - var flowType = getTypeAtFlowNode(antecedent); + var type = getTypeAtFlowNode(antecedent); flowLoopCount--; - if (!firstAntecedentType) { - firstAntecedentType = flowType; - } - var type = getTypeFromFlowType(flowType); // If we see a value appear in the cache it is a sign that control flow analysis // was restarted and completed by checkExpressionCached. We can simply pick up // the resulting type and bail out. @@ -24886,12 +23451,6 @@ var ts; if (!ts.contains(antecedentTypes, type)) { antecedentTypes.push(type); } - // If an antecedent type is not a subset of the declared type, we need to perform - // subtype reduction. This happens when a "foreign" type is injected into the control - // flow using the instanceof operator or a user defined type predicate. - if (!isTypeSubsetOf(type, declaredType)) { - subtypeReduction = true; - } // If the type at a particular antecedent path is the declared type there is no // reason to process more antecedents since the only possible outcome is subtypes // that will be removed in the final union type anyway. @@ -24899,37 +23458,10 @@ var ts; break; } } - // The result is incomplete if the first antecedent (the non-looping control flow path) - // is incomplete. - var result = getUnionType(antecedentTypes, subtypeReduction); - if (isIncomplete(firstAntecedentType)) { - return createFlowType(result, /*incomplete*/ true); - } - return cache[key] = result; - } - function isMatchingReferenceDiscriminant(expr) { - return expr.kind === 172 /* PropertyAccessExpression */ && - declaredType.flags & 524288 /* Union */ && - isMatchingReference(reference, expr.expression) && - isDiscriminantProperty(declaredType, expr.name.text); - } - function narrowTypeByDiscriminant(type, propAccess, narrowType) { - var propName = propAccess.name.text; - var propType = getTypeOfPropertyOfType(type, propName); - var narrowedPropType = propType && narrowType(propType); - return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); + return cache[key] = getUnionType(antecedentTypes); } function narrowTypeByTruthiness(type, expr, assumeTrue) { - if (isMatchingReference(reference, expr)) { - return getTypeWithFacts(type, assumeTrue ? 1048576 /* Truthy */ : 2097152 /* Falsy */); - } - if (isMatchingReferenceDiscriminant(expr)) { - return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 1048576 /* Truthy */ : 2097152 /* Falsy */); }); - } - if (containsMatchingReferenceDiscriminant(reference, expr)) { - return declaredType; - } - return type; + return isMatchingReference(reference, expr) ? getTypeWithFacts(type, assumeTrue ? 1048576 /* Truthy */ : 2097152 /* Falsy */) : type; } function narrowTypeByBinaryExpression(type, expr, assumeTrue) { switch (expr.operatorToken.kind) { @@ -24939,29 +23471,26 @@ var ts; case 31 /* ExclamationEqualsToken */: case 32 /* EqualsEqualsEqualsToken */: case 33 /* ExclamationEqualsEqualsToken */: - var operator_1 = expr.operatorToken.kind; - var left_1 = getReferenceCandidate(expr.left); - var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 182 /* TypeOfExpression */ && right_1.kind === 9 /* StringLiteral */) { - return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); + var left = expr.left; + var operator = expr.operatorToken.kind; + var right = expr.right; + if (isNullOrUndefinedLiteral(right)) { + return narrowTypeByNullCheck(type, left, operator, right, assumeTrue); } - if (right_1.kind === 182 /* TypeOfExpression */ && left_1.kind === 9 /* StringLiteral */) { - return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); + if (isNullOrUndefinedLiteral(left)) { + return narrowTypeByNullCheck(type, right, operator, left, assumeTrue); } - if (isMatchingReference(reference, left_1)) { - return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); + if (left.kind === 182 /* TypeOfExpression */ && right.kind === 9 /* StringLiteral */) { + return narrowTypeByTypeof(type, left, operator, right, assumeTrue); } - if (isMatchingReference(reference, right_1)) { - return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); + if (right.kind === 182 /* TypeOfExpression */ && left.kind === 9 /* StringLiteral */) { + return narrowTypeByTypeof(type, right, operator, left, assumeTrue); } - if (isMatchingReferenceDiscriminant(left_1)) { - return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); + if (left.kind === 172 /* PropertyAccessExpression */) { + return narrowTypeByDiscriminant(type, left, operator, right, assumeTrue); } - if (isMatchingReferenceDiscriminant(right_1)) { - return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); - } - if (containsMatchingReferenceDiscriminant(reference, left_1) || containsMatchingReferenceDiscriminant(reference, right_1)) { - return declaredType; + if (right.kind === 172 /* PropertyAccessExpression */) { + return narrowTypeByDiscriminant(type, right, operator, left, assumeTrue); } break; case 91 /* InstanceOfKeyword */: @@ -24971,38 +23500,25 @@ var ts; } return type; } - function narrowTypeByEquality(type, operator, value, assumeTrue) { - if (type.flags & 1 /* Any */) { - return type; - } + function narrowTypeByNullCheck(type, target, operator, literal, assumeTrue) { + // We have '==', '!=', '===', or '!==' operator with 'null' or 'undefined' as value if (operator === 31 /* ExclamationEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } - var valueType = checkExpression(value); - if (valueType.flags & 6144 /* Nullable */) { - if (!strictNullChecks) { - return type; - } - var doubleEquals = operator === 30 /* EqualsEqualsToken */ || operator === 31 /* ExclamationEqualsToken */; - var facts = doubleEquals ? - assumeTrue ? 65536 /* EQUndefinedOrNull */ : 524288 /* NEUndefinedOrNull */ : - value.kind === 93 /* NullKeyword */ ? - assumeTrue ? 32768 /* EQNull */ : 262144 /* NENull */ : - assumeTrue ? 16384 /* EQUndefined */ : 131072 /* NEUndefined */; - return getTypeWithFacts(type, facts); - } - if (type.flags & 2589191 /* NotUnionOrUnit */) { + if (!strictNullChecks || !isMatchingReference(reference, getReferenceFromExpression(target))) { return type; } - if (assumeTrue) { - var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType !== neverType ? narrowedType : type; - } - return isUnitType(valueType) ? filterType(type, function (t) { return t !== valueType; }) : type; + var doubleEquals = operator === 30 /* EqualsEqualsToken */ || operator === 31 /* ExclamationEqualsToken */; + var facts = doubleEquals ? + assumeTrue ? 65536 /* EQUndefinedOrNull */ : 524288 /* NEUndefinedOrNull */ : + literal.kind === 93 /* NullKeyword */ ? + assumeTrue ? 32768 /* EQNull */ : 262144 /* NENull */ : + assumeTrue ? 16384 /* EQUndefined */ : 131072 /* NEUndefined */; + return getTypeWithFacts(type, facts); } function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { // We have '==', '!=', '====', or !==' operator with 'typeof xxx' and string literal operands - var target = getReferenceCandidate(typeOfExpr.expression); + var target = getReferenceFromExpression(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the // narrowed type of 'y' to its declared type. @@ -25014,38 +23530,72 @@ var ts; if (operator === 31 /* ExclamationEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } - if (assumeTrue && !(type.flags & 524288 /* Union */)) { + if (assumeTrue && !(type.flags & 16384 /* Union */)) { // We narrow a non-union type to an exact primitive type if the non-union type - // is a supertype of that primitive type. For example, type 'any' can be narrowed + // is a supertype of that primtive type. For example, type 'any' can be narrowed // to one of the primitive types. - var targetType = typeofTypesByName[literal.text]; + var targetType = ts.getProperty(typeofTypesByName, literal.text); if (targetType && isTypeSubtypeOf(targetType, type)) { return targetType; } } var facts = assumeTrue ? - typeofEQFacts[literal.text] || 64 /* TypeofEQHostObject */ : - typeofNEFacts[literal.text] || 8192 /* TypeofNEHostObject */; + ts.getProperty(typeofEQFacts, literal.text) || 64 /* TypeofEQHostObject */ : + ts.getProperty(typeofNEFacts, literal.text) || 8192 /* TypeofNEHostObject */; return getTypeWithFacts(type, facts); } + function narrowTypeByDiscriminant(type, propAccess, operator, value, assumeTrue) { + // We have '==', '!=', '===', or '!==' operator with property access as target + if (!isMatchingReference(reference, propAccess.expression)) { + return type; + } + var propName = propAccess.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return type; + } + var discriminantType = value.kind === 9 /* StringLiteral */ ? getStringLiteralTypeForText(value.text) : checkExpression(value); + if (!isStringLiteralUnionType(discriminantType)) { + return type; + } + if (operator === 31 /* ExclamationEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */) { + assumeTrue = !assumeTrue; + } + if (assumeTrue) { + return filterType(type, function (t) { return areTypesComparable(getTypeOfPropertyOfType(t, propName), discriminantType); }); + } + if (discriminantType.flags & 256 /* StringLiteral */) { + return filterType(type, function (t) { return getTypeOfPropertyOfType(t, propName) !== discriminantType; }); + } + return type; + } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { - // We only narrow if all case expressions specify values with unit types + // We have switch statement with property access expression + if (!isMatchingReference(reference, switchStatement.expression.expression)) { + return type; + } + var propName = switchStatement.expression.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return type; + } var switchTypes = getSwitchClauseTypes(switchStatement); if (!switchTypes.length) { return type; } var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); - var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); - var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType === neverType ? neverType : filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }); + var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, undefined); + var caseTypes = hasDefaultClause ? ts.filter(clauseTypes, function (t) { return !!t; }) : clauseTypes; + var discriminantType = caseTypes.length ? getUnionType(caseTypes) : undefined; + var caseType = discriminantType && filterType(type, function (t) { return isTypeComparableTo(discriminantType, getTypeOfPropertyOfType(t, propName)); }); if (!hasDefaultClause) { return caseType; } - var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, t)); }); - return caseType === neverType ? defaultType : getUnionType([caseType, defaultType]); + var defaultType = filterType(type, function (t) { return !eachTypeContainedIn(getTypeOfPropertyOfType(t, propName), switchTypes); }); + return caseType ? getUnionType([caseType, defaultType]) : defaultType; } function narrowTypeByInstanceof(type, expr, assumeTrue) { - var left = getReferenceCandidate(expr.left); + var left = getReferenceFromExpression(expr.left); if (!isMatchingReference(reference, left)) { // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the // narrowed type of 'y' to its declared type. @@ -25054,6 +23604,10 @@ var ts; } return type; } + // We never narrow type any in an instanceof guard + if (isTypeAny(type)) { + return type; + } // Check that right operand is a function type with a prototype property var rightType = checkExpression(expr.right); if (!isTypeSubtypeOf(rightType, globalFunctionType)) { @@ -25068,17 +23622,13 @@ var ts; targetType = prototypePropertyType; } } - // Don't narrow from 'any' if the target type is exactly 'Object' or 'Function' - if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) { - return type; - } if (!targetType) { // Target type is type of construct signature var constructSignatures = void 0; - if (rightType.flags & 65536 /* Interface */) { + if (rightType.flags & 2048 /* Interface */) { constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; } - else if (rightType.flags & 2097152 /* Anonymous */) { + else if (rightType.flags & 65536 /* Anonymous */) { constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); } if (constructSignatures && constructSignatures.length) { @@ -25092,29 +23642,28 @@ var ts; } function getNarrowedType(type, candidate, assumeTrue) { if (!assumeTrue) { - return filterType(type, function (t) { return !isTypeInstanceOf(t, candidate); }); + return type.flags & 16384 /* Union */ ? + getUnionType(ts.filter(type.types, function (t) { return !isTypeSubtypeOf(t, candidate); })) : + type; } - // If the current type is a union type, remove all constituents that couldn't be instances of + // If the current type is a union type, remove all constituents that aren't assignable to // the candidate type. If one or more constituents remain, return a union of those. - if (type.flags & 524288 /* Union */) { - var assignableType = filterType(type, function (t) { return isTypeInstanceOf(t, candidate); }); - if (assignableType !== neverType) { - return assignableType; + if (type.flags & 16384 /* Union */) { + var assignableConstituents = ts.filter(type.types, function (t) { return isTypeAssignableTo(t, candidate); }); + if (assignableConstituents.length) { + return getUnionType(assignableConstituents); } } - // If the candidate type is a subtype of the target type, narrow to the candidate type. - // Otherwise, if the target type is assignable to the candidate type, keep the target type. - // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate - // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the - // two types. - var targetType = type.flags & 16384 /* TypeParameter */ ? getApparentType(type) : type; - return isTypeSubtypeOf(candidate, type) ? candidate : + // If the candidate type is assignable to the target type, narrow to the candidate type. + // Otherwise, if the current type is assignable to the candidate, keep the current type. + // Otherwise, the types are completely unrelated, so narrow to the empty type. + var targetType = type.flags & 512 /* TypeParameter */ ? getApparentType(type) : type; + return isTypeAssignableTo(candidate, targetType) ? candidate : isTypeAssignableTo(type, candidate) ? type : - isTypeAssignableTo(candidate, targetType) ? candidate : - getIntersectionType([type, candidate]); + getIntersectionType([type, candidate]); } function narrowTypeByTypePredicate(type, callExpression, assumeTrue) { - if (!hasMatchingArgument(callExpression, reference)) { + if (type.flags & 1 /* Any */ || !hasMatchingArgument(callExpression, reference)) { return type; } var signature = getResolvedSignature(callExpression); @@ -25122,10 +23671,6 @@ var ts; if (!predicate) { return type; } - // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function' - if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { - return type; - } if (ts.isIdentifierTypePredicate(predicate)) { var predicateArgument = callExpression.arguments[predicate.parameterIndex]; if (predicateArgument) { @@ -25207,49 +23752,20 @@ var ts; function getControlFlowContainer(node) { while (true) { node = node.parent; - if (ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || - node.kind === 226 /* ModuleBlock */ || - node.kind === 256 /* SourceFile */ || - node.kind === 145 /* PropertyDeclaration */) { + if (ts.isFunctionLike(node) || node.kind === 226 /* ModuleBlock */ || node.kind === 256 /* SourceFile */ || node.kind === 145 /* PropertyDeclaration */) { return node; } } } - // Check if a parameter is assigned anywhere within its declaring function. - function isParameterAssigned(symbol) { - var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; - var links = getNodeLinks(func); - if (!(links.flags & 4194304 /* AssignmentsMarked */)) { - links.flags |= 4194304 /* AssignmentsMarked */; - if (!hasParentWithAssignmentsMarked(func)) { - markParameterAssignments(func); - } - } - return symbol.isAssigned || false; - } - function hasParentWithAssignmentsMarked(node) { - while (true) { - node = node.parent; - if (!node) { - return false; - } - if (ts.isFunctionLike(node) && getNodeLinks(node).flags & 4194304 /* AssignmentsMarked */) { - return true; - } - } - } - function markParameterAssignments(node) { - if (node.kind === 69 /* Identifier */) { - if (ts.isAssignmentTarget(node)) { - var symbol = getResolvedSymbol(node); - if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 142 /* Parameter */) { - symbol.isAssigned = true; - } - } - } - else { - ts.forEachChild(node, markParameterAssignments); + function isDeclarationIncludedInFlow(reference, declaration, includeOuterFunctions) { + var declarationContainer = getControlFlowContainer(declaration); + var container = getControlFlowContainer(reference); + while (container !== declarationContainer && + (container.kind === 179 /* FunctionExpression */ || container.kind === 180 /* ArrowFunction */) && + (includeOuterFunctions || ts.getImmediatelyInvokedFunctionExpression(container))) { + container = getControlFlowContainer(container); } + return container === declarationContainer; } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); @@ -25295,37 +23811,16 @@ var ts; checkCollisionWithCapturedThisVariable(node, node); checkNestedBlockScopedBinding(node, symbol); var type = getTypeOfSymbol(localOrExportSymbol); - var declaration = localOrExportSymbol.valueDeclaration; - // We only narrow variables and parameters occurring in a non-assignment position. For all other - // entities we simply return the declared type. - if (!(localOrExportSymbol.flags & 3 /* Variable */) || ts.isAssignmentTarget(node) || !declaration) { + if (!(localOrExportSymbol.flags & 3 /* Variable */) || ts.isAssignmentTarget(node)) { return type; } - // The declaration container is the innermost function that encloses the declaration of the variable - // or parameter. The flow container is the innermost function starting with which we analyze the control - // flow graph to determine the control flow based type. - var isParameter = ts.getRootDeclaration(declaration).kind === 142 /* Parameter */; - var declarationContainer = getControlFlowContainer(declaration); - var flowContainer = getControlFlowContainer(node); - var isOuterVariable = flowContainer !== declarationContainer; - // When the control flow originates in a function expression or arrow function and we are referencing - // a const variable or parameter from an outer function, we extend the origin of the control flow - // analysis to include the immediately enclosing function. - while (flowContainer !== declarationContainer && - (flowContainer.kind === 179 /* FunctionExpression */ || flowContainer.kind === 180 /* ArrowFunction */) && - (isReadonlySymbol(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { - flowContainer = getControlFlowContainer(flowContainer); - } - // We only look for uninitialized variables in strict null checking mode, and only when we can analyze - // the entire control flow graph from the variable's declaration (i.e. when the flow container and - // declaration container are the same). - var assumeInitialized = !strictNullChecks || (type.flags & 1 /* Any */) !== 0 || isParameter || - isOuterVariable || ts.isInAmbientContext(declaration); - var flowType = getFlowTypeOfReference(node, type, assumeInitialized, flowContainer); - // A variable is considered uninitialized when it is possible to analyze the entire control flow graph - // from declaration to use, and when the variable's declared type doesn't include undefined but the - // control flow based type does include undefined. - if (!assumeInitialized && !(getFalsyFlags(type) & 2048 /* Undefined */) && getFalsyFlags(flowType) & 2048 /* Undefined */) { + var declaration = localOrExportSymbol.valueDeclaration; + var includeOuterFunctions = isReadonlySymbol(localOrExportSymbol); + var assumeInitialized = !strictNullChecks || (type.flags & 1 /* Any */) !== 0 || !declaration || + ts.getRootDeclaration(declaration).kind === 142 /* Parameter */ || ts.isInAmbientContext(declaration) || + !isDeclarationIncludedInFlow(node, declaration, includeOuterFunctions); + var flowType = getFlowTypeOfReference(node, type, assumeInitialized, includeOuterFunctions); + if (!assumeInitialized && !(getCombinedTypeFlags(type) & 32 /* Undefined */) && getCombinedTypeFlags(flowType) & 32 /* Undefined */) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); // Return the declared type to reduce follow-on errors return type; @@ -25533,6 +24028,10 @@ var ts; return getInferredClassType(classSymbol); } } + var type = getContextuallyTypedThisType(container); + if (type) { + return type; + } var thisType = getThisTypeOfDeclaration(container); if (thisType) { return thisType; @@ -25541,7 +24040,7 @@ var ts; if (ts.isClassLike(container.parent)) { var symbol = getSymbolOfNode(container.parent); var type = container.flags & 32 /* Static */ ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; - return getFlowTypeOfReference(node, type, /*assumeInitialized*/ true, /*flowContainer*/ undefined); + return getFlowTypeOfReference(node, type, /*assumeInitialized*/ true, /*includeOuterFunctions*/ true); } if (ts.isInJavaScriptFile(node)) { var type = getTypeForThisExpressionFromJSDoc(container); @@ -25750,11 +24249,11 @@ var ts; return false; } } - function getContextualThisParameter(func) { + function getContextuallyTypedThisType(func) { if (isContextSensitiveFunctionOrObjectLiteralMethod(func) && func.kind !== 180 /* ArrowFunction */) { var contextualSignature = getContextualSignature(func); if (contextualSignature) { - return contextualSignature.thisParameter; + return getThisTypeOfSignature(contextualSignature); } } return undefined; @@ -25821,7 +24320,7 @@ var ts; } } if (ts.isBindingPattern(declaration.name)) { - return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false); + return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true); } if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; @@ -25909,10 +24408,6 @@ var ts; var binaryExpression = node.parent; var operator = binaryExpression.operatorToken.kind; if (operator >= 56 /* FirstAssignment */ && operator <= 68 /* LastAssignment */) { - // Don't do this for special property assignments to avoid circularity - if (ts.getSpecialPropertyAssignmentKind(binaryExpression) !== 0 /* None */) { - return undefined; - } // In an assignment expression, the right operand is contextually typed by the type of the left operand. if (node === binaryExpression.right) { return checkExpression(binaryExpression.left); @@ -25938,14 +24433,14 @@ var ts; // is a union type, the mapping function is applied to each constituent type and a union of the resulting // types is returned. function applyToContextualType(type, mapper) { - if (!(type.flags & 524288 /* Union */)) { + if (!(type.flags & 16384 /* Union */)) { return mapper(type); } var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var current = types_11[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var current = types_8[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -25963,7 +24458,7 @@ var ts; } function getTypeOfPropertyOfContextualType(type, name) { return applyToContextualType(type, function (t) { - var prop = t.flags & 4161536 /* StructuredType */ ? getPropertyOfType(t, name) : undefined; + var prop = t.flags & 130048 /* StructuredType */ ? getPropertyOfType(t, name) : undefined; return prop ? getTypeOfSymbol(prop) : undefined; }); } @@ -25972,7 +24467,7 @@ var ts; } // Return true if the given contextual type is a tuple-like type function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 524288 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); + return !!(type.flags & 16384 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); } // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one @@ -26110,30 +24605,6 @@ var ts; } return undefined; } - function isLiteralTypeLocation(node) { - var parent = node.parent; - switch (parent.kind) { - case 187 /* BinaryExpression */: - switch (parent.operatorToken.kind) { - case 32 /* EqualsEqualsEqualsToken */: - case 33 /* ExclamationEqualsEqualsToken */: - case 30 /* EqualsEqualsToken */: - case 31 /* ExclamationEqualsToken */: - return true; - } - break; - case 188 /* ConditionalExpression */: - return (node === parent.whenTrue || - node === parent.whenFalse) && - isLiteralTypeLocation(parent); - case 178 /* ParenthesizedExpression */: - return isLiteralTypeLocation(parent); - case 249 /* CaseClause */: - case 166 /* LiteralType */: - return true; - } - return false; - } // If the given type is an object or union type, if that type has a single signature, and if // that signature is non-generic, return the signature. Otherwise return undefined. function getNonGenericSignature(type) { @@ -26170,13 +24641,13 @@ var ts; if (!type) { return undefined; } - if (!(type.flags & 524288 /* Union */)) { + if (!(type.flags & 16384 /* Union */)) { return getNonGenericSignature(type); } var signatureList; var types = type.types; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var current = types_12[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var current = types_9[_i]; var signature = getNonGenericSignature(current); if (signature) { if (!signatureList) { @@ -26272,7 +24743,7 @@ var ts; // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". if (inDestructuringPattern && elementTypes.length) { - var type = cloneTypeReference(createTupleType(elementTypes)); + var type = createNewTupleType(elementTypes); type.pattern = node; return type; } @@ -26286,7 +24757,7 @@ var ts; for (var i = elementTypes.length; i < patternElements.length; i++) { var patternElement = patternElements[i]; if (hasDefaultValue(patternElement)) { - elementTypes.push(contextualType.typeArguments[i]); + elementTypes.push(contextualType.elementTypes[i]); } else { if (patternElement.kind !== 193 /* OmittedExpression */) { @@ -26301,9 +24772,7 @@ var ts; } } } - return createArrayType(elementTypes.length ? - getUnionType(elementTypes, /*subtypeReduction*/ true) : - strictNullChecks ? neverType : undefinedWideningType); + return createArrayType(elementTypes.length ? getUnionType(elementTypes) : strictNullChecks ? neverType : undefinedWideningType); } function isNumericName(name) { return name.kind === 140 /* ComputedPropertyName */ ? isNumericComputedName(name) : isNumericLiteralName(name.text); @@ -26311,7 +24780,7 @@ var ts; function isNumericComputedName(name) { // It seems odd to consider an expression of type Any to result in a numeric name, // but this behavior is consistent with checkIndexedAccess - return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 340 /* NumberLike */); + return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 132 /* NumberLike */); } function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { return isTypeAny(type) || isTypeOfKind(type, kind); @@ -26346,7 +24815,7 @@ var ts; links.resolvedType = checkExpression(node.expression); // This will allow types number, string, symbol or any. It will also allow enums, the unknown // type, and any union of these types (like string | number). - if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 340 /* NumberLike */ | 34 /* StringLike */ | 512 /* ESSymbol */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 132 /* NumberLike */ | 258 /* StringLike */ | 16777216 /* ESSymbol */)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -26362,14 +24831,14 @@ var ts; propTypes.push(getTypeOfSymbol(properties[i])); } } - var unionType = propTypes.length ? getUnionType(propTypes, /*subtypeReduction*/ true) : undefinedType; + var unionType = propTypes.length ? getUnionType(propTypes) : undefinedType; return createIndexInfo(unionType, /*isReadonly*/ false); } function checkObjectLiteral(node, contextualMapper) { var inDestructuringPattern = ts.isAssignmentTarget(node); // Grammar checking checkGrammarObjectLiteralExpression(node, inDestructuringPattern); - var propertiesTable = ts.createMap(); + var propertiesTable = {}; var propertiesArray = []; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && @@ -26409,7 +24878,7 @@ var ts; patternWithComputedProperties = true; } } - else if (contextualTypeHasPattern && !(contextualType.flags & 536870912 /* ObjectLiteralPatternWithComputedProperties */)) { + else if (contextualTypeHasPattern && !(contextualType.flags & 67108864 /* ObjectLiteralPatternWithComputedProperties */)) { // If object literal is contextually typed by the implied type of a binding pattern, and if the // binding pattern specifies a default value for the property, make the property optional. var impliedProp = getPropertyOfType(contextualType, member.name); @@ -26456,7 +24925,7 @@ var ts; if (contextualTypeHasPattern) { for (var _b = 0, _c = getPropertiesOfType(contextualType); _b < _c.length; _b++) { var prop = _c[_b]; - if (!propertiesTable[prop.name]) { + if (!ts.hasProperty(propertiesTable, prop.name)) { if (!(prop.flags & 536870912 /* Optional */)) { error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } @@ -26468,8 +24937,8 @@ var ts; var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 0 /* String */) : undefined; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 1 /* Number */) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16777216 /* FreshObjectLiteral */; - result.flags |= 8388608 /* ObjectLiteral */ | 67108864 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 234881024 /* PropagatingFlags */) | (patternWithComputedProperties ? 536870912 /* ObjectLiteralPatternWithComputedProperties */ : 0); + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576 /* FreshObjectLiteral */; + result.flags |= 524288 /* ObjectLiteral */ | 4194304 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 14680064 /* PropagatingFlags */) | (patternWithComputedProperties ? 67108864 /* ObjectLiteralPatternWithComputedProperties */ : 0); if (inDestructuringPattern) { result.pattern = node; } @@ -26536,9 +25005,10 @@ var ts; var correspondingPropSymbol = getPropertyOfType(elementAttributesType, node.name.text); correspondingPropType = correspondingPropSymbol && getTypeOfSymbol(correspondingPropSymbol); if (isUnhyphenatedJsxName(node.name.text)) { - var attributeType = getTypeOfPropertyOfType(elementAttributesType, getTextOfPropertyName(node.name)) || getIndexTypeOfType(elementAttributesType, 0 /* String */); - if (attributeType) { - correspondingPropType = attributeType; + // Maybe there's a string indexer? + var indexerType = getIndexTypeOfType(elementAttributesType, 0 /* String */); + if (indexerType) { + correspondingPropType = indexerType; } else { // If there's no corresponding property with this name, error @@ -26629,7 +25099,7 @@ var ts; * For example, in the element , the element instance type is `MyClass` (not `typeof MyClass`). */ function getJsxElementInstanceType(node, valueType) { - ts.Debug.assert(!(valueType.flags & 524288 /* Union */)); + ts.Debug.assert(!(valueType.flags & 16384 /* Union */)); if (isTypeAny(valueType)) { // Short-circuit if the class tag is using an element type 'any' return anyType; @@ -26645,7 +25115,7 @@ var ts; return unknownType; } } - return getUnionType(signatures.map(getReturnTypeOfSignature), /*subtypeReduction*/ true); + return getUnionType(signatures.map(getReturnTypeOfSignature)); } /// e.g. "props" for React.d.ts, /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all @@ -26654,9 +25124,9 @@ var ts; /// non-intrinsic elements' attributes type is the element instance type) function getJsxElementPropertiesName() { // JSX - var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); + var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1536 /* Namespace */, /*diagnosticMessage*/ undefined); // JSX.ElementAttributesProperty [symbol] - var attribsPropTypeSym = jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.ElementAttributesPropertyNameContainer, 793064 /* Type */); + var attribsPropTypeSym = jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.ElementAttributesPropertyNameContainer, 793056 /* Type */); // JSX.ElementAttributesProperty [type] var attribPropType = attribsPropTypeSym && getDeclaredTypeOfSymbol(attribsPropTypeSym); // The properties of JSX.ElementAttributesProperty @@ -26687,17 +25157,17 @@ var ts; if (!elemType) { elemType = checkExpression(node.tagName); } - if (elemType.flags & 524288 /* Union */) { + if (elemType.flags & 16384 /* Union */) { var types = elemType.types; return getUnionType(types.map(function (type) { return getResolvedJsxType(node, type, elemClassType); - }), /*subtypeReduction*/ true); + })); } // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type if (elemType.flags & 2 /* String */) { return anyType; } - else if (elemType.flags & 32 /* StringLiteral */) { + else if (elemType.flags & 256 /* StringLiteral */) { // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { @@ -26761,7 +25231,7 @@ var ts; // Props is of type 'any' or unknown return attributesType; } - else if (attributesType.flags & 524288 /* Union */) { + else if (attributesType.flags & 16384 /* Union */) { // Props cannot be a union type error(node.tagName, ts.Diagnostics.JSX_element_attributes_type_0_may_not_be_a_union_type, typeToString(attributesType)); return anyType; @@ -26859,7 +25329,7 @@ var ts; getSymbolLinks(reactSym).referenced = true; } var targetAttributesType = getJsxElementAttributesType(node); - var nameTable = ts.createMap(); + var nameTable = {}; // Process this array in right-to-left order so we know which // attributes (mostly from spreads) are being overwritten and // thus should have their types ignored @@ -26882,7 +25352,7 @@ var ts; var targetProperties = getPropertiesOfType(targetAttributesType); for (var i = 0; i < targetProperties.length; i++) { if (!(targetProperties[i].flags & 536870912 /* Optional */) && - !nameTable[targetProperties[i].name]) { + nameTable[targetProperties[i].name] === undefined) { error(node, ts.Diagnostics.Property_0_is_missing_in_type_1, targetProperties[i].name, typeToString(targetAttributesType)); } } @@ -26975,12 +25445,12 @@ var ts; return true; } // An instance property must be accessed through an instance of the enclosing class - if (type.flags & 268435456 /* ThisType */) { + if (type.flags & 33554432 /* ThisType */) { // get the original type -- represented as the type constraint of the 'this' type type = getConstraintOfTypeParameter(type); } // TODO: why is the first part of this check here? - if (!(getTargetType(type).flags & (32768 /* Class */ | 65536 /* Interface */) && hasBaseType(type, enclosingClass))) { + if (!(getTargetType(type).flags & (1024 /* Class */ | 2048 /* Interface */) && hasBaseType(type, enclosingClass))) { error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); return false; } @@ -26989,9 +25459,9 @@ var ts; function checkNonNullExpression(node) { var type = checkExpression(node); if (strictNullChecks) { - var kind = getFalsyFlags(type) & 6144 /* Nullable */; + var kind = getCombinedTypeFlags(type) & 96 /* Nullable */; if (kind) { - error(node, kind & 2048 /* Undefined */ ? kind & 4096 /* Null */ ? + error(node, kind & 32 /* Undefined */ ? kind & 64 /* Null */ ? ts.Diagnostics.Object_is_possibly_null_or_undefined : ts.Diagnostics.Object_is_possibly_undefined : ts.Diagnostics.Object_is_possibly_null); @@ -27012,14 +25482,14 @@ var ts; return type; } var apparentType = getApparentType(getWidenedType(type)); - if (apparentType === unknownType || (type.flags & 16384 /* TypeParameter */ && isTypeAny(apparentType))) { + if (apparentType === unknownType || (type.flags & 512 /* TypeParameter */ && isTypeAny(apparentType))) { // handle cases when type is Type parameter with invalid or any constraint return apparentType; } var prop = getPropertyOfType(apparentType, right.text); if (!prop) { if (right.text && !checkAndReportErrorForExtendingInterface(node)) { - error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type.flags & 268435456 /* ThisType */ ? apparentType : type)); + error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type.flags & 33554432 /* ThisType */ ? apparentType : type)); } return unknownType; } @@ -27038,18 +25508,15 @@ var ts; checkClassPropertyAccess(node, left, apparentType, prop); } var propType = getTypeOfSymbol(prop); - if (prop.flags & 8 /* EnumMember */ && isLiteralContextForType(node, propType)) { - propType = getDeclaredTypeOfSymbol(prop); - } // Only compute control flow type if this is a property access expression that isn't an // assignment target, and the referenced property was declared as a variable, property, // accessor, or optional method. if (node.kind !== 172 /* PropertyAccessExpression */ || ts.isAssignmentTarget(node) || !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && - !(prop.flags & 8192 /* Method */ && propType.flags & 524288 /* Union */)) { + !(prop.flags & 8192 /* Method */ && propType.flags & 16384 /* Union */)) { return propType; } - return getFlowTypeOfReference(node, propType, /*assumeInitialized*/ true, /*flowContainer*/ undefined); + return getFlowTypeOfReference(node, propType, /*assumeInitialized*/ true, /*includeOuterFunctions*/ false); } function isValidPropertyAccess(node, propertyName) { var left = node.kind === 172 /* PropertyAccessExpression */ @@ -27162,10 +25629,9 @@ var ts; } } // Check for compatible indexer types. - var allowedNullableFlags = strictNullChecks ? 0 : 6144 /* Nullable */; - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 34 /* StringLike */ | 340 /* NumberLike */ | 512 /* ESSymbol */ | allowedNullableFlags)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 258 /* StringLike */ | 132 /* NumberLike */ | 16777216 /* ESSymbol */)) { // Try to use a number indexer. - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 340 /* NumberLike */ | allowedNullableFlags) || isForInVariableForNumericPropertyNames(node.argumentExpression)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 132 /* NumberLike */) || isForInVariableForNumericPropertyNames(node.argumentExpression)) { var numberIndexInfo = getIndexInfoOfType(objectType, 1 /* Number */); if (numberIndexInfo) { getNodeLinks(node).resolvedIndexInfo = numberIndexInfo; @@ -27229,7 +25695,7 @@ var ts; return false; } // Make sure the property type is the primitive symbol type - if ((expressionType.flags & 512 /* ESSymbol */) === 0) { + if ((expressionType.flags & 16777216 /* ESSymbol */) === 0) { if (reportError) { error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); } @@ -27308,7 +25774,7 @@ var ts; lastSymbol = symbol; // specialized signatures always need to be placed before non-specialized signatures regardless // of the cutoff position; see GH#1133 - if (signature.hasLiteralTypes) { + if (signature.hasStringLiterals) { specializedIndex++; spliceIndex = specializedIndex; // The cutoff index always needs to be greater than or equal to the specialized signature index @@ -27401,7 +25867,7 @@ var ts; } // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. function getSingleCallSignature(type) { - if (type.flags & 2588672 /* ObjectType */) { + if (type.flags & 80896 /* ObjectType */) { var resolved = resolveStructuredTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -27535,7 +26001,9 @@ var ts; // If the effective argument type is 'undefined', there is no synthetic type // for the argument. In that case, we should check the argument. if (argType === undefined) { - argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + argType = arg.kind === 9 /* StringLiteral */ && !reportErrors + ? getStringLiteralTypeForText(arg.text) + : checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); } // Use argument expression as error location when reporting errors var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; @@ -27720,10 +26188,10 @@ var ts; case 69 /* Identifier */: case 8 /* NumericLiteral */: case 9 /* StringLiteral */: - return getLiteralTypeForText(32 /* StringLiteral */, element.name.text); + return getStringLiteralTypeForText(element.name.text); case 140 /* ComputedPropertyName */: var nameType = checkComputedPropertyName(element.name); - if (isTypeOfKind(nameType, 512 /* ESSymbol */)) { + if (isTypeOfKind(nameType, 16777216 /* ESSymbol */)) { return nameType; } else { @@ -28074,10 +26542,16 @@ var ts; // that the user will not add any. var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - // TS 1.0 Spec: 4.12 - // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual + // TS 1.0 spec: 4.12 + // If FuncExpr is of type Any, or of an object type that has no call or construct signatures + // but is a subtype of the Function interface, the call is an untyped function call. In an + // untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual // types are provided for the argument expressions, and the result is always of type Any. - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + // We exclude union types because we may have a union of function types that happen to have + // no common signatures. + if (isTypeAny(funcType) || + (isTypeAny(apparentType) && funcType.flags & 512 /* TypeParameter */) || + (!callSignatures.length && !constructSignatures.length && !(funcType.flags & 16384 /* Union */) && isTypeAssignableTo(funcType, globalFunctionType))) { // The unknownType indicates that an error already occurred (and was reported). No // need to report another error in this case. if (funcType !== unknownType && node.typeArguments) { @@ -28099,28 +26573,6 @@ var ts; } return resolveCall(node, callSignatures, candidatesOutArray); } - /** - * TS 1.0 spec: 4.12 - * If FuncExpr is of type Any, or of an object type that has no call or construct signatures - * but is a subtype of the Function interface, the call is an untyped function call. - */ - function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { - if (isTypeAny(funcType)) { - return true; - } - if (isTypeAny(apparentFuncType) && funcType.flags & 16384 /* TypeParameter */) { - return true; - } - if (!numCallSignatures && !numConstructSignatures) { - // We exclude union types because we may have a union of function types that happen to have - // no common signatures. - if (funcType.flags & 524288 /* Union */) { - return false; - } - return isTypeAssignableTo(funcType, globalFunctionType); - } - return false; - } function resolveNewExpression(node, candidatesOutArray) { if (node.arguments && languageVersion < 1 /* ES5 */) { var spreadIndex = getSpreadArgumentIndex(node.arguments); @@ -28198,20 +26650,8 @@ var ts; } var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); - // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected) + // A private or protected constructor can only be instantiated within it's own class if (!isNodeWithinClass(node, declaringClassDeclaration)) { - var containingClass = ts.getContainingClass(node); - if (containingClass) { - var containingType = getTypeOfNode(containingClass); - var baseTypes = getBaseTypes(containingType); - if (baseTypes.length) { - var baseType = baseTypes[0]; - if (flags & 16 /* Protected */ && - baseType.symbol === declaration.parent.symbol) { - return true; - } - } - } if (flags & 8 /* Private */) { error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); } @@ -28230,8 +26670,7 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { + if (isTypeAny(tagType) || (!callSignatures.length && !(tagType.flags & 16384 /* Union */) && isTypeAssignableTo(tagType, globalFunctionType))) { return resolveUntypedCall(node); } if (!callSignatures.length) { @@ -28268,8 +26707,7 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + if (funcType === anyType || (!callSignatures.length && !(funcType.flags & 16384 /* Union */) && isTypeAssignableTo(funcType, globalFunctionType))) { return resolveUntypedCall(node); } var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); @@ -28304,10 +26742,10 @@ var ts; // or that a different candidatesOutArray was passed in. Therefore, we need to redo the work // to correctly fill the candidatesOutArray. var cached = links.resolvedSignature; - if (cached && cached !== resolvingSignature && !candidatesOutArray) { + if (cached && cached !== anySignature && !candidatesOutArray) { return cached; } - links.resolvedSignature = resolvingSignature; + links.resolvedSignature = anySignature; var result = resolveSignature(node, candidatesOutArray); // If signature resolution originated in control flow type analysis (for example to compute the // assigned type in a flow assignment) we don't cache the result as it may be based on temporary @@ -28318,12 +26756,12 @@ var ts; function getResolvedOrAnySignature(node) { // If we're already in the process of resolving the given signature, don't resolve again as // that could cause infinite recursion. Instead, return anySignature. - return getNodeLinks(node).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(node); + return getNodeLinks(node).resolvedSignature === anySignature ? anySignature : getResolvedSignature(node); } function getInferredClassType(symbol) { var links = getSymbolLinks(symbol); if (!links.inferredClassType) { - links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined); + links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined); } return links.inferredClassType; } @@ -28392,7 +26830,7 @@ var ts; if (strictNullChecks) { var declaration = symbol.valueDeclaration; if (declaration && declaration.initializer) { - return includeFalsyTypes(type, 2048 /* Undefined */); + return addTypeKind(type, 32 /* Undefined */); } } return type; @@ -28404,12 +26842,6 @@ var ts; } function assignContextualParameterTypes(signature, context, mapper) { var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); - if (context.thisParameter) { - if (!signature.thisParameter) { - signature.thisParameter = createTransientSymbol(context.thisParameter, undefined); - } - assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter), mapper); - } for (var i = 0; i < len; i++) { var parameter = signature.parameters[i]; var contextualParameterType = getTypeAtPosition(context, i); @@ -28549,7 +26981,7 @@ var ts; } // When yield/return statements are contextually typed we allow the return type to be a union type. // Otherwise we require the yield/return expressions to have a best common supertype. - type = contextualSignature ? getUnionType(types, /*subtypeReduction*/ true) : getCommonSupertype(types); + type = contextualSignature ? getUnionType(types) : getCommonSupertype(types); if (!type) { if (funcIsGenerator) { error(func, ts.Diagnostics.No_best_common_type_exists_among_yield_expressions); @@ -28558,7 +26990,7 @@ var ts; else { error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); // Defer to unioning the return types so we get a) downstream errors earlier and b) better Salsa experience - return isAsync ? createPromiseReturnType(func, getUnionType(types, /*subtypeReduction*/ true)) : getUnionType(types, /*subtypeReduction*/ true); + return isAsync ? createPromiseReturnType(func, getUnionType(types)) : getUnionType(types); } } if (funcIsGenerator) { @@ -28592,18 +27024,24 @@ var ts; return aggregatedTypes; } function isExhaustiveSwitchStatement(node) { - if (!node.possiblyExhaustive) { + var expr = node.expression; + if (!node.possiblyExhaustive || expr.kind !== 172 /* PropertyAccessExpression */) { return false; } - var type = checkExpression(node.expression); - if (!isUnitUnionType(type)) { + var type = checkExpression(expr.expression); + if (!(type.flags & 16384 /* Union */)) { + return false; + } + var propName = expr.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { return false; } var switchTypes = getSwitchClauseTypes(node); if (!switchTypes.length) { return false; } - return eachTypeContainedIn(type, switchTypes); + return eachTypeContainedIn(propType, switchTypes); } function functionHasImplicitReturn(func) { if (!(func.flags & 32768 /* HasImplicitReturn */)) { @@ -28667,7 +27105,7 @@ var ts; return; } // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. - if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 1024 /* Void */)) { + if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 16 /* Void */)) { return; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. @@ -28796,7 +27234,7 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 340 /* NumberLike */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 132 /* NumberLike */)) { error(operand, diagnostic); return false; } @@ -28908,22 +27346,16 @@ var ts; } function checkPrefixUnaryExpression(node) { var operandType = checkExpression(node.operand); - if (node.operator === 36 /* MinusToken */ && node.operand.kind === 8 /* NumericLiteral */ && isLiteralContextForType(node, numberType)) { - return getLiteralTypeForText(64 /* NumberLiteral */, "" + -node.operand.text); - } switch (node.operator) { case 35 /* PlusToken */: case 36 /* MinusToken */: case 50 /* TildeToken */: - if (maybeTypeOfKind(operandType, 512 /* ESSymbol */)) { + if (maybeTypeOfKind(operandType, 16777216 /* ESSymbol */)) { error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } return numberType; case 49 /* ExclamationToken */: - var facts = getTypeFacts(operandType) & (1048576 /* Truthy */ | 2097152 /* Falsy */); - return facts === 1048576 /* Truthy */ ? falseType : - facts === 2097152 /* Falsy */ ? trueType : - booleanType; + return booleanType; case 41 /* PlusPlusToken */: case 42 /* MinusMinusToken */: var ok = checkArithmeticOperandType(node.operand, getNonNullableType(operandType), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); @@ -28950,10 +27382,10 @@ var ts; if (type.flags & kind) { return true; } - if (type.flags & 1572864 /* UnionOrIntersection */) { + if (type.flags & 49152 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -28968,20 +27400,20 @@ var ts; if (type.flags & kind) { return true; } - if (type.flags & 524288 /* Union */) { + if (type.flags & 16384 /* Union */) { var types = type.types; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; if (!isTypeOfKind(t, kind)) { return false; } } return true; } - if (type.flags & 1048576 /* Intersection */) { + if (type.flags & 32768 /* Intersection */) { var types = type.types; - for (var _a = 0, types_15 = types; _a < types_15.length; _a++) { - var t = types_15[_a]; + for (var _a = 0, types_12 = types; _a < types_12.length; _a++) { + var t = types_12[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -28990,7 +27422,7 @@ var ts; return false; } function isConstEnumObjectType(type) { - return type.flags & (2588672 /* ObjectType */ | 2097152 /* Anonymous */) && type.symbol && isConstEnumSymbol(type.symbol); + return type.flags & (80896 /* ObjectType */ | 65536 /* Anonymous */) && type.symbol && isConstEnumSymbol(type.symbol); } function isConstEnumSymbol(symbol) { return (symbol.flags & 128 /* ConstEnum */) !== 0; @@ -29001,7 +27433,7 @@ var ts; // and the right operand to be of type Any or a subtype of the 'Function' interface type. // The result is always of the Boolean primitive type. // NOTE: do not raise error if leftType is unknown as related error was already reported - if (isTypeOfKind(leftType, 8190 /* Primitive */)) { + if (isTypeOfKind(leftType, 16777726 /* Primitive */)) { error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } // NOTE: do not raise error if right is unknown as related error was already reported @@ -29015,10 +27447,10 @@ var ts; // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, // and the right operand to be of type Any, an object type, or a type parameter type. // The result is always of the Boolean primitive type. - if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 34 /* StringLike */ | 340 /* NumberLike */ | 512 /* ESSymbol */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258 /* StringLike */ | 132 /* NumberLike */ | 16777216 /* ESSymbol */)) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 2588672 /* ObjectType */ | 16384 /* TypeParameter */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 80896 /* ObjectType */ | 512 /* TypeParameter */)) { error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; @@ -29089,11 +27521,8 @@ var ts; return checkDestructuringAssignment(element, type, contextualMapper); } else { - // We still need to check element expression here because we may need to set appropriate flag on the expression - // such as NodeCheckFlags.LexicalThis on "this"expression. - checkExpression(element); if (isTupleType(sourceType)) { - error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); + error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), sourceType.elementTypes.length, elements.length); } else { error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); @@ -29125,7 +27554,7 @@ var ts; // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. if (strictNullChecks && - !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 2048 /* Undefined */)) { + !(getCombinedTypeFlags(checkExpression(prop.objectAssignmentInitializer)) & 32 /* Undefined */)) { sourceType = getTypeWithFacts(sourceType, 131072 /* NEUndefined */); } checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, contextualMapper); @@ -29155,14 +27584,7 @@ var ts; return sourceType; } function isTypeEqualityComparableTo(source, target) { - return (target.flags & 6144 /* Nullable */) !== 0 || isTypeComparableTo(source, target); - } - function getBestChoiceType(type1, type2) { - var firstAssignableToSecond = isTypeAssignableTo(type1, type2); - var secondAssignableToFirst = isTypeAssignableTo(type2, type1); - return secondAssignableToFirst && !firstAssignableToSecond ? type1 : - firstAssignableToSecond && !secondAssignableToFirst ? type2 : - getUnionType([type1, type2], /*subtypeReduction*/ true); + return (target.flags & 96 /* Nullable */) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, contextualMapper) { return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, contextualMapper, node); @@ -29203,17 +27625,17 @@ var ts; // as having the primitive type Number. If one operand is the null or undefined value, // it is treated as having the type of the other operand. // The result is always of the Number primitive type. - if (leftType.flags & 6144 /* Nullable */) + if (leftType.flags & 96 /* Nullable */) leftType = rightType; - if (rightType.flags & 6144 /* Nullable */) + if (rightType.flags & 96 /* Nullable */) rightType = leftType; leftType = getNonNullableType(leftType); rightType = getNonNullableType(rightType); var suggestedOperator = void 0; // if a user tries to apply a bitwise operator to 2 boolean operands // try and return them a helpful suggestion - if ((leftType.flags & 136 /* BooleanLike */) && - (rightType.flags & 136 /* BooleanLike */) && + if ((leftType.flags & 8 /* Boolean */) && + (rightType.flags & 8 /* Boolean */) && (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator)); } @@ -29232,20 +27654,20 @@ var ts; // The binary + operator requires both operands to be of the Number primitive type or an enum type, // or at least one of the operands to be of type Any or the String primitive type. // If one operand is the null or undefined value, it is treated as having the type of the other operand. - if (leftType.flags & 6144 /* Nullable */) + if (leftType.flags & 96 /* Nullable */) leftType = rightType; - if (rightType.flags & 6144 /* Nullable */) + if (rightType.flags & 96 /* Nullable */) rightType = leftType; leftType = getNonNullableType(leftType); rightType = getNonNullableType(rightType); var resultType = void 0; - if (isTypeOfKind(leftType, 340 /* NumberLike */) && isTypeOfKind(rightType, 340 /* NumberLike */)) { + if (isTypeOfKind(leftType, 132 /* NumberLike */) && isTypeOfKind(rightType, 132 /* NumberLike */)) { // Operands of an enum type are treated as having the primitive type Number. // If both operands are of the Number primitive type, the result is of the Number primitive type. resultType = numberType; } else { - if (isTypeOfKind(leftType, 34 /* StringLike */) || isTypeOfKind(rightType, 34 /* StringLike */)) { + if (isTypeOfKind(leftType, 258 /* StringLike */) || isTypeOfKind(rightType, 258 /* StringLike */)) { // If one or both operands are of the String primitive type, the result is of the String primitive type. resultType = stringType; } @@ -29281,12 +27703,6 @@ var ts; case 31 /* ExclamationEqualsToken */: case 32 /* EqualsEqualsEqualsToken */: case 33 /* ExclamationEqualsEqualsToken */: - var leftIsUnit = isUnitUnionType(leftType); - var rightIsUnit = isUnitUnionType(rightType); - if (!leftIsUnit || !rightIsUnit) { - leftType = leftIsUnit ? getBaseTypeOfUnitType(leftType) : leftType; - rightType = rightIsUnit ? getBaseTypeOfUnitType(rightType) : rightType; - } if (!isTypeEqualityComparableTo(leftType, rightType) && !isTypeEqualityComparableTo(rightType, leftType)) { reportOperatorError(); } @@ -29296,13 +27712,9 @@ var ts; case 90 /* InKeyword */: return checkInExpression(left, right, leftType, rightType); case 51 /* AmpersandAmpersandToken */: - return getTypeFacts(leftType) & 1048576 /* Truthy */ ? - includeFalsyTypes(rightType, getFalsyFlags(strictNullChecks ? leftType : getBaseTypeOfUnitType(rightType))) : - leftType; + return strictNullChecks ? addTypeKind(rightType, getCombinedTypeFlags(leftType) & 112 /* Falsy */) : rightType; case 52 /* BarBarToken */: - return getTypeFacts(leftType) & 2097152 /* Falsy */ ? - getBestChoiceType(removeDefinitelyFalsyTypes(leftType), rightType) : - leftType; + return getUnionType([getNonNullableType(leftType), rightType]); case 56 /* EqualsToken */: checkAssignmentOperator(rightType); return getRegularTypeOfObjectLiteral(rightType); @@ -29311,8 +27723,8 @@ var ts; } // Return true if there was no error, false if there was an error. function checkForDisallowedESSymbolOperand(operator) { - var offendingSymbolOperand = maybeTypeOfKind(leftType, 512 /* ESSymbol */) ? left : - maybeTypeOfKind(rightType, 512 /* ESSymbol */) ? right : + var offendingSymbolOperand = maybeTypeOfKind(leftType, 16777216 /* ESSymbol */) ? left : + maybeTypeOfKind(rightType, 16777216 /* ESSymbol */) ? right : undefined; if (offendingSymbolOperand) { error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); @@ -29412,66 +27824,14 @@ var ts; checkExpression(node.condition); var type1 = checkExpression(node.whenTrue, contextualMapper); var type2 = checkExpression(node.whenFalse, contextualMapper); - return getBestChoiceType(type1, type2); + return getUnionType([type1, type2]); } - function typeContainsLiteralFromEnum(type, enumType) { - if (type.flags & 524288 /* Union */) { - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (t.flags & 256 /* EnumLiteral */ && t.baseType === enumType) { - return true; - } - } - } - if (type.flags & 256 /* EnumLiteral */) { - return type.baseType === enumType; - } - return false; - } - function isLiteralContextForType(node, type) { - if (isLiteralTypeLocation(node)) { - return true; - } + function checkStringLiteralExpression(node) { var contextualType = getContextualType(node); - if (contextualType) { - if (contextualType.flags & 16384 /* TypeParameter */) { - var apparentType = getApparentTypeOfTypeParameter(contextualType); - // If the type parameter is constrained to the base primitive type we're checking for, - // consider this a literal context. For example, given a type parameter 'T extends string', - // this causes us to infer string literal types for T. - if (type === apparentType) { - return true; - } - contextualType = apparentType; - } - if (type.flags & 2 /* String */) { - return maybeTypeOfKind(contextualType, 32 /* StringLiteral */); - } - if (type.flags & 4 /* Number */) { - return maybeTypeOfKind(contextualType, (64 /* NumberLiteral */ | 256 /* EnumLiteral */)); - } - if (type.flags & 8 /* Boolean */) { - return maybeTypeOfKind(contextualType, 128 /* BooleanLiteral */); - } - if (type.flags & 16 /* Enum */) { - return typeContainsLiteralFromEnum(contextualType, type); - } - } - return false; - } - function checkLiteralExpression(node) { - if (node.kind === 8 /* NumericLiteral */) { - checkGrammarNumericLiteral(node); - } - switch (node.kind) { - case 9 /* StringLiteral */: - return isLiteralContextForType(node, stringType) ? getLiteralTypeForText(32 /* StringLiteral */, node.text) : stringType; - case 8 /* NumericLiteral */: - return isLiteralContextForType(node, numberType) ? getLiteralTypeForText(64 /* NumberLiteral */, node.text) : numberType; - case 99 /* TrueKeyword */: - case 84 /* FalseKeyword */: - return isLiteralContextForType(node, booleanType) ? node.kind === 99 /* TrueKeyword */ ? trueType : falseType : booleanType; + if (contextualType && isStringLiteralUnionType(contextualType)) { + return getStringLiteralTypeForText(node.text); } + return stringType; } function checkTemplateExpression(node) { // We just want to check each expressions, but we are unconcerned with @@ -29570,6 +27930,11 @@ var ts; } return type; } + function checkNumericLiteral(node) { + // Grammar checking + checkGrammarNumericLiteral(node); + return numberType; + } function checkExpressionWorker(node, contextualMapper) { switch (node.kind) { case 69 /* Identifier */: @@ -29580,13 +27945,15 @@ var ts; return checkSuperExpression(node); case 93 /* NullKeyword */: return nullWideningType; - case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: case 99 /* TrueKeyword */: case 84 /* FalseKeyword */: - return checkLiteralExpression(node); + return booleanType; + case 8 /* NumericLiteral */: + return checkNumericLiteral(node); case 189 /* TemplateExpression */: return checkTemplateExpression(node); + case 9 /* StringLiteral */: + return checkStringLiteralExpression(node); case 11 /* NoSubstitutionTemplateLiteral */: return stringType; case 10 /* RegularExpressionLiteral */: @@ -29835,27 +28202,22 @@ var ts; checkAsyncFunctionReturnType(node); } } - if (noUnusedIdentifiers && !node.body) { + if (!node.body) { checkUnusedTypeParameters(node); } } } function checkClassForDuplicateDeclarations(node) { - var Accessor; - (function (Accessor) { - Accessor[Accessor["Getter"] = 1] = "Getter"; - Accessor[Accessor["Setter"] = 2] = "Setter"; - Accessor[Accessor["Property"] = 3] = "Property"; - })(Accessor || (Accessor = {})); - var instanceNames = ts.createMap(); - var staticNames = ts.createMap(); + var getter = 1, setter = 2, property = getter | setter; + var instanceNames = {}; + var staticNames = {}; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; if (member.kind === 148 /* Constructor */) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var param = _c[_b]; if (ts.isParameterPropertyDeclaration(param)) { - addName(instanceNames, param.name, param.name.text, 3 /* Property */); + addName(instanceNames, param.name, param.name.text, property); } } } @@ -29866,21 +28228,21 @@ var ts; if (memberName) { switch (member.kind) { case 149 /* GetAccessor */: - addName(names, member.name, memberName, 1 /* Getter */); + addName(names, member.name, memberName, getter); break; case 150 /* SetAccessor */: - addName(names, member.name, memberName, 2 /* Setter */); + addName(names, member.name, memberName, setter); break; case 145 /* PropertyDeclaration */: - addName(names, member.name, memberName, 3 /* Property */); + addName(names, member.name, memberName, property); break; } } } } function addName(names, location, name, meaning) { - var prev = names[name]; - if (prev) { + if (ts.hasProperty(names, name)) { + var prev = names[name]; if (prev & meaning) { error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); } @@ -29894,7 +28256,7 @@ var ts; } } function checkObjectTypeForDuplicateDeclarations(node) { - var names = ts.createMap(); + var names = {}; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; if (member.kind == 144 /* PropertySignature */) { @@ -29908,7 +28270,7 @@ var ts; default: continue; } - if (names[memberName]) { + if (ts.hasProperty(names, memberName)) { error(member.symbol.valueDeclaration.name, ts.Diagnostics.Duplicate_identifier_0, memberName); error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); } @@ -30075,7 +28437,12 @@ var ts; checkSignatureDeclaration(node); if (node.kind === 149 /* GetAccessor */) { if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 32768 /* HasImplicitReturn */)) { - if (!(node.flags & 65536 /* HasExplicitReturn */)) { + if (node.flags & 65536 /* HasExplicitReturn */) { + if (compilerOptions.noImplicitReturns) { + error(node.name, ts.Diagnostics.Not_all_code_paths_return_a_value); + } + } + else { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); } } @@ -30104,10 +28471,7 @@ var ts; checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type); } } - var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 149 /* GetAccessor */) { - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); - } + getTypeOfAccessors(getSymbolOfNode(node)); } if (node.parent.kind !== 171 /* ObjectLiteralExpression */) { checkSourceElement(node.body); @@ -30161,9 +28525,6 @@ var ts; checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } - if (type.flags & 16 /* Enum */ && !type.memberTypes && getNodeLinks(node).resolvedSymbol.flags & 8 /* EnumMember */) { - error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); - } } } function checkTypeQuery(node) { @@ -30471,10 +28832,10 @@ var ts; case 224 /* EnumDeclaration */: return 2097152 /* ExportType */ | 1048576 /* ExportValue */; case 229 /* ImportEqualsDeclaration */: - var result_2 = 0; + var result_1 = 0; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_2 |= getDeclarationSpaces(d); }); - return result_2; + ts.forEach(target.declarations, function (d) { result_1 |= getDeclarationSpaces(d); }); + return result_1; default: return 1048576 /* ExportValue */; } @@ -30511,7 +28872,7 @@ var ts; if (isTypeAny(promise)) { return undefined; } - if (promise.flags & 131072 /* Reference */) { + if (promise.flags & 4096 /* Reference */) { if (promise.target === tryGetGlobalPromiseType() || promise.target === getGlobalPromiseLikeType()) { return promise.typeArguments[0]; @@ -30537,7 +28898,7 @@ var ts; if (onfulfilledParameterSignatures.length === 0) { return undefined; } - return getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), /*subtypeReduction*/ true); + return getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); } function getTypeOfFirstParameterOfSignature(signature) { return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType; @@ -30555,13 +28916,13 @@ var ts; function checkAwaitedType(type, location, message) { return checkAwaitedTypeWorker(type); function checkAwaitedTypeWorker(type) { - if (type.flags & 524288 /* Union */) { + if (type.flags & 16384 /* Union */) { var types = []; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var constituentType = _a[_i]; types.push(checkAwaitedTypeWorker(constituentType)); } - return getUnionType(types, /*subtypeReduction*/ true); + return getUnionType(types); } else { var promisedType = getPromisedType(type); @@ -30783,7 +29144,7 @@ var ts; // serialize the type metadata. if (node && node.kind === 155 /* TypeReference */) { var root = getFirstIdentifier(node.typeName); - var meaning = root.parent.kind === 155 /* TypeReference */ ? 793064 /* Type */ : 1920 /* Namespace */; + var meaning = root.parent.kind === 155 /* TypeReference */ ? 793056 /* Type */ : 1536 /* Namespace */; // Resolve type so we know which symbol is referenced var rootSymbol = resolveName(root, root.text, meaning | 8388608 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); // Resolved symbol is alias @@ -30973,19 +29334,20 @@ var ts; function checkUnusedLocalsAndParameters(node) { if (node.parent.kind !== 222 /* InterfaceDeclaration */ && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { var _loop_1 = function(key) { - var local = node.locals[key]; - if (!local.isReferenced) { - if (local.valueDeclaration && local.valueDeclaration.kind === 142 /* Parameter */) { - var parameter = local.valueDeclaration; - if (compilerOptions.noUnusedParameters && - !ts.isParameterPropertyDeclaration(parameter) && - !parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(parameter)) { - error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); + if (ts.hasProperty(node.locals, key)) { + var local_1 = node.locals[key]; + if (!local_1.isReferenced) { + if (local_1.valueDeclaration && local_1.valueDeclaration.kind === 142 /* Parameter */) { + var parameter = local_1.valueDeclaration; + if (compilerOptions.noUnusedParameters && + !ts.isParameterPropertyDeclaration(parameter) && + !parameterNameStartsWithUnderscore(parameter)) { + error(local_1.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local_1.name); + } + } + else if (compilerOptions.noUnusedLocals) { + ts.forEach(local_1.declarations, function (d) { return error(d.name || d, ts.Diagnostics._0_is_declared_but_never_used, local_1.name); }); } - } - else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return error(d.name || d, ts.Diagnostics._0_is_declared_but_never_used, local.name); }); } } }; @@ -30994,9 +29356,6 @@ var ts; } } } - function parameterIsThisKeyword(parameter) { - return parameter.name && parameter.name.originalKeywordKind === 97 /* ThisKeyword */; - } function parameterNameStartsWithUnderscore(parameter) { return parameter.name && parameter.name.kind === 69 /* Identifier */ && parameter.name.text.charCodeAt(0) === 95 /* _ */; } @@ -31014,7 +29373,7 @@ var ts; for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; if (!parameter.symbol.isReferenced && parameter.flags & 8 /* Private */) { - error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_never_used, parameter.symbol.name); + error(parameter.name, ts.Diagnostics._0_is_declared_but_never_used, parameter.symbol.name); } } } @@ -31025,16 +29384,9 @@ var ts; function checkUnusedTypeParameters(node) { if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { if (node.typeParameters) { - // Only report errors on the last declaration for the type parameter container; - // this ensures that all uses have been accounted for. - var symbol = getSymbolOfNode(node); - var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations); - if (lastDeclaration !== node) { - return; - } for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { var typeParameter = _a[_i]; - if (!getMergedSymbol(typeParameter.symbol).isReferenced) { + if (!typeParameter.symbol.isReferenced) { error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name); } } @@ -31044,12 +29396,14 @@ var ts; function checkUnusedModuleMembers(node) { if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { for (var key in node.locals) { - var local = node.locals[key]; - if (!local.isReferenced && !local.exportSymbol) { - for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (!ts.isAmbientModule(declaration)) { - error(declaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); + if (ts.hasProperty(node.locals, key)) { + var local = node.locals[key]; + if (!local.isReferenced && !local.exportSymbol) { + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (!ts.isAmbientModule(declaration)) { + error(declaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); + } } } } @@ -31538,7 +29892,7 @@ var ts; if (varExpr.kind === 170 /* ArrayLiteralExpression */ || varExpr.kind === 171 /* ObjectLiteralExpression */) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } - else if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 34 /* StringLike */)) { + else if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258 /* StringLike */)) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); } else { @@ -31549,7 +29903,7 @@ var ts; var rightType = checkNonNullExpression(node.expression); // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved // in this case error about missing name is already reported - do not report extra one - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 2588672 /* ObjectType */ | 16384 /* TypeParameter */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 80896 /* ObjectType */ | 512 /* TypeParameter */)) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); } checkSourceElement(node.statement); @@ -31631,7 +29985,7 @@ var ts; if (!typeAsIterable.iterableElementType) { // As an optimization, if the type is instantiated directly using the globalIterableType (Iterable), // then just grab its type argument. - if ((type.flags & 131072 /* Reference */) && type.target === getGlobalIterableType()) { + if ((type.flags & 4096 /* Reference */) && type.target === getGlobalIterableType()) { typeAsIterable.iterableElementType = type.typeArguments[0]; } else { @@ -31646,7 +30000,7 @@ var ts; } return undefined; } - typeAsIterable.iterableElementType = getElementTypeOfIterator(getUnionType(ts.map(iteratorFunctionSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true), errorNode); + typeAsIterable.iterableElementType = getElementTypeOfIterator(getUnionType(ts.map(iteratorFunctionSignatures, getReturnTypeOfSignature)), errorNode); } } return typeAsIterable.iterableElementType; @@ -31672,7 +30026,7 @@ var ts; if (!typeAsIterator.iteratorElementType) { // As an optimization, if the type is instantiated directly using the globalIteratorType (Iterator), // then just grab its type argument. - if ((type.flags & 131072 /* Reference */) && type.target === getGlobalIteratorType()) { + if ((type.flags & 4096 /* Reference */) && type.target === getGlobalIteratorType()) { typeAsIterator.iteratorElementType = type.typeArguments[0]; } else { @@ -31687,7 +30041,7 @@ var ts; } return undefined; } - var iteratorNextResult = getUnionType(ts.map(iteratorNextFunctionSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); + var iteratorNextResult = getUnionType(ts.map(iteratorNextFunctionSignatures, getReturnTypeOfSignature)); if (isTypeAny(iteratorNextResult)) { return undefined; } @@ -31709,7 +30063,7 @@ var ts; } // As an optimization, if the type is instantiated directly using the globalIterableIteratorType (IterableIterator), // then just grab its type argument. - if ((type.flags & 131072 /* Reference */) && type.target === getGlobalIterableIteratorType()) { + if ((type.flags & 4096 /* Reference */) && type.target === getGlobalIterableIteratorType()) { return type.typeArguments[0]; } return getElementTypeOfIterable(type, /*errorNode*/ undefined) || @@ -31737,10 +30091,10 @@ var ts; // After we remove all types that are StringLike, we will know if there was a string constituent // based on whether the remaining type is the same as the initial type. var arrayType = arrayOrStringType; - if (arrayOrStringType.flags & 524288 /* Union */) { - arrayType = getUnionType(ts.filter(arrayOrStringType.types, function (t) { return !(t.flags & 34 /* StringLike */); }), /*subtypeReduction*/ true); + if (arrayOrStringType.flags & 16384 /* Union */) { + arrayType = getUnionType(ts.filter(arrayOrStringType.types, function (t) { return !(t.flags & 258 /* StringLike */); })); } - else if (arrayOrStringType.flags & 34 /* StringLike */) { + else if (arrayOrStringType.flags & 258 /* StringLike */) { arrayType = neverType; } var hasStringConstituent = arrayOrStringType !== arrayType; @@ -31772,10 +30126,10 @@ var ts; var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */) || unknownType; if (hasStringConstituent) { // This is just an optimization for the case where arrayOrStringType is string | string[] - if (arrayElementType.flags & 34 /* StringLike */) { + if (arrayElementType.flags & 258 /* StringLike */) { return stringType; } - return getUnionType([arrayElementType, stringType], /*subtypeReduction*/ true); + return getUnionType([arrayElementType, stringType]); } return arrayElementType; } @@ -31789,7 +30143,7 @@ var ts; } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { var unwrappedReturnType = ts.isAsyncFunctionLike(func) ? getPromisedType(returnType) : returnType; - return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 1024 /* Void */ | 1 /* Any */); + return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16 /* Void */ | 1 /* Any */); } function checkReturnStatement(node) { // Grammar checking @@ -31941,7 +30295,7 @@ var ts; else { var identifierName = catchClause.variableDeclaration.name.text; var locals = catchClause.block.locals; - if (locals) { + if (locals && ts.hasProperty(locals, identifierName)) { var localSymbol = locals[identifierName]; if (localSymbol && (localSymbol.flags & 2 /* BlockScopedVariable */) !== 0) { grammarErrorOnNode(localSymbol.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, identifierName); @@ -31966,7 +30320,7 @@ var ts; checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); }); - if (type.flags & 32768 /* Class */ && ts.isClassLike(type.symbol.valueDeclaration)) { + if (type.flags & 1024 /* Class */ && ts.isClassLike(type.symbol.valueDeclaration)) { var classDeclaration = type.symbol.valueDeclaration; for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; @@ -31985,7 +30339,7 @@ var ts; if (stringIndexType && numberIndexType) { errorNode = declaredNumberIndexer || declaredStringIndexer; // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer - if (!errorNode && (type.flags & 65536 /* Interface */)) { + if (!errorNode && (type.flags & 2048 /* Interface */)) { var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); }); errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; } @@ -32010,7 +30364,7 @@ var ts; else if (indexDeclaration) { errorNode = indexDeclaration; } - else if (containingType.flags & 65536 /* Interface */) { + else if (containingType.flags & 2048 /* Interface */) { // for interfaces property and indexer might be inherited from different bases // check if any base class already has both property and indexer. // check should be performed only if 'type' is the first type that brings property\indexer together @@ -32125,11 +30479,6 @@ var ts; } checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); - if (baseType_1.symbol.valueDeclaration && !ts.isInAmbientContext(baseType_1.symbol.valueDeclaration)) { - if (!isBlockScopedNameDeclaredBeforeUse(baseType_1.symbol.valueDeclaration, node)) { - error(baseTypeNode, ts.Diagnostics.A_class_must_be_declared_after_its_base_class); - } - } if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */)) { // When the static base type is a "class-like" constructor function (but not actually a class), we verify // that all instantiated base constructor signatures return the same type. We can simply compare the type @@ -32147,15 +30496,15 @@ var ts; if (implementedTypeNodes) { for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { var typeRefNode = implementedTypeNodes_1[_b]; - if (!ts.isEntityNameExpression(typeRefNode.expression)) { + if (!ts.isSupportedExpressionWithTypeArguments(typeRefNode)) { error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); } checkTypeReferenceNode(typeRefNode); if (produceDiagnostics) { var t = getTypeFromTypeNode(typeRefNode); if (t !== unknownType) { - var declaredType = (t.flags & 131072 /* Reference */) ? t.target : t; - if (declaredType.flags & (32768 /* Class */ | 65536 /* Interface */)) { + var declaredType = (t.flags & 4096 /* Reference */) ? t.target : t; + if (declaredType.flags & (1024 /* Class */ | 2048 /* Interface */)) { checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_implements_interface_1); } else { @@ -32309,7 +30658,7 @@ var ts; if (baseTypes.length < 2) { return true; } - var seen = ts.createMap(); + var seen = {}; ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen[p.name] = { prop: p, containingType: type }; }); var ok = true; for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { @@ -32317,11 +30666,11 @@ var ts; var properties = getPropertiesOfObjectType(getTypeWithThisArgument(base, type.thisType)); for (var _a = 0, properties_4 = properties; _a < properties_4.length; _a++) { var prop = properties_4[_a]; - var existing = seen[prop.name]; - if (!existing) { + if (!ts.hasProperty(seen, prop.name)) { seen[prop.name] = { prop: prop, containingType: base }; } else { + var existing = seen[prop.name]; var isInheritedProperty = existing.containingType !== type; if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) { ok = false; @@ -32362,7 +30711,7 @@ var ts; checkObjectTypeForDuplicateDeclarations(node); } ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) { - if (!ts.isEntityNameExpression(heritageElement.expression)) { + if (!ts.isSupportedExpressionWithTypeArguments(heritageElement)) { error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); } checkTypeReferenceNode(heritageElement); @@ -32370,7 +30719,7 @@ var ts; ts.forEach(node.members, checkSourceElement); if (produceDiagnostics) { checkTypeForDuplicateIndexSignatures(node); - registerForUnusedIdentifiersCheck(node); + checkUnusedTypeParameters(node); } } function checkTypeAliasDeclaration(node) { @@ -32723,6 +31072,10 @@ var ts; } } } + if (compilerOptions.noImplicitAny && !node.body) { + // Ambient shorthand module is an implicit any + reportImplicitAnyError(node, anyType); + } if (node.body) { checkSourceElement(node.body); if (!ts.isGlobalScopeAugmentation(node)) { @@ -32784,20 +31137,19 @@ var ts; } } function getFirstIdentifier(node) { - switch (node.kind) { - case 69 /* Identifier */: - return node; - case 139 /* QualifiedName */: - do { - node = node.left; - } while (node.kind !== 69 /* Identifier */); - return node; - case 172 /* PropertyAccessExpression */: - do { - node = node.expression; - } while (node.kind !== 69 /* Identifier */); - return node; + while (true) { + if (node.kind === 139 /* QualifiedName */) { + node = node.left; + } + else if (node.kind === 172 /* PropertyAccessExpression */) { + node = node.expression; + } + else { + break; + } } + ts.Debug.assert(node.kind === 69 /* Identifier */); + return node; } function checkExternalImportOrExportDeclaration(node) { var moduleName = ts.getExternalModuleName(node); @@ -32837,8 +31189,8 @@ var ts; // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). var excludedMeanings = (symbol.flags & (107455 /* Value */ | 1048576 /* ExportValue */) ? 107455 /* Value */ : 0) | - (symbol.flags & 793064 /* Type */ ? 793064 /* Type */ : 0) | - (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); + (symbol.flags & 793056 /* Type */ ? 793056 /* Type */ : 0) | + (symbol.flags & 1536 /* Namespace */ ? 1536 /* Namespace */ : 0); if (target.flags & excludedMeanings) { var message = node.kind === 238 /* ExportSpecifier */ ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : @@ -32895,11 +31247,11 @@ var ts; if (target.flags & 107455 /* Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 107455 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { + if (!(resolveEntityName(moduleName, 107455 /* Value */ | 1536 /* Namespace */).flags & 1536 /* Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 793064 /* Type */) { + if (target.flags & 793056 /* Type */) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -32949,7 +31301,7 @@ var ts; if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) - var symbol = resolveName(exportedName, exportedName.text, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */, + var symbol = resolveName(exportedName, exportedName.text, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, exportedName.text); @@ -33019,7 +31371,7 @@ var ts; var _a = exports[id], declarations = _a.declarations, flags = _a.flags; // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries. // (TS Exceptions: namespaces, function overloads, enums, and interfaces) - if (flags & (1920 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) { + if (flags & (1536 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) { continue; } var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverload); @@ -33202,10 +31554,9 @@ var ts; } } function checkSourceFile(node) { - ts.performance.mark("beforeCheck"); + var start = new Date().getTime(); checkSourceFileWorker(node); - ts.performance.mark("afterCheck"); - ts.performance.measure("Check", "beforeCheck", "afterCheck"); + ts.checkTime += new Date().getTime() - start; } // Fully type check a source file and collect the relevant diagnostics. function checkSourceFileWorker(node) { @@ -33285,7 +31636,7 @@ var ts; return false; } function getSymbolsInScope(location, meaning) { - var symbols = ts.createMap(); + var symbols = {}; var memberFlags = 0; if (isInsideWithStatementBody(location)) { // We cannot answer semantic questions within a with block, do not proceed any further @@ -33323,7 +31674,7 @@ var ts; // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. // Note: that the memberFlags come from previous iteration. if (!(memberFlags & 32 /* Static */)) { - copySymbols(getSymbolOfNode(location).members, meaning & 793064 /* Type */); + copySymbols(getSymbolOfNode(location).members, meaning & 793056 /* Type */); } break; case 179 /* FunctionExpression */: @@ -33354,7 +31705,7 @@ var ts; // We will copy all symbol regardless of its reserved name because // symbolsToArray will check whether the key is a reserved name and // it will not copy symbol with reserved name to the array - if (!symbols[id]) { + if (!ts.hasProperty(symbols, id)) { symbols[id] = symbol; } } @@ -33443,15 +31794,17 @@ var ts; default: } } - if (entityName.parent.kind === 235 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { + if (entityName.parent.kind === 235 /* ExportAssignment */) { return resolveEntityName(entityName, - /*all meanings*/ 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */); + /*all meanings*/ 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */); } - if (entityName.kind !== 172 /* PropertyAccessExpression */ && isInRightSideOfImportOrExportAssignment(entityName)) { - // Since we already checked for ExportAssignment, this really could only be an Import - var importEqualsDeclaration = ts.getAncestor(entityName, 229 /* ImportEqualsDeclaration */); - ts.Debug.assert(importEqualsDeclaration !== undefined); - return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importEqualsDeclaration, /*dontResolveAlias*/ true); + if (entityName.kind !== 172 /* PropertyAccessExpression */) { + if (isInRightSideOfImportOrExportAssignment(entityName)) { + // Since we already checked for ExportAssignment, this really could only be an Import + var importEqualsDeclaration = ts.getAncestor(entityName, 229 /* ImportEqualsDeclaration */); + ts.Debug.assert(importEqualsDeclaration !== undefined); + return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importEqualsDeclaration, /*dontResolveAlias*/ true); + } } if (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; @@ -33460,14 +31813,14 @@ var ts; var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. if (entityName.parent.kind === 194 /* ExpressionWithTypeArguments */) { - meaning = 793064 /* Type */; + meaning = 793056 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { meaning |= 107455 /* Value */; } } else { - meaning = 1920 /* Namespace */; + meaning = 1536 /* Namespace */; } meaning |= 8388608 /* Alias */; return resolveEntityName(entityName, meaning); @@ -33499,7 +31852,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = (entityName.parent.kind === 155 /* TypeReference */ || entityName.parent.kind === 267 /* JSDocTypeReference */) ? 793064 /* Type */ : 1920 /* Namespace */; + var meaning = (entityName.parent.kind === 155 /* TypeReference */ || entityName.parent.kind === 267 /* JSDocTypeReference */) ? 793056 /* Type */ : 1536 /* Namespace */; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.parent.kind === 246 /* JsxAttribute */) { @@ -33603,7 +31956,7 @@ var ts; function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */); + resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */); } function getTypeOfNode(node) { if (isInsideWithStatementBody(node)) { @@ -33717,7 +32070,7 @@ var ts; var propsByName = createSymbolTable(getPropertiesOfType(type)); if (getSignaturesOfType(type, 0 /* Call */).length || getSignaturesOfType(type, 1 /* Construct */).length) { ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { - if (!propsByName[p.name]) { + if (!ts.hasProperty(propsByName, p.name)) { propsByName[p.name] = p; } }); @@ -33754,8 +32107,8 @@ var ts; } function moduleExportsSomeValue(moduleReferenceExpression) { var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); - if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { - // If the module is not found or is shorthand, assume that it may export a value. + if (!moduleSymbol) { + // module not found - be conservative return true; } var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol); @@ -33768,7 +32121,7 @@ var ts; // otherwise - check if at least one export is value symbolLinks.exportsSomeValue = hasExportAssignment ? !!(moduleSymbol.flags & 107455 /* Value */) - : ts.forEachProperty(getExportsOfModule(moduleSymbol), isValue); + : ts.forEachValue(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { @@ -33956,7 +32309,7 @@ var ts; return undefined; } function isFunctionType(type) { - return type.flags & 2588672 /* ObjectType */ && getSignaturesOfType(type, 0 /* Call */).length > 0; + return type.flags & 80896 /* ObjectType */ && getSignaturesOfType(type, 0 /* Call */).length > 0; } function getTypeReferenceSerializationKind(typeName) { // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. @@ -33966,7 +32319,7 @@ var ts; return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue; } // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. - var typeSymbol = resolveEntityName(typeName, 793064 /* Type */, /*ignoreErrors*/ true); + var typeSymbol = resolveEntityName(typeName, 793056 /* Type */, /*ignoreErrors*/ true); // We might not be able to resolve type symbol so use unknown type in that case (eg error case) if (!typeSymbol) { return ts.TypeReferenceSerializationKind.ObjectType; @@ -33978,22 +32331,22 @@ var ts; else if (type.flags & 1 /* Any */) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (isTypeOfKind(type, 1024 /* Void */)) { + else if (isTypeOfKind(type, 16 /* Void */)) { return ts.TypeReferenceSerializationKind.VoidType; } - else if (isTypeOfKind(type, 136 /* BooleanLike */)) { + else if (isTypeOfKind(type, 8 /* Boolean */)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeOfKind(type, 340 /* NumberLike */)) { + else if (isTypeOfKind(type, 132 /* NumberLike */)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (isTypeOfKind(type, 34 /* StringLike */)) { + else if (isTypeOfKind(type, 258 /* StringLike */)) { return ts.TypeReferenceSerializationKind.StringLikeType; } - else if (isTupleType(type)) { + else if (isTypeOfKind(type, 8192 /* Tuple */)) { return ts.TypeReferenceSerializationKind.ArrayLikeType; } - else if (isTypeOfKind(type, 512 /* ESSymbol */)) { + else if (isTypeOfKind(type, 16777216 /* ESSymbol */)) { return ts.TypeReferenceSerializationKind.ESSymbolType; } else if (isFunctionType(type)) { @@ -34029,7 +32382,7 @@ var ts; getSymbolDisplayBuilder().buildTypeDisplay(baseType, writer, enclosingDeclaration, flags); } function hasGlobalName(name) { - return !!globals[name]; + return ts.hasProperty(globals, name); } function getReferencedValueSymbol(reference) { return getNodeLinks(reference).resolvedSymbol || @@ -34050,14 +32403,14 @@ var ts; // populate reverse mapping: file path -> type reference directive that was resolved to this file fileToDirective = ts.createFileMap(); for (var key in resolvedTypeReferenceDirectives) { + if (!ts.hasProperty(resolvedTypeReferenceDirectives, key)) { + continue; + } var resolvedDirective = resolvedTypeReferenceDirectives[key]; if (!resolvedDirective) { continue; } var file = host.getSourceFile(resolvedDirective.resolvedFileName); - if (!file) { - continue; - } fileToDirective.set(file.path, key); } } @@ -34101,7 +32454,7 @@ var ts; // identifiers are treated as values only if they appear in type queries var meaning = (node.kind === 172 /* PropertyAccessExpression */) || (node.kind === 69 /* Identifier */ && isInTypeQuery(node)) ? 107455 /* Value */ | 1048576 /* ExportValue */ - : 793064 /* Type */ | 1920 /* Namespace */; + : 793056 /* Type */ | 1536 /* Namespace */; var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; } @@ -34186,13 +32539,7 @@ var ts; (augmentations || (augmentations = [])).push(file.moduleAugmentations); } if (file.symbol && file.symbol.globalExports) { - // Merge in UMD exports with first-in-wins semantics (see #9771) - var source = file.symbol.globalExports; - for (var id in source) { - if (!(id in globals)) { - globals[id] = source[id]; - } - } + mergeSymbolTable(globals, file.symbol.globalExports); } }); if (augmentations) { @@ -34227,7 +32574,7 @@ var ts; getGlobalTypedPropertyDescriptorType = ts.memoize(function () { return getGlobalType("TypedPropertyDescriptor", /*arity*/ 1); }); getGlobalESSymbolConstructorSymbol = ts.memoize(function () { return getGlobalValueSymbol("Symbol"); }); getGlobalPromiseType = ts.memoize(function () { return getGlobalType("Promise", /*arity*/ 1); }); - tryGetGlobalPromiseType = ts.memoize(function () { return getGlobalSymbol("Promise", 793064 /* Type */, /*diagnostic*/ undefined) && getGlobalPromiseType(); }); + tryGetGlobalPromiseType = ts.memoize(function () { return getGlobalSymbol("Promise", 793056 /* Type */, /*diagnostic*/ undefined) && getGlobalPromiseType(); }); getGlobalPromiseLikeType = ts.memoize(function () { return getGlobalType("PromiseLike", /*arity*/ 1); }); getInstantiatedGlobalPromiseLikeType = ts.memoize(createInstantiatedPromiseLikeType); getGlobalPromiseConstructorSymbol = ts.memoize(function () { return getGlobalValueSymbol("Promise"); }); @@ -34247,7 +32594,7 @@ var ts; getGlobalIterableIteratorType = ts.memoize(function () { return emptyGenericType; }); } anyArrayType = createArrayType(anyType); - var symbol = getGlobalSymbol("ReadonlyArray", 793064 /* Type */, /*diagnostic*/ undefined); + var symbol = getGlobalSymbol("ReadonlyArray", 793056 /* Type */, /*diagnostic*/ undefined); globalReadonlyArrayType = symbol && getTypeOfGlobalSymbol(symbol, /*arity*/ 1); anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; } @@ -34262,7 +32609,7 @@ var ts; // build the thenable type that is used to verify against a non-promise "thenable" operand to `await`. var thenPropertySymbol = createSymbol(67108864 /* Transient */ | 4 /* Property */, "then"); getSymbolLinks(thenPropertySymbol).type = globalFunctionType; - var thenableType = createObjectType(2097152 /* Anonymous */); + var thenableType = createObjectType(65536 /* Anonymous */); thenableType.properties = [thenPropertySymbol]; thenableType.members = createSymbolTable(thenableType.properties); thenableType.callSignatures = []; @@ -34291,9 +32638,49 @@ var ts; return false; } function checkGrammarModifiers(node) { - var quickResult = reportObviousModifierErrors(node); - if (quickResult !== undefined) { - return quickResult; + switch (node.kind) { + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + case 148 /* Constructor */: + case 145 /* PropertyDeclaration */: + case 144 /* PropertySignature */: + case 147 /* MethodDeclaration */: + case 146 /* MethodSignature */: + case 153 /* IndexSignature */: + case 225 /* ModuleDeclaration */: + case 230 /* ImportDeclaration */: + case 229 /* ImportEqualsDeclaration */: + case 236 /* ExportDeclaration */: + case 235 /* ExportAssignment */: + case 179 /* FunctionExpression */: + case 180 /* ArrowFunction */: + case 142 /* Parameter */: + break; + case 220 /* FunctionDeclaration */: + if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 118 /* AsyncKeyword */) && + node.parent.kind !== 226 /* ModuleBlock */ && node.parent.kind !== 256 /* SourceFile */) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + break; + case 221 /* ClassDeclaration */: + case 222 /* InterfaceDeclaration */: + case 200 /* VariableStatement */: + case 223 /* TypeAliasDeclaration */: + if (node.modifiers && node.parent.kind !== 226 /* ModuleBlock */ && node.parent.kind !== 256 /* SourceFile */) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + break; + case 224 /* EnumDeclaration */: + if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 74 /* ConstKeyword */) && + node.parent.kind !== 226 /* ModuleBlock */ && node.parent.kind !== 256 /* SourceFile */) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + break; + default: + return false; + } + if (!node.modifiers) { + return; } var lastStatic, lastPrivate, lastProtected, lastDeclare, lastAsync, lastReadonly; var flags = 0; @@ -34487,60 +32874,6 @@ var ts; return checkGrammarAsyncModifier(node, lastAsync); } } - /** - * true | false: Early return this value from checkGrammarModifiers. - * undefined: Need to do full checking on the modifiers. - */ - function reportObviousModifierErrors(node) { - return !node.modifiers - ? false - : shouldReportBadModifier(node) - ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here) - : undefined; - } - function shouldReportBadModifier(node) { - switch (node.kind) { - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - case 148 /* Constructor */: - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - case 153 /* IndexSignature */: - case 225 /* ModuleDeclaration */: - case 230 /* ImportDeclaration */: - case 229 /* ImportEqualsDeclaration */: - case 236 /* ExportDeclaration */: - case 235 /* ExportAssignment */: - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - case 142 /* Parameter */: - return false; - default: - if (node.parent.kind === 226 /* ModuleBlock */ || node.parent.kind === 256 /* SourceFile */) { - return false; - } - switch (node.kind) { - case 220 /* FunctionDeclaration */: - return nodeHasAnyModifiersExcept(node, 118 /* AsyncKeyword */); - case 221 /* ClassDeclaration */: - return nodeHasAnyModifiersExcept(node, 115 /* AbstractKeyword */); - case 222 /* InterfaceDeclaration */: - case 200 /* VariableStatement */: - case 223 /* TypeAliasDeclaration */: - return true; - case 224 /* EnumDeclaration */: - return nodeHasAnyModifiersExcept(node, 74 /* ConstKeyword */); - default: - ts.Debug.fail(); - return false; - } - } - } - function nodeHasAnyModifiersExcept(node, allowedModifier) { - return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier; - } function checkGrammarAsyncModifier(node, asyncModifier) { if (languageVersion < 2 /* ES6 */) { return grammarErrorOnNode(asyncModifier, ts.Diagnostics.Async_functions_are_only_available_when_targeting_ECMAScript_2015_or_higher); @@ -34778,7 +33111,7 @@ var ts; } } function checkGrammarObjectLiteralExpression(node, inDestructuring) { - var seen = ts.createMap(); + var seen = {}; var Property = 1; var GetAccessor = 2; var SetAccessor = 4; @@ -34834,7 +33167,7 @@ var ts; if (effectiveName === undefined) { return "continue"; } - if (!seen[effectiveName]) { + if (!ts.hasProperty(seen, effectiveName)) { seen[effectiveName] = currentKind; } else { @@ -34862,7 +33195,7 @@ var ts; } } function checkGrammarJsxElement(node) { - var seen = ts.createMap(); + var seen = {}; for (var _i = 0, _a = node.attributes; _i < _a.length; _i++) { var attr = _a[_i]; if (attr.kind === 247 /* JsxSpreadAttribute */) { @@ -34870,7 +33203,7 @@ var ts; } var jsxAttr = attr; var name_22 = jsxAttr.name; - if (!seen[name_22.text]) { + if (!ts.hasProperty(seen, name_22.text)) { seen[name_22.text] = true; } else { @@ -35220,7 +33553,7 @@ var ts; } } function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { - // A declare modifier is required for any top level .d.ts declaration except export=, export default, export as namespace + // A declare modifier is required for any top level .d.ts declaration except export=, export default, // interfaces and imports categories: // // DeclarationElement: @@ -35238,7 +33571,6 @@ var ts; node.kind === 229 /* ImportEqualsDeclaration */ || node.kind === 236 /* ExportDeclaration */ || node.kind === 235 /* ExportAssignment */ || - node.kind === 228 /* NamespaceExportDeclaration */ || (node.flags & 2 /* Ambient */) || (node.flags & (1 /* Export */ | 512 /* Default */))) { return false; @@ -35299,15 +33631,7 @@ var ts; return true; } } - function getAmbientModules() { - var result = []; - for (var sym in globals) { - if (ambientModuleSymbolRegex.test(sym)) { - result.push(globals[sym]); - } - } - return result; - } + var _a; } ts.createTypeChecker = createTypeChecker; })(ts || (ts = {})); @@ -35344,7 +33668,6 @@ var ts; ts.getNullSourceMapWriter = getNullSourceMapWriter; function createSourceMapWriter(host, writer) { var compilerOptions = host.getCompilerOptions(); - var extendedDiagnostics = compilerOptions.extendedDiagnostics; var currentSourceFile; var sourceMapDir; // The directory in which sourcemap will be var stopOverridingSpan = false; @@ -35508,9 +33831,6 @@ var ts; if (pos === -1) { return; } - if (extendedDiagnostics) { - ts.performance.mark("beforeSourcemap"); - } var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos); // Convert the location to be one-based. sourceLinePos.line++; @@ -35543,10 +33863,6 @@ var ts; lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; } updateLastEncodedAndRecordedSpans(); - if (extendedDiagnostics) { - ts.performance.mark("afterSourcemap"); - ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); - } } function getStartPos(range) { var rangeHasDecorators = !!range.decorators; @@ -35649,11 +33965,11 @@ var ts; return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined); function getDeclarationDiagnosticsFromFile(_a, sources, isBundledEmit) { var declarationFilePath = _a.declarationFilePath; - emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit, /*emitOnlyDtsFiles*/ false); + emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit); } } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles) { + function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit) { var newLine = host.getNewLine(); var compilerOptions = host.getCompilerOptions(); var write; @@ -35700,7 +34016,7 @@ var ts; // global file reference is added only // - if it is not bundled emit (because otherwise it would be self reference) // - and it is not already added - if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference, emitOnlyDtsFiles)) { + if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference)) { addedGlobalFileReference = true; } emittedReferencedFiles.push(referencedFile); @@ -35754,7 +34070,9 @@ var ts; }); if (usedTypeDirectiveReferences) { for (var directive in usedTypeDirectiveReferences) { - referencesOutput += "/// " + newLine; + if (ts.hasProperty(usedTypeDirectiveReferences, directive)) { + referencesOutput += "/// " + newLine; + } } } return { @@ -35852,11 +34170,11 @@ var ts; return; } if (!usedTypeDirectiveReferences) { - usedTypeDirectiveReferences = ts.createMap(); + usedTypeDirectiveReferences = {}; } for (var _i = 0, typeReferenceDirectives_1 = typeReferenceDirectives; _i < typeReferenceDirectives_1.length; _i++) { var directive = typeReferenceDirectives_1[_i]; - if (!(directive in usedTypeDirectiveReferences)) { + if (!ts.hasProperty(usedTypeDirectiveReferences, directive)) { usedTypeDirectiveReferences[directive] = directive; } } @@ -35901,7 +34219,7 @@ var ts; } else { errorNameNode = declaration.name; - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); + resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); errorNameNode = undefined; } } @@ -35914,7 +34232,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); errorNameNode = undefined; } } @@ -35964,7 +34282,7 @@ var ts; case 93 /* NullKeyword */: case 127 /* NeverKeyword */: case 165 /* ThisType */: - case 166 /* LiteralType */: + case 166 /* StringLiteralType */: return writeTextOfNode(currentText, type); case 194 /* ExpressionWithTypeArguments */: return emitExpressionWithTypeArguments(type); @@ -36015,7 +34333,7 @@ var ts; writeEntityName(entityName); } function emitExpressionWithTypeArguments(node) { - if (ts.isEntityNameExpression(node.expression)) { + if (ts.isSupportedExpressionWithTypeArguments(node)) { ts.Debug.assert(node.expression.kind === 69 /* Identifier */ || node.expression.kind === 172 /* PropertyAccessExpression */); emitEntityName(node.expression); if (node.typeArguments) { @@ -36089,14 +34407,14 @@ var ts; // do not need to keep track of created temp names. function getExportDefaultTempVariableName() { var baseName = "_default"; - if (!(baseName in currentIdentifiers)) { + if (!ts.hasProperty(currentIdentifiers, baseName)) { return baseName; } var count = 0; while (true) { count++; var name_23 = baseName + "_" + count; - if (!(name_23 in currentIdentifiers)) { + if (!ts.hasProperty(currentIdentifiers, name_23)) { return name_23; } } @@ -36116,7 +34434,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); + resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); write(";"); writeLine(); write(node.isExportEquals ? "export = " : "export default "); @@ -36529,7 +34847,7 @@ var ts; emitCommaList(typeReferences, emitTypeOfTypeReference); } function emitTypeOfTypeReference(node) { - if (ts.isEntityNameExpression(node.expression)) { + if (ts.isSupportedExpressionWithTypeArguments(node)) { emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError); } else if (!isImplementsList && node.expression.kind === 93 /* NullKeyword */) { @@ -36537,7 +34855,7 @@ var ts; } else { writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); + resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); } function getHeritageClauseVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; @@ -36635,10 +34953,8 @@ var ts; // it if it's not a well known symbol. In that case, the text of the name will be exactly // what we want, namely the name expression enclosed in brackets. writeTextOfNode(currentText, node.name); - // If optional property emit ? but in the case of parameterProperty declaration with "?" indicating optional parameter for the constructor - // we don't want to emit property declaration with "?" - if ((node.kind === 145 /* PropertyDeclaration */ || node.kind === 144 /* PropertySignature */ || - (node.kind === 142 /* Parameter */ && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { + // If optional property emit ? + if ((node.kind === 145 /* PropertyDeclaration */ || node.kind === 144 /* PropertySignature */ || node.kind === 142 /* Parameter */) && ts.hasQuestionToken(node)) { write("?"); } if ((node.kind === 145 /* PropertyDeclaration */ || node.kind === 144 /* PropertySignature */) && node.parent.kind === 159 /* TypeLiteral */) { @@ -37174,7 +35490,7 @@ var ts; * @param referencedFile * @param addBundledFileReference Determines if global file reference corresponding to bundled file should be emitted or not */ - function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { + function writeReferencePath(referencedFile, addBundledFileReference) { var declFileName; var addedBundledEmitReference = false; if (ts.isDeclarationFile(referencedFile)) { @@ -37183,7 +35499,7 @@ var ts; } else { // Get the declaration file path - ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile, emitOnlyDtsFiles); + ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile); } if (declFileName) { declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, @@ -37203,8 +35519,8 @@ var ts; } } /* @internal */ - function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) { - var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles); + function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) { + var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit); var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; if (!emitSkipped) { var declarationOutput = emitDeclarationResult.referencesOutput @@ -37253,7 +35569,7 @@ var ts; Jump[Jump["Continue"] = 4] = "Continue"; Jump[Jump["Return"] = 8] = "Return"; })(Jump || (Jump = {})); - var entities = ts.createMap({ + var entities = { "quot": 0x0022, "amp": 0x0026, "apos": 0x0027, @@ -37507,7 +35823,7 @@ var ts; "clubs": 0x2663, "hearts": 0x2665, "diams": 0x2666 - }); + }; // Flags enum to track count of temp variables and a few dedicated names var TempFlags; (function (TempFlags) { @@ -37521,7 +35837,7 @@ var ts; CopyDirection[CopyDirection["ToOutParameter"] = 1] = "ToOutParameter"; })(CopyDirection || (CopyDirection = {})); // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature - function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles) { + function emitFiles(resolver, host, targetSourceFile) { // emit output for the __extends helper function var extendsHelper = "\nvar __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n};"; var assignHelper = "\nvar __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n};"; @@ -37541,7 +35857,7 @@ var ts; var emitSkipped = false; var newLine = host.getNewLine(); var emitJavaScript = createFileEmitter(); - ts.forEachExpectedEmitFile(host, emitFile, targetSourceFile, emitOnlyDtsFiles); + ts.forEachExpectedEmitFile(host, emitFile, targetSourceFile); return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -37550,7 +35866,7 @@ var ts; }; function isUniqueLocalName(name, container) { for (var node = container; ts.isNodeDescendentOf(node, container); node = node.nextContainer) { - if (node.locals && name in node.locals) { + if (node.locals && ts.hasProperty(node.locals, name)) { // We conservatively include alias symbols to cover cases where they're emitted as locals if (node.locals[name].flags & (107455 /* Value */ | 1048576 /* ExportValue */ | 8388608 /* Alias */)) { return false; @@ -37562,13 +35878,13 @@ var ts; function setLabeledJump(state, isBreak, labelText, labelMarker) { if (isBreak) { if (!state.labeledNonLocalBreaks) { - state.labeledNonLocalBreaks = ts.createMap(); + state.labeledNonLocalBreaks = {}; } state.labeledNonLocalBreaks[labelText] = labelMarker; } else { if (!state.labeledNonLocalContinues) { - state.labeledNonLocalContinues = ts.createMap(); + state.labeledNonLocalContinues = {}; } state.labeledNonLocalContinues[labelText] = labelMarker; } @@ -37635,26 +35951,26 @@ var ts; /** If removeComments is true, no leading-comments needed to be emitted **/ var emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos) { } : emitLeadingCommentsOfPositionWorker; var setSourceMapWriterEmit = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? changeSourceMapEmit : function (writer) { }; - var moduleEmitDelegates = ts.createMap((_a = {}, + var moduleEmitDelegates = (_a = {}, _a[ts.ModuleKind.ES6] = emitES6Module, _a[ts.ModuleKind.AMD] = emitAMDModule, _a[ts.ModuleKind.System] = emitSystemModule, _a[ts.ModuleKind.UMD] = emitUMDModule, _a[ts.ModuleKind.CommonJS] = emitCommonJSModule, _a - )); - var bundleEmitDelegates = ts.createMap((_b = {}, + ); + var bundleEmitDelegates = (_b = {}, _b[ts.ModuleKind.ES6] = function () { }, _b[ts.ModuleKind.AMD] = emitAMDModule, _b[ts.ModuleKind.System] = emitSystemModule, _b[ts.ModuleKind.UMD] = function () { }, _b[ts.ModuleKind.CommonJS] = function () { }, _b - )); + ); return doEmit; function doEmit(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit) { sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); - generatedNameSet = ts.createMap(); + generatedNameSet = {}; nodeToGeneratedName = []; decoratedClassAliases = []; isOwnFileEmit = !isBundledEmit; @@ -37667,7 +35983,7 @@ var ts; writeLine(); var sourceMappingURL = sourceMap.getSourceMappingURL(); if (sourceMappingURL) { - write("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Sometimes tools can sometimes see this line as a source mapping url comment + write("//# sourceMappingURL=" + sourceMappingURL); } writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, /*writeByteOrderMark*/ compilerOptions.emitBOM, sourceFiles); // reset the state @@ -37716,8 +36032,8 @@ var ts; } function isUniqueName(name) { return !resolver.hasGlobalName(name) && - !(name in currentFileIdentifiers) && - !(name in generatedNameSet); + !ts.hasProperty(currentFileIdentifiers, name) && + !ts.hasProperty(generatedNameSet, name); } // Return the next available name in the pattern _a ... _z, _0, _1, ... // TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name. @@ -38743,10 +37059,6 @@ var ts; else if (node.parent.kind === 188 /* ConditionalExpression */ && node.parent.condition === node) { return true; } - else if (node.parent.kind === 185 /* PrefixUnaryExpression */ || node.parent.kind === 181 /* DeleteExpression */ || - node.parent.kind === 182 /* TypeOfExpression */ || node.parent.kind === 183 /* VoidExpression */) { - return true; - } return false; } function needsParenthesisForPropertyAccessOrInvocation(node) { @@ -39420,7 +37732,7 @@ var ts; operand.kind === 196 /* NonNullExpression */) { operand = operand.expression; } - // We have an expression of the form: (SubExpr) or (SubExpr as Type) + // We have an expression of the form: (SubExpr) // Emitting this as (SubExpr) is really not desirable. We would like to emit the subexpr as is. // Omitting the parentheses, however, could cause change in the semantics of the generated // code if the casted expression has a lower precedence than the rest of the expression, e.g.: @@ -39434,7 +37746,6 @@ var ts; operand.kind !== 181 /* DeleteExpression */ && operand.kind !== 186 /* PostfixUnaryExpression */ && operand.kind !== 175 /* NewExpression */ && - !(operand.kind === 187 /* BinaryExpression */ && node.expression.kind === 195 /* AsExpression */) && !(operand.kind === 174 /* CallExpression */ && node.parent.kind === 175 /* NewExpression */) && !(operand.kind === 179 /* FunctionExpression */ && node.parent.kind === 174 /* CallExpression */) && !(operand.kind === 8 /* NumericLiteral */ && node.parent.kind === 172 /* PropertyAccessExpression */)) { @@ -39476,7 +37787,7 @@ var ts; if (modulekind === ts.ModuleKind.System || node.kind !== 69 /* Identifier */ || ts.nodeIsSynthesized(node)) { return false; } - return !exportEquals && exportSpecifiers && node.text in exportSpecifiers; + return !exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, node.text); } function emitPrefixUnaryExpression(node) { var isPlusPlusOrMinusMinus = (node.operator === 41 /* PlusPlusToken */ @@ -39569,7 +37880,7 @@ var ts; * if we should also export the value after its it changed * - check if node is a source level declaration to emit it differently, * i.e non-exported variable statement 'var x = 1' is hoisted so - * when we emit variable statement 'var' should be dropped. + * we we emit variable statement 'var' should be dropped. */ function isSourceFileLevelDeclarationInSystemJsModule(node, isExported) { if (!node || !isCurrentFileSystemExternalModule()) { @@ -40021,12 +38332,12 @@ var ts; // Don't initialize seen unless we have at least one element. // Emit a comma to separate for all but the first element. if (!seen) { - seen = ts.createMap(); + seen = {}; } else { write(", "); } - if (!(id.text in seen)) { + if (!ts.hasProperty(seen, id.text)) { emit(id); seen[id.text] = id.text; } @@ -40550,7 +38861,7 @@ var ts; } if (convertedLoopState) { if (!convertedLoopState.labels) { - convertedLoopState.labels = ts.createMap(); + convertedLoopState.labels = {}; } convertedLoopState.labels[node.label.text] = node.label.text; } @@ -40653,7 +38964,7 @@ var ts; if (modulekind === ts.ModuleKind.System) { return; } - if (!exportEquals && exportSpecifiers && name.text in exportSpecifiers) { + if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { for (var _a = 0, _b = exportSpecifiers[name.text]; _a < _b.length; _a++) { var specifier = _b[_a]; writeLine(); @@ -41191,13 +39502,12 @@ var ts; } function emitRestParameter(node) { if (languageVersion < 2 /* ES6 */ && ts.hasDeclaredRestParameter(node)) { - var restParam = node.parameters[node.parameters.length - 1]; + var restIndex = node.parameters.length - 1; + var restParam = node.parameters[restIndex]; // A rest parameter cannot have a binding pattern, so let's just ignore it if it does. if (ts.isBindingPattern(restParam.name)) { return; } - var skipThisCount = node.parameters.length && node.parameters[0].name.originalKeywordKind === 97 /* ThisKeyword */ ? 1 : 0; - var restIndex = node.parameters.length - 1 - skipThisCount; var tempName = createTempVariable(268435456 /* _i */).text; writeLine(); emitLeadingComments(restParam); @@ -41332,7 +39642,7 @@ var ts; write("("); if (node) { var parameters = node.parameters; - var skipCount = node.parameters.length && node.parameters[0].name.originalKeywordKind === 97 /* ThisKeyword */ ? 1 : 0; + var skipCount = node.parameters.length && node.parameters[0].name.text === "this" ? 1 : 0; var omitCount = languageVersion < 2 /* ES6 */ && ts.hasDeclaredRestParameter(node) ? 1 : 0; emitList(parameters, skipCount, parameters.length - omitCount - skipCount, /*multiLine*/ false, /*trailingComma*/ false); } @@ -41854,22 +40164,18 @@ var ts; emitSignatureParameters(ctor); } else { - // The ES2015 spec specifies in 14.5.14. Runtime Semantics: ClassDefinitionEvaluation: - // If constructor is empty, then - // If ClassHeritag_eopt is present and protoParent is not null, then - // Let constructor be the result of parsing the source text - // constructor(...args) { super (...args);} - // using the syntactic grammar with the goal symbol MethodDefinition[~Yield]. + // Based on EcmaScript6 section 14.5.14: Runtime Semantics: ClassDefinitionEvaluation. + // If constructor is empty, then, + // If ClassHeritageopt is present, then + // Let constructor be the result of parsing the String "constructor(... args){ super (...args);}" using the syntactic grammar with the goal symbol MethodDefinition. // Else, - // Let constructor be the result of parsing the source text - // constructor( ){ } - // using the syntactic grammar with the goal symbol MethodDefinition[~Yield]. - // - // While we could emit the '...args' rest parameter, certain later tools in the pipeline might - // downlevel the '...args' portion less efficiently by naively copying the contents of 'arguments' to an array. - // Instead, we'll avoid using a rest parameter and spread into the super call as - // 'super(...arguments)' instead of 'super(...args)', as you can see below. - write("()"); + // Let constructor be the result of parsing the String "constructor( ){ }" using the syntactic grammar with the goal symbol MethodDefinition + if (baseTypeElement) { + write("(...args)"); + } + else { + write("()"); + } } } var startIndex = 0; @@ -41903,8 +40209,7 @@ var ts; write("_super.apply(this, arguments);"); } else { - // See comment above on using '...arguments' instead of '...args'. - write("super(...arguments);"); + write("super(...args);"); } emitEnd(baseTypeElement); } @@ -42042,13 +40347,13 @@ var ts; if (isES6ExportedDeclaration(node) && !(node.flags & 512 /* Default */) && decoratedClassAlias === undefined) { write("export "); } + if (!isHoistedDeclarationInSystemModule) { + write("let "); + } if (decoratedClassAlias !== undefined) { - write("let " + decoratedClassAlias); + write("" + decoratedClassAlias); } else { - if (!isHoistedDeclarationInSystemModule) { - write("let "); - } emitDeclarationName(node); } write(" = "); @@ -42063,17 +40368,11 @@ var ts; // If the class has static properties, and it's a class expression, then we'll need // to specialize the emit a bit. for a class expression of the form: // - // (class C { static a = 1; static b = 2; ... }) + // class C { static a = 1; static b = 2; ... } // // We'll emit: // - // ((C_1 = class C { - // // Normal class body - // }, - // C_1.a = 1, - // C_1.b = 2, - // C_1)); - // var C_1; + // (_temp = class C { ... }, _temp.a = 1, _temp.b = 2, _temp) // // This keeps the expression as an expression, while ensuring that the static parts // of it have been initialized by the time it is used. @@ -42081,7 +40380,7 @@ var ts; var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 192 /* ClassExpression */; var generatedName; if (isClassExpressionWithStaticProperties) { - generatedName = node.name ? getGeneratedNameForNode(node.name) : makeUniqueName("classExpression"); + generatedName = getGeneratedNameForNode(node.name); var synthesizedNode = ts.createSynthesizedNode(69 /* Identifier */); synthesizedNode.text = generatedName; recordTempDeclaration(synthesizedNode); @@ -42526,7 +40825,7 @@ var ts; write("Boolean"); return; case 132 /* StringKeyword */: - case 166 /* LiteralType */: + case 166 /* StringLiteralType */: write("String"); return; case 130 /* NumberKeyword */: @@ -42624,11 +40923,10 @@ var ts; } if (valueDeclaration) { var parameters = valueDeclaration.parameters; - var skipThisCount = parameters.length && parameters[0].name.originalKeywordKind === 97 /* ThisKeyword */ ? 1 : 0; var parameterCount = parameters.length; - if (parameterCount > skipThisCount) { - for (var i = skipThisCount; i < parameterCount; i++) { - if (i > skipThisCount) { + if (parameterCount > 0) { + for (var i = 0; i < parameterCount; i++) { + if (i > 0) { write(", "); } if (parameters[i].dotDotDotToken) { @@ -42896,7 +41194,7 @@ var ts; * Here we check if alternative name was provided for a given moduleName and return it if possible. */ function tryRenameExternalModule(moduleName) { - if (renamedDependencies && moduleName.text in renamedDependencies) { + if (renamedDependencies && ts.hasProperty(renamedDependencies, moduleName.text)) { return "\"" + renamedDependencies[moduleName.text] + "\""; } return undefined; @@ -43005,7 +41303,7 @@ var ts; // import { x, y } from "foo" // import d, * as x from "foo" // import d, { x, y } from "foo" - var isNakedImport = node.kind === 230 /* ImportDeclaration */ && !node.importClause; + var isNakedImport = 230 /* ImportDeclaration */ && !node.importClause; if (!isNakedImport) { write(varOrConst); write(getGeneratedNameForNode(node)); @@ -43216,7 +41514,7 @@ var ts; } function collectExternalModuleInfo(sourceFile) { externalImports = []; - exportSpecifiers = ts.createMap(); + exportSpecifiers = {}; exportEquals = undefined; hasExportStarsToExportValues = false; for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) { @@ -43344,7 +41642,7 @@ var ts; return undefined; } // local names set should only be added if we have anything exported - if (!exportedDeclarations && !ts.someProperties(exportSpecifiers)) { + if (!exportedDeclarations && ts.isEmpty(exportSpecifiers)) { // no exported declarations (export var ...) or export specifiers (export {x}) // check if we have any non star export declarations. var hasExportDeclarationWithExportClause = false; @@ -43467,7 +41765,7 @@ var ts; if (hoistedVars) { writeLine(); write("var "); - var seen = ts.createMap(); + var seen = {}; for (var i = 0; i < hoistedVars.length; i++) { var local = hoistedVars[i]; var name_32 = local.kind === 69 /* Identifier */ @@ -43476,7 +41774,7 @@ var ts; if (name_32) { // do not emit duplicate entries (in case of declaration merging) in the list of hoisted variables var text = ts.unescapeIdentifier(name_32.text); - if (text in seen) { + if (ts.hasProperty(seen, text)) { continue; } else { @@ -43792,7 +42090,7 @@ var ts; write("System.register("); writeModuleName(node, emitRelativePathAsModuleName); write("["); - var groupIndices = ts.createMap(); + var groupIndices = {}; var dependencyGroups = []; for (var i = 0; i < externalImports.length; i++) { var text = getExternalModuleNameText(externalImports[i], emitRelativePathAsModuleName); @@ -43802,7 +42100,7 @@ var ts; // text should be quoted string // for deduplication purposes in key remove leading and trailing quotes so 'a' and "a" will be considered the same var key = text.substr(1, text.length - 2); - if (key in groupIndices) { + if (ts.hasProperty(groupIndices, key)) { // deduplicate/group entries in dependency list by the dependency name var groupIndex = groupIndices[key]; dependencyGroups[groupIndex].push(externalImports[i]); @@ -44603,26 +42901,22 @@ var ts; } var _a, _b; } - function emitFile(_a, sourceFiles, isBundledEmit, emitOnlyDtsFiles) { + function emitFile(_a, sourceFiles, isBundledEmit) { var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath; - if (!emitOnlyDtsFiles) { - // Make sure not to write js File and source map file if any of them cannot be written - if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { - emitJavaScript(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); - } - else { - emitSkipped = true; - } + // Make sure not to write js File and source map file if any of them cannot be written + if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { + emitJavaScript(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + } + else { + emitSkipped = true; } if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; + emitSkipped = ts.writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; } if (!emitSkipped && emittedFilesList) { - if (!emitOnlyDtsFiles) { - emittedFilesList.push(jsFilePath); - if (sourceMapFilePath) { - emittedFilesList.push(sourceMapFilePath); - } + emittedFilesList.push(jsFilePath); + if (sourceMapFilePath) { + emittedFilesList.push(sourceMapFilePath); } if (declarationFilePath) { emittedFilesList.push(declarationFilePath); @@ -44637,13 +42931,17 @@ var ts; /// var ts; (function (ts) { + /* @internal */ ts.programTime = 0; + /* @internal */ ts.emitTime = 0; + /* @internal */ ts.ioReadTime = 0; + /* @internal */ ts.ioWriteTime = 0; /** The version of the TypeScript compiler release */ - ts.version = "2.0.5"; + ts.version = "2.0.0"; var emptyArray = []; - function findConfigFile(searchPath, fileExists, configName) { - if (configName === void 0) { configName = "tsconfig.json"; } + var defaultTypeRoots = ["node_modules/@types"]; + function findConfigFile(searchPath, fileExists) { while (true) { - var fileName = ts.combinePaths(searchPath, configName); + var fileName = ts.combinePaths(searchPath, "tsconfig.json"); if (fileExists(fileName)) { return fileName; } @@ -44700,8 +42998,94 @@ var ts; return ts.getNormalizedPathFromPathComponents(commonPathComponents); } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; + function trace(host, message) { + host.trace(ts.formatMessage.apply(undefined, arguments)); + } + function isTraceEnabled(compilerOptions, host) { + return compilerOptions.traceResolution && host.trace !== undefined; + } + /* @internal */ + function hasZeroOrOneAsteriskCharacter(str) { + var seenAsterisk = false; + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) === 42 /* asterisk */) { + if (!seenAsterisk) { + seenAsterisk = true; + } + else { + // have already seen asterisk + return false; + } + } + } + return true; + } + ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; + function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { + return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; + } + function moduleHasNonRelativeName(moduleName) { + if (ts.isRootedDiskPath(moduleName)) { + return false; + } + var i = moduleName.lastIndexOf("./", 1); + var startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === 46 /* dot */); + return !startsWithDotSlashOrDotDotSlash; + } + function tryReadTypesSection(packageJsonPath, baseDirectory, state) { + var jsonContent; + try { + var jsonText = state.host.readFile(packageJsonPath); + jsonContent = jsonText ? JSON.parse(jsonText) : {}; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + jsonContent = {}; + } + var typesFile; + var fieldName; + // first try to read content of 'typings' section (backward compatibility) + if (jsonContent.typings) { + if (typeof jsonContent.typings === "string") { + fieldName = "typings"; + typesFile = jsonContent.typings; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, "typings", typeof jsonContent.typings); + } + } + } + // then read 'types' + if (!typesFile && jsonContent.types) { + if (typeof jsonContent.types === "string") { + fieldName = "types"; + typesFile = jsonContent.types; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, "types", typeof jsonContent.types); + } + } + } + if (typesFile) { + var typesFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath); + } + return typesFilePath; + } + // Use the main module for inferring types if no types package specified and the allowJs is set + if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); + } + var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); + return mainFilePath; + } + return undefined; + } var typeReferenceExtensions = [".d.ts"]; - // @internal function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { return options.typeRoots; @@ -44713,39 +43097,18 @@ var ts; else if (host.getCurrentDirectory) { currentDirectory = host.getCurrentDirectory(); } - return currentDirectory && getDefaultTypeRoots(currentDirectory, host); - } - ts.getEffectiveTypeRoots = getEffectiveTypeRoots; - /** - * Returns the path to every node_modules/@types directory from some ancestor directory. - * Returns undefined if there are none. - */ - function getDefaultTypeRoots(currentDirectory, host) { - if (!host.directoryExists) { - return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + if (!currentDirectory) { + return undefined; } - var typeRoots; - while (true) { - var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes); - if (host.directoryExists(atTypes)) { - (typeRoots || (typeRoots = [])).push(atTypes); - } - var parent_15 = ts.getDirectoryPath(currentDirectory); - if (parent_15 === currentDirectory) { - break; - } - currentDirectory = parent_15; - } - return typeRoots; + return ts.map(defaultTypeRoots, function (d) { return ts.combinePaths(currentDirectory, d); }); } - var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); /** * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups * is assumed to be the same as root directory of the project. */ function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { - var traceEnabled = ts.isTraceEnabled(options, host); + var traceEnabled = isTraceEnabled(options, host); var moduleResolutionState = { compilerOptions: options, host: host, @@ -44756,18 +43119,18 @@ var ts; if (traceEnabled) { if (containingFile === undefined) { if (typeRoots === undefined) { - ts.trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); } else { - ts.trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); } } else { if (typeRoots === undefined) { - ts.trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); } else { - ts.trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); } } } @@ -44775,17 +43138,17 @@ var ts; // Check primary library paths if (typeRoots && typeRoots.length) { if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); } var primarySearchPaths = typeRoots; for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) { var typeRoot = primarySearchPaths_1[_i]; var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); - var resolvedFile_1 = ts.loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !ts.directoryProbablyExists(candidateDirectory, host), moduleResolutionState); + var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState); if (resolvedFile_1) { if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true); + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true); } return { resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 }, @@ -44796,7 +43159,7 @@ var ts; } else { if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); + trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); } } var resolvedFile; @@ -44807,21 +43170,21 @@ var ts; if (initialLocationForSecondaryLookup !== undefined) { // check secondary locations if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); + trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - resolvedFile = ts.loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*checkOneLevel*/ false); + resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState); if (traceEnabled) { if (resolvedFile) { - ts.trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); } else { - ts.trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); } } } else { if (traceEnabled) { - ts.trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); + trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); } } return { @@ -44832,8 +43195,494 @@ var ts; }; } ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; + function resolveModuleName(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + } + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + if (traceEnabled) { + trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + var result; + switch (moduleResolution) { + case ts.ModuleResolutionKind.NodeJs: + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); + break; + case ts.ModuleResolutionKind.Classic: + result = classicNameResolver(moduleName, containingFile, compilerOptions, host); + break; + } + if (traceEnabled) { + if (result.resolvedModule) { + trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); + } + else { + trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); + } + } + return result; + } + ts.resolveModuleName = resolveModuleName; + /** + * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to + * mitigate differences between design time structure of the project and its runtime counterpart so the same import name + * can be resolved successfully by TypeScript compiler and runtime module loader. + * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will + * fallback to standard resolution routine. + * + * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative + * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will + * be '/a/b/c/d' + * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names + * will be resolved based on the content of the module name. + * Structure of 'paths' compiler options + * 'paths': { + * pattern-1: [...substitutions], + * pattern-2: [...substitutions], + * ... + * pattern-n: [...substitutions] + * } + * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against + * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case. + * If pattern contains '*' then to match pattern "*" module name must start with the and end with . + * denotes part of the module name between and . + * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked. + * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module + * from the candidate location. + * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every + * substitution in the list and replace '*' with string. If candidate location is not rooted it + * will be converted to absolute using baseUrl. + * For example: + * baseUrl: /a/b/c + * "paths": { + * // match all module names + * "*": [ + * "*", // use matched name as is, + * // will be looked as /a/b/c/ + * + * "folder1/*" // substitution will convert matched name to 'folder1/', + * // since it is not rooted then final candidate location will be /a/b/c/folder1/ + * ], + * // match module names that start with 'components/' + * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/ to '/root/components/folder1/', + * // it is rooted so it will be final candidate location + * } + * + * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if + * they were in the same location. For example lets say there are two files + * '/local/src/content/file1.ts' + * '/shared/components/contracts/src/content/protocols/file2.ts' + * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so + * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime. + * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all + * root dirs were merged together. + * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ]. + * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file: + * '/local/src/content/protocols/file2' and try to load it - failure. + * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will + * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining + * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. + */ + function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (moduleHasNonRelativeName(moduleName)) { + return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); + } + else { + return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); + } + } + function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.rootDirs) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var matchedRootDir; + var matchedNormalizedPrefix; + for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { + var rootDir = _a[_i]; + // rootDirs are expected to be absolute + // in case of tsconfig.json this will happen automatically - compiler will expand relative names + // using location of tsconfig.json as base location + var normalizedRoot = ts.normalizePath(rootDir); + if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { + normalizedRoot += ts.directorySeparator; + } + var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && + (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); + } + if (isLongestMatchingPrefix) { + matchedNormalizedPrefix = normalizedRoot; + matchedRootDir = rootDir; + } + } + if (matchedNormalizedPrefix) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); + } + var suffix = candidate.substr(matchedNormalizedPrefix.length); + // first - try to load from a initial location + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); + } + // then try to resolve using remaining entries in rootDirs + for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { + var rootDir = _c[_b]; + if (rootDir === matchedRootDir) { + // skip the initially matched entry + continue; + } + var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); + } + var baseDirectory = ts.getDirectoryPath(candidate_1); + var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + if (resolvedFileName_1) { + return resolvedFileName_1; + } + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); + } + } + return undefined; + } + function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.baseUrl) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + } + // string is for exact match + var matchedPattern = undefined; + if (state.compilerOptions.paths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + matchedPattern = matchPatternOrExact(ts.getKeys(state.compilerOptions.paths), moduleName); + } + if (matchedPattern) { + var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName); + var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) { + var subst = _a[_i]; + var path = matchedStar ? subst.replace("*", matchedStar) : subst; + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + } + return undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); + } + return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + } + } + /** + * patternStrings contains both pattern strings (containing "*") and regular strings. + * Return an exact match if possible, or a pattern match, or undefined. + * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.) + */ + function matchPatternOrExact(patternStrings, candidate) { + var patterns = []; + for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { + var patternString = patternStrings_1[_i]; + var pattern = tryParsePattern(patternString); + if (pattern) { + patterns.push(pattern); + } + else if (patternString === candidate) { + // pattern was matched as is - no need to search further + return patternString; + } + } + return findBestPatternMatch(patterns, function (_) { return _; }, candidate); + } + function patternText(_a) { + var prefix = _a.prefix, suffix = _a.suffix; + return prefix + "*" + suffix; + } + /** + * Given that candidate matches pattern, returns the text matching the '*'. + * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar" + */ + function matchedText(pattern, candidate) { + ts.Debug.assert(isPatternMatch(pattern, candidate)); + return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); + } + /** Return the object corresponding to the best pattern to match `candidate`. */ + /* @internal */ + function findBestPatternMatch(values, getPattern, candidate) { + var matchedValue = undefined; + // use length of prefix as betterness criteria + var longestMatchPrefixLength = -1; + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var v = values_1[_i]; + var pattern = getPattern(v); + if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { + longestMatchPrefixLength = pattern.prefix.length; + matchedValue = v; + } + } + return matchedValue; + } + ts.findBestPatternMatch = findBestPatternMatch; + function isPatternMatch(_a, candidate) { + var prefix = _a.prefix, suffix = _a.suffix; + return candidate.length >= prefix.length + suffix.length && + ts.startsWith(candidate, prefix) && + ts.endsWith(candidate, suffix); + } + /* @internal */ + function tryParsePattern(pattern) { + // This should be verified outside of here and a proper error thrown. + ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); + var indexOfStar = pattern.indexOf("*"); + return indexOfStar === -1 ? undefined : { + prefix: pattern.substr(0, indexOfStar), + suffix: pattern.substr(indexOfStar + 1) + }; + } + ts.tryParsePattern = tryParsePattern; + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { + var containingDirectory = ts.getDirectoryPath(containingFile); + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var traceEnabled = isTraceEnabled(compilerOptions, host); + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); + var isExternalLibraryImport = false; + if (!resolvedFileName) { + if (moduleHasNonRelativeName(moduleName)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); + } + resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state); + isExternalLibraryImport = resolvedFileName !== undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); + } + } + if (resolvedFileName && host.realpath) { + var originalFileName = resolvedFileName; + resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName)); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); + } + } + return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; + function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); + } + var resolvedFileName = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); + return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); + } + /* @internal */ + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + /** + * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary + * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. + */ + function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + // First try to keep/add an extension: importing "./foo.ts" can be matched by a file "./foo.ts", and "./foo" by "./foo.d.ts" + var resolvedByAddingOrKeepingExtension = loadModuleFromFileWorker(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); + if (resolvedByAddingOrKeepingExtension) { + return resolvedByAddingOrKeepingExtension; + } + // Then try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one, e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" + if (ts.hasJavaScriptFileExtension(candidate)) { + var extensionless = ts.removeFileExtension(candidate); + if (state.traceEnabled) { + var extension = candidate.substring(extensionless.length); + trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); + } + return loadModuleFromFileWorker(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); + } + } + function loadModuleFromFileWorker(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing + var directory = ts.getDirectoryPath(candidate); + if (directory) { + onlyRecordFailures = !directoryProbablyExists(directory, state.host); + } + } + return ts.forEach(extensions, tryLoad); + function tryLoad(ext) { + if (state.skipTsx && ts.isJsxOrTsxExtension(ext)) { + return undefined; + } + var fileName = ts.fileExtensionIs(candidate, ext) ? candidate : candidate + ext; + if (!onlyRecordFailures && state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); + } + return fileName; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); + } + failedLookupLocation.push(fileName); + return undefined; + } + } + } + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { + var packageJsonPath = ts.combinePaths(candidate, "package.json"); + var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); + if (directoryExists && state.host.fileExists(packageJsonPath)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); + if (typesFile) { + var result = loadModuleFromFile(typesFile, extensions, failedLookupLocation, !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host), state); + if (result) { + return result; + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field); + } + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); + } + // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results + failedLookupLocation.push(packageJsonPath); + } + return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); + } + function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { + var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); + var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions); + var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); + if (result) { + return result; + } + result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); + if (result) { + return result; + } + } + function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state) { + directory = ts.normalizeSlashes(directory); + while (true) { + var baseName = ts.getBaseFileName(directory); + if (baseName !== "node_modules") { + // Try to load source from the package + var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); + if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { + // Always prefer a TypeScript (.ts, .tsx, .d.ts) file shipped with the package + return packageResult; + } + else { + // Else prefer a types package over non-TypeScript results (e.g. JavaScript files) + var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); + if (typesResult || packageResult) { + return typesResult || packageResult; + } + } + } + var parentPath = ts.getDirectoryPath(directory); + if (parentPath === directory) { + break; + } + directory = parentPath; + } + return undefined; + } + function classicNameResolver(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; + var failedLookupLocations = []; + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var containingDirectory = ts.getDirectoryPath(containingFile); + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); + if (resolvedFileName) { + return createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/ false, failedLookupLocations); + } + var referencedSourceFile; + if (moduleHasNonRelativeName(moduleName)) { + while (true) { + var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); + if (referencedSourceFile) { + break; + } + var parentPath = ts.getDirectoryPath(containingDirectory); + if (parentPath === containingDirectory) { + break; + } + containingDirectory = parentPath; + } + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); + } + return referencedSourceFile + ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } + : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; + } + ts.classicNameResolver = classicNameResolver; + /* @internal */ + ts.defaultInitCompilerOptions = { + module: ts.ModuleKind.CommonJS, + target: 1 /* ES5 */, + noImplicitAny: false, + sourceMap: false + }; function createCompilerHost(options, setParentNodes) { - var existingDirectories = ts.createMap(); + var existingDirectories = {}; function getCanonicalFileName(fileName) { // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. // otherwise use toLowerCase as a canonical form. @@ -44844,10 +43693,9 @@ var ts; function getSourceFile(fileName, languageVersion, onError) { var text; try { - ts.performance.mark("beforeIORead"); + var start = new Date().getTime(); text = ts.sys.readFile(fileName, options.charset); - ts.performance.mark("afterIORead"); - ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); + ts.ioReadTime += new Date().getTime() - start; } catch (e) { if (onError) { @@ -44860,7 +43708,7 @@ var ts; return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined; } function directoryExists(directoryPath) { - if (directoryPath in existingDirectories) { + if (ts.hasProperty(existingDirectories, directoryPath)) { return true; } if (ts.sys.directoryExists(directoryPath)) { @@ -44879,11 +43727,11 @@ var ts; var outputFingerprints; function writeFileIfUpdated(fileName, data, writeByteOrderMark) { if (!outputFingerprints) { - outputFingerprints = ts.createMap(); + outputFingerprints = {}; } var hash = ts.sys.createHash(data); var mtimeBefore = ts.sys.getModifiedTime(fileName); - if (mtimeBefore && fileName in outputFingerprints) { + if (mtimeBefore && ts.hasProperty(outputFingerprints, fileName)) { var fingerprint = outputFingerprints[fileName]; // If output has not been changed, and the file has no external modification if (fingerprint.byteOrderMark === writeByteOrderMark && @@ -44902,7 +43750,7 @@ var ts; } function writeFile(fileName, data, writeByteOrderMark, onError) { try { - ts.performance.mark("beforeIOWrite"); + var start = new Date().getTime(); ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { writeFileIfUpdated(fileName, data, writeByteOrderMark); @@ -44910,8 +43758,7 @@ var ts; else { ts.sys.writeFile(fileName, data, writeByteOrderMark); } - ts.performance.mark("afterIOWrite"); - ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + ts.ioWriteTime += new Date().getTime() - start; } catch (e) { if (onError) { @@ -44950,22 +43797,6 @@ var ts; return ts.sortAndDeduplicateDiagnostics(diagnostics); } ts.getPreEmitDiagnostics = getPreEmitDiagnostics; - function formatDiagnostics(diagnostics, host) { - var output = ""; - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; - if (diagnostic.file) { - var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; - var fileName = diagnostic.file.fileName; - var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }); - output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): "; - } - var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); - output += category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine(); - } - return output; - } - ts.formatDiagnostics = formatDiagnostics; function flattenDiagnosticMessageText(messageText, newLine) { if (typeof messageText === "string") { return messageText; @@ -44994,25 +43825,33 @@ var ts; return []; } var resolutions = []; - var cache = ts.createMap(); + var cache = {}; for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { var name_34 = names_1[_i]; - var result = name_34 in cache - ? cache[name_34] - : cache[name_34] = loader(name_34, containingFile); + var result = void 0; + if (ts.hasProperty(cache, name_34)) { + result = cache[name_34]; + } + else { + result = loader(name_34, containingFile); + cache[name_34] = result; + } resolutions.push(result); } return resolutions; } + function getInferredTypesRoot(options, rootFiles, host) { + return computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } /** - * Given a set of options, returns the set of type directive names + * Given a set of options and a set of root files, returns the set of type directive names * that should be included for this program automatically. * This list could either come from the config file, * or from enumerating the types root + initial secondary types lookup location. * More type directives might appear in the program later as a result of loading actual source files; * this list is only the set of defaults that are implicitly included. */ - function getAutomaticTypeDirectiveNames(options, host) { + function getAutomaticTypeDirectiveNames(options, rootFiles, host) { // Use explicit type list from tsconfig.json if (options.types) { return options.types; @@ -45025,17 +43864,7 @@ var ts; for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { var root = typeRoots_1[_i]; if (host.directoryExists(root)) { - for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { - var typeDirectivePath = _b[_a]; - var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = ts.pathToPackageJson(ts.combinePaths(root, normalized)); - // tslint:disable-next-line:no-null-keyword - var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null; - if (!isNotNeededPackage) { - // Return just the type directive names - result.push(ts.getBaseFileName(normalized)); - } - } + result = result.concat(host.getDirectories(root)); } } } @@ -45050,7 +43879,7 @@ var ts; var diagnosticsProducingTypeChecker; var noDiagnosticsTypeChecker; var classifiableNames; - var resolvedTypeReferenceDirectives = ts.createMap(); + var resolvedTypeReferenceDirectives = {}; var fileProcessingDiagnostics = ts.createDiagnosticCollection(); // The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules. // This works as imported modules are discovered recursively in a depth first manner, specifically: @@ -45059,14 +43888,14 @@ var ts; // - This calls resolveModuleNames, and then calls findSourceFile for each resolved module. // As all these operations happen - and are nested - within the createProgram call, they close over the below variables. // The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses. - var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; - var currentNodeModulesDepth = 0; + var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 2; + var currentNodeModulesJsDepth = 0; // If a module has some of its imports skipped due to being at the depth limit under node_modules, then track // this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed. - var modulesWithElidedImports = ts.createMap(); - // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled. - var sourceFilesFoundSearchingNodeModules = ts.createMap(); - ts.performance.mark("beforeProgram"); + var modulesWithElidedImports = {}; + // Track source files that are JavaScript files found by searching under node_modules, as these shouldn't be compiled. + var sourceFilesFoundSearchingNodeModules = {}; + var start = new Date().getTime(); host = host || createCompilerHost(options); var skipDefaultLib = options.noLib; var programDiagnostics = ts.createDiagnosticCollection(); @@ -45079,7 +43908,7 @@ var ts; resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }; } else { - var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; + var loader_1 = function (moduleName, containingFile) { return resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(moduleNames, containingFile, loader_1); }; } var resolveTypeReferenceDirectiveNamesWorker; @@ -45097,10 +43926,10 @@ var ts; if (!tryReuseStructureFromOldProgram()) { ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false); }); // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders - var typeReferences = getAutomaticTypeDirectiveNames(options, host); + var typeReferences = getAutomaticTypeDirectiveNames(options, rootNames, host); if (typeReferences) { - // This containingFilename needs to match with the one used in managed-side - var containingFilename = ts.combinePaths(host.getCurrentDirectory(), "__inferred type names__.ts"); + var inferredRoot = getInferredTypesRoot(options, rootNames, host); + var containingFilename = ts.combinePaths(inferredRoot, "__inferred type names__.ts"); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i]); @@ -45148,12 +43977,10 @@ var ts; getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, - getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, - dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker + getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; } }; verifyCompilerOptions(); - ts.performance.mark("afterProgram"); - ts.performance.measure("Program", "beforeProgram", "afterProgram"); + ts.programTime += new Date().getTime() - start; return program; function getCommonSourceDirectory() { if (typeof commonSourceDirectory === "undefined") { @@ -45177,10 +44004,10 @@ var ts; if (!classifiableNames) { // Initialize a checker so that all our files are bound. getTypeChecker(); - classifiableNames = ts.createMap(); + classifiableNames = {}; for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { var sourceFile = files_2[_i]; - ts.copyProperties(sourceFile.classifiableNames, classifiableNames); + ts.copyMap(sourceFile.classifiableNames, classifiableNames); } } return classifiableNames; @@ -45205,7 +44032,7 @@ var ts; (oldOptions.maxNodeModuleJsDepth !== options.maxNodeModuleJsDepth) || !ts.arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) || !ts.arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) || - !ts.equalOwnProperties(oldOptions.paths, options.paths)) { + !ts.mapIsEqualTo(oldOptions.paths, options.paths)) { return false; } ts.Debug.assert(!oldProgram.structureIsReused); @@ -45311,7 +44138,7 @@ var ts; getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, - isSourceFileFromExternalLibrary: function (file) { return !!sourceFilesFoundSearchingNodeModules[file.path]; }, + isSourceFileFromExternalLibrary: function (file) { return !!ts.lookUp(sourceFilesFoundSearchingNodeModules, file.path); }, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked }; @@ -45319,19 +44146,17 @@ var ts; function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true)); } - function dropDiagnosticsProducingTypeChecker() { - diagnosticsProducingTypeChecker = undefined; - } function getTypeChecker() { return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false)); } - function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { - return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles); }); + function emit(sourceFile, writeFileCallback, cancellationToken) { + var _this = this; + return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); }); } function isEmitBlocked(emitFileName) { return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); } - function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { + function emitWorker(program, sourceFile, writeFileCallback, cancellationToken) { var declarationDiagnostics = []; if (options.noEmit) { return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; @@ -45362,10 +44187,9 @@ var ts; // files need to be type checked. And the way to specify that all files need to be type // checked is to not pass the file to getEmitResolver. var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); - ts.performance.mark("beforeEmit"); - var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles); - ts.performance.mark("afterEmit"); - ts.performance.measure("Emit", "beforeEmit", "afterEmit"); + var start = new Date().getTime(); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile); + ts.emitTime += new Date().getTime() - start; return emitResult; } function getSourceFile(fileName) { @@ -45517,16 +44341,16 @@ var ts; case 175 /* NewExpression */: var expression = node; if (expression.typeArguments && expression.typeArguments.length > 0) { - var start = expression.typeArguments.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, expression.typeArguments.end - start, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); + var start_2 = expression.typeArguments.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start_2, expression.typeArguments.end - start_2, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); return true; } break; case 142 /* Parameter */: var parameter = node; if (parameter.modifiers) { - var start = parameter.modifiers.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, parameter.modifiers.end - start, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); + var start_3 = parameter.modifiers.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start_3, parameter.modifiers.end - start_3, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); return true; } if (parameter.questionToken) { @@ -45570,8 +44394,8 @@ var ts; } function checkTypeParameters(typeParameters) { if (typeParameters) { - var start = typeParameters.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, typeParameters.end - start, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); + var start_4 = typeParameters.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start_4, typeParameters.end - start_4, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); return true; } return false; @@ -45779,19 +44603,9 @@ var ts; if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); } - // If the file was previously found via a node_modules search, but is now being processed as a root file, - // then everything it sucks in may also be marked incorrectly, and needs to be checked again. - if (file_1 && sourceFilesFoundSearchingNodeModules[file_1.path] && currentNodeModulesDepth == 0) { - sourceFilesFoundSearchingNodeModules[file_1.path] = false; - if (!options.noResolve) { - processReferencedFiles(file_1, ts.getDirectoryPath(fileName), isDefaultLib); - processTypeReferenceDirectives(file_1); - } - modulesWithElidedImports[file_1.path] = false; - processImportedModules(file_1, ts.getDirectoryPath(fileName)); - } - else if (file_1 && modulesWithElidedImports[file_1.path]) { - if (currentNodeModulesDepth < maxNodeModulesJsDepth) { + // See if we need to reprocess the imports due to prior skipped imports + if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) { + if (currentNodeModulesJsDepth < maxNodeModulesJsDepth) { modulesWithElidedImports[file_1.path] = false; processImportedModules(file_1, ts.getDirectoryPath(fileName)); } @@ -45809,7 +44623,6 @@ var ts; }); filesByName.set(path, file); if (file) { - sourceFilesFoundSearchingNodeModules[path] = (currentNodeModulesDepth > 0); file.path = path; if (host.useCaseSensitiveFileNames()) { // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case @@ -45845,16 +44658,14 @@ var ts; }); } function processTypeReferenceDirectives(file) { - // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. - var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); + var typeDirectives = ts.map(file.typeReferenceDirectives, function (l) { return l.fileName; }); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; var resolvedTypeReferenceDirective = resolutions[i]; // store resolved type directive on the file - var fileName = ref.fileName.toLocaleLowerCase(); - ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective); - processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end); + ts.setResolvedTypeReferenceDirective(file, ref.fileName, resolvedTypeReferenceDirective); + processTypeReferenceDirective(ref.fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end); } } function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, refFile, refPos, refEnd) { @@ -45875,7 +44686,7 @@ var ts; if (previousResolution) { var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) { - fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_to_resolve_this_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); } // don't overwrite previous resolution result saveResolution = false; @@ -45911,7 +44722,7 @@ var ts; function processImportedModules(file, basePath) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { - file.resolvedModules = ts.createMap(); + file.resolvedModules = {}; var moduleNames = ts.map(ts.concatenate(file.imports, file.moduleAugmentations), getTextOfLiteral); var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory)); for (var i = 0; i < moduleNames.length; i++) { @@ -45926,9 +44737,12 @@ var ts; var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport; var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName); if (isFromNodeModulesSearch) { - currentNodeModulesDepth++; + sourceFilesFoundSearchingNodeModules[resolvedPath] = true; } - var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth; + if (isJsFileFromNodeModules) { + currentNodeModulesJsDepth++; + } + var elideImport = isJsFileFromNodeModules && currentNodeModulesJsDepth > maxNodeModulesJsDepth; var shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport; if (elideImport) { modulesWithElidedImports[file.path] = true; @@ -45937,8 +44751,8 @@ var ts; findSourceFile(resolution.resolvedFileName, resolvedPath, /*isDefaultLib*/ false, /*isReference*/ false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); } - if (isFromNodeModulesSearch) { - currentNodeModulesDepth--; + if (isJsFileFromNodeModules) { + currentNodeModulesJsDepth--; } } } @@ -46006,18 +44820,15 @@ var ts; if (!ts.hasProperty(options.paths, key)) { continue; } - if (!ts.hasZeroOrOneAsteriskCharacter(key)) { + if (!hasZeroOrOneAsteriskCharacter(key)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); } if (ts.isArray(options.paths[key])) { - if (options.paths[key].length === 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key)); - } for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { var subst = _a[_i]; var typeOfSubst = typeof subst; if (typeOfSubst === "string") { - if (!ts.hasZeroOrOneAsteriskCharacter(subst)) { + if (!hasZeroOrOneAsteriskCharacter(subst)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key)); } } @@ -46059,7 +44870,7 @@ var ts; } var languageVersion = options.target || 0 /* ES3 */; var outFile = options.outFile || options.out; - var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); + var firstExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) ? f : undefined; }); if (options.isolatedModules) { if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES6 */) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); @@ -46070,19 +44881,19 @@ var ts; programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); } } - else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES6 */ && options.module === ts.ModuleKind.None) { + else if (firstExternalModuleSourceFile && languageVersion < 2 /* ES6 */ && options.module === ts.ModuleKind.None) { // We cannot use createDiagnosticFromNode because nodes do not have parents yet - var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); + var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } // Cannot specify module gen that isn't amd or system with --out if (outFile) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); } - else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) { - var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); + else if (options.module === undefined && firstExternalModuleSourceFile) { + var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); } } // there has to be common source directory if user specified --outdir || --sourceRoot @@ -46149,15 +44960,12 @@ var ts; /// var ts; (function (ts) { - /* @internal */ - ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; /* @internal */ ts.optionDeclarations = [ { name: "charset", type: "string" }, - ts.compileOnSaveCommandLineOption, { name: "declaration", shortName: "d", @@ -46174,10 +44982,6 @@ var ts; name: "diagnostics", type: "boolean" }, - { - name: "extendedDiagnostics", - type: "boolean" - }, { name: "emitBOM", type: "boolean" @@ -46208,10 +45012,10 @@ var ts; }, { name: "jsx", - type: ts.createMap({ + type: { "preserve": 1 /* Preserve */, "react": 2 /* React */ - }), + }, paramType: ts.Diagnostics.KIND, description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react }, @@ -46238,7 +45042,7 @@ var ts; { name: "module", shortName: "m", - type: ts.createMap({ + type: { "none": ts.ModuleKind.None, "commonjs": ts.ModuleKind.CommonJS, "amd": ts.ModuleKind.AMD, @@ -46246,16 +45050,16 @@ var ts; "umd": ts.ModuleKind.UMD, "es6": ts.ModuleKind.ES6, "es2015": ts.ModuleKind.ES2015 - }), + }, description: ts.Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015, paramType: ts.Diagnostics.KIND }, { name: "newLine", - type: ts.createMap({ + type: { "crlf": 0 /* CarriageReturnLineFeed */, "lf": 1 /* LineFeed */ - }), + }, description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix, paramType: ts.Diagnostics.NEWLINE }, @@ -46273,10 +45077,6 @@ var ts; type: "boolean", description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported }, - { - name: "noErrorTruncation", - type: "boolean" - }, { name: "noImplicitAny", type: "boolean", @@ -46290,12 +45090,12 @@ var ts; { name: "noUnusedLocals", type: "boolean", - description: ts.Diagnostics.Report_errors_on_unused_locals + description: ts.Diagnostics.Report_Errors_on_Unused_Locals }, { name: "noUnusedParameters", type: "boolean", - description: ts.Diagnostics.Report_errors_on_unused_parameters + description: ts.Diagnostics.Report_Errors_on_Unused_Parameters }, { name: "noLib", @@ -46401,12 +45201,12 @@ var ts; { name: "target", shortName: "t", - type: ts.createMap({ + type: { "es3": 0 /* ES3 */, "es5": 1 /* ES5 */, "es6": 2 /* ES6 */, "es2015": 2 /* ES2015 */ - }), + }, description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015, paramType: ts.Diagnostics.VERSION }, @@ -46435,10 +45235,10 @@ var ts; }, { name: "moduleResolution", - type: ts.createMap({ + type: { "node": ts.ModuleResolutionKind.NodeJs, "classic": ts.ModuleResolutionKind.Classic - }), + }, description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6 }, { @@ -46543,7 +45343,7 @@ var ts; type: "list", element: { name: "lib", - type: ts.createMap({ + type: { // JavaScript only "es5": "lib.es5.d.ts", "es6": "lib.es2015.d.ts", @@ -46568,7 +45368,7 @@ var ts; "es2016.array.include": "lib.es2016.array.include.d.ts", "es2017.object": "lib.es2017.object.d.ts", "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts" - }) + } }, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon }, @@ -46605,21 +45405,14 @@ var ts; } } ]; - /* @internal */ - ts.defaultInitCompilerOptions = { - module: ts.ModuleKind.CommonJS, - target: 1 /* ES5 */, - noImplicitAny: false, - sourceMap: false - }; var optionNameMapCache; /* @internal */ function getOptionNameMap() { if (optionNameMapCache) { return optionNameMapCache; } - var optionNameMap = ts.createMap(); - var shortOptionNames = ts.createMap(); + var optionNameMap = {}; + var shortOptionNames = {}; ts.forEach(ts.optionDeclarations, function (option) { optionNameMap[option.name.toLowerCase()] = option; if (option.shortName) { @@ -46633,9 +45426,9 @@ var ts; /* @internal */ function createCompilerDiagnosticForInvalidCustomType(opt) { var namesOfType = []; - for (var key in opt.type) { + ts.forEachKey(opt.type, function (key) { namesOfType.push(" '" + key + "'"); - } + }); return ts.createCompilerDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); } ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; @@ -46643,7 +45436,7 @@ var ts; function parseCustomTypeOption(opt, value, errors) { var key = trimString((value || "")).toLowerCase(); var map = opt.type; - if (key in map) { + if (ts.hasProperty(map, key)) { return map[key]; } else { @@ -46695,10 +45488,10 @@ var ts; else if (s.charCodeAt(0) === 45 /* minus */) { s = s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1).toLowerCase(); // Try to translate short option names to their full equivalents. - if (s in shortOptionNames) { + if (ts.hasProperty(shortOptionNames, s)) { s = shortOptionNames[s]; } - if (s in optionNameMap) { + if (ts.hasProperty(optionNameMap, s)) { var opt = optionNameMap[s]; if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -46800,101 +45593,16 @@ var ts; * @param fileName The path to the config file * @param jsonText The text of the config file */ - function parseConfigFileTextToJson(fileName, jsonText, stripComments) { - if (stripComments === void 0) { stripComments = true; } + function parseConfigFileTextToJson(fileName, jsonText) { try { - var jsonTextToParse = stripComments ? removeComments(jsonText) : jsonText; - return { config: /\S/.test(jsonTextToParse) ? JSON.parse(jsonTextToParse) : {} }; + var jsonTextWithoutComments = removeComments(jsonText); + return { config: /\S/.test(jsonTextWithoutComments) ? JSON.parse(jsonTextWithoutComments) : {} }; } catch (e) { return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) }; } } ts.parseConfigFileTextToJson = parseConfigFileTextToJson; - /** - * Generate tsconfig configuration when running command line "--init" - * @param options commandlineOptions to be generated into tsconfig.json - * @param fileNames array of filenames to be generated into tsconfig.json - */ - /* @internal */ - function generateTSConfig(options, fileNames) { - var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); - var configurations = { - compilerOptions: serializeCompilerOptions(compilerOptions) - }; - if (fileNames && fileNames.length) { - // only set the files property if we have at least one file - configurations.files = fileNames; - } - return configurations; - function getCustomTypeMapOfCommandLineOption(optionDefinition) { - if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { - // this is of a type CommandLineOptionOfPrimitiveType - return undefined; - } - else if (optionDefinition.type === "list") { - return getCustomTypeMapOfCommandLineOption(optionDefinition.element); - } - else { - return optionDefinition.type; - } - } - function getNameOfCompilerOptionValue(value, customTypeMap) { - // There is a typeMap associated with this command-line option so use it to map value back to its name - for (var key in customTypeMap) { - if (customTypeMap[key] === value) { - return key; - } - } - return undefined; - } - function serializeCompilerOptions(options) { - var result = ts.createMap(); - var optionsNameMap = getOptionNameMap().optionNameMap; - for (var name_35 in options) { - if (ts.hasProperty(options, name_35)) { - // tsconfig only options cannot be specified via command line, - // so we can assume that only types that can appear here string | number | boolean - switch (name_35) { - case "init": - case "watch": - case "version": - case "help": - case "project": - break; - default: - var value = options[name_35]; - var optionDefinition = optionsNameMap[name_35.toLowerCase()]; - if (optionDefinition) { - var customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition); - if (!customTypeMap) { - // There is no map associated with this compiler option then use the value as-is - // This is the case if the value is expect to be string, number, boolean or list of string - result[name_35] = value; - } - else { - if (optionDefinition.type === "list") { - var convertedValue = []; - for (var _i = 0, _a = value; _i < _a.length; _i++) { - var element = _a[_i]; - convertedValue.push(getNameOfCompilerOptionValue(element, customTypeMap)); - } - result[name_35] = convertedValue; - } - else { - // There is a typeMap associated with this command-line option so use it to map value back to its name - result[name_35] = getNameOfCompilerOptionValue(value, customTypeMap); - } - } - } - break; - } - } - } - return result; - } - } - ts.generateTSConfig = generateTSConfig; /** * Remove the comments from a json like text. * Comments can be single line comments (starting with # or //) or multiline comments using / * * / @@ -46919,6 +45627,9 @@ var ts; } return output; } + // Skip over any minified JavaScript files (ending in ".min.js") + // Skip over dotted files and folders as well + var ignoreFileNamePattern = /(\.min\.js$)|([\\/]\.[\w.])/; /** * Parse the contents of a config file (tsconfig.json). * @param json The contents of the config file to parse @@ -46934,15 +45645,13 @@ var ts; var typingOptions = convertTypingOptionsFromJsonWorker(json["typingOptions"], basePath, errors, configFileName); options.configFilePath = configFileName; var _a = getFileNames(errors), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; - var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); return { options: options, fileNames: fileNames, typingOptions: typingOptions, raw: json, errors: errors, - wildcardDirectories: wildcardDirectories, - compileOnSave: compileOnSave + wildcardDirectories: wildcardDirectories }; function getFileNames(errors) { var fileNames; @@ -46991,17 +45700,6 @@ var ts; } } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; - function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { - if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { - return false; - } - var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); - if (typeof result === "boolean" && result) { - return result; - } - return false; - } - ts.convertCompileOnSaveOptionFromJson = convertCompileOnSaveOptionFromJson; function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { var errors = []; var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); @@ -47015,7 +45713,7 @@ var ts; } ts.convertTypingOptionsFromJson = convertTypingOptionsFromJson; function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2 } : {}; + var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true } : {}; convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); return options; } @@ -47032,7 +45730,7 @@ var ts; } var optionNameMap = ts.arrayToMap(optionDeclarations, function (opt) { return opt.name; }); for (var id in jsonOptions) { - if (id in optionNameMap) { + if (ts.hasProperty(optionNameMap, id)) { var opt = optionNameMap[id]; defaultOptions[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors); } @@ -47067,7 +45765,7 @@ var ts; } function convertJsonOptionOfCustomType(opt, value, errors) { var key = value.toLowerCase(); - if (key in opt.type) { + if (ts.hasProperty(opt.type, key)) { return opt.type[key]; } else { @@ -47167,11 +45865,11 @@ var ts; // Literal file names (provided via the "files" array in tsconfig.json) are stored in a // file map with a possibly case insensitive key. We use this map later when when including // wildcard paths. - var literalFileMap = ts.createMap(); + var literalFileMap = {}; // Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a // file map with a possibly case insensitive key. We use this map to store paths matched // via wildcard, and to handle extension priority. - var wildcardFileMap = ts.createMap(); + var wildcardFileMap = {}; if (include) { include = validateSpecs(include, errors, /*allowTrailingRecursion*/ false); } @@ -47207,13 +45905,16 @@ var ts; if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { continue; } + if (ignoreFileNamePattern.test(file)) { + continue; + } // We may have included a wildcard path with a lower priority // extension due to the user-defined order of entries in the // "include" array. If there is a lower priority extension in the // same directory, we should remove it. removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); var key = keyMapper(file); - if (!(key in literalFileMap) && !(key in wildcardFileMap)) { + if (!ts.hasProperty(literalFileMap, key) && !ts.hasProperty(wildcardFileMap, key)) { wildcardFileMap[key] = file; } } @@ -47262,20 +45963,20 @@ var ts; // /a/b/a?z - Watch /a/b directly to catch any new file matching a?z var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); - var wildcardDirectories = ts.createMap(); + var wildcardDirectories = {}; if (include !== undefined) { var recursiveKeys = []; for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { var file = include_1[_i]; - var name_36 = ts.normalizePath(ts.combinePaths(path, file)); - if (excludeRegex && excludeRegex.test(name_36)) { + var name_35 = ts.normalizePath(ts.combinePaths(path, file)); + if (excludeRegex && excludeRegex.test(name_35)) { continue; } - var match = wildcardDirectoryPattern.exec(name_36); + var match = wildcardDirectoryPattern.exec(name_35); if (match) { var key = useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(); - var flags = watchRecursivePattern.test(name_36) ? 1 /* Recursive */ : 0 /* None */; - var existingFlags = wildcardDirectories[key]; + var flags = watchRecursivePattern.test(name_35) ? 1 /* Recursive */ : 0 /* None */; + var existingFlags = ts.getProperty(wildcardDirectories, key); if (existingFlags === undefined || existingFlags < flags) { wildcardDirectories[key] = flags; if (flags === 1 /* Recursive */) { @@ -47286,10 +45987,12 @@ var ts; } // Remove any subpaths under an existing recursively watched directory. for (var key in wildcardDirectories) { - for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { - var recursiveKey = recursiveKeys_1[_a]; - if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { - delete wildcardDirectories[key]; + if (ts.hasProperty(wildcardDirectories, key)) { + for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { + var recursiveKey = recursiveKeys_1[_a]; + if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { + delete wildcardDirectories[key]; + } } } } @@ -47310,7 +46013,7 @@ var ts; for (var i = 0 /* Highest */; i < adjustedExtensionPriority; i++) { var higherPriorityExtension = extensions[i]; var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); - if (higherPriorityPath in literalFiles || higherPriorityPath in wildcardFiles) { + if (ts.hasProperty(literalFiles, higherPriorityPath) || ts.hasProperty(wildcardFiles, higherPriorityPath)) { return true; } } @@ -47446,28 +46149,28 @@ var ts; switch (n.kind) { case 199 /* Block */: if (!ts.isFunctionBlock(n)) { - var parent_16 = n.parent; + var parent_15 = n.parent; var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile); var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile); // Check if the block is standalone, or 'attached' to some parent statement. // If the latter, we want to collapse the block, but consider its hint span // to be the entire span of the parent. - if (parent_16.kind === 204 /* DoStatement */ || - parent_16.kind === 207 /* ForInStatement */ || - parent_16.kind === 208 /* ForOfStatement */ || - parent_16.kind === 206 /* ForStatement */ || - parent_16.kind === 203 /* IfStatement */ || - parent_16.kind === 205 /* WhileStatement */ || - parent_16.kind === 212 /* WithStatement */ || - parent_16.kind === 252 /* CatchClause */) { - addOutliningSpan(parent_16, openBrace, closeBrace, autoCollapse(n)); + if (parent_15.kind === 204 /* DoStatement */ || + parent_15.kind === 207 /* ForInStatement */ || + parent_15.kind === 208 /* ForOfStatement */ || + parent_15.kind === 206 /* ForStatement */ || + parent_15.kind === 203 /* IfStatement */ || + parent_15.kind === 205 /* WhileStatement */ || + parent_15.kind === 212 /* WithStatement */ || + parent_15.kind === 252 /* CatchClause */) { + addOutliningSpan(parent_15, openBrace, closeBrace, autoCollapse(n)); break; } - if (parent_16.kind === 216 /* TryStatement */) { + if (parent_15.kind === 216 /* TryStatement */) { // Could be the try-block, or the finally-block. - var tryStatement = parent_16; + var tryStatement = parent_15; if (tryStatement.tryBlock === n) { - addOutliningSpan(parent_16, openBrace, closeBrace, autoCollapse(n)); + addOutliningSpan(parent_15, openBrace, closeBrace, autoCollapse(n)); break; } else if (tryStatement.finallyBlock === n) { @@ -47527,7 +46230,7 @@ var ts; (function (ts) { var NavigateTo; (function (NavigateTo) { - function getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount, excludeDts) { + function getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; // This means "compare in a case insensitive manner." @@ -47536,12 +46239,12 @@ var ts; ts.forEach(program.getSourceFiles(), function (sourceFile) { cancellationToken.throwIfCancellationRequested(); var nameToDeclarations = sourceFile.getNamedDeclarations(); - for (var name_37 in nameToDeclarations) { - var declarations = nameToDeclarations[name_37]; + for (var name_36 in nameToDeclarations) { + var declarations = ts.getProperty(nameToDeclarations, name_36); if (declarations) { // First do a quick check to see if the name of the declaration matches the // last portion of the (possibly) dotted name they're searching for. - var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_37); + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_36); if (!matches) { continue; } @@ -47554,17 +46257,14 @@ var ts; if (!containers) { return undefined; } - matches = patternMatcher.getMatches(containers, name_37); + matches = patternMatcher.getMatches(containers, name_36); if (!matches) { continue; } } var fileName = sourceFile.fileName; var matchKind = bestMatchKind(matches); - if (excludeDts && ts.fileExtensionIs(declaration.getSourceFile().fileName, ".d.ts")) { - continue; - } - rawItems.push({ name: name_37, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); + rawItems.push({ name: name_36, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); } } } @@ -47846,9 +46546,9 @@ var ts; case 169 /* BindingElement */: case 218 /* VariableDeclaration */: var decl = node; - var name_38 = decl.name; - if (ts.isBindingPattern(name_38)) { - addChildrenRecursively(name_38); + var name_37 = decl.name; + if (ts.isBindingPattern(name_37)) { + addChildrenRecursively(name_37); } else if (decl.initializer && isFunctionOrClassExpression(decl.initializer)) { // For `const x = function() {}`, just use the function node, not the const. @@ -47911,7 +46611,7 @@ var ts; } /** Merge declarations of the same kind. */ function mergeChildren(children) { - var nameToItems = ts.createMap(); + var nameToItems = {}; ts.filterMutate(children, function (child) { var decl = child.node; var name = decl.name && nodeText(decl.name); @@ -47919,7 +46619,7 @@ var ts; // Anonymous items are never merged. return true; } - var itemsWithSameName = nameToItems[name]; + var itemsWithSameName = ts.getProperty(nameToItems, name); if (!itemsWithSameName) { nameToItems[name] = child; return true; @@ -48162,7 +46862,7 @@ var ts; function convertToTopLevelItem(n) { return { text: getItemName(n.node), - kind: ts.getNodeKind(n.node), + kind: nodeKind(n.node), kindModifiers: ts.getNodeModifiers(n.node), spans: getSpans(n), childItems: ts.map(n.children, convertToChildItem) || emptyChildItemArray, @@ -48173,7 +46873,7 @@ var ts; function convertToChildItem(n) { return { text: getItemName(n.node), - kind: ts.getNodeKind(n.node), + kind: nodeKind(n.node), kindModifiers: ts.getNodeModifiers(n.node), spans: getSpans(n), childItems: emptyChildItemArray, @@ -48193,6 +46893,49 @@ var ts; return spans; } } + // TODO: GH#9145: We should just use getNodeKind. No reason why navigationBar and navigateTo should have different behaviors. + function nodeKind(node) { + switch (node.kind) { + case 256 /* SourceFile */: + return ts.ScriptElementKind.moduleElement; + case 255 /* EnumMember */: + return ts.ScriptElementKind.memberVariableElement; + case 218 /* VariableDeclaration */: + case 169 /* BindingElement */: + var variableDeclarationNode = void 0; + var name_38; + if (node.kind === 169 /* BindingElement */) { + name_38 = node.name; + variableDeclarationNode = node; + // binding elements are added only for variable declarations + // bubble up to the containing variable declaration + while (variableDeclarationNode && variableDeclarationNode.kind !== 218 /* VariableDeclaration */) { + variableDeclarationNode = variableDeclarationNode.parent; + } + ts.Debug.assert(!!variableDeclarationNode); + } + else { + ts.Debug.assert(!ts.isBindingPattern(node.name)); + variableDeclarationNode = node; + name_38 = node.name; + } + if (ts.isConst(variableDeclarationNode)) { + return ts.ScriptElementKind.constElement; + } + else if (ts.isLet(variableDeclarationNode)) { + return ts.ScriptElementKind.letElement; + } + else { + return ts.ScriptElementKind.variableElement; + } + case 180 /* ArrowFunction */: + return ts.ScriptElementKind.functionElement; + case 279 /* JSDocTypedefTag */: + return ts.ScriptElementKind.typeElement; + default: + return ts.getNodeKind(node); + } + } function getModuleName(moduleDeclaration) { // We want to maintain quotation marks. if (ts.isAmbientModule(moduleDeclaration)) { @@ -48272,7 +47015,7 @@ var ts; // we see the name of a module that is used everywhere, or the name of an overload). As // such, we cache the information we compute about the candidate for the life of this // pattern matcher so we don't have to compute it multiple times. - var stringToWordSpans = ts.createMap(); + var stringToWordSpans = {}; pattern = pattern.trim(); var dotSeparatedSegments = pattern.split(".").map(function (p) { return createSegment(p.trim()); }); var invalidPattern = dotSeparatedSegments.length === 0 || ts.forEach(dotSeparatedSegments, segmentIsInvalid); @@ -48328,7 +47071,7 @@ var ts; return totalMatch; } function getWordSpans(word) { - if (!(word in stringToWordSpans)) { + if (!ts.hasProperty(stringToWordSpans, word)) { stringToWordSpans[word] = breakIntoWordSpans(word); } return stringToWordSpans[word]; @@ -48344,7 +47087,7 @@ var ts; else { // b) Check if the part is a prefix of the candidate, in a case insensitive or sensitive // manner. If it does, return that there was a prefix match. - return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, /*isCaseSensitive:*/ ts.startsWith(candidate, chunk.text)); + return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, /*isCaseSensitive:*/ startsWith(candidate, chunk.text)); } } var isLowercase = chunk.isLowerCase; @@ -48610,6 +47353,14 @@ var ts; var str = String.fromCharCode(ch); return str === str.toLowerCase(); } + function startsWith(string, search) { + for (var i = 0, n = search.length; i < n; i++) { + if (string.charCodeAt(i) !== search.charCodeAt(i)) { + return false; + } + } + return true; + } // Assumes 'value' is already lowercase. function indexOfIgnoringCase(string, value) { for (var i = 0, n = string.length - value.length; i <= n; i++) { @@ -49000,7 +47751,7 @@ var ts; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; var nameToDeclarations = sourceFile.getNamedDeclarations(); - var declarations = nameToDeclarations[name.text]; + var declarations = ts.getProperty(nameToDeclarations, name.text); if (declarations) { for (var _b = 0, declarations_8 = declarations; _b < declarations_8.length; _b++) { var declaration = declarations_8[_b]; @@ -49359,8 +48110,6 @@ var ts; /* @internal */ var ts; (function (ts) { - // Matches the beginning of a triple slash directive - var tripleSlashDirectivePrefixRegex = /^\/\/\/\s*= node.end) { + if (c.kind === 282 /* SyntaxList */ && c.pos <= node.pos && c.end >= node.end) { return c; } }); @@ -49753,7 +48502,8 @@ var ts; ts.findPrecedingToken = findPrecedingToken; function isInString(sourceFile, position) { var previousToken = findPrecedingToken(position, sourceFile); - if (previousToken && previousToken.kind === 9 /* StringLiteral */) { + if (previousToken && + (previousToken.kind === 9 /* StringLiteral */ || previousToken.kind === 166 /* StringLiteralType */)) { var start = previousToken.getStart(); var end = previousToken.getEnd(); // To be "in" one of these literals, the position has to be: @@ -49936,6 +48686,7 @@ var ts; ts.isComment = isComment; function isStringOrRegularExpressionOrTemplateLiteral(kind) { if (kind === 9 /* StringLiteral */ + || kind === 166 /* StringLiteralType */ || kind === 10 /* RegularExpressionLiteral */ || ts.isTemplateLiteralKind(kind)) { return true; @@ -50005,27 +48756,6 @@ var ts; return false; } ts.isArrayLiteralOrObjectLiteralDestructuringPattern = isArrayLiteralOrObjectLiteralDestructuringPattern; - function hasTrailingDirectorySeparator(path) { - var lastCharacter = path.charAt(path.length - 1); - return lastCharacter === "/" || lastCharacter === "\\"; - } - ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; - function isInReferenceComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, isReferenceComment); - function isReferenceComment(c) { - var commentText = sourceFile.text.substring(c.pos, c.end); - return tripleSlashDirectivePrefixRegex.test(commentText); - } - } - ts.isInReferenceComment = isInReferenceComment; - function isInNonReferenceComment(sourceFile, position) { - return isInCommentHelper(sourceFile, position, isNonReferenceComment); - function isNonReferenceComment(c) { - var commentText = sourceFile.text.substring(c.pos, c.end); - return !tripleSlashDirectivePrefixRegex.test(commentText); - } - } - ts.isInNonReferenceComment = isInNonReferenceComment; })(ts || (ts = {})); // Display-part writer helpers /* @internal */ @@ -50260,43 +48990,16 @@ var ts; if (host && host.getScriptKind) { scriptKind = host.getScriptKind(fileName); } - if (!scriptKind) { + if (!scriptKind || scriptKind === 0 /* Unknown */) { scriptKind = ts.getScriptKindFromFileName(fileName); } return ts.ensureScriptKind(fileName, scriptKind); } ts.getScriptKind = getScriptKind; - function sanitizeConfigFile(configFileName, content) { - var options = { - fileName: "config.js", - compilerOptions: { - target: 2 /* ES6 */, - removeComments: true - }, - reportDiagnostics: true - }; - var _a = ts.transpileModule("(" + content + ")", options), outputText = _a.outputText, diagnostics = _a.diagnostics; - // Becasue the content was wrapped in "()", the start position of diagnostics needs to be subtract by 1 - // also, the emitted result will have "(" in the beginning and ");" in the end. We need to strip these - // as well - var trimmedOutput = outputText.trim(); - for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { - var diagnostic = diagnostics_3[_i]; - diagnostic.start = diagnostic.start - 1; - } - var _b = ts.parseConfigFileTextToJson(configFileName, trimmedOutput.substring(1, trimmedOutput.length - 2), /*stripComments*/ false), config = _b.config, error = _b.error; - return { - configJsonObject: config || {}, - diagnostics: error ? ts.concatenate(diagnostics, [error]) : diagnostics - }; - } - ts.sanitizeConfigFile = sanitizeConfigFile; })(ts || (ts = {})); // Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. // See LICENSE.txt in the project root for complete license information. -/// -/// -/// +/// /* @internal */ var ts; (function (ts) { @@ -50307,7 +49010,6 @@ var ts; // A map of loose file names to library names // that we are confident require typings var safeList; - var EmptySafeList = ts.createMap(); /** * @param host is the object providing I/O related operations. * @param fileNames are the file names that belong to the same project @@ -50319,18 +49021,21 @@ var ts; */ function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typingOptions, compilerOptions) { // A typing name to typing file path mapping - var inferredTypings = ts.createMap(); + var inferredTypings = {}; if (!typingOptions || !typingOptions.enableAutoDiscovery) { return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; } // Only infer typings for .js and .jsx files - fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { - var kind = ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)); - return kind === 1 /* JS */ || kind === 2 /* JSX */; - }); + fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { return ts.scriptKindIs(f, /*LanguageServiceHost*/ undefined, 1 /* JS */, 2 /* JSX */); }); if (!safeList) { var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); - safeList = result.config ? ts.createMap(result.config) : EmptySafeList; + if (result.config) { + safeList = result.config; + } + else { + safeList = {}; + } + ; } var filesToWatch = []; // Directories to search for package.json, bower.json and other typing information @@ -50355,7 +49060,7 @@ var ts; getTypingNamesFromSourceFileNames(fileNames); // Add the cached typing locations for inferred typings that are already installed for (var name_39 in packageNameToTypingLocation) { - if (name_39 in inferredTypings && !inferredTypings[name_39]) { + if (ts.hasProperty(inferredTypings, name_39) && !inferredTypings[name_39]) { inferredTypings[name_39] = packageNameToTypingLocation[name_39]; } } @@ -50384,7 +49089,7 @@ var ts; } for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) { var typing = typingNames_1[_i]; - if (!(typing in inferredTypings)) { + if (!ts.hasProperty(inferredTypings, typing)) { inferredTypings[typing] = undefined; } } @@ -50398,16 +49103,16 @@ var ts; var jsonConfig = result.config; filesToWatch.push(jsonPath); if (jsonConfig.dependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.dependencies)); + mergeTypings(ts.getKeys(jsonConfig.dependencies)); } if (jsonConfig.devDependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.devDependencies)); + mergeTypings(ts.getKeys(jsonConfig.devDependencies)); } if (jsonConfig.optionalDependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.optionalDependencies)); + mergeTypings(ts.getKeys(jsonConfig.optionalDependencies)); } if (jsonConfig.peerDependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.peerDependencies)); + mergeTypings(ts.getKeys(jsonConfig.peerDependencies)); } } } @@ -50421,10 +49126,13 @@ var ts; var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension); var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); }); var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); }); - if (safeList !== EmptySafeList) { - mergeTypings(ts.filter(cleanedTypingNames, function (f) { return f in safeList; })); + if (safeList === undefined) { + mergeTypings(cleanedTypingNames); } - var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)) === 2 /* JSX */; }); + else { + mergeTypings(ts.filter(cleanedTypingNames, function (f) { return ts.hasProperty(safeList, f); })); + } + var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.scriptKindIs(f, /*LanguageServiceHost*/ undefined, 2 /* JSX */); }); if (hasJsxFile) { mergeTypings(["react"]); } @@ -50439,7 +49147,7 @@ var ts; return; } var typingNames = []; - var fileNames = host.readDirectory(nodeModulesPath, [".json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); + var fileNames = host.readDirectory(nodeModulesPath, ["*.json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { var fileName = fileNames_2[_i]; var normalizedFileName = ts.normalizePath(fileName); @@ -50497,7 +49205,6 @@ var ts; ScanAction[ScanAction["RescanSlashToken"] = 2] = "RescanSlashToken"; ScanAction[ScanAction["RescanTemplateToken"] = 3] = "RescanTemplateToken"; ScanAction[ScanAction["RescanJsxIdentifier"] = 4] = "RescanJsxIdentifier"; - ScanAction[ScanAction["RescanJsxText"] = 5] = "RescanJsxText"; })(ScanAction || (ScanAction = {})); function getFormattingScanner(sourceFile, startPos, endPos) { ts.Debug.assert(scanner === undefined); @@ -50589,9 +49296,6 @@ var ts; } return false; } - function shouldRescanJsxText(node) { - return node && node.kind === 244 /* JsxText */; - } function shouldRescanSlashToken(container) { return container.kind === 10 /* RegularExpressionLiteral */; } @@ -50622,9 +49326,7 @@ var ts; ? 3 /* RescanTemplateToken */ : shouldRescanJsxIdentifier(n) ? 4 /* RescanJsxIdentifier */ - : shouldRescanJsxText(n) - ? 5 /* RescanJsxText */ - : 0 /* Scan */; + : 0 /* Scan */; if (lastTokenInfo && expectedScanAction === lastScanAction) { // readTokenInfo was called before with the same expected scan action. // No need to re-scan text, return existing 'lastTokenInfo' @@ -50659,10 +49361,6 @@ var ts; currentToken = scanner.scanJsxIdentifier(); lastScanAction = 4 /* RescanJsxIdentifier */; } - else if (expectedScanAction === 5 /* RescanJsxText */) { - currentToken = scanner.reScanJsxToken(); - lastScanAction = 5 /* RescanJsxText */; - } else { lastScanAction = 0 /* Scan */; } @@ -51052,7 +49750,7 @@ var ts; this.NoSpaceBetweenReturnAndSemicolon = new formatting.Rule(formatting.RuleDescriptor.create1(94 /* ReturnKeyword */, 23 /* SemicolonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // Add a space between statements. All keywords except (do,else,case) has open/close parens after them. // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any] - this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([18 /* CloseParenToken */, 79 /* DoKeyword */, 80 /* ElseKeyword */, 71 /* CaseKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNotForContext), 2 /* Space */)); + this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([18 /* CloseParenToken */, 79 /* DoKeyword */, 80 /* ElseKeyword */, 71 /* CaseKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isNonJsxElementContext, Rules.IsNotForContext), 2 /* Space */)); // This low-pri rule takes care of "try {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter. this.SpaceAfterTryFinally = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([100 /* TryKeyword */, 85 /* FinallyKeyword */]), 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); // get x() {} @@ -51099,12 +49797,6 @@ var ts; this.SpaceBetweenAsyncAndFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(118 /* AsyncKeyword */, 87 /* FunctionKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); // template string this.NoSpaceBetweenTagAndTemplateString = new formatting.Rule(formatting.RuleDescriptor.create3(69 /* Identifier */, formatting.Shared.TokenRange.FromTokens([11 /* NoSubstitutionTemplateLiteral */, 12 /* TemplateHead */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - // jsx opening element - this.SpaceBeforeJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 69 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNextTokenParentJsxAttribute, Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.SpaceBeforeSlashInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 39 /* SlashToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); - this.NoSpaceBeforeGreaterThanTokenInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create1(39 /* SlashToken */, 27 /* GreaterThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 56 /* EqualsToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create3(56 /* EqualsToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // These rules are higher in priority than user-configurable rules. this.HighPriorityCommonRules = [ this.IgnoreBeforeComment, this.IgnoreAfterLineComment, @@ -51132,8 +49824,6 @@ var ts; this.SpaceAfterVoidOperator, this.SpaceBetweenAsyncAndOpenParen, this.SpaceBetweenAsyncAndFunctionKeyword, this.NoSpaceBetweenTagAndTemplateString, - this.SpaceBeforeJsxAttribute, this.SpaceBeforeSlashInJsxOpeningElement, this.NoSpaceBeforeGreaterThanTokenInJsxOpeningElement, - this.NoSpaceBeforeEqualInJsxAttribute, this.NoSpaceAfterEqualInJsxAttribute, // TypeScript-specific rules this.NoSpaceAfterConstructor, this.NoSpaceAfterModuleImport, this.SpaceAfterCertainTypeScriptKeywords, this.SpaceBeforeCertainTypeScriptKeywords, @@ -51167,8 +49857,8 @@ var ts; /// Rules controlled by user options /// // Insert space after comma delimiter - this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2 /* Space */)); - this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonJsxElementContext), 8 /* Delete */)); + this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isNonJsxElementContext, Rules.IsNextTokenNotCloseBracket), 2 /* Space */)); + this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isNonJsxElementContext), 8 /* Delete */)); // Insert space before and after binary operators this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); this.SpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); @@ -51205,10 +49895,10 @@ var ts; this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([13 /* TemplateMiddle */, 14 /* TemplateTail */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); this.SpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([13 /* TemplateMiddle */, 14 /* TemplateTail */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); // No space after { and before } in JSX expression - this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8 /* Delete */)); - this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2 /* Space */)); - this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 8 /* Delete */)); - this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsJsxExpressionContext), 2 /* Space */)); + this.NoSpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isJsxExpressionContext), 8 /* Delete */)); + this.SpaceAfterOpenBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isJsxExpressionContext), 2 /* Space */)); + this.NoSpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isJsxExpressionContext), 8 /* Delete */)); + this.SpaceBeforeCloseBraceInJsxExpression = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.isJsxExpressionContext), 2 /* Space */)); // Insert space after function keyword for anonymous functions this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(87 /* FunctionKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */)); this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(87 /* FunctionKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 8 /* Delete */)); @@ -51420,21 +50110,12 @@ var ts; Rules.IsNonJsxSameLineTokenContext = function (context) { return context.TokensAreOnSameLine() && context.contextNode.kind !== 244 /* JsxText */; }; - Rules.IsNonJsxElementContext = function (context) { + Rules.isNonJsxElementContext = function (context) { return context.contextNode.kind !== 241 /* JsxElement */; }; - Rules.IsJsxExpressionContext = function (context) { + Rules.isJsxExpressionContext = function (context) { return context.contextNode.kind === 248 /* JsxExpression */; }; - Rules.IsNextTokenParentJsxAttribute = function (context) { - return context.nextTokenParent.kind === 246 /* JsxAttribute */; - }; - Rules.IsJsxAttributeContext = function (context) { - return context.contextNode.kind === 246 /* JsxAttribute */; - }; - Rules.IsJsxSelfClosingElementContext = function (context) { - return context.contextNode.kind === 242 /* JsxSelfClosingElement */; - }; Rules.IsNotBeforeBlockInFunctionDeclarationContext = function (context) { return !Rules.IsFunctionDeclContext(context) && !Rules.IsBeforeBlockContext(context); }; @@ -51819,25 +50500,25 @@ var ts; }; RulesProvider.prototype.createActiveRules = function (options) { var rules = this.globalRules.HighPriorityCommonRules.slice(0); - if (options.insertSpaceAfterCommaDelimiter) { + if (options.InsertSpaceAfterCommaDelimiter) { rules.push(this.globalRules.SpaceAfterComma); } else { rules.push(this.globalRules.NoSpaceAfterComma); } - if (options.insertSpaceAfterFunctionKeywordForAnonymousFunctions) { + if (options.InsertSpaceAfterFunctionKeywordForAnonymousFunctions) { rules.push(this.globalRules.SpaceAfterAnonymousFunctionKeyword); } else { rules.push(this.globalRules.NoSpaceAfterAnonymousFunctionKeyword); } - if (options.insertSpaceAfterKeywordsInControlFlowStatements) { + if (options.InsertSpaceAfterKeywordsInControlFlowStatements) { rules.push(this.globalRules.SpaceAfterKeywordInControl); } else { rules.push(this.globalRules.NoSpaceAfterKeywordInControl); } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { + if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { rules.push(this.globalRules.SpaceAfterOpenParen); rules.push(this.globalRules.SpaceBeforeCloseParen); rules.push(this.globalRules.NoSpaceBetweenParens); @@ -51847,7 +50528,7 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseParen); rules.push(this.globalRules.NoSpaceBetweenParens); } - if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { + if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { rules.push(this.globalRules.SpaceAfterOpenBracket); rules.push(this.globalRules.SpaceBeforeCloseBracket); rules.push(this.globalRules.NoSpaceBetweenBrackets); @@ -51857,7 +50538,7 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseBracket); rules.push(this.globalRules.NoSpaceBetweenBrackets); } - if (options.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { + if (options.InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle); rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail); } @@ -51865,7 +50546,7 @@ var ts; rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle); rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail); } - if (options.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) { + if (options.InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) { rules.push(this.globalRules.SpaceAfterOpenBraceInJsxExpression); rules.push(this.globalRules.SpaceBeforeCloseBraceInJsxExpression); } @@ -51873,13 +50554,13 @@ var ts; rules.push(this.globalRules.NoSpaceAfterOpenBraceInJsxExpression); rules.push(this.globalRules.NoSpaceBeforeCloseBraceInJsxExpression); } - if (options.insertSpaceAfterSemicolonInForStatements) { + if (options.InsertSpaceAfterSemicolonInForStatements) { rules.push(this.globalRules.SpaceAfterSemicolonInFor); } else { rules.push(this.globalRules.NoSpaceAfterSemicolonInFor); } - if (options.insertSpaceBeforeAndAfterBinaryOperators) { + if (options.InsertSpaceBeforeAndAfterBinaryOperators) { rules.push(this.globalRules.SpaceBeforeBinaryOperator); rules.push(this.globalRules.SpaceAfterBinaryOperator); } @@ -51887,10 +50568,10 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeBinaryOperator); rules.push(this.globalRules.NoSpaceAfterBinaryOperator); } - if (options.placeOpenBraceOnNewLineForControlBlocks) { + if (options.PlaceOpenBraceOnNewLineForControlBlocks) { rules.push(this.globalRules.NewLineBeforeOpenBraceInControl); } - if (options.placeOpenBraceOnNewLineForFunctions) { + if (options.PlaceOpenBraceOnNewLineForFunctions) { rules.push(this.globalRules.NewLineBeforeOpenBraceInFunction); rules.push(this.globalRules.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock); } @@ -52128,7 +50809,7 @@ var ts; break; } if (formatting.SmartIndenter.shouldIndentChildNode(n, child)) { - return options.indentSize; + return options.IndentSize; } previousLine = line; child = n; @@ -52200,7 +50881,7 @@ var ts; } function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) { var indentation = inheritedIndentation; - var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0; + var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.IndentSize : 0; if (effectiveParentStartLine === startLine) { // if node is located on the same line with the parent // - inherit indentation from the parent @@ -52208,7 +50889,7 @@ var ts; indentation = startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(); - delta = Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta); + delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta(node) + delta); } else if (indentation === -1 /* Unknown */) { if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { @@ -52237,9 +50918,8 @@ var ts; case 147 /* MethodDeclaration */: if (node.asteriskToken) { return 37 /* AsteriskToken */; - } /* - fall-through - */ + } + // fall-through case 145 /* PropertyDeclaration */: case 142 /* Parameter */: return node.name.kind; @@ -52289,13 +50969,13 @@ var ts; recomputeIndentation: function (lineAdded) { if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent, node)) { if (lineAdded) { - indentation += options.indentSize; + indentation += options.IndentSize; } else { - indentation -= options.indentSize; + indentation -= options.IndentSize; } if (formatting.SmartIndenter.shouldIndentChildNode(node)) { - delta = options.indentSize; + delta = options.IndentSize; } else { delta = 0; @@ -52715,7 +51395,7 @@ var ts; // edit should not be applied only if we have one line feed between elements var lineDelta = currentStartLine - previousStartLine; if (lineDelta !== 1) { - recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.newLineCharacter); + recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.NewLineCharacter); } break; case 2 /* Space */: @@ -52776,14 +51456,14 @@ var ts; var internedSpacesIndentation; function getIndentationString(indentation, options) { // reset interned strings if FormatCodeOptions were changed - var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.tabSize || internedSizes.indentSize !== options.indentSize); + var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.TabSize || internedSizes.indentSize !== options.IndentSize); if (resetInternedStrings) { - internedSizes = { tabSize: options.tabSize, indentSize: options.indentSize }; + internedSizes = { tabSize: options.TabSize, indentSize: options.IndentSize }; internedTabsIndentation = internedSpacesIndentation = undefined; } - if (!options.convertTabsToSpaces) { - var tabs = Math.floor(indentation / options.tabSize); - var spaces = indentation - tabs * options.tabSize; + if (!options.ConvertTabsToSpaces) { + var tabs = Math.floor(indentation / options.TabSize); + var spaces = indentation - tabs * options.TabSize; var tabString = void 0; if (!internedTabsIndentation) { internedTabsIndentation = []; @@ -52798,13 +51478,13 @@ var ts; } else { var spacesString = void 0; - var quotient = Math.floor(indentation / options.indentSize); - var remainder = indentation % options.indentSize; + var quotient = Math.floor(indentation / options.IndentSize); + var remainder = indentation % options.IndentSize; if (!internedSpacesIndentation) { internedSpacesIndentation = []; } if (internedSpacesIndentation[quotient] === undefined) { - spacesString = repeat(" ", options.indentSize * quotient); + spacesString = repeat(" ", options.IndentSize * quotient); internedSpacesIndentation[quotient] = spacesString; } else { @@ -52841,7 +51521,7 @@ var ts; } // no indentation when the indent style is set to none, // so we can return fast - if (options.indentStyle === ts.IndentStyle.None) { + if (options.IndentStyle === ts.IndentStyle.None) { return 0; } var precedingToken = ts.findPrecedingToken(position, sourceFile); @@ -52857,7 +51537,7 @@ var ts; // indentation is first non-whitespace character in a previous line // for block indentation, we should look for a line which contains something that's not // whitespace. - if (options.indentStyle === ts.IndentStyle.Block) { + if (options.IndentStyle === ts.IndentStyle.Block) { // move backwards until we find a line with a non-whitespace character, // then find the first non-whitespace character for that line. var current_1 = position; @@ -52891,7 +51571,7 @@ var ts; indentationDelta = 0; } else { - indentationDelta = lineAtPosition !== currentStart.line ? options.indentSize : 0; + indentationDelta = lineAtPosition !== currentStart.line ? options.IndentSize : 0; } break; } @@ -52902,7 +51582,7 @@ var ts; } actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { - return actualIndentation + options.indentSize; + return actualIndentation + options.IndentSize; } previous = current; current = current.parent; @@ -52914,15 +51594,15 @@ var ts; return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, options); } SmartIndenter.getIndentation = getIndentation; + function getBaseIndentation(options) { + return options.BaseIndentSize || 0; + } + SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) { var start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, /*indentationDelta*/ 0, sourceFile, options); } SmartIndenter.getIndentationForNode = getIndentationForNode; - function getBaseIndentation(options) { - return options.baseIndentSize || 0; - } - SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, options) { var parent = current.parent; var parentStart; @@ -52957,7 +51637,7 @@ var ts; } // increase indentation if parent node wants its content to be indented and parent and child nodes don't start on the same line if (shouldIndentChildNode(parent, current) && !parentAndChildShareLine) { - indentationDelta += options.indentSize; + indentationDelta += options.IndentSize; } current = parent; currentStart = parentStart; @@ -53167,7 +51847,7 @@ var ts; break; } if (ch === 9 /* tab */) { - column += options.tabSize + (column % options.tabSize); + column += options.TabSize + (column % options.TabSize); } else { column++; @@ -53309,21 +51989,6 @@ var ts; } ScriptSnapshot.fromString = fromString; })(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {})); - function realizeDiagnostics(diagnostics, newLine) { - return diagnostics.map(function (d) { return realizeDiagnostic(d, newLine); }); - } - ts.realizeDiagnostics = realizeDiagnostics; - function realizeDiagnostic(diagnostic, newLine) { - return { - message: ts.flattenDiagnosticMessageText(diagnostic.messageText, newLine), - start: diagnostic.start, - length: diagnostic.length, - /// TODO: no need for the tolowerCase call - category: ts.DiagnosticCategory[diagnostic.category].toLowerCase(), - code: diagnostic.code - }; - } - ts.realizeDiagnostic = realizeDiagnostic; var scanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ true); var emptyArray = []; var jsDocTagNames = [ @@ -53368,20 +52033,19 @@ var ts; "version" ]; var jsDocCompletionEntries; - function createNode(kind, pos, end, parent) { - var node = kind >= 139 /* FirstNode */ ? new NodeObject(kind, pos, end) : - kind === 69 /* Identifier */ ? new IdentifierObject(kind, pos, end) : - new TokenObject(kind, pos, end); + function createNode(kind, pos, end, flags, parent) { + var node = new NodeObject(kind, pos, end); + node.flags = flags; node.parent = parent; return node; } var NodeObject = (function () { function NodeObject(kind, pos, end) { + this.kind = kind; this.pos = pos; this.end = end; this.flags = 0 /* None */; this.parent = undefined; - this.kind = kind; } NodeObject.prototype.getSourceFile = function () { return ts.getSourceFileOfNode(this); @@ -53416,14 +52080,14 @@ var ts; var token = useJSDocScanner ? scanner.scanJSDocToken() : scanner.scan(); var textPos = scanner.getTextPos(); if (textPos <= end) { - nodes.push(createNode(token, pos, textPos, this)); + nodes.push(createNode(token, pos, textPos, 0, this)); } pos = textPos; } return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(286 /* SyntaxList */, nodes.pos, nodes.end, this); + var list = createNode(282 /* SyntaxList */, nodes.pos, nodes.end, 0, this); list._children = []; var pos = nodes.pos; for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { @@ -53446,16 +52110,13 @@ var ts; scanner.setText((sourceFile || this.getSourceFile()).text); children = []; var pos_3 = this.pos; - var useJSDocScanner_1 = this.kind >= 273 /* FirstJSDocTagNode */ && this.kind <= 285 /* LastJSDocTagNode */; + var useJSDocScanner_1 = this.kind >= 273 /* FirstJSDocTagNode */ && this.kind <= 281 /* LastJSDocTagNode */; var processNode = function (node) { - var isJSDocTagNode = ts.isJSDocTag(node); - if (!isJSDocTagNode && pos_3 < node.pos) { + if (pos_3 < node.pos) { pos_3 = _this.addSyntheticNodes(children, pos_3, node.pos, useJSDocScanner_1); } children.push(node); - if (!isJSDocTagNode) { - pos_3 = node.end; - } + pos_3 = node.end; }; var processNodes = function (nodes) { if (pos_3 < nodes.pos) { @@ -53512,74 +52173,6 @@ var ts; }; return NodeObject; }()); - var TokenOrIdentifierObject = (function () { - function TokenOrIdentifierObject(pos, end) { - // Set properties in same order as NodeObject - this.pos = pos; - this.end = end; - this.flags = 0 /* None */; - this.parent = undefined; - } - TokenOrIdentifierObject.prototype.getSourceFile = function () { - return ts.getSourceFileOfNode(this); - }; - TokenOrIdentifierObject.prototype.getStart = function (sourceFile, includeJsDocComment) { - return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment); - }; - TokenOrIdentifierObject.prototype.getFullStart = function () { - return this.pos; - }; - TokenOrIdentifierObject.prototype.getEnd = function () { - return this.end; - }; - TokenOrIdentifierObject.prototype.getWidth = function (sourceFile) { - return this.getEnd() - this.getStart(sourceFile); - }; - TokenOrIdentifierObject.prototype.getFullWidth = function () { - return this.end - this.pos; - }; - TokenOrIdentifierObject.prototype.getLeadingTriviaWidth = function (sourceFile) { - return this.getStart(sourceFile) - this.pos; - }; - TokenOrIdentifierObject.prototype.getFullText = function (sourceFile) { - return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end); - }; - TokenOrIdentifierObject.prototype.getText = function (sourceFile) { - return (sourceFile || this.getSourceFile()).text.substring(this.getStart(), this.getEnd()); - }; - TokenOrIdentifierObject.prototype.getChildCount = function (sourceFile) { - return 0; - }; - TokenOrIdentifierObject.prototype.getChildAt = function (index, sourceFile) { - return undefined; - }; - TokenOrIdentifierObject.prototype.getChildren = function (sourceFile) { - return emptyArray; - }; - TokenOrIdentifierObject.prototype.getFirstToken = function (sourceFile) { - return undefined; - }; - TokenOrIdentifierObject.prototype.getLastToken = function (sourceFile) { - return undefined; - }; - return TokenOrIdentifierObject; - }()); - var TokenObject = (function (_super) { - __extends(TokenObject, _super); - function TokenObject(kind, pos, end) { - _super.call(this, pos, end); - this.kind = kind; - } - return TokenObject; - }(TokenOrIdentifierObject)); - var IdentifierObject = (function (_super) { - __extends(IdentifierObject, _super); - function IdentifierObject(kind, pos, end) { - _super.call(this, pos, end); - } - return IdentifierObject; - }(TokenOrIdentifierObject)); - IdentifierObject.prototype.kind = 69 /* Identifier */; var SymbolObject = (function () { function SymbolObject(flags, name) { this.flags = flags; @@ -53924,7 +52517,7 @@ var ts; return this.checker.getIndexTypeOfType(this, 1 /* Number */); }; TypeObject.prototype.getBaseTypes = function () { - return this.flags & (32768 /* Class */ | 65536 /* Interface */) + return this.flags & (1024 /* Class */ | 2048 /* Interface */) ? this.checker.getBaseTypes(this) : undefined; }; @@ -53983,7 +52576,7 @@ var ts; return this.namedDeclarations; }; SourceFileObject.prototype.computeNamedDeclarations = function () { - var result = ts.createMap(); + var result = {}; ts.forEachChild(this, visit); return result; function addDeclaration(declaration) { @@ -53994,13 +52587,13 @@ var ts; } } function getDeclarations(name) { - return result[name] || (result[name] = []); + return ts.getProperty(result, name) || (result[name] = []); } function getDeclarationName(declaration) { if (declaration.name) { - var result_3 = getTextOfIdentifierOrLiteral(declaration.name); - if (result_3 !== undefined) { - return result_3; + var result_2 = getTextOfIdentifierOrLiteral(declaration.name); + if (result_2 !== undefined) { + return result_2; } if (declaration.name.kind === 140 /* ComputedPropertyName */) { var expr = declaration.name.expression; @@ -54140,30 +52733,6 @@ var ts; IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; })(ts.IndentStyle || (ts.IndentStyle = {})); var IndentStyle = ts.IndentStyle; - function toEditorSettings(optionsAsMap) { - var allPropertiesAreCamelCased = true; - for (var key in optionsAsMap) { - if (ts.hasProperty(optionsAsMap, key) && !isCamelCase(key)) { - allPropertiesAreCamelCased = false; - break; - } - } - if (allPropertiesAreCamelCased) { - return optionsAsMap; - } - var settings = {}; - for (var key in optionsAsMap) { - if (ts.hasProperty(optionsAsMap, key)) { - var newKey = isCamelCase(key) ? key : key.charAt(0).toLowerCase() + key.substr(1); - settings[newKey] = optionsAsMap[key]; - } - } - return settings; - } - ts.toEditorSettings = toEditorSettings; - function isCamelCase(s) { - return !s.length || s.charAt(0) === s.charAt(0).toLowerCase(); - } (function (SymbolDisplayPartKind) { SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; SymbolDisplayPartKind[SymbolDisplayPartKind["className"] = 1] = "className"; @@ -54238,8 +52807,6 @@ var ts; ScriptElementKind.typeElement = "type"; /** enum E */ ScriptElementKind.enumElement = "enum"; - // TODO: GH#9983 - ScriptElementKind.enumMemberElement = "const"; /** * Inside module and script only * const v = .. @@ -54280,8 +52847,6 @@ var ts; ScriptElementKind.alias = "alias"; ScriptElementKind.constElement = "const"; ScriptElementKind.letElement = "let"; - ScriptElementKind.directory = "directory"; - ScriptElementKind.externalModuleName = "external module name"; })(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {})); var ScriptElementKindModifier; (function (ScriptElementKindModifier) { @@ -54370,9 +52935,9 @@ var ts; return false; } // If the parent is not sourceFile or module block it is local variable - for (var parent_17 = declaration.parent; !ts.isFunctionBlock(parent_17); parent_17 = parent_17.parent) { + for (var parent_16 = declaration.parent; !ts.isFunctionBlock(parent_16); parent_16 = parent_16.parent) { // Reached source file or module block - if (parent_17.kind === 256 /* SourceFile */ || parent_17.kind === 226 /* ModuleBlock */) { + if (parent_16.kind === 256 /* SourceFile */ || parent_16.kind === 226 /* ModuleBlock */) { return false; } } @@ -54388,7 +52953,7 @@ var ts; }; } ts.getDefaultCompilerOptions = getDefaultCompilerOptions; - // Cache host information about script should be refreshed + // Cache host information about scrip Should be refreshed // at each language service public entry point, since we don't know when // set of scripts handled by the host changes. var HostCache = (function () { @@ -54458,24 +53023,49 @@ var ts; }; return HostCache; }()); + var SyntaxTreeCache = (function () { + function SyntaxTreeCache(host) { + this.host = host; + } + SyntaxTreeCache.prototype.getCurrentSourceFile = function (fileName) { + var scriptSnapshot = this.host.getScriptSnapshot(fileName); + if (!scriptSnapshot) { + // The host does not know about this file. + throw new Error("Could not find file: '" + fileName + "'."); + } + var scriptKind = ts.getScriptKind(fileName, this.host); + var version = this.host.getScriptVersion(fileName); + var sourceFile; + if (this.currentFileName !== fileName) { + // This is a new file, just parse it + sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 2 /* Latest */, version, /*setNodeParents*/ true, scriptKind); + } + else if (this.currentFileVersion !== version) { + // This is the same file, just a newer version. Incrementally parse the file. + var editRange = scriptSnapshot.getChangeRange(this.currentFileScriptSnapshot); + sourceFile = updateLanguageServiceSourceFile(this.currentSourceFile, scriptSnapshot, version, editRange); + } + if (sourceFile) { + // All done, ensure state is up to date + this.currentFileVersion = version; + this.currentFileName = fileName; + this.currentFileScriptSnapshot = scriptSnapshot; + this.currentSourceFile = sourceFile; + } + return this.currentSourceFile; + }; + return SyntaxTreeCache; + }()); function setSourceFileFields(sourceFile, scriptSnapshot, version) { sourceFile.version = version; sourceFile.scriptSnapshot = scriptSnapshot; } - /** - * Matches a triple slash reference directive with an incomplete string literal for its path. Used - * to determine if the caret is currently within the string literal and capture the literal fragment - * for completions. - * For example, this matches /// = commentRange.pos && position <= commentRange.end && commentRange; }); - if (!range) { - return undefined; - } - var text = sourceFile.text.substr(range.pos, position - range.pos); - var match = tripleSlashDirectiveFragmentRegex.exec(text); - if (match) { - var prefix = match[1]; - var kind = match[2]; - var toComplete = match[3]; - var scriptPath = ts.getDirectoryPath(sourceFile.path); - var entries_3; - if (kind === "path") { - // Give completions for a relative path - var span = getDirectoryFragmentTextSpan(toComplete, range.pos + prefix.length); - entries_3 = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(program.getCompilerOptions()), /*includeExtensions*/ true, span, sourceFile.path); - } - else { - // Give completions based on the typings available - var span = { start: range.pos + prefix.length, length: match[0].length - prefix.length }; - entries_3 = getCompletionEntriesFromTypings(host, program.getCompilerOptions(), scriptPath, span); - } - return { - isMemberCompletion: false, - isNewIdentifierLocation: true, - entries: entries_3 - }; - } - return undefined; - } - function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { - if (result === void 0) { result = []; } - // Check for typings specified in compiler options - if (options.types) { - for (var _i = 0, _a = options.types; _i < _a.length; _i++) { - var moduleName = _a[_i]; - result.push(createCompletionEntryForModule(moduleName, ScriptElementKind.externalModuleName, span)); - } - } - else if (host.getDirectories) { - var typeRoots = ts.getEffectiveTypeRoots(options, host); - for (var _b = 0, typeRoots_2 = typeRoots; _b < typeRoots_2.length; _b++) { - var root = typeRoots_2[_b]; - getCompletionEntriesFromDirectories(host, options, root, span, result); - } - } - if (host.getDirectories) { - // Also get all @types typings installed in visible node_modules directories - for (var _c = 0, _d = findPackageJsons(scriptPath); _c < _d.length; _c++) { - var package = _d[_c]; - var typesDir = ts.combinePaths(ts.getDirectoryPath(package), "node_modules/@types"); - getCompletionEntriesFromDirectories(host, options, typesDir, span, result); - } - } - return result; - } - function getCompletionEntriesFromDirectories(host, options, directory, span, result) { - if (host.getDirectories && tryDirectoryExists(host, directory)) { - var directories = tryGetDirectories(host, directory); - if (directories) { - for (var _i = 0, directories_3 = directories; _i < directories_3.length; _i++) { - var typeDirectory = directories_3[_i]; - typeDirectory = ts.normalizePath(typeDirectory); - result.push(createCompletionEntryForModule(ts.getBaseFileName(typeDirectory), ScriptElementKind.externalModuleName, span)); - } - } - } - } - function findPackageJsons(currentDir) { - var paths = []; - var currentConfigPath; - while (true) { - currentConfigPath = ts.findConfigFile(currentDir, function (f) { return tryFileExists(host, f); }, "package.json"); - if (currentConfigPath) { - paths.push(currentConfigPath); - currentDir = ts.getDirectoryPath(currentConfigPath); - var parent_21 = ts.getDirectoryPath(currentDir); - if (currentDir === parent_21) { - break; - } - currentDir = parent_21; - } - else { - break; - } - } - return paths; - } - function enumerateNodeModulesVisibleToScript(host, scriptPath) { - var result = []; - if (host.readFile && host.fileExists) { - for (var _i = 0, _a = findPackageJsons(scriptPath); _i < _a.length; _i++) { - var packageJson = _a[_i]; - var package = tryReadingPackageJson(packageJson); - if (!package) { - return; - } - var nodeModulesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules"); - var foundModuleNames = []; - // Provide completions for all non @types dependencies - for (var _b = 0, nodeModulesDependencyKeys_1 = nodeModulesDependencyKeys; _b < nodeModulesDependencyKeys_1.length; _b++) { - var key = nodeModulesDependencyKeys_1[_b]; - addPotentialPackageNames(package[key], foundModuleNames); - } - for (var _c = 0, foundModuleNames_1 = foundModuleNames; _c < foundModuleNames_1.length; _c++) { - var moduleName = foundModuleNames_1[_c]; - var moduleDir = ts.combinePaths(nodeModulesDir, moduleName); - result.push({ - moduleName: moduleName, - moduleDir: moduleDir - }); - } - } - } - return result; - function tryReadingPackageJson(filePath) { - try { - var fileText = tryReadFile(host, filePath); - return fileText ? JSON.parse(fileText) : undefined; - } - catch (e) { - return undefined; - } - } - function addPotentialPackageNames(dependencies, result) { - if (dependencies) { - for (var dep in dependencies) { - if (dependencies.hasOwnProperty(dep) && !ts.startsWith(dep, "@types/")) { - result.push(dep); - } - } - } - } - } - function createCompletionEntryForModule(name, kind, replacementSpan) { - return { name: name, kind: kind, kindModifiers: ScriptElementKindModifier.none, sortText: name, replacementSpan: replacementSpan }; - } - // Replace everything after the last directory seperator that appears - function getDirectoryFragmentTextSpan(text, textStart) { - var index = text.lastIndexOf(ts.directorySeparator); - var offset = index !== -1 ? index + 1 : 0; - return { start: textStart + offset, length: text.length - offset }; - } - // Returns true if the path is explicitly relative to the script (i.e. relative to . or ..) - function isPathRelativeToScript(path) { - if (path && path.length >= 2 && path.charCodeAt(0) === 46 /* dot */) { - var slashIndex = path.length >= 3 && path.charCodeAt(1) === 46 /* dot */ ? 2 : 1; - var slashCharCode = path.charCodeAt(slashIndex); - return slashCharCode === 47 /* slash */ || slashCharCode === 92 /* backslash */; - } - return false; - } - function normalizeAndPreserveTrailingSlash(path) { - return ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(ts.normalizePath(path)) : ts.normalizePath(path); - } - function tryGetDirectories(host, directoryName) { - return tryIOAndConsumeErrors(host, host.getDirectories, directoryName); - } - function tryReadDirectory(host, path, extensions, exclude, include) { - return tryIOAndConsumeErrors(host, host.readDirectory, path, extensions, exclude, include); - } - function tryReadFile(host, path) { - return tryIOAndConsumeErrors(host, host.readFile, path); - } - function tryFileExists(host, path) { - return tryIOAndConsumeErrors(host, host.fileExists, path); - } - function tryDirectoryExists(host, path) { - try { - return ts.directoryProbablyExists(path, host); - } - catch (e) { } - return undefined; - } - function tryIOAndConsumeErrors(host, toApply) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - try { - return toApply && toApply.apply(host, args); - } - catch (e) { } - return undefined; - } } function getCompletionEntryDetails(fileName, position, entryName) { synchronizeHostData(); @@ -57310,7 +55346,7 @@ var ts; displayParts.push(ts.keywordPart(92 /* NewKeyword */)); displayParts.push(ts.spacePart()); } - if (!(type.flags & 2097152 /* Anonymous */) && type.symbol) { + if (!(type.flags & 65536 /* Anonymous */) && type.symbol) { ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */)); } addSignatureDisplayParts(signature, allSignatures, 8 /* WriteArrowStyleSignature */); @@ -57379,7 +55415,7 @@ var ts; displayParts.push(ts.spacePart()); displayParts.push(ts.operatorPart(56 /* EqualsToken */)); displayParts.push(ts.spacePart()); - ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 512 /* InTypeAlias */)); + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration)); } if (symbolFlags & 384 /* Enum */) { addNewLineIfDisplayPartsExist(); @@ -57458,14 +55494,7 @@ var ts; } if (symbolFlags & 8388608 /* Alias */) { addNewLineIfDisplayPartsExist(); - if (symbol.declarations[0].kind === 228 /* NamespaceExportDeclaration */) { - displayParts.push(ts.keywordPart(82 /* ExportKeyword */)); - displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(126 /* NamespaceKeyword */)); - } - else { - displayParts.push(ts.keywordPart(89 /* ImportKeyword */)); - } + displayParts.push(ts.keywordPart(89 /* ImportKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); ts.forEach(symbol.declarations, function (declaration) { @@ -57538,27 +55567,6 @@ var ts; } if (!documentation) { documentation = symbol.getDocumentationComment(); - if (documentation.length === 0 && symbol.flags & 4 /* Property */) { - // For some special property access expressions like `experts.foo = foo` or `module.exports.foo = foo` - // there documentation comments might be attached to the right hand side symbol of their declarations. - // The pattern of such special property access is that the parent symbol is the symbol of the file. - if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 256 /* SourceFile */; })) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (!declaration.parent || declaration.parent.kind !== 187 /* BinaryExpression */) { - continue; - } - var rhsSymbol = program.getTypeChecker().getSymbolAtLocation(declaration.parent.right); - if (!rhsSymbol) { - continue; - } - documentation = rhsSymbol.getDocumentationComment(); - if (documentation.length > 0) { - break; - } - } - } - } } return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind }; function addNewLineIfDisplayPartsExist() { @@ -57765,7 +55773,7 @@ var ts; // Type reference directives var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); if (typeReferenceDirective) { - var referenceFile = program.getResolvedTypeReferenceDirectives()[typeReferenceDirective.fileName]; + var referenceFile = ts.lookUp(program.getResolvedTypeReferenceDirectives(), typeReferenceDirective.fileName); if (referenceFile && referenceFile.resolvedFileName) { return [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)]; } @@ -57840,14 +55848,14 @@ var ts; if (!type) { return undefined; } - if (type.flags & 524288 /* Union */ && !(type.flags & 16 /* Enum */)) { - var result_4 = []; + if (type.flags & 16384 /* Union */) { + var result_3 = []; ts.forEach(type.types, function (t) { if (t.symbol) { - ts.addRange(/*to*/ result_4, /*from*/ getDefinitionFromSymbol(t.symbol, node)); + ts.addRange(/*to*/ result_3, /*from*/ getDefinitionFromSymbol(t.symbol, node)); } }); - return result_4; + return result_3; } if (!type.symbol) { return undefined; @@ -57897,14 +55905,14 @@ var ts; if (!referencedSymbols) { return undefined; } - var fileNameToDocumentHighlights = ts.createMap(); + var fileNameToDocumentHighlights = {}; var result = []; for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) { var referencedSymbol = referencedSymbols_1[_i]; for (var _a = 0, _b = referencedSymbol.references; _a < _b.length; _a++) { var referenceEntry = _b[_a]; var fileName_1 = referenceEntry.fileName; - var documentHighlights = fileNameToDocumentHighlights[fileName_1]; + var documentHighlights = ts.getProperty(fileNameToDocumentHighlights, fileName_1); if (!documentHighlights) { documentHighlights = { fileName: fileName_1, highlightSpans: [] }; fileNameToDocumentHighlights[fileName_1] = documentHighlights; @@ -58053,19 +56061,19 @@ var ts; function getThrowStatementOwner(throwStatement) { var child = throwStatement; while (child.parent) { - var parent_22 = child.parent; - if (ts.isFunctionBlock(parent_22) || parent_22.kind === 256 /* SourceFile */) { - return parent_22; + var parent_20 = child.parent; + if (ts.isFunctionBlock(parent_20) || parent_20.kind === 256 /* SourceFile */) { + return parent_20; } // A throw-statement is only owned by a try-statement if the try-statement has // a catch clause, and if the throw-statement occurs within the try block. - if (parent_22.kind === 216 /* TryStatement */) { - var tryStatement = parent_22; + if (parent_20.kind === 216 /* TryStatement */) { + var tryStatement = parent_20; if (tryStatement.tryBlock === child && tryStatement.catchClause) { return child; } } - child = parent_22; + child = parent_20; } return undefined; } @@ -58527,7 +56535,7 @@ var ts; var sourceFile = sourceFiles_4[_i]; cancellationToken.throwIfCancellationRequested(); var nameTable = getNameTable(sourceFile); - if (nameTable[internedName] !== undefined) { + if (ts.lookUp(nameTable, internedName) !== undefined) { result = result || []; getReferencesInNode(sourceFile, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex); } @@ -58547,8 +56555,7 @@ var ts; name: name, kind: info.symbolKind, fileName: declarations[0].getSourceFile().fileName, - textSpan: ts.createTextSpan(declarations[0].getStart(), 0), - displayParts: info.displayParts + textSpan: ts.createTextSpan(declarations[0].getStart(), 0) }; } function getAliasSymbolForPropertyNameSymbol(symbol, location) { @@ -58717,8 +56724,7 @@ var ts; fileName: targetLabel.getSourceFile().fileName, kind: ScriptElementKind.label, name: labelName, - textSpan: ts.createTextSpanFromBounds(targetLabel.getStart(), targetLabel.getEnd()), - displayParts: [ts.displayPart(labelName, SymbolDisplayPartKind.text)] + textSpan: ts.createTextSpanFromBounds(targetLabel.getStart(), targetLabel.getEnd()) }; return [{ definition: definition, references: references }]; } @@ -58750,6 +56756,7 @@ var ts; */ function getReferencesInNode(container, searchSymbol, searchText, searchLocation, searchMeaning, findInStrings, findInComments, result, symbolToIndex) { var sourceFile = container.getSourceFile(); + var tripleSlashDirectivePrefixRegex = /^\/\/\/\s*= 0 ? s : undefined; }); + var result_4 = []; + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result_4, /*previousIterationSymbolsCache*/ {}); + return ts.forEach(result_4, function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); } return undefined; }); @@ -59193,20 +57203,20 @@ var ts; var contextualType = typeChecker.getContextualType(objectLiteral); var name = getNameFromObjectLiteralElement(node); if (name && contextualType) { - var result_6 = []; - var symbol_2 = contextualType.getProperty(name); - if (symbol_2) { - result_6.push(symbol_2); + var result_5 = []; + var symbol_1 = contextualType.getProperty(name); + if (symbol_1) { + result_5.push(symbol_1); } - if (contextualType.flags & 524288 /* Union */) { + if (contextualType.flags & 16384 /* Union */) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_6.push(symbol); + result_5.push(symbol); } }); } - return result_6; + return result_5; } return undefined; } @@ -59271,12 +57281,12 @@ var ts; return false; } /// NavigateTo - function getNavigateToItems(searchValue, maxResultCount, excludeDts) { + function getNavigateToItems(searchValue, maxResultCount) { synchronizeHostData(); var checker = getProgram().getTypeChecker(); - return ts.NavigateTo.getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount, excludeDts); + return ts.NavigateTo.getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount); } - function getEmitOutput(fileName, emitDeclarationsOnly) { + function getEmitOutput(fileName) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var outputFiles = []; @@ -59287,7 +57297,7 @@ var ts; text: data }); } - var emitOutput = program.emit(sourceFile, writeFile, cancellationToken, emitDeclarationsOnly); + var emitOutput = program.emit(sourceFile, writeFile, cancellationToken); return { outputFiles: outputFiles, emitSkipped: emitOutput.emitSkipped @@ -59445,6 +57455,7 @@ var ts; case 172 /* PropertyAccessExpression */: case 139 /* QualifiedName */: case 9 /* StringLiteral */: + case 166 /* StringLiteralType */: case 84 /* FalseKeyword */: case 99 /* TrueKeyword */: case 93 /* NullKeyword */: @@ -59798,9 +57809,6 @@ var ts; * False will mean that node is not classified and traverse routine should recurse into node contents. */ function tryClassifyNode(node) { - if (ts.isJSDocTag(node)) { - return true; - } if (ts.nodeIsMissing(node)) { return true; } @@ -59883,7 +57891,7 @@ var ts; else if (tokenKind === 8 /* NumericLiteral */) { return 4 /* numericLiteral */; } - else if (tokenKind === 9 /* StringLiteral */) { + else if (tokenKind === 9 /* StringLiteral */ || tokenKind === 166 /* StringLiteralType */) { return token.parent.kind === 246 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; } else if (tokenKind === 10 /* RegularExpressionLiteral */) { @@ -60001,37 +58009,33 @@ var ts; return undefined; } } - function getIndentationAtPosition(fileName, position, optionsOrSettings) { - var start = ts.timestamp(); - var settings = toEditorSettings(optionsOrSettings); + function getIndentationAtPosition(fileName, position, editorOptions) { + var start = new Date().getTime(); var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - log("getIndentationAtPosition: getCurrentSourceFile: " + (ts.timestamp() - start)); - start = ts.timestamp(); - var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, settings); - log("getIndentationAtPosition: computeIndentation : " + (ts.timestamp() - start)); + log("getIndentationAtPosition: getCurrentSourceFile: " + (new Date().getTime() - start)); + start = new Date().getTime(); + var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, editorOptions); + log("getIndentationAtPosition: computeIndentation : " + (new Date().getTime() - start)); return result; } - function getFormattingEditsForRange(fileName, start, end, optionsOrSettings) { - var settings = toEditorSettings(optionsOrSettings); + function getFormattingEditsForRange(fileName, start, end, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(settings), settings); + return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(options), options); } - function getFormattingEditsForDocument(fileName, optionsOrSettings) { - var settings = toEditorSettings(optionsOrSettings); + function getFormattingEditsForDocument(fileName, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.formatting.formatDocument(sourceFile, getRuleProvider(settings), settings); + return ts.formatting.formatDocument(sourceFile, getRuleProvider(options), options); } - function getFormattingEditsAfterKeystroke(fileName, position, key, optionsOrSettings) { - var settings = toEditorSettings(optionsOrSettings); + function getFormattingEditsAfterKeystroke(fileName, position, key, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); if (key === "}") { - return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(settings), settings); + return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(options), options); } else if (key === ";") { - return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(settings), settings); + return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(options), options); } else if (key === "\n") { - return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(settings), settings); + return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(options), options); } return []; } @@ -60311,9 +58315,9 @@ var ts; } } function getStringLiteralTypeForNode(node, typeChecker) { - var searchNode = node.parent.kind === 166 /* LiteralType */ ? node.parent : node; + var searchNode = node.parent.kind === 166 /* StringLiteralType */ ? node.parent : node; var type = typeChecker.getTypeAtLocation(searchNode); - if (type && type.flags & 32 /* StringLiteral */) { + if (type && type.flags & 256 /* StringLiteral */) { return type; } return undefined; @@ -60459,7 +58463,7 @@ var ts; } ts.getNameTable = getNameTable; function initializeNameTable(sourceFile) { - var nameTable = ts.createMap(); + var nameTable = {}; walk(sourceFile); sourceFile.nameTable = nameTable; function walk(node) { @@ -60563,7 +58567,7 @@ var ts; var lastEnd = 0; for (var i = 0, n = dense.length; i < n; i += 3) { var start = dense[i]; - var length_5 = dense[i + 1]; + var length_3 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -60572,8 +58576,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: TokenClass.Whitespace }); } } - entries.push({ length: length_5, classification: convertClassification(type) }); - lastEnd = start + length_5; + entries.push({ length: length_3, classification: convertClassification(type) }); + lastEnd = start + length_3; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -60753,7 +58757,7 @@ var ts; var end = scanner.getTextPos(); addResult(start, end, classFromKind(token)); if (end >= text.length) { - if (token === 9 /* StringLiteral */) { + if (token === 9 /* StringLiteral */ || token === 166 /* StringLiteralType */) { // Check to see if we finished up on a multiline string literal. var tokenText = scanner.getTokenText(); if (scanner.isUnterminated()) { @@ -60892,6 +58896,7 @@ var ts; case 8 /* NumericLiteral */: return 4 /* numericLiteral */; case 9 /* StringLiteral */: + case 166 /* StringLiteralType */: return 6 /* stringLiteral */; case 10 /* RegularExpressionLiteral */: return 7 /* regularExpressionLiteral */; @@ -60932,8 +58937,6 @@ var ts; function initializeServices() { ts.objectAllocator = { getNodeConstructor: function () { return NodeObject; }, - getTokenConstructor: function () { return TokenObject; }, - getIdentifierConstructor: function () { return IdentifierObject; }, getSourceFileConstructor: function () { return SourceFileObject; }, getSymbolConstructor: function () { return SymbolObject; }, getTypeConstructor: function () { return TypeObject; }, @@ -61559,7 +59562,7 @@ var ts; // /// /* @internal */ -var debugObjectHost = new Function("return this")(); +var debugObjectHost = this; // We need to use 'null' to interface with the managed side. /* tslint:disable:no-null-keyword */ /* tslint:disable:no-in-operator */ @@ -61612,7 +59615,7 @@ var ts; this.resolveModuleNames = function (moduleNames, containingFile) { var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile)); return ts.map(moduleNames, function (name) { - var result = ts.getProperty(resolutionsInFile, name); + var result = ts.lookUp(resolutionsInFile, name); return result ? { resolvedFileName: result } : undefined; }); }; @@ -61623,7 +59626,7 @@ var ts; if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) { this.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { var typeDirectivesForFile = JSON.parse(_this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile)); - return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); }); + return ts.map(typeDirectiveNames, function (name) { return ts.lookUp(typeDirectivesForFile, name); }); }; } } @@ -61647,12 +59650,6 @@ var ts; } return this.shimHost.getProjectVersion(); }; - LanguageServiceShimHostAdapter.prototype.getTypeRootsVersion = function () { - if (!this.shimHost.getTypeRootsVersion) { - return 0; - } - return this.shimHost.getTypeRootsVersion(); - }; LanguageServiceShimHostAdapter.prototype.useCaseSensitiveFileNames = function () { return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; }; @@ -61704,21 +59701,11 @@ var ts; return this.shimHost.getCurrentDirectory(); }; LanguageServiceShimHostAdapter.prototype.getDirectories = function (path) { - return JSON.parse(this.shimHost.getDirectories(path)); + return this.shimHost.getDirectories(path); }; LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) { return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); }; - LanguageServiceShimHostAdapter.prototype.readDirectory = function (path, extensions, exclude, include, depth) { - var pattern = ts.getFileMatcherPatterns(path, extensions, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); - return JSON.parse(this.shimHost.readDirectory(path, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); - }; - LanguageServiceShimHostAdapter.prototype.readFile = function (path, encoding) { - return this.shimHost.readFile(path, encoding); - }; - LanguageServiceShimHostAdapter.prototype.fileExists = function (path) { - return this.shimHost.fileExists(path); - }; return LanguageServiceShimHostAdapter; }()); ts.LanguageServiceShimHostAdapter = LanguageServiceShimHostAdapter; @@ -61732,7 +59719,7 @@ var ts; this.lastCancellationCheckTime = 0; } ThrottledCancellationToken.prototype.isCancellationRequested = function () { - var time = ts.timestamp(); + var time = Date.now(); var duration = Math.abs(time - this.lastCancellationCheckTime); if (duration > 10) { // Check no more than once every 10 ms. @@ -61785,9 +59772,6 @@ var ts; CoreServicesShimHostAdapter.prototype.readDirectoryFallback = function (rootDir, extension, exclude) { return JSON.parse(this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude))); }; - CoreServicesShimHostAdapter.prototype.getDirectories = function (path) { - return JSON.parse(this.shimHost.getDirectories(path)); - }; return CoreServicesShimHostAdapter; }()); ts.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter; @@ -61795,11 +59779,11 @@ var ts; var start; if (logPerformance) { logger.log(actionDescription); - start = ts.timestamp(); + start = Date.now(); } var result = action(); if (logPerformance) { - var end = ts.timestamp(); + var end = Date.now(); logger.log(actionDescription + " completed in " + (end - start) + " msec"); if (typeof result === "string") { var str = result; @@ -61838,6 +59822,20 @@ var ts; }; return ShimBase; }()); + function realizeDiagnostics(diagnostics, newLine) { + return diagnostics.map(function (d) { return realizeDiagnostic(d, newLine); }); + } + ts.realizeDiagnostics = realizeDiagnostics; + function realizeDiagnostic(diagnostic, newLine) { + return { + message: ts.flattenDiagnosticMessageText(diagnostic.messageText, newLine), + start: diagnostic.start, + length: diagnostic.length, + /// TODO: no need for the tolowerCase call + category: ts.DiagnosticCategory[diagnostic.category].toLowerCase(), + code: diagnostic.code + }; + } var LanguageServiceShimObject = (function (_super) { __extends(LanguageServiceShimObject, _super); function LanguageServiceShimObject(factory, host, languageService) { @@ -62171,13 +60169,6 @@ var ts; }; }); }; - CoreServicesShimObject.prototype.getAutomaticTypeDirectiveNames = function (compilerOptionsJson) { - var _this = this; - return this.forwardJSONCall("getAutomaticTypeDirectiveNames('" + compilerOptionsJson + "')", function () { - var compilerOptions = JSON.parse(compilerOptionsJson); - return ts.getAutomaticTypeDirectiveNames(compilerOptions, _this.host); - }); - }; CoreServicesShimObject.prototype.convertFileReferences = function (refs) { if (!refs) { return undefined; @@ -62204,7 +60195,7 @@ var ts; typingOptions: {}, files: [], raw: {}, - errors: [ts.realizeDiagnostic(result.error, "\r\n")] + errors: [realizeDiagnostic(result.error, "\r\n")] }; } var normalizedFileName = ts.normalizeSlashes(fileName); @@ -62214,7 +60205,7 @@ var ts; typingOptions: configFile.typingOptions, files: configFile.fileNames, raw: configFile.raw, - errors: ts.realizeDiagnostics(configFile.errors, "\r\n") + errors: realizeDiagnostics(configFile.errors, "\r\n") }; }); }; @@ -62313,5 +60304,5 @@ var TypeScript; // 'toolsVersion' gets consumed by the managed side, so it's not unused. // TODO: it should be moved into a namespace though. /* @internal */ -var toolsVersion = "2.0"; +var toolsVersion = "1.9"; /* tslint:enable:no-unused-variable */ diff --git a/package.json b/package.json index 0269dc17a45..1f943f89788 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "typescript", "author": "Microsoft Corp.", "homepage": "http://typescriptlang.org/", - "version": "2.0.5", + "version": "2.1.0", "license": "Apache-2.0", "description": "TypeScript is a language for application scale JavaScript development", "keywords": [ @@ -75,8 +75,9 @@ "through2": "latest", "travis-fold": "latest", "ts-node": "latest", - "tslint": "3.15.1", - "typescript": "2.0.*" + "tsd": "latest", + "tslint": "next", + "typescript": "next" }, "scripts": { "pretest": "jake tests", diff --git a/scripts/browserify-optional.js b/scripts/browserify-optional.js new file mode 100644 index 00000000000..43997c7803c --- /dev/null +++ b/scripts/browserify-optional.js @@ -0,0 +1,24 @@ +// simple script to optionally elide source-map-support (or other optional modules) when running browserify. + +var stream = require("stream"), + Transform = stream.Transform, + resolve = require("browser-resolve"); + +var requirePattern = /require\s*\(\s*['"](source-map-support)['"]\s*\)/; +module.exports = function (file) { + return new Transform({ + transform: function (data, encoding, cb) { + var text = encoding === "buffer" ? data.toString("utf8") : data; + this.push(new Buffer(text.replace(requirePattern, function (originalText, moduleName) { + try { + resolve.sync(moduleName, { filename: file }); + return originalText; + } + catch (e) { + return "(function () { throw new Error(\"module '" + moduleName + "' not found.\"); })()"; + } + }), "utf8")); + cb(); + } + }); +}; \ No newline at end of file diff --git a/scripts/tslint/preferConstRule.ts b/scripts/tslint/preferConstRule.ts index 1d316692468..9425d2b6079 100644 --- a/scripts/tslint/preferConstRule.ts +++ b/scripts/tslint/preferConstRule.ts @@ -9,44 +9,12 @@ export class Rule extends Lint.Rules.AbstractRule { } } -function isBindingPattern(node: ts.Node): node is ts.BindingPattern { - return !!node && (node.kind === ts.SyntaxKind.ArrayBindingPattern || node.kind === ts.SyntaxKind.ObjectBindingPattern); -} - -function walkUpBindingElementsAndPatterns(node: ts.Node): ts.Node { - while (node && (node.kind === ts.SyntaxKind.BindingElement || isBindingPattern(node))) { - node = node.parent; - } - - return node; -} - -function getCombinedNodeFlags(node: ts.Node): ts.NodeFlags { - node = walkUpBindingElementsAndPatterns(node); - - let flags = node.flags; - if (node.kind === ts.SyntaxKind.VariableDeclaration) { - node = node.parent; - } - - if (node && node.kind === ts.SyntaxKind.VariableDeclarationList) { - flags |= node.flags; - node = node.parent; - } - - if (node && node.kind === ts.SyntaxKind.VariableStatement) { - flags |= node.flags; - } - - return flags; -} - function isLet(node: ts.Node) { - return !!(getCombinedNodeFlags(node) & ts.NodeFlags.Let); + return !!(ts.getCombinedNodeFlags(node) & ts.NodeFlags.Let); } function isExported(node: ts.Node) { - return !!(getCombinedNodeFlags(node) & ts.NodeFlags.Export); + return !!(ts.getCombinedModifierFlags(node) & ts.ModifierFlags.Export); } function isAssignmentOperator(token: ts.SyntaxKind): boolean { @@ -125,11 +93,16 @@ class PreferConstWalker extends Lint.RuleWalker { private visitBindingPatternIdentifiers(pattern: ts.BindingPattern) { for (const element of pattern.elements) { - if (element.name.kind === ts.SyntaxKind.Identifier) { - this.markAssignment(element.name as ts.Identifier); + if (element.kind !== ts.SyntaxKind.BindingElement) { + continue; + } + + const name = (element).name; + if (name.kind === ts.SyntaxKind.Identifier) { + this.markAssignment(name as ts.Identifier); } else { - this.visitBindingPatternIdentifiers(element.name as ts.BindingPattern); + this.visitBindingPatternIdentifiers(name as ts.BindingPattern); } } } @@ -223,7 +196,9 @@ class PreferConstWalker extends Lint.RuleWalker { private collectBindingPatternIdentifiers(value: ts.VariableDeclaration, pattern: ts.BindingPattern, table: ts.MapLike) { for (const element of pattern.elements) { - this.collectNameIdentifiers(value, element.name, table); + if (element.kind === ts.SyntaxKind.BindingElement) { + this.collectNameIdentifiers(value, (element).name, table); + } } } } diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 7a69b2cc1e0..1a0aabd97fd 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -28,7 +28,7 @@ namespace ts { return ModuleInstanceState.ConstEnumOnly; } // 3. non-exported import declarations - else if ((node.kind === SyntaxKind.ImportDeclaration || node.kind === SyntaxKind.ImportEqualsDeclaration) && !(node.flags & NodeFlags.Export)) { + else if ((node.kind === SyntaxKind.ImportDeclaration || node.kind === SyntaxKind.ImportEqualsDeclaration) && !(hasModifier(node, ModifierFlags.Export))) { return ModuleInstanceState.NonInstantiated; } // 4. other uninstantiated module declarations. @@ -132,6 +132,10 @@ namespace ts { const unreachableFlow: FlowNode = { flags: FlowFlags.Unreachable }; const reportedUnreachableFlow: FlowNode = { flags: FlowFlags.Unreachable }; + // state used to aggregate transform flags during bind. + let subtreeTransformFlags: TransformFlags = TransformFlags.None; + let skipTransformFlagAggregation: boolean; + function bindSourceFile(f: SourceFile, opts: CompilerOptions) { file = f; options = opts; @@ -139,6 +143,7 @@ namespace ts { inStrictMode = !!file.externalModuleIndicator; classifiableNames = createMap(); symbolCount = 0; + skipTransformFlagAggregation = isDeclarationFile(file); Symbol = objectAllocator.getSymbolConstructor(); @@ -165,6 +170,7 @@ namespace ts { activeLabels = undefined; hasExplicitReturn = false; emitFlags = NodeFlags.None; + subtreeTransformFlags = TransformFlags.None; } return bindSourceFile; @@ -254,7 +260,7 @@ namespace ts { case SyntaxKind.FunctionDeclaration: case SyntaxKind.ClassDeclaration: - return node.flags & NodeFlags.Default ? "default" : undefined; + return hasModifier(node, ModifierFlags.Default) ? "default" : undefined; case SyntaxKind.JSDocFunctionType: return isJSDocConstructSignature(node) ? "__new" : "__call"; case SyntaxKind.Parameter: @@ -263,7 +269,7 @@ namespace ts { Debug.assert(node.parent.kind === SyntaxKind.JSDocFunctionType); let functionType = node.parent; let index = indexOf(functionType.parameters, node); - return "p" + index; + return "arg" + index; case SyntaxKind.JSDocTypedefTag: const parentNode = node.parent && node.parent.parent; let nameFromParentNode: string; @@ -294,7 +300,7 @@ namespace ts { function declareSymbol(symbolTable: SymbolTable, parent: Symbol, node: Declaration, includes: SymbolFlags, excludes: SymbolFlags): Symbol { Debug.assert(!hasDynamicName(node)); - const isDefaultExport = node.flags & NodeFlags.Default; + const isDefaultExport = hasModifier(node, ModifierFlags.Default); // The exported symbol for an export default function/class node is always named "default" const name = isDefaultExport && parent ? "default" : getDeclarationName(node); @@ -351,7 +357,7 @@ namespace ts { : Diagnostics.Duplicate_identifier_0; forEach(symbol.declarations, declaration => { - if (declaration.flags & NodeFlags.Default) { + if (hasModifier(declaration, ModifierFlags.Default)) { message = Diagnostics.A_module_cannot_have_multiple_default_exports; } }); @@ -373,7 +379,7 @@ namespace ts { } function declareModuleMember(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags): Symbol { - const hasExportModifier = getCombinedNodeFlags(node) & NodeFlags.Export; + const hasExportModifier = getCombinedModifierFlags(node) & ModifierFlags.Export; if (symbolFlags & SymbolFlags.Alias) { if (node.kind === SyntaxKind.ExportSpecifier || (node.kind === SyntaxKind.ImportEqualsDeclaration && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); @@ -514,13 +520,28 @@ namespace ts { } function bindChildren(node: Node): void { + if (skipTransformFlagAggregation) { + bindChildrenWorker(node); + } + else if (node.transformFlags & TransformFlags.HasComputedFlags) { + skipTransformFlagAggregation = true; + bindChildrenWorker(node); + skipTransformFlagAggregation = false; + } + else { + const savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + bindChildrenWorker(node); + subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); + } + } + + function bindChildrenWorker(node: Node): void { // Binding of JsDocComment should be done before the current block scope container changes. // because the scope of JsDocComment should not be affected by whether the current node is a // container or not. if (isInJavaScriptFile(node) && node.jsDocComments) { - for (const jsDocComment of node.jsDocComments) { - bind(jsDocComment); - } + forEach(node.jsDocComments, bind); } if (checkUnreachable(node)) { forEachChild(node, bind); @@ -569,6 +590,9 @@ namespace ts { case SyntaxKind.PrefixUnaryExpression: bindPrefixUnaryExpressionFlow(node); break; + case SyntaxKind.PostfixUnaryExpression: + bindPostfixUnaryExpressionFlow(node); + break; case SyntaxKind.BinaryExpression: bindBinaryExpressionFlow(node); break; @@ -1084,6 +1108,16 @@ namespace ts { } else { forEachChild(node, bind); + if (node.operator === SyntaxKind.PlusEqualsToken || node.operator === SyntaxKind.MinusMinusToken) { + bindAssignmentTargetFlow(node.operand); + } + } + } + + function bindPostfixUnaryExpressionFlow(node: PostfixUnaryExpression) { + forEachChild(node, bind); + if (node.operator === SyntaxKind.PlusPlusToken || node.operator === SyntaxKind.MinusMinusToken) { + bindAssignmentTargetFlow(node.operand); } } @@ -1128,8 +1162,8 @@ namespace ts { currentFlow = finishFlowLabel(postExpressionLabel); } - function bindInitializedVariableFlow(node: VariableDeclaration | BindingElement) { - const name = node.name; + function bindInitializedVariableFlow(node: VariableDeclaration | ArrayBindingElement) { + const name = !isOmittedExpression(node) ? node.name : undefined; if (isBindingPattern(name)) { for (const child of name.elements) { bindInitializedVariableFlow(child); @@ -1309,7 +1343,7 @@ namespace ts { } function declareClassMember(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags) { - return node.flags & NodeFlags.Static + return hasModifier(node, ModifierFlags.Static) ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); } @@ -1346,7 +1380,7 @@ namespace ts { function bindModuleDeclaration(node: ModuleDeclaration) { setExportContextFlag(node); if (isAmbientModule(node)) { - if (node.flags & NodeFlags.Export) { + if (hasModifier(node, ModifierFlags.Export)) { errorOnFirstToken(node, Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); } if (isExternalModuleAugmentation(node)) { @@ -1613,7 +1647,7 @@ namespace ts { } } - function checkStrictModeNumericLiteral(node: LiteralExpression) { + function checkStrictModeNumericLiteral(node: NumericLiteral) { if (inStrictMode && node.isOctalLiteral) { file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); } @@ -1688,6 +1722,9 @@ namespace ts { } parent = saveParent; } + else if (!skipTransformFlagAggregation && (node.transformFlags & TransformFlags.HasComputedFlags) === 0) { + subtreeTransformFlags |= computeTransformFlagsForNode(node, 0); + } inStrictMode = saveInStrictMode; } @@ -1758,7 +1795,7 @@ namespace ts { case SyntaxKind.DeleteExpression: return checkStrictModeDeleteExpression(node); case SyntaxKind.NumericLiteral: - return checkStrictModeNumericLiteral(node); + return checkStrictModeNumericLiteral(node); case SyntaxKind.PostfixUnaryExpression: return checkStrictModePostfixUnaryExpression(node); case SyntaxKind.PrefixUnaryExpression: @@ -1790,7 +1827,7 @@ namespace ts { return bindPropertyOrMethodOrAccessor(node, SymbolFlags.EnumMember, SymbolFlags.EnumMemberExcludes); case SyntaxKind.JsxSpreadAttribute: - emitFlags |= NodeFlags.HasJsxSpreadAttribute; + emitFlags |= NodeFlags.HasJsxSpreadAttributes; return; case SyntaxKind.CallSignature: @@ -2205,7 +2242,7 @@ namespace ts { if (currentFlow === unreachableFlow) { const reportError = // report error on all statements except empty ones - (isStatement(node) && node.kind !== SyntaxKind.EmptyStatement) || + (isStatementButNotDeclaration(node) && node.kind !== SyntaxKind.EmptyStatement) || // report error on class declarations node.kind === SyntaxKind.ClassDeclaration || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set @@ -2242,4 +2279,763 @@ namespace ts { return true; } } + + /** + * Computes the transform flags for a node, given the transform flags of its subtree + * + * @param node The node to analyze + * @param subtreeFlags Transform flags computed for this node's subtree + */ + export function computeTransformFlagsForNode(node: Node, subtreeFlags: TransformFlags): TransformFlags { + const kind = node.kind; + switch (kind) { + case SyntaxKind.CallExpression: + return computeCallExpression(node, subtreeFlags); + + case SyntaxKind.ModuleDeclaration: + return computeModuleDeclaration(node, subtreeFlags); + + case SyntaxKind.ParenthesizedExpression: + return computeParenthesizedExpression(node, subtreeFlags); + + case SyntaxKind.BinaryExpression: + return computeBinaryExpression(node, subtreeFlags); + + case SyntaxKind.ExpressionStatement: + return computeExpressionStatement(node, subtreeFlags); + + case SyntaxKind.Parameter: + return computeParameter(node, subtreeFlags); + + case SyntaxKind.ArrowFunction: + return computeArrowFunction(node, subtreeFlags); + + case SyntaxKind.FunctionExpression: + return computeFunctionExpression(node, subtreeFlags); + + case SyntaxKind.FunctionDeclaration: + return computeFunctionDeclaration(node, subtreeFlags); + + case SyntaxKind.VariableDeclaration: + return computeVariableDeclaration(node, subtreeFlags); + + case SyntaxKind.VariableDeclarationList: + return computeVariableDeclarationList(node, subtreeFlags); + + case SyntaxKind.VariableStatement: + return computeVariableStatement(node, subtreeFlags); + + case SyntaxKind.LabeledStatement: + return computeLabeledStatement(node, subtreeFlags); + + case SyntaxKind.ClassDeclaration: + return computeClassDeclaration(node, subtreeFlags); + + case SyntaxKind.ClassExpression: + return computeClassExpression(node, subtreeFlags); + + case SyntaxKind.HeritageClause: + return computeHeritageClause(node, subtreeFlags); + + case SyntaxKind.ExpressionWithTypeArguments: + return computeExpressionWithTypeArguments(node, subtreeFlags); + + case SyntaxKind.Constructor: + return computeConstructor(node, subtreeFlags); + + case SyntaxKind.PropertyDeclaration: + return computePropertyDeclaration(node, subtreeFlags); + + case SyntaxKind.MethodDeclaration: + return computeMethod(node, subtreeFlags); + + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + return computeAccessor(node, subtreeFlags); + + case SyntaxKind.ImportEqualsDeclaration: + return computeImportEquals(node, subtreeFlags); + + case SyntaxKind.PropertyAccessExpression: + return computePropertyAccess(node, subtreeFlags); + + default: + return computeOther(node, kind, subtreeFlags); + } + } + + function computeCallExpression(node: CallExpression, subtreeFlags: TransformFlags) { + let transformFlags = subtreeFlags; + const expression = node.expression; + const expressionKind = expression.kind; + + if (subtreeFlags & TransformFlags.ContainsSpreadElementExpression + || isSuperOrSuperProperty(expression, expressionKind)) { + // If the this node contains a SpreadElementExpression, or is a super call, then it is an ES6 + // node. + transformFlags |= TransformFlags.AssertES6; + } + + node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; + return transformFlags & ~TransformFlags.ArrayLiteralOrCallOrNewExcludes; + } + + function isSuperOrSuperProperty(node: Node, kind: SyntaxKind) { + switch (kind) { + case SyntaxKind.SuperKeyword: + return true; + + case SyntaxKind.PropertyAccessExpression: + case SyntaxKind.ElementAccessExpression: + const expression = (node).expression; + const expressionKind = expression.kind; + return expressionKind === SyntaxKind.SuperKeyword; + } + + return false; + } + + function computeBinaryExpression(node: BinaryExpression, subtreeFlags: TransformFlags) { + let transformFlags = subtreeFlags; + const operatorTokenKind = node.operatorToken.kind; + const leftKind = node.left.kind; + + if (operatorTokenKind === SyntaxKind.EqualsToken + && (leftKind === SyntaxKind.ObjectLiteralExpression + || leftKind === SyntaxKind.ArrayLiteralExpression)) { + // Destructuring assignments are ES6 syntax. + transformFlags |= TransformFlags.AssertES6 | TransformFlags.DestructuringAssignment; + } + else if (operatorTokenKind === SyntaxKind.AsteriskAsteriskToken + || operatorTokenKind === SyntaxKind.AsteriskAsteriskEqualsToken) { + // Exponentiation is ES7 syntax. + transformFlags |= TransformFlags.AssertES7; + } + + node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; + return transformFlags & ~TransformFlags.NodeExcludes; + } + + function computeParameter(node: ParameterDeclaration, subtreeFlags: TransformFlags) { + let transformFlags = subtreeFlags; + const modifierFlags = getModifierFlags(node); + const name = node.name; + const initializer = node.initializer; + const dotDotDotToken = node.dotDotDotToken; + + // If the parameter has a question token, then it is TypeScript syntax. + if (node.questionToken) { + transformFlags |= TransformFlags.AssertTypeScript; + } + + // If the parameter's name is 'this', then it is TypeScript syntax. + if (subtreeFlags & TransformFlags.ContainsDecorators + || (name && isIdentifier(name) && name.originalKeywordKind === SyntaxKind.ThisKeyword)) { + transformFlags |= TransformFlags.AssertTypeScript; + } + + // If a parameter has an accessibility modifier, then it is TypeScript syntax. + if (modifierFlags & ModifierFlags.ParameterPropertyModifier) { + transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.ContainsParameterPropertyAssignments; + } + + // If a parameter has an initializer, a binding pattern or a dotDotDot token, then + // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. + if (subtreeFlags & TransformFlags.ContainsBindingPattern || initializer || dotDotDotToken) { + transformFlags |= TransformFlags.AssertES6 | TransformFlags.ContainsDefaultValueAssignments; + } + + node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; + return transformFlags & ~TransformFlags.ParameterExcludes; + } + + function computeParenthesizedExpression(node: ParenthesizedExpression, subtreeFlags: TransformFlags) { + let transformFlags = subtreeFlags; + const expression = node.expression; + const expressionKind = expression.kind; + const expressionTransformFlags = expression.transformFlags; + + // If the node is synthesized, it means the emitter put the parentheses there, + // not the user. If we didn't want them, the emitter would not have put them + // there. + if (expressionKind === SyntaxKind.AsExpression + || expressionKind === SyntaxKind.TypeAssertionExpression) { + transformFlags |= TransformFlags.AssertTypeScript; + } + + // If the expression of a ParenthesizedExpression is a destructuring assignment, + // then the ParenthesizedExpression is a destructuring assignment. + if (expressionTransformFlags & TransformFlags.DestructuringAssignment) { + transformFlags |= TransformFlags.DestructuringAssignment; + } + + node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; + return transformFlags & ~TransformFlags.NodeExcludes; + } + + function computeClassDeclaration(node: ClassDeclaration, subtreeFlags: TransformFlags) { + let transformFlags: TransformFlags; + const modifierFlags = getModifierFlags(node); + + if (modifierFlags & ModifierFlags.Ambient) { + // An ambient declaration is TypeScript syntax. + transformFlags = TransformFlags.AssertTypeScript; + } + else { + // A ClassDeclaration is ES6 syntax. + transformFlags = subtreeFlags | TransformFlags.AssertES6; + + // A class with a parameter property assignment, property initializer, or decorator is + // TypeScript syntax. + // An exported declaration may be TypeScript syntax. + if ((subtreeFlags & TransformFlags.TypeScriptClassSyntaxMask) + || (modifierFlags & ModifierFlags.Export)) { + transformFlags |= TransformFlags.AssertTypeScript; + } + + if (subtreeFlags & TransformFlags.ContainsLexicalThisInComputedPropertyName) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= TransformFlags.ContainsLexicalThis; + } + } + + node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; + return transformFlags & ~TransformFlags.ClassExcludes; + } + + function computeClassExpression(node: ClassExpression, subtreeFlags: TransformFlags) { + // A ClassExpression is ES6 syntax. + let transformFlags = subtreeFlags | TransformFlags.AssertES6; + + // A class with a parameter property assignment, property initializer, or decorator is + // TypeScript syntax. + if (subtreeFlags & TransformFlags.TypeScriptClassSyntaxMask) { + transformFlags |= TransformFlags.AssertTypeScript; + } + + if (subtreeFlags & TransformFlags.ContainsLexicalThisInComputedPropertyName) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= TransformFlags.ContainsLexicalThis; + } + + node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; + return transformFlags & ~TransformFlags.ClassExcludes; + } + + function computeHeritageClause(node: HeritageClause, subtreeFlags: TransformFlags) { + let transformFlags = subtreeFlags; + + switch (node.token) { + case SyntaxKind.ExtendsKeyword: + // An `extends` HeritageClause is ES6 syntax. + transformFlags |= TransformFlags.AssertES6; + break; + + case SyntaxKind.ImplementsKeyword: + // An `implements` HeritageClause is TypeScript syntax. + transformFlags |= TransformFlags.AssertTypeScript; + break; + + default: + Debug.fail("Unexpected token for heritage clause"); + break; + } + + node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; + return transformFlags & ~TransformFlags.NodeExcludes; + } + + function computeExpressionWithTypeArguments(node: ExpressionWithTypeArguments, subtreeFlags: TransformFlags) { + // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the + // extends clause of a class. + let transformFlags = subtreeFlags | TransformFlags.AssertES6; + + // If an ExpressionWithTypeArguments contains type arguments, then it + // is TypeScript syntax. + if (node.typeArguments) { + transformFlags |= TransformFlags.AssertTypeScript; + } + + node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; + return transformFlags & ~TransformFlags.NodeExcludes; + } + + function computeConstructor(node: ConstructorDeclaration, subtreeFlags: TransformFlags) { + let transformFlags = subtreeFlags; + const body = node.body; + + if (body === undefined) { + // An overload constructor is TypeScript syntax. + transformFlags |= TransformFlags.AssertTypeScript; + } + + node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; + return transformFlags & ~TransformFlags.ConstructorExcludes; + } + + function computeMethod(node: MethodDeclaration, subtreeFlags: TransformFlags) { + // A MethodDeclaration is ES6 syntax. + let transformFlags = subtreeFlags | TransformFlags.AssertES6; + const modifierFlags = getModifierFlags(node); + const body = node.body; + const typeParameters = node.typeParameters; + const asteriskToken = node.asteriskToken; + + // A MethodDeclaration is TypeScript syntax if it is either async, abstract, overloaded, + // generic, or has a decorator. + if (!body + || typeParameters + || (modifierFlags & (ModifierFlags.Async | ModifierFlags.Abstract)) + || (subtreeFlags & TransformFlags.ContainsDecorators)) { + transformFlags |= TransformFlags.AssertTypeScript; + } + + // Currently, we only support generators that were originally async function bodies. + if (asteriskToken && node.emitFlags & NodeEmitFlags.AsyncFunctionBody) { + transformFlags |= TransformFlags.AssertGenerator; + } + + node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; + return transformFlags & ~TransformFlags.MethodOrAccessorExcludes; + } + + function computeAccessor(node: AccessorDeclaration, subtreeFlags: TransformFlags) { + let transformFlags = subtreeFlags; + const modifierFlags = getModifierFlags(node); + const body = node.body; + + // A MethodDeclaration is TypeScript syntax if it is either async, abstract, overloaded, + // generic, or has a decorator. + if (!body + || (modifierFlags & (ModifierFlags.Async | ModifierFlags.Abstract)) + || (subtreeFlags & TransformFlags.ContainsDecorators)) { + transformFlags |= TransformFlags.AssertTypeScript; + } + + node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; + return transformFlags & ~TransformFlags.MethodOrAccessorExcludes; + } + + function computePropertyDeclaration(node: PropertyDeclaration, subtreeFlags: TransformFlags) { + // A PropertyDeclaration is TypeScript syntax. + let transformFlags = subtreeFlags | TransformFlags.AssertTypeScript; + + // If the PropertyDeclaration has an initializer, we need to inform its ancestor + // so that it handle the transformation. + if (node.initializer) { + transformFlags |= TransformFlags.ContainsPropertyInitializer; + } + + node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; + return transformFlags & ~TransformFlags.NodeExcludes; + } + + function computeFunctionDeclaration(node: FunctionDeclaration, subtreeFlags: TransformFlags) { + let transformFlags: TransformFlags; + const modifierFlags = getModifierFlags(node); + const body = node.body; + const asteriskToken = node.asteriskToken; + + if (!body || (modifierFlags & ModifierFlags.Ambient)) { + // An ambient declaration is TypeScript syntax. + // A FunctionDeclaration without a body is an overload and is TypeScript syntax. + transformFlags = TransformFlags.AssertTypeScript; + } + else { + transformFlags = subtreeFlags | TransformFlags.ContainsHoistedDeclarationOrCompletion; + + // If a FunctionDeclaration is exported, then it is either ES6 or TypeScript syntax. + if (modifierFlags & ModifierFlags.Export) { + transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.AssertES6; + } + + // If a FunctionDeclaration is async, then it is TypeScript syntax. + if (modifierFlags & ModifierFlags.Async) { + transformFlags |= TransformFlags.AssertTypeScript; + } + + // If a FunctionDeclaration's subtree has marked the container as needing to capture the + // lexical this, or the function contains parameters with initializers, then this node is + // ES6 syntax. + if (subtreeFlags & TransformFlags.ES6FunctionSyntaxMask) { + transformFlags |= TransformFlags.AssertES6; + } + + // If a FunctionDeclaration is generator function and is the body of a + // transformed async function, then this node can be transformed to a + // down-level generator. + // Currently we do not support transforming any other generator fucntions + // down level. + if (asteriskToken && node.emitFlags & NodeEmitFlags.AsyncFunctionBody) { + transformFlags |= TransformFlags.AssertGenerator; + } + } + + node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; + return transformFlags & ~TransformFlags.FunctionExcludes; + } + + function computeFunctionExpression(node: FunctionExpression, subtreeFlags: TransformFlags) { + let transformFlags = subtreeFlags; + const modifierFlags = getModifierFlags(node); + const asteriskToken = node.asteriskToken; + + // An async function expression is TypeScript syntax. + if (modifierFlags & ModifierFlags.Async) { + transformFlags |= TransformFlags.AssertTypeScript; + } + + // If a FunctionExpression's subtree has marked the container as needing to capture the + // lexical this, or the function contains parameters with initializers, then this node is + // ES6 syntax. + if (subtreeFlags & TransformFlags.ES6FunctionSyntaxMask) { + transformFlags |= TransformFlags.AssertES6; + } + + // If a FunctionExpression is generator function and is the body of a + // transformed async function, then this node can be transformed to a + // down-level generator. + // Currently we do not support transforming any other generator fucntions + // down level. + if (asteriskToken && node.emitFlags & NodeEmitFlags.AsyncFunctionBody) { + transformFlags |= TransformFlags.AssertGenerator; + } + + node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; + return transformFlags & ~TransformFlags.FunctionExcludes; + } + + function computeArrowFunction(node: ArrowFunction, subtreeFlags: TransformFlags) { + // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. + let transformFlags = subtreeFlags | TransformFlags.AssertES6; + const modifierFlags = getModifierFlags(node); + + // An async arrow function is TypeScript syntax. + if (modifierFlags & ModifierFlags.Async) { + transformFlags |= TransformFlags.AssertTypeScript; + } + + // If an ArrowFunction contains a lexical this, its container must capture the lexical this. + if (subtreeFlags & TransformFlags.ContainsLexicalThis) { + transformFlags |= TransformFlags.ContainsCapturedLexicalThis; + } + + node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; + return transformFlags & ~TransformFlags.ArrowFunctionExcludes; + } + + function computePropertyAccess(node: PropertyAccessExpression, subtreeFlags: TransformFlags) { + let transformFlags = subtreeFlags; + const expression = node.expression; + const expressionKind = expression.kind; + + // If a PropertyAccessExpression starts with a super keyword, then it is + // ES6 syntax, and requires a lexical `this` binding. + if (expressionKind === SyntaxKind.SuperKeyword) { + transformFlags |= TransformFlags.ContainsLexicalThis; + } + + node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; + return transformFlags & ~TransformFlags.NodeExcludes; + } + + function computeVariableDeclaration(node: VariableDeclaration, subtreeFlags: TransformFlags) { + let transformFlags = subtreeFlags; + const nameKind = node.name.kind; + + // A VariableDeclaration with a binding pattern is ES6 syntax. + if (nameKind === SyntaxKind.ObjectBindingPattern || nameKind === SyntaxKind.ArrayBindingPattern) { + transformFlags |= TransformFlags.AssertES6 | TransformFlags.ContainsBindingPattern; + } + + node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; + return transformFlags & ~TransformFlags.NodeExcludes; + } + + function computeVariableStatement(node: VariableStatement, subtreeFlags: TransformFlags) { + let transformFlags: TransformFlags; + const modifierFlags = getModifierFlags(node); + const declarationListTransformFlags = node.declarationList.transformFlags; + + // An ambient declaration is TypeScript syntax. + if (modifierFlags & ModifierFlags.Ambient) { + transformFlags = TransformFlags.AssertTypeScript; + } + else { + transformFlags = subtreeFlags; + + // If a VariableStatement is exported, then it is either ES6 or TypeScript syntax. + if (modifierFlags & ModifierFlags.Export) { + transformFlags |= TransformFlags.AssertES6 | TransformFlags.AssertTypeScript; + } + + if (declarationListTransformFlags & TransformFlags.ContainsBindingPattern) { + transformFlags |= TransformFlags.AssertES6; + } + } + + node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; + return transformFlags & ~TransformFlags.NodeExcludes; + } + + function computeLabeledStatement(node: LabeledStatement, subtreeFlags: TransformFlags) { + let transformFlags = subtreeFlags; + + // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. + if (subtreeFlags & TransformFlags.ContainsBlockScopedBinding + && isIterationStatement(node, /*lookInLabeledStatements*/ true)) { + transformFlags |= TransformFlags.AssertES6; + } + + node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; + return transformFlags & ~TransformFlags.NodeExcludes; + } + + function computeImportEquals(node: ImportEqualsDeclaration, subtreeFlags: TransformFlags) { + let transformFlags = subtreeFlags; + + // An ImportEqualsDeclaration with a namespace reference is TypeScript. + if (!isExternalModuleImportEqualsDeclaration(node)) { + transformFlags |= TransformFlags.AssertTypeScript; + } + + node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; + return transformFlags & ~TransformFlags.NodeExcludes; + } + + function computeExpressionStatement(node: ExpressionStatement, subtreeFlags: TransformFlags) { + let transformFlags = subtreeFlags; + + // If the expression of an expression statement is a destructuring assignment, + // then we treat the statement as ES6 so that we can indicate that we do not + // need to hold on to the right-hand side. + if (node.expression.transformFlags & TransformFlags.DestructuringAssignment) { + transformFlags |= TransformFlags.AssertES6; + } + + node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; + return transformFlags & ~TransformFlags.NodeExcludes; + } + + function computeModuleDeclaration(node: ModuleDeclaration, subtreeFlags: TransformFlags) { + let transformFlags = TransformFlags.AssertTypeScript; + const modifierFlags = getModifierFlags(node); + + if ((modifierFlags & ModifierFlags.Ambient) === 0) { + transformFlags |= subtreeFlags; + } + + node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; + return transformFlags & ~TransformFlags.ModuleExcludes; + } + + function computeVariableDeclarationList(node: VariableDeclarationList, subtreeFlags: TransformFlags) { + let transformFlags = subtreeFlags | TransformFlags.ContainsHoistedDeclarationOrCompletion; + + if (subtreeFlags & TransformFlags.ContainsBindingPattern) { + transformFlags |= TransformFlags.AssertES6; + } + + // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. + if (node.flags & NodeFlags.BlockScoped) { + transformFlags |= TransformFlags.AssertES6 | TransformFlags.ContainsBlockScopedBinding; + } + + node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; + return transformFlags & ~TransformFlags.VariableDeclarationListExcludes; + } + + function computeOther(node: Node, kind: SyntaxKind, subtreeFlags: TransformFlags) { + // Mark transformations needed for each node + let transformFlags = subtreeFlags; + let excludeFlags = TransformFlags.NodeExcludes; + + switch (kind) { + case SyntaxKind.PublicKeyword: + case SyntaxKind.PrivateKeyword: + case SyntaxKind.ProtectedKeyword: + case SyntaxKind.AbstractKeyword: + case SyntaxKind.DeclareKeyword: + case SyntaxKind.AsyncKeyword: + case SyntaxKind.ConstKeyword: + case SyntaxKind.AwaitExpression: + case SyntaxKind.EnumDeclaration: + case SyntaxKind.EnumMember: + case SyntaxKind.TypeAssertionExpression: + case SyntaxKind.AsExpression: + case SyntaxKind.NonNullExpression: + case SyntaxKind.ReadonlyKeyword: + // These nodes are TypeScript syntax. + transformFlags |= TransformFlags.AssertTypeScript; + break; + + case SyntaxKind.JsxElement: + case SyntaxKind.JsxSelfClosingElement: + case SyntaxKind.JsxOpeningElement: + case SyntaxKind.JsxText: + case SyntaxKind.JsxClosingElement: + case SyntaxKind.JsxAttribute: + case SyntaxKind.JsxSpreadAttribute: + case SyntaxKind.JsxExpression: + // These nodes are Jsx syntax. + transformFlags |= TransformFlags.AssertJsx; + break; + + case SyntaxKind.ExportKeyword: + // This node is both ES6 and TypeScript syntax. + transformFlags |= TransformFlags.AssertES6 | TransformFlags.AssertTypeScript; + break; + + case SyntaxKind.DefaultKeyword: + case SyntaxKind.NoSubstitutionTemplateLiteral: + case SyntaxKind.TemplateHead: + case SyntaxKind.TemplateMiddle: + case SyntaxKind.TemplateTail: + case SyntaxKind.TemplateExpression: + case SyntaxKind.TaggedTemplateExpression: + case SyntaxKind.ShorthandPropertyAssignment: + case SyntaxKind.ForOfStatement: + // These nodes are ES6 syntax. + transformFlags |= TransformFlags.AssertES6; + break; + + case SyntaxKind.YieldExpression: + // This node is ES6 syntax. + transformFlags |= TransformFlags.AssertES6 | TransformFlags.ContainsYield; + break; + + case SyntaxKind.AnyKeyword: + case SyntaxKind.NumberKeyword: + case SyntaxKind.NeverKeyword: + case SyntaxKind.StringKeyword: + case SyntaxKind.BooleanKeyword: + case SyntaxKind.SymbolKeyword: + case SyntaxKind.VoidKeyword: + case SyntaxKind.TypeParameter: + case SyntaxKind.PropertySignature: + case SyntaxKind.MethodSignature: + case SyntaxKind.CallSignature: + case SyntaxKind.ConstructSignature: + case SyntaxKind.IndexSignature: + case SyntaxKind.TypePredicate: + case SyntaxKind.TypeReference: + case SyntaxKind.FunctionType: + case SyntaxKind.ConstructorType: + case SyntaxKind.TypeQuery: + case SyntaxKind.TypeLiteral: + case SyntaxKind.ArrayType: + case SyntaxKind.TupleType: + case SyntaxKind.UnionType: + case SyntaxKind.IntersectionType: + case SyntaxKind.ParenthesizedType: + case SyntaxKind.InterfaceDeclaration: + case SyntaxKind.TypeAliasDeclaration: + case SyntaxKind.ThisType: + case SyntaxKind.LiteralType: + // Types and signatures are TypeScript syntax, and exclude all other facts. + transformFlags = TransformFlags.AssertTypeScript; + excludeFlags = TransformFlags.TypeExcludes; + break; + + case SyntaxKind.ComputedPropertyName: + // Even though computed property names are ES6, we don't treat them as such. + // This is so that they can flow through PropertyName transforms unaffected. + // Instead, we mark the container as ES6, so that it can properly handle the transform. + transformFlags |= TransformFlags.ContainsComputedPropertyName; + if (subtreeFlags & TransformFlags.ContainsLexicalThis) { + // A computed method name like `[this.getName()](x: string) { ... }` needs to + // distinguish itself from the normal case of a method body containing `this`: + // `this` inside a method doesn't need to be rewritten (the method provides `this`), + // whereas `this` inside a computed name *might* need to be rewritten if the class/object + // is inside an arrow function: + // `_this = this; () => class K { [_this.getName()]() { ... } }` + // To make this distinction, use ContainsLexicalThisInComputedPropertyName + // instead of ContainsLexicalThis for computed property names + transformFlags |= TransformFlags.ContainsLexicalThisInComputedPropertyName; + } + break; + + case SyntaxKind.SpreadElementExpression: + // This node is ES6 syntax, but is handled by a containing node. + transformFlags |= TransformFlags.ContainsSpreadElementExpression; + break; + + case SyntaxKind.SuperKeyword: + // This node is ES6 syntax. + transformFlags |= TransformFlags.AssertES6; + break; + + case SyntaxKind.ThisKeyword: + // Mark this node and its ancestors as containing a lexical `this` keyword. + transformFlags |= TransformFlags.ContainsLexicalThis; + break; + + case SyntaxKind.ObjectBindingPattern: + case SyntaxKind.ArrayBindingPattern: + // These nodes are ES6 syntax. + transformFlags |= TransformFlags.AssertES6 | TransformFlags.ContainsBindingPattern; + break; + + case SyntaxKind.Decorator: + // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. + transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.ContainsDecorators; + break; + + case SyntaxKind.ObjectLiteralExpression: + excludeFlags = TransformFlags.ObjectLiteralExcludes; + if (subtreeFlags & TransformFlags.ContainsComputedPropertyName) { + // If an ObjectLiteralExpression contains a ComputedPropertyName, then it + // is an ES6 node. + transformFlags |= TransformFlags.AssertES6; + } + + if (subtreeFlags & TransformFlags.ContainsLexicalThisInComputedPropertyName) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= TransformFlags.ContainsLexicalThis; + } + + break; + + case SyntaxKind.ArrayLiteralExpression: + case SyntaxKind.NewExpression: + excludeFlags = TransformFlags.ArrayLiteralOrCallOrNewExcludes; + if (subtreeFlags & TransformFlags.ContainsSpreadElementExpression) { + // If the this node contains a SpreadElementExpression, then it is an ES6 + // node. + transformFlags |= TransformFlags.AssertES6; + } + + break; + + case SyntaxKind.DoStatement: + case SyntaxKind.WhileStatement: + case SyntaxKind.ForStatement: + case SyntaxKind.ForInStatement: + // A loop containing a block scoped binding *may* need to be transformed from ES6. + if (subtreeFlags & TransformFlags.ContainsBlockScopedBinding) { + transformFlags |= TransformFlags.AssertES6; + } + + break; + + case SyntaxKind.SourceFile: + if (subtreeFlags & TransformFlags.ContainsCapturedLexicalThis) { + transformFlags |= TransformFlags.AssertES6; + } + + break; + + case SyntaxKind.ReturnStatement: + case SyntaxKind.ContinueStatement: + case SyntaxKind.BreakStatement: + transformFlags |= TransformFlags.ContainsHoistedDeclarationOrCompletion; + break; + } + + node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; + return transformFlags & ~excludeFlags; + } } diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 6ebbd83e375..51550ef873f 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -132,6 +132,7 @@ namespace ts { const esSymbolType = createIntrinsicType(TypeFlags.ESSymbol, "symbol"); const voidType = createIntrinsicType(TypeFlags.Void, "void"); const neverType = createIntrinsicType(TypeFlags.Never, "never"); + const silentNeverType = createIntrinsicType(TypeFlags.Never, "never"); const emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); const emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); @@ -147,6 +148,7 @@ namespace ts { const anySignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); const unknownSignature = createSignature(undefined, undefined, undefined, emptyArray, unknownType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); const resolvingSignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + const silentNeverSignature = createSignature(undefined, undefined, undefined, emptyArray, silentNeverType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); const enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); @@ -161,6 +163,7 @@ namespace ts { let getGlobalESSymbolConstructorSymbol: () => Symbol; let getGlobalPromiseConstructorSymbol: () => Symbol; + let tryGetGlobalPromiseConstructorSymbol: () => Symbol; let globalObjectType: ObjectType; let globalFunctionType: ObjectType; @@ -641,7 +644,7 @@ namespace ts { const initializerOfNonStaticProperty = current.parent && current.parent.kind === SyntaxKind.PropertyDeclaration && - (current.parent.flags & NodeFlags.Static) === 0 && + (getModifierFlags(current.parent) & ModifierFlags.Static) === 0 && (current.parent).initializer === current; if (initializerOfNonStaticProperty) { @@ -761,7 +764,7 @@ namespace ts { // local variables of the constructor. This effectively means that entities from outer scopes // by the same name as a constructor parameter or local variable are inaccessible // in initializer expressions for instance member variables. - if (isClassLike(location.parent) && !(location.flags & NodeFlags.Static)) { + if (isClassLike(location.parent) && !(getModifierFlags(location) & ModifierFlags.Static)) { const ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { if (getSymbol(ctor.locals, name, meaning & SymbolFlags.Value)) { @@ -775,7 +778,7 @@ namespace ts { case SyntaxKind.ClassExpression: case SyntaxKind.InterfaceDeclaration: if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & SymbolFlags.Type)) { - if (lastLocation && lastLocation.flags & NodeFlags.Static) { + if (lastLocation && getModifierFlags(lastLocation) & ModifierFlags.Static) { // TypeScript 1.0 spec (April 2014): 3.4.1 // The scope of a type parameter extends over the entire declaration with which the type // parameter list is associated, with the exception of static member declarations in classes. @@ -876,7 +879,8 @@ namespace ts { if (nameNotFoundMessage) { if (!errorLocation || !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && - !checkAndReportErrorForExtendingInterface(errorLocation)) { + !checkAndReportErrorForExtendingInterface(errorLocation) && + !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning)) { error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : declarationNameToString(nameArg)); } } @@ -946,7 +950,7 @@ namespace ts { // No static member is present. // Check if we're in an instance method and look for a relevant instance member. - if (location === container && !(location.flags & NodeFlags.Static)) { + if (location === container && !(getModifierFlags(location) & ModifierFlags.Static)) { const instanceType = (getDeclaredTypeOfSymbol(classSymbol)).thisType; if (getPropertyOfType(instanceType, name)) { error(errorLocation, Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, typeof nameArg === "string" ? nameArg : declarationNameToString(nameArg)); @@ -986,6 +990,16 @@ namespace ts { } } + function checkAndReportErrorForUsingTypeAsValue(errorLocation: Node, name: string, meaning: SymbolFlags): boolean { + if (meaning & (SymbolFlags.Value & ~SymbolFlags.NamespaceModule)) { + const symbol = resolveSymbol(resolveName(errorLocation, name, SymbolFlags.Type & ~SymbolFlags.Value, /*nameNotFoundMessage*/undefined, /*nameArg*/ undefined)); + if (symbol && !(symbol.flags & SymbolFlags.NamespaceModule)) { + error(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, name); + return true; + } + } + return false; + } function checkResolvedBlockScopedVariable(result: Symbol, errorLocation: Node): void { Debug.assert((result.flags & SymbolFlags.BlockScopedVariable) !== 0); @@ -1276,7 +1290,7 @@ namespace ts { } // Resolves a qualified name and any involved aliases - function resolveEntityName(name: EntityNameOrEntityNameExpression, meaning: SymbolFlags, ignoreErrors?: boolean, dontResolveAlias?: boolean): Symbol | undefined { + function resolveEntityName(name: EntityNameOrEntityNameExpression, meaning: SymbolFlags, ignoreErrors?: boolean, dontResolveAlias?: boolean, location?: Node): Symbol | undefined { if (nodeIsMissing(name)) { return undefined; } @@ -1285,7 +1299,7 @@ namespace ts { if (name.kind === SyntaxKind.Identifier) { const message = meaning === SymbolFlags.Namespace ? Diagnostics.Cannot_find_namespace_0 : Diagnostics.Cannot_find_name_0; - symbol = resolveName(name, (name).text, meaning, ignoreErrors ? undefined : message, name); + symbol = resolveName(location || name, (name).text, meaning, ignoreErrors ? undefined : message, name); if (!symbol) { return undefined; } @@ -1294,18 +1308,17 @@ namespace ts { const left = name.kind === SyntaxKind.QualifiedName ? (name).left : (name).expression; const right = name.kind === SyntaxKind.QualifiedName ? (name).right : (name).name; - const namespace = resolveEntityName(left, SymbolFlags.Namespace, ignoreErrors); + const namespace = resolveEntityName(left, SymbolFlags.Namespace, ignoreErrors, /*dontResolveAlias*/ false, location); if (!namespace || nodeIsMissing(right)) { return undefined; } else if (namespace === unknownSymbol) { return namespace; } - symbol = getSymbol(getExportsOfSymbol(namespace), right.text, meaning); if (!symbol) { if (!ignoreErrors) { - error(right, Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(namespace), declarationNameToString(right)); + error(right, Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), declarationNameToString(right)); } return undefined; } @@ -1327,10 +1340,13 @@ namespace ts { } const moduleReferenceLiteral = moduleReferenceExpression; + return resolveExternalModule(location, moduleReferenceLiteral.text, moduleNotFoundError, moduleReferenceLiteral); + } + function resolveExternalModule(location: Node, moduleReference: string, moduleNotFoundError: DiagnosticMessage, errorNode: Node): Symbol { // Module names are escaped in our symbol table. However, string literal values aren't. // Escape the name in the "require(...)" clause to ensure we find the right symbol. - const moduleName = escapeIdentifier(moduleReferenceLiteral.text); + const moduleName = escapeIdentifier(moduleReference); if (moduleName === undefined) { return; @@ -1345,7 +1361,7 @@ namespace ts { } } - const resolvedModule = getResolvedModule(getSourceFileOfNode(location), moduleReferenceLiteral.text); + const resolvedModule = getResolvedModule(getSourceFileOfNode(location), moduleReference); const sourceFile = resolvedModule && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { @@ -1354,7 +1370,7 @@ namespace ts { } if (moduleNotFoundError) { // report errors only if it was requested - error(moduleReferenceLiteral, Diagnostics.File_0_is_not_a_module, sourceFile.fileName); + error(errorNode, Diagnostics.File_0_is_not_a_module, sourceFile.fileName); } return undefined; } @@ -1371,10 +1387,10 @@ namespace ts { const tsExtension = tryExtractTypeScriptExtension(moduleName); if (tsExtension) { const diag = Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; - error(moduleReferenceLiteral, diag, tsExtension, removeExtension(moduleName, tsExtension)); + error(errorNode, diag, tsExtension, removeExtension(moduleName, tsExtension)); } else { - error(moduleReferenceLiteral, moduleNotFoundError, moduleName); + error(errorNode, moduleNotFoundError, moduleName); } } return undefined; @@ -1744,7 +1760,15 @@ namespace ts { return false; } - function isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags): SymbolAccessibilityResult { + /** + * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested + * + * @param symbol a Symbol to check if accessible + * @param enclosingDeclaration a Node containing reference to the symbol + * @param meaning a SymbolFlags to check if such meaning of the symbol is accessible + * @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible + */ + function isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags, shouldComputeAliasesToMakeVisible: boolean): SymbolAccessibilityResult { if (symbol && enclosingDeclaration && !(symbol.flags & SymbolFlags.TypeParameter)) { const initialSymbol = symbol; let meaningToLook = meaning; @@ -1752,7 +1776,7 @@ namespace ts { // Symbol is accessible if it by itself is accessible const accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, /*useOnlyExternalAliasing*/ false); if (accessibleSymbolChain) { - const hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0]); + const hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); if (!hasAccessibleDeclarations) { return { accessibility: SymbolAccessibility.NotAccessible, @@ -1816,7 +1840,7 @@ namespace ts { return isAmbientModule(declaration) || (declaration.kind === SyntaxKind.SourceFile && isExternalOrCommonJsModule(declaration)); } - function hasVisibleDeclarations(symbol: Symbol): SymbolVisibilityResult { + function hasVisibleDeclarations(symbol: Symbol, shouldComputeAliasToMakeVisible: boolean): SymbolVisibilityResult { let aliasesToMakeVisible: AnyImportSyntax[]; if (forEach(symbol.declarations, declaration => !getIsDeclarationVisible(declaration))) { return undefined; @@ -1830,16 +1854,21 @@ namespace ts { const anyImportSyntax = getAnyImportSyntax(declaration); if (anyImportSyntax && - !(anyImportSyntax.flags & NodeFlags.Export) && // import clause without export + !(getModifierFlags(anyImportSyntax) & ModifierFlags.Export) && // import clause without export isDeclarationVisible(anyImportSyntax.parent)) { - getNodeLinks(declaration).isVisible = true; - if (aliasesToMakeVisible) { - if (!contains(aliasesToMakeVisible, anyImportSyntax)) { - aliasesToMakeVisible.push(anyImportSyntax); + // In function "buildTypeDisplay" where we decide whether to write type-alias or serialize types, + // we want to just check if type- alias is accessible or not but we don't care about emitting those alias at that time + // since we will do the emitting later in trackSymbol. + if (shouldComputeAliasToMakeVisible) { + getNodeLinks(declaration).isVisible = true; + if (aliasesToMakeVisible) { + if (!contains(aliasesToMakeVisible, anyImportSyntax)) { + aliasesToMakeVisible.push(anyImportSyntax); + } + } + else { + aliasesToMakeVisible = [anyImportSyntax]; } - } - else { - aliasesToMakeVisible = [anyImportSyntax]; } return true; } @@ -1874,7 +1903,7 @@ namespace ts { const symbol = resolveName(enclosingDeclaration, (firstIdentifier).text, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); // Verify if the symbol is accessible - return (symbol && hasVisibleDeclarations(symbol)) || { + return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || { accessibility: SymbolAccessibility.NotAccessible, errorSymbolName: getTextOfNode(firstIdentifier), errorNode: firstIdentifier @@ -1957,11 +1986,11 @@ namespace ts { return result || types; } - function visibilityToString(flags: NodeFlags) { - if (flags === NodeFlags.Private) { + function visibilityToString(flags: ModifierFlags) { + if (flags === ModifierFlags.Private) { return "private"; } - if (flags === NodeFlags.Protected) { + if (flags === ModifierFlags.Protected) { return "protected"; } return "public"; @@ -2065,7 +2094,7 @@ namespace ts { parentSymbol = symbol; } - // const the writer know we just wrote out a symbol. The declaration emitter writer uses + // Let the writer know we just wrote out a symbol. The declaration emitter writer uses // this to determine if an import it has previously seen (and not written out) needs // to be written to the file once the walk of the tree is complete. // @@ -2073,37 +2102,34 @@ namespace ts { // up front (for example, during checking) could determine if we need to emit the imports // and we could then access that data during declaration emit. writer.trackSymbol(symbol, enclosingDeclaration, meaning); - function walkSymbol(symbol: Symbol, meaning: SymbolFlags): void { - if (symbol) { - const accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & SymbolFormatFlags.UseOnlyExternalAliasing)); + /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ + function walkSymbol(symbol: Symbol, meaning: SymbolFlags, endOfChain: boolean): void { + const accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & SymbolFormatFlags.UseOnlyExternalAliasing)); - if (!accessibleSymbolChain || - needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { + if (!accessibleSymbolChain || + needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - // Go up and add our parent. - walkSymbol( - getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol), - getQualifiedLeftMeaning(meaning)); + // Go up and add our parent. + const parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent) { + walkSymbol(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); } + } - if (accessibleSymbolChain) { - for (const accessibleSymbol of accessibleSymbolChain) { - appendParentTypeArgumentsAndSymbolName(accessibleSymbol); - } + if (accessibleSymbolChain) { + for (const accessibleSymbol of accessibleSymbolChain) { + appendParentTypeArgumentsAndSymbolName(accessibleSymbol); } - else { - // If we didn't find accessible symbol chain for this symbol, break if this is external module - if (!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) { - return; - } + } + else if ( + // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. + endOfChain || + // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) + !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && + // If a parent symbol is an anonymous type, don't write it. + !(symbol.flags & (SymbolFlags.TypeLiteral | SymbolFlags.ObjectLiteral))) { - // if this is anonymous type break - if (symbol.flags & SymbolFlags.TypeLiteral || symbol.flags & SymbolFlags.ObjectLiteral) { - return; - } - - appendParentTypeArgumentsAndSymbolName(symbol); - } + appendParentTypeArgumentsAndSymbolName(symbol); } } @@ -2113,11 +2139,11 @@ namespace ts { const isTypeParameter = symbol.flags & SymbolFlags.TypeParameter; const typeFormatFlag = TypeFormatFlags.UseFullyQualifiedType & typeFlags; if (!isTypeParameter && (enclosingDeclaration || typeFormatFlag)) { - walkSymbol(symbol, meaning); - return; + walkSymbol(symbol, meaning, /*endOfChain*/ true); + } + else { + appendParentTypeArgumentsAndSymbolName(symbol); } - - return appendParentTypeArgumentsAndSymbolName(symbol); } function buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]) { @@ -2152,14 +2178,11 @@ namespace ts { // The specified symbol flags need to be reinterpreted as type flags buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, SymbolFlags.Type, SymbolFormatFlags.None, nextFlags); } - else if (!(flags & TypeFormatFlags.InTypeAlias) && type.flags & (TypeFlags.Anonymous | TypeFlags.UnionOrIntersection) && type.aliasSymbol) { - if (type.flags & TypeFlags.Anonymous || !(flags & TypeFormatFlags.UseTypeAliasValue)) { - const typeArguments = type.aliasTypeArguments; - writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); - } - else { - writeUnionOrIntersectionType(type, nextFlags); - } + else if (!(flags & TypeFormatFlags.InTypeAlias) && type.flags & (TypeFlags.Anonymous | TypeFlags.UnionOrIntersection) && type.aliasSymbol && + isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, SymbolFlags.Type, /*shouldComputeAliasesToMakeVisible*/ false).accessibility === SymbolAccessibility.Accessible) { + // Only write out inferred type with its corresponding type-alias if type-alias is visible + const typeArguments = type.aliasTypeArguments; + writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); } else if (type.flags & TypeFlags.UnionOrIntersection) { writeUnionOrIntersectionType(type, nextFlags); @@ -2311,7 +2334,7 @@ namespace ts { function shouldWriteTypeOfFunctionSymbol() { const isStaticMethodSymbol = !!(symbol.flags & SymbolFlags.Method && // typeof static method - forEach(symbol.declarations, declaration => declaration.flags & NodeFlags.Static)); + forEach(symbol.declarations, declaration => getModifierFlags(declaration) & ModifierFlags.Static)); const isNonLocalFunctionSymbol = !!(symbol.flags & SymbolFlags.Function) && (symbol.parent || // is exported function symbol forEach(symbol.declarations, declaration => @@ -2507,8 +2530,8 @@ namespace ts { } } - function buildBindingElementDisplay(bindingElement: BindingElement, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, symbolStack?: Symbol[]) { - if (bindingElement.kind === SyntaxKind.OmittedExpression) { + function buildBindingElementDisplay(bindingElement: ArrayBindingElement, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, symbolStack?: Symbol[]) { + if (isOmittedExpression(bindingElement)) { return; } Debug.assert(bindingElement.kind === SyntaxKind.BindingElement); @@ -2678,7 +2701,7 @@ namespace ts { } const parent = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) - if (!(getCombinedNodeFlags(node) & NodeFlags.Export) && + if (!(getCombinedModifierFlags(node) & ModifierFlags.Export) && !(node.kind !== SyntaxKind.ImportEqualsDeclaration && parent.kind !== SyntaxKind.SourceFile && isInAmbientContext(parent))) { return isGlobalSourceFile(parent); } @@ -2691,7 +2714,7 @@ namespace ts { case SyntaxKind.SetAccessor: case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: - if (node.flags & (NodeFlags.Private | NodeFlags.Protected)) { + if (getModifierFlags(node) & (ModifierFlags.Private | ModifierFlags.Protected)) { // Private/protected properties/methods are not visible return false; } @@ -2924,7 +2947,7 @@ namespace ts { // undefined or any type of the parent. if (!parentType || isTypeAny(parentType)) { if (declaration.initializer) { - return checkExpressionCached(declaration.initializer); + return checkDeclarationInitializer(declaration); } return parentType; } @@ -3095,7 +3118,8 @@ namespace ts { // Use the type of the initializer expression if one is present if (declaration.initializer) { - return addOptionality(checkExpressionCached(declaration.initializer), /*optional*/ declaration.questionToken && includeOptionality); + const type = checkDeclarationInitializer(declaration); + return addOptionality(type, /*optional*/ declaration.questionToken && includeOptionality); } // If it is a short-hand property assignment, use the type of the identifier @@ -3117,7 +3141,7 @@ namespace ts { // pattern. Otherwise, it is the type any. function getTypeFromBindingElement(element: BindingElement, includePatternInType?: boolean, reportErrors?: boolean): Type { if (element.initializer) { - return checkExpressionCached(element.initializer); + return checkDeclarationInitializer(element); } if (isBindingPattern(element.name)) { return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); @@ -3129,7 +3153,7 @@ namespace ts { } // Return the type implied by an object binding pattern - function getTypeFromObjectBindingPattern(pattern: BindingPattern, includePatternInType: boolean, reportErrors: boolean): Type { + function getTypeFromObjectBindingPattern(pattern: ObjectBindingPattern, includePatternInType: boolean, reportErrors: boolean): Type { const members = createMap(); let hasComputedProperties = false; forEach(pattern.elements, e => { @@ -3160,13 +3184,13 @@ namespace ts { // Return the type implied by an array binding pattern function getTypeFromArrayBindingPattern(pattern: BindingPattern, includePatternInType: boolean, reportErrors: boolean): Type { const elements = pattern.elements; - if (elements.length === 0 || elements[elements.length - 1].dotDotDotToken) { + const lastElement = lastOrUndefined(elements); + if (elements.length === 0 || (!isOmittedExpression(lastElement) && lastElement.dotDotDotToken)) { return languageVersion >= ScriptTarget.ES6 ? createIterableType(anyType) : anyArrayType; } // If the pattern has at least one element, and no rest element, then it should imply a tuple type. - const elementTypes = map(elements, e => e.kind === SyntaxKind.OmittedExpression ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors)); + const elementTypes = map(elements, e => isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors)); let result = createTupleType(elementTypes); - if (includePatternInType) { result = cloneTypeReference(result); result.pattern = pattern; @@ -3183,8 +3207,8 @@ namespace ts { // the parameter. function getTypeFromBindingPattern(pattern: BindingPattern, includePatternInType?: boolean, reportErrors?: boolean): Type { return pattern.kind === SyntaxKind.ObjectBindingPattern - ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) - : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); + ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) + : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); } // Return the type associated with a variable, parameter, or property declaration. In the simple case this is the type @@ -3401,7 +3425,7 @@ namespace ts { function getTypeOfEnumMember(symbol: Symbol): Type { const links = getSymbolLinks(symbol); if (!links.type) { - links.type = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); + links.type = getDeclaredTypeOfEnumMember(symbol); } return links.type; } @@ -3546,7 +3570,7 @@ namespace ts { function getInstantiatedConstructorsForTypeArguments(type: ObjectType, typeArgumentNodes: TypeNode[]): Signature[] { let signatures = getConstructorsForTypeArguments(type, typeArgumentNodes); if (typeArgumentNodes) { - const typeArguments = map(typeArgumentNodes, getTypeFromTypeNode); + const typeArguments = map(typeArgumentNodes, getTypeFromTypeNodeNoAlias); signatures = map(signatures, sig => getSignatureInstantiation(sig, typeArguments)); } return signatures; @@ -4109,7 +4133,7 @@ namespace ts { return [createSignature(undefined, classType.localTypeParameters, undefined, emptyArray, classType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; } const baseTypeNode = getBaseTypeNodeOfClass(classType); - const typeArguments = map(baseTypeNode.typeArguments, getTypeFromTypeNode); + const typeArguments = map(baseTypeNode.typeArguments, getTypeFromTypeNodeNoAlias); const typeArgCount = typeArguments ? typeArguments.length : 0; const result: Signature[] = []; for (const baseSig of baseSignatures) { @@ -4400,7 +4424,7 @@ namespace ts { const type = getApparentType(current); if (type !== unknownType) { const prop = getPropertyOfType(type, name); - if (prop && !(getDeclarationFlagsFromSymbol(prop) & (NodeFlags.Private | NodeFlags.Protected))) { + if (prop && !(getDeclarationModifierFlagsFromSymbol(prop) & (ModifierFlags.Private | ModifierFlags.Protected))) { commonFlags &= prop.flags; if (!props) { props = [prop]; @@ -4906,7 +4930,7 @@ namespace ts { const declaration = getIndexDeclarationOfSymbol(symbol, kind); if (declaration) { return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, - (declaration.flags & NodeFlags.Readonly) !== 0, declaration); + (getModifierFlags(declaration) & ModifierFlags.Readonly) !== 0, declaration); } return undefined; } @@ -5025,7 +5049,7 @@ namespace ts { // In a type reference, the outer type parameters of the referenced class or interface are automatically // supplied as type arguments and the type reference only specifies arguments for the local type parameters // of the class or interface. - return createTypeReference(type, concatenate(type.outerTypeParameters, map(node.typeArguments, getTypeFromTypeNode))); + return createTypeReference(type, concatenate(type.outerTypeParameters, map(node.typeArguments, getTypeFromTypeNodeNoAlias))); } if (node.typeArguments) { error(node, Diagnostics.Type_0_is_not_generic, typeToString(type)); @@ -5046,7 +5070,7 @@ namespace ts { error(node, Diagnostics.Generic_type_0_requires_1_type_argument_s, symbolToString(symbol), typeParameters.length); return unknownType; } - const typeArguments = map(node.typeArguments, getTypeFromTypeNode); + const typeArguments = map(node.typeArguments, getTypeFromTypeNodeNoAlias); const id = getTypeListId(typeArguments); return links.instantiations[id] || (links.instantiations[id] = instantiateType(type, createTypeMapper(typeParameters, typeArguments))); } @@ -5301,7 +5325,7 @@ namespace ts { function getTypeFromTupleTypeNode(node: TupleTypeNode): Type { const links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = createTupleType(map(node.elementTypes, getTypeFromTypeNode)); + links.resolvedType = createTupleType(map(node.elementTypes, getTypeFromTypeNodeNoAlias)); } return links.resolvedType; } @@ -5391,7 +5415,7 @@ namespace ts { while (i > 0) { i--; if (isSubtypeOfAny(types[i], types)) { - types.splice(i, 1); + orderedRemoveItemAt(types, i); } } } @@ -5449,7 +5473,7 @@ namespace ts { function getTypeFromUnionTypeNode(node: UnionTypeNode, aliasSymbol?: Symbol, aliasTypeArguments?: Type[]): Type { const links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getUnionType(map(node.types, getTypeFromTypeNode), /*subtypeReduction*/ false, aliasSymbol, aliasTypeArguments); + links.resolvedType = getUnionType(map(node.types, getTypeFromTypeNodeNoAlias), /*subtypeReduction*/ false, aliasSymbol, aliasTypeArguments); } return links.resolvedType; } @@ -5506,7 +5530,7 @@ namespace ts { function getTypeFromIntersectionTypeNode(node: IntersectionTypeNode, aliasSymbol?: Symbol, aliasTypeArguments?: Type[]): Type { const links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getIntersectionType(map(node.types, getTypeFromTypeNode), aliasSymbol, aliasTypeArguments); + links.resolvedType = getIntersectionType(map(node.types, getTypeFromTypeNodeNoAlias), aliasSymbol, aliasTypeArguments); } return links.resolvedType; } @@ -5554,7 +5578,7 @@ namespace ts { function getTypeFromJSDocTupleType(node: JSDocTupleType): Type { const links = getNodeLinks(node); if (!links.resolvedType) { - const types = map(node.types, getTypeFromTypeNode); + const types = map(node.types, getTypeFromTypeNodeNoAlias); links.resolvedType = createTupleType(types); } return links.resolvedType; @@ -5564,8 +5588,8 @@ namespace ts { const container = getThisContainer(node, /*includeArrowFunctions*/ false); const parent = container && container.parent; if (parent && (isClassLike(parent) || parent.kind === SyntaxKind.InterfaceDeclaration)) { - if (!(container.flags & NodeFlags.Static) && - (container.kind !== SyntaxKind.Constructor || isNodeDescendentOf(node, (container).body))) { + if (!(getModifierFlags(container) & ModifierFlags.Static) && + (container.kind !== SyntaxKind.Constructor || isNodeDescendantOf(node, (container).body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } } @@ -5581,6 +5605,10 @@ namespace ts { return links.resolvedType; } + function getTypeFromTypeNodeNoAlias(type: TypeNode) { + return getTypeFromTypeNode(type, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined); + } + function getTypeFromTypeNode(node: TypeNode, aliasSymbol?: Symbol, aliasTypeArguments?: Type[]): Type { switch (node.kind) { case SyntaxKind.AnyKeyword: @@ -5642,12 +5670,13 @@ namespace ts { case SyntaxKind.JSDocThisType: case SyntaxKind.JSDocOptionalType: return getTypeFromTypeNode((node).type); + case SyntaxKind.JSDocRecordType: + return getTypeFromTypeNode((node as JSDocRecordType).literal); case SyntaxKind.FunctionType: case SyntaxKind.ConstructorType: case SyntaxKind.TypeLiteral: case SyntaxKind.JSDocTypeLiteral: case SyntaxKind.JSDocFunctionType: - case SyntaxKind.JSDocRecordType: return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node, aliasSymbol, aliasTypeArguments); // This function assumes that an identifier or qualified name is a type expression // Callers should first ensure this by calling isTypeNode @@ -5712,7 +5741,7 @@ namespace ts { function getInferenceMapper(context: InferenceContext): TypeMapper { if (!context.mapper) { const mapper: TypeMapper = t => { - const typeParameters = context.typeParameters; + const typeParameters = context.signature.typeParameters; for (let i = 0; i < typeParameters.length; i++) { if (t === typeParameters[i]) { context.inferences[i].isFixed = true; @@ -5721,7 +5750,7 @@ namespace ts { } return t; }; - mapper.mappedTypes = context.typeParameters; + mapper.mappedTypes = context.signature.typeParameters; mapper.context = context; context.mapper = mapper; } @@ -6475,6 +6504,9 @@ namespace ts { if (source.flags & TypeFlags.ObjectType && target.flags & TypeFlags.Primitive) { tryElaborateErrorsForPrimitivesAndObjects(source, target); } + else if (source.symbol && source.flags & TypeFlags.ObjectType && globalObjectType === source) { + reportError(Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); + } reportRelationError(headMessage, source, target); } return Ternary.False; @@ -6743,24 +6775,24 @@ namespace ts { } } else if (!(targetProp.flags & SymbolFlags.Prototype)) { - const sourcePropFlags = getDeclarationFlagsFromSymbol(sourceProp); - const targetPropFlags = getDeclarationFlagsFromSymbol(targetProp); - if (sourcePropFlags & NodeFlags.Private || targetPropFlags & NodeFlags.Private) { + const sourcePropFlags = getDeclarationModifierFlagsFromSymbol(sourceProp); + const targetPropFlags = getDeclarationModifierFlagsFromSymbol(targetProp); + if (sourcePropFlags & ModifierFlags.Private || targetPropFlags & ModifierFlags.Private) { if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { if (reportErrors) { - if (sourcePropFlags & NodeFlags.Private && targetPropFlags & NodeFlags.Private) { + if (sourcePropFlags & ModifierFlags.Private && targetPropFlags & ModifierFlags.Private) { reportError(Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); } else { reportError(Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), - typeToString(sourcePropFlags & NodeFlags.Private ? source : target), - typeToString(sourcePropFlags & NodeFlags.Private ? target : source)); + typeToString(sourcePropFlags & ModifierFlags.Private ? source : target), + typeToString(sourcePropFlags & ModifierFlags.Private ? target : source)); } } return Ternary.False; } } - else if (targetPropFlags & NodeFlags.Protected) { + else if (targetPropFlags & ModifierFlags.Protected) { const sourceDeclaredInClass = sourceProp.parent && sourceProp.parent.flags & SymbolFlags.Class; const sourceClass = sourceDeclaredInClass ? getDeclaredTypeOfSymbol(getParentOfSymbol(sourceProp)) : undefined; const targetClass = getDeclaredTypeOfSymbol(getParentOfSymbol(targetProp)); @@ -6772,7 +6804,7 @@ namespace ts { return Ternary.False; } } - else if (sourcePropFlags & NodeFlags.Protected) { + else if (sourcePropFlags & ModifierFlags.Protected) { if (reportErrors) { reportError(Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); @@ -6982,21 +7014,21 @@ namespace ts { return true; } - const sourceAccessibility = sourceSignature.declaration.flags & (NodeFlags.Private | NodeFlags.Protected); - const targetAccessibility = targetSignature.declaration.flags & (NodeFlags.Private | NodeFlags.Protected); + const sourceAccessibility = getModifierFlags(sourceSignature.declaration) & ModifierFlags.NonPublicAccessibilityModifier; + const targetAccessibility = getModifierFlags(targetSignature.declaration) & ModifierFlags.NonPublicAccessibilityModifier; // A public, protected and private signature is assignable to a private signature. - if (targetAccessibility === NodeFlags.Private) { + if (targetAccessibility === ModifierFlags.Private) { return true; } // A public and protected signature is assignable to a protected signature. - if (targetAccessibility === NodeFlags.Protected && sourceAccessibility !== NodeFlags.Private) { + if (targetAccessibility === ModifierFlags.Protected && sourceAccessibility !== ModifierFlags.Private) { return true; } // Only a public signature is assignable to public signature. - if (targetAccessibility !== NodeFlags.Protected && !sourceAccessibility) { + if (targetAccessibility !== ModifierFlags.Protected && !sourceAccessibility) { return true; } @@ -7014,7 +7046,7 @@ namespace ts { const symbol = type.symbol; if (symbol && symbol.flags & SymbolFlags.Class) { const declaration = getClassLikeDeclarationOfSymbol(symbol); - if (declaration && declaration.flags & NodeFlags.Abstract) { + if (declaration && getModifierFlags(declaration) & ModifierFlags.Abstract) { return true; } } @@ -7054,8 +7086,8 @@ namespace ts { if (sourceProp === targetProp) { return Ternary.True; } - const sourcePropAccessibility = getDeclarationFlagsFromSymbol(sourceProp) & (NodeFlags.Private | NodeFlags.Protected); - const targetPropAccessibility = getDeclarationFlagsFromSymbol(targetProp) & (NodeFlags.Private | NodeFlags.Protected); + const sourcePropAccessibility = getDeclarationModifierFlagsFromSymbol(sourceProp) & ModifierFlags.NonPublicAccessibilityModifier; + const targetPropAccessibility = getDeclarationModifierFlagsFromSymbol(targetProp) & ModifierFlags.NonPublicAccessibilityModifier; if (sourcePropAccessibility !== targetPropAccessibility) { return Ternary.False; } @@ -7162,15 +7194,36 @@ namespace ts { return true; } + function literalTypesWithSameBaseType(types: Type[]): boolean { + let commonBaseType: Type; + for (const t of types) { + const baseType = getBaseTypeOfLiteralType(t); + if (!commonBaseType) { + commonBaseType = baseType; + } + if (baseType === t || baseType !== commonBaseType) { + return false; + } + } + return true; + } + + // When the candidate types are all literal types with the same base type, the common + // supertype is a union of those literal types. Otherwise, the common supertype is the + // first type that is a supertype of each of the other types. + function getSupertypeOrUnion(types: Type[]): Type { + return literalTypesWithSameBaseType(types) ? getUnionType(types) : forEach(types, t => isSupertypeOfEach(t, types) ? t : undefined); + } + function getCommonSupertype(types: Type[]): Type { if (!strictNullChecks) { - return forEach(types, t => isSupertypeOfEach(t, types) ? t : undefined); + return getSupertypeOrUnion(types); } const primaryTypes = filter(types, t => !(t.flags & TypeFlags.Nullable)); if (!primaryTypes.length) { return getUnionType(types, /*subtypeReduction*/ true); } - const supertype = forEach(primaryTypes, t => isSupertypeOfEach(t, primaryTypes) ? t : undefined); + const supertype = getSupertypeOrUnion(primaryTypes); return supertype && includeFalsyTypes(supertype, getFalsyFlagsOfTypes(types) & TypeFlags.Nullable); } @@ -7234,18 +7287,18 @@ namespace ts { return (type.flags & (TypeFlags.Literal | TypeFlags.Undefined | TypeFlags.Null)) !== 0; } - function isUnitUnionType(type: Type): boolean { + function isLiteralType(type: Type): boolean { return type.flags & TypeFlags.Boolean ? true : type.flags & TypeFlags.Union ? type.flags & TypeFlags.Enum ? true : !forEach((type).types, t => !isUnitType(t)) : isUnitType(type); } - function getBaseTypeOfUnitType(type: Type): Type { + function getBaseTypeOfLiteralType(type: Type): Type { return type.flags & TypeFlags.StringLiteral ? stringType : type.flags & TypeFlags.NumberLiteral ? numberType : type.flags & TypeFlags.BooleanLiteral ? booleanType : type.flags & TypeFlags.EnumLiteral ? (type).baseType : - type.flags & TypeFlags.Union && !(type.flags & TypeFlags.Enum) ? getUnionType(map((type).types, getBaseTypeOfUnitType)) : + type.flags & TypeFlags.Union && !(type.flags & TypeFlags.Enum) ? getUnionType(map((type).types, getBaseTypeOfLiteralType)) : type; } @@ -7499,14 +7552,13 @@ namespace ts { } } - function createInferenceContext(typeParameters: TypeParameter[], inferUnionTypes: boolean): InferenceContext { - const inferences = map(typeParameters, createTypeInferencesObject); - + function createInferenceContext(signature: Signature, inferUnionTypes: boolean): InferenceContext { + const inferences = map(signature.typeParameters, createTypeInferencesObject); return { - typeParameters, + signature, inferUnionTypes, inferences, - inferredTypes: new Array(typeParameters.length), + inferredTypes: new Array(signature.typeParameters.length), }; } @@ -7514,6 +7566,7 @@ namespace ts { return { primary: undefined, secondary: undefined, + topLevel: true, isFixed: false, }; } @@ -7535,13 +7588,18 @@ namespace ts { return type.couldContainTypeParameters; } - function inferTypes(context: InferenceContext, source: Type, target: Type) { + function isTypeParameterAtTopLevel(type: Type, typeParameter: TypeParameter): boolean { + return type === typeParameter || type.flags & TypeFlags.UnionOrIntersection && forEach((type).types, t => isTypeParameterAtTopLevel(t, typeParameter)); + } + + function inferTypes(context: InferenceContext, originalSource: Type, originalTarget: Type) { + const typeParameters = context.signature.typeParameters; let sourceStack: Type[]; let targetStack: Type[]; let depth = 0; let inferiority = 0; const visited = createMap(); - inferFromTypes(source, target); + inferFromTypes(originalSource, originalTarget); function isInProcess(source: Type, target: Type) { for (let i = 0; i < depth; i++) { @@ -7566,16 +7624,24 @@ namespace ts { } return; } - // Find each target constituent type that has an identically matching source - // constituent type, and for each such target constituent type infer from the type to - // itself. When inferring from a type to itself we effectively find all type parameter - // occurrences within that type and infer themselves as their type arguments. + // Find each source constituent type that has an identically matching target constituent + // type, and for each such type infer from the type to itself. When inferring from a + // type to itself we effectively find all type parameter occurrences within that type + // and infer themselves as their type arguments. We have special handling for numeric + // and string literals because the number and string types are not represented as unions + // of all their possible values. let matchingTypes: Type[]; - for (const t of (target).types) { - if (typeIdenticalToSomeType(t, (source).types)) { + for (const t of (source).types) { + if (typeIdenticalToSomeType(t, (target).types)) { (matchingTypes || (matchingTypes = [])).push(t); inferFromTypes(t, t); } + else if (t.flags & (TypeFlags.NumberLiteral | TypeFlags.StringLiteral)) { + const b = getBaseTypeOfLiteralType(t); + if (typeIdenticalToSomeType(b, (target).types)) { + (matchingTypes || (matchingTypes = [])).push(t, b); + } + } } // Next, to improve the quality of inferences, reduce the source and target types by // removing the identically matched constituents. For example, when inferring from @@ -7595,7 +7661,6 @@ namespace ts { if (source.flags & TypeFlags.ContainsAnyFunctionType) { return; } - const typeParameters = context.typeParameters; for (let i = 0; i < typeParameters.length; i++) { if (target === typeParameters[i]) { const inferences = context.inferences[i]; @@ -7612,6 +7677,9 @@ namespace ts { if (!contains(candidates, source)) { candidates.push(source); } + if (!isTypeParameterAtTopLevel(originalTarget, target)) { + inferences.topLevel = false; + } } return; } @@ -7632,7 +7700,7 @@ namespace ts { let typeParameter: TypeParameter; // First infer to each type in union or intersection that isn't a type parameter for (const t of targetTypes) { - if (t.flags & TypeFlags.TypeParameter && contains(context.typeParameters, t)) { + if (t.flags & TypeFlags.TypeParameter && contains(typeParameters, t)) { typeParameter = t; typeParameterCount++; } @@ -7707,8 +7775,12 @@ namespace ts { } } + function inferFromParameterTypes(source: Type, target: Type) { + return inferFromTypes(source, target); + } + function inferFromSignature(source: Signature, target: Signature) { - forEachMatchingParameterType(source, target, inferFromTypes); + forEachMatchingParameterType(source, target, inferFromParameterTypes); if (source.typePredicate && target.typePredicate && source.typePredicate.kind === target.typePredicate.kind) { inferFromTypes(source.typePredicate.type, target.typePredicate.type); @@ -7767,14 +7839,28 @@ namespace ts { return inferences.primary || inferences.secondary || emptyArray; } + function hasPrimitiveConstraint(type: TypeParameter): boolean { + const constraint = getConstraintOfTypeParameter(type); + return constraint && maybeTypeOfKind(constraint, TypeFlags.Primitive); + } + function getInferredType(context: InferenceContext, index: number): Type { let inferredType = context.inferredTypes[index]; let inferenceSucceeded: boolean; if (!inferredType) { const inferences = getInferenceCandidates(context, index); if (inferences.length) { + // We widen inferred literal types if + // all inferences were made to top-level ocurrences of the type parameter, and + // the type parameter has no constraint or its constraint includes no primitive or literal types, and + // the type parameter was fixed during inference or does not occur at top-level in the return type. + const signature = context.signature; + const widenLiteralTypes = context.inferences[index].topLevel && + !hasPrimitiveConstraint(signature.typeParameters[index]) && + (context.inferences[index].isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), signature.typeParameters[index])); + const baseInferences = widenLiteralTypes ? map(inferences, getBaseTypeOfLiteralType) : inferences; // Infer widened union or supertype, or the unknown type for no common supertype - const unionOrSuperType = context.inferUnionTypes ? getUnionType(inferences, /*subtypeReduction*/ true) : getCommonSupertype(inferences); + const unionOrSuperType = context.inferUnionTypes ? getUnionType(baseInferences, /*subtypeReduction*/ true) : getCommonSupertype(baseInferences); inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType; inferenceSucceeded = !!unionOrSuperType; } @@ -7790,7 +7876,7 @@ namespace ts { // Only do the constraint check if inference succeeded (to prevent cascading errors) if (inferenceSucceeded) { - const constraint = getConstraintOfTypeParameter(context.typeParameters[index]); + const constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); if (constraint) { const instantiatedConstraint = instantiateType(constraint, getInferenceMapper(context)); if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { @@ -7937,7 +8023,7 @@ namespace ts { if (prop && prop.flags & SymbolFlags.SyntheticProperty) { if ((prop).isDiscriminantProperty === undefined) { (prop).isDiscriminantProperty = !(prop).hasCommonType && - isUnitUnionType(getTypeOfSymbol(prop)); + isLiteralType(getTypeOfSymbol(prop)); } return (prop).isDiscriminantProperty; } @@ -7989,8 +8075,11 @@ namespace ts { // we remove type string. function getAssignmentReducedType(declaredType: UnionType, assignedType: Type) { if (declaredType !== assignedType) { + if (assignedType.flags & TypeFlags.Never) { + return assignedType; + } const reducedType = filterType(declaredType, t => typeMaybeAssignableTo(assignedType, t)); - if (reducedType !== neverType) { + if (!(reducedType.flags & TypeFlags.Never)) { return reducedType; } } @@ -8270,7 +8359,7 @@ namespace ts { const visitedFlowStart = visitedFlowCount; const result = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); visitedFlowCount = visitedFlowStart; - if (reference.parent.kind === SyntaxKind.NonNullExpression && getTypeWithFacts(result, TypeFacts.NEUndefinedOrNull) === neverType) { + if (reference.parent.kind === SyntaxKind.NonNullExpression && getTypeWithFacts(result, TypeFacts.NEUndefinedOrNull).flags & TypeFlags.Never) { return declaredType; } return result; @@ -8340,7 +8429,8 @@ namespace ts { // Assignments only narrow the computed type if the declared type is a union type. Thus, we // only need to evaluate the assigned type if the declared type is a union type. if (isMatchingReference(reference, node)) { - return declaredType.flags & TypeFlags.Union ? + const isIncrementOrDecrement = node.parent.kind === SyntaxKind.PrefixUnaryExpression || node.parent.kind === SyntaxKind.PostfixUnaryExpression; + return declaredType.flags & TypeFlags.Union && !isIncrementOrDecrement ? getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : declaredType; } @@ -8358,17 +8448,18 @@ namespace ts { function getTypeAtFlowCondition(flow: FlowCondition): FlowType { const flowType = getTypeAtFlowNode(flow.antecedent); let type = getTypeFromFlowType(flowType); - if (type !== neverType) { + if (!(type.flags & TypeFlags.Never)) { // If we have an antecedent type (meaning we're reachable in some way), we first // attempt to narrow the antecedent type. If that produces the never type, and if // the antecedent type is incomplete (i.e. a transient type in a loop), then we // take the type guard as an indication that control *could* reach here once we - // have the complete type. We proceed by reverting to the declared type and then - // narrow that. + // have the complete type. We proceed by switching to the silent never type which + // doesn't report errors when operators are applied to it. Note that this is the + // *only* place a silent never type is ever generated. const assumeTrue = (flow.flags & FlowFlags.TrueCondition) !== 0; type = narrowType(type, flow.expression, assumeTrue); - if (type === neverType && isIncomplete(flowType)) { - type = narrowType(declaredType, flow.expression, assumeTrue); + if (type.flags & TypeFlags.Never && isIncomplete(flowType)) { + type = silentNeverType; } } return createFlowType(type, isIncomplete(flowType)); @@ -8577,7 +8668,7 @@ namespace ts { } if (assumeTrue) { const narrowedType = filterType(type, t => areTypesComparable(t, valueType)); - return narrowedType !== neverType ? narrowedType : type; + return narrowedType.flags & TypeFlags.Never ? type : narrowedType; } return isUnitType(valueType) ? filterType(type, t => t !== valueType) : type; } @@ -8620,12 +8711,12 @@ namespace ts { const clauseTypes = switchTypes.slice(clauseStart, clauseEnd); const hasDefaultClause = clauseStart === clauseEnd || contains(clauseTypes, neverType); const discriminantType = getUnionType(clauseTypes); - const caseType = discriminantType === neverType ? neverType : filterType(type, t => isTypeComparableTo(discriminantType, t)); + const caseType = discriminantType.flags & TypeFlags.Never ? neverType : filterType(type, t => isTypeComparableTo(discriminantType, t)); if (!hasDefaultClause) { return caseType; } const defaultType = filterType(type, t => !(isUnitType(t) && contains(switchTypes, t))); - return caseType === neverType ? defaultType : getUnionType([caseType, defaultType]); + return caseType.flags & TypeFlags.Never ? defaultType : getUnionType([caseType, defaultType]); } function narrowTypeByInstanceof(type: Type, expr: BinaryExpression, assumeTrue: boolean): Type { @@ -8689,7 +8780,7 @@ namespace ts { // the candidate type. If one or more constituents remain, return a union of those. if (type.flags & TypeFlags.Union) { const assignableType = filterType(type, t => isTypeInstanceOf(t, candidate)); - if (assignableType !== neverType) { + if (!(assignableType.flags & TypeFlags.Never)) { return assignableType; } } @@ -8790,7 +8881,7 @@ namespace ts { // The location isn't a reference to the given symbol, meaning we're being asked // a hypothetical question of what type the symbol would have if there was a reference // to it at the given location. Since we have no control flow information for the - // hypotherical reference (control flow information is created and attached by the + // hypothetical reference (control flow information is created and attached by the // binder), we simply return the declared type of the symbol. return getTypeOfSymbol(symbol); } @@ -8864,10 +8955,13 @@ namespace ts { // can explicitly bound arguments objects if (symbol === argumentsSymbol) { const container = getContainingFunction(node); - if (container.kind === SyntaxKind.ArrowFunction) { - if (languageVersion < ScriptTarget.ES6) { + if (languageVersion < ScriptTarget.ES6) { + if (container.kind === SyntaxKind.ArrowFunction) { error(node, Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } + else if (hasModifier(container, ModifierFlags.Async)) { + error(node, Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method); + } } if (node.flags & NodeFlags.AwaitContext) { @@ -8881,22 +8975,41 @@ namespace ts { const localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); - // Due to the emit for class decorators, any reference to the class from inside of the class body - // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind - // behavior of class names in ES6. - if (languageVersion === ScriptTarget.ES6 - && localOrExportSymbol.flags & SymbolFlags.Class - && localOrExportSymbol.valueDeclaration.kind === SyntaxKind.ClassDeclaration - && nodeIsDecorated(localOrExportSymbol.valueDeclaration)) { - let container = getContainingClass(node); - while (container !== undefined) { - if (container === localOrExportSymbol.valueDeclaration && container.name !== node) { - getNodeLinks(container).flags |= NodeCheckFlags.ClassWithBodyScopedClassBinding; - getNodeLinks(node).flags |= NodeCheckFlags.BodyScopedClassBinding; - break; - } + if (localOrExportSymbol.flags & SymbolFlags.Class) { + const declaration = localOrExportSymbol.valueDeclaration; + // Due to the emit for class decorators, any reference to the class from inside of the class body + // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind + // behavior of class names in ES6. + if (languageVersion === ScriptTarget.ES6 + && declaration.kind === SyntaxKind.ClassDeclaration + && nodeIsDecorated(declaration)) { + let container = getContainingClass(node); + while (container !== undefined) { + if (container === declaration && container.name !== node) { + getNodeLinks(declaration).flags |= NodeCheckFlags.ClassWithConstructorReference; + getNodeLinks(node).flags |= NodeCheckFlags.ConstructorReferenceInClass; + break; + } - container = getContainingClass(container); + container = getContainingClass(container); + } + } + else if (declaration.kind === SyntaxKind.ClassExpression) { + // When we emit a class expression with static members that contain a reference + // to the constructor in the initializer, we will need to substitute that + // binding with an alias as the class name is not in scope. + let container = getThisContainer(node, /*includeArrowFunctions*/ false); + while (container !== undefined) { + if (container.parent === declaration) { + if (container.kind === SyntaxKind.PropertyDeclaration && hasModifier(container, ModifierFlags.Static)) { + getNodeLinks(declaration).flags |= NodeCheckFlags.ClassWithConstructorReference; + getNodeLinks(node).flags |= NodeCheckFlags.ConstructorReferenceInClass; + } + break; + } + + container = getThisContainer(container, /*includeArrowFunctions*/ false); + } } } @@ -9142,7 +9255,7 @@ namespace ts { break; case SyntaxKind.PropertyDeclaration: case SyntaxKind.PropertySignature: - if (container.flags & NodeFlags.Static) { + if (getModifierFlags(container) & ModifierFlags.Static) { error(node, Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } @@ -9180,9 +9293,10 @@ namespace ts { return thisType; } } + if (isClassLike(container.parent)) { const symbol = getSymbolOfNode(container.parent); - const type = container.flags & NodeFlags.Static ? getTypeOfSymbol(symbol) : (getDeclaredTypeOfSymbol(symbol)).thisType; + const type = hasModifier(container, ModifierFlags.Static) ? getTypeOfSymbol(symbol) : (getDeclaredTypeOfSymbol(symbol)).thisType; return getFlowTypeOfReference(node, type, /*assumeInitialized*/ true, /*flowContainer*/ undefined); } @@ -9261,7 +9375,7 @@ namespace ts { return unknownType; } - if ((container.flags & NodeFlags.Static) || isCallExpression) { + if ((getModifierFlags(container) & ModifierFlags.Static) || isCallExpression) { nodeCheckFlag = NodeCheckFlags.SuperStatic; } else { @@ -9326,8 +9440,8 @@ namespace ts { // This helper creates an object with a "value" property that wraps the `super` property or indexed access for both get and set. // This is required for destructuring assignments, as a call expression cannot be used as the target of a destructuring assignment // while a property access can. - if (container.kind === SyntaxKind.MethodDeclaration && container.flags & NodeFlags.Async) { - if (isSuperPropertyOrElementAccess(node.parent) && isAssignmentTarget(node.parent)) { + if (container.kind === SyntaxKind.MethodDeclaration && getModifierFlags(container) & ModifierFlags.Async) { + if (isSuperProperty(node.parent) && isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= NodeCheckFlags.AsyncMethodWithSuperBinding; } else { @@ -9392,7 +9506,7 @@ namespace ts { // topmost container must be something that is directly nested in the class declaration\object literal expression if (isClassLike(container.parent) || container.parent.kind === SyntaxKind.ObjectLiteralExpression) { - if (container.flags & NodeFlags.Static) { + if (getModifierFlags(container) & ModifierFlags.Static) { return container.kind === SyntaxKind.MethodDeclaration || container.kind === SyntaxKind.MethodSignature || container.kind === SyntaxKind.GetAccessor || @@ -9436,14 +9550,14 @@ namespace ts { if (parameter.dotDotDotToken) { const restTypes: Type[] = []; for (let i = indexOfParameter; i < iife.arguments.length; i++) { - restTypes.push(getTypeOfExpression(iife.arguments[i])); + restTypes.push(getBaseTypeOfLiteralType(checkExpression(iife.arguments[i]))); } return createArrayType(getUnionType(restTypes)); } const links = getNodeLinks(iife); const cached = links.resolvedSignature; links.resolvedSignature = anySignature; - const type = checkExpression(iife.arguments[indexOfParameter]); + const type = getBaseTypeOfLiteralType(checkExpression(iife.arguments[indexOfParameter])); links.resolvedSignature = cached; return type; } @@ -9794,6 +9908,7 @@ namespace ts { case SyntaxKind.BinaryExpression: return getContextualTypeForBinaryOperand(node); case SyntaxKind.PropertyAssignment: + case SyntaxKind.ShorthandPropertyAssignment: return getContextualTypeForObjectLiteralElement(parent); case SyntaxKind.ArrayLiteralExpression: return getContextualTypeForElementExpression(node); @@ -9813,31 +9928,6 @@ namespace ts { return undefined; } - function isLiteralTypeLocation(node: Node): boolean { - const parent = node.parent; - switch (parent.kind) { - case SyntaxKind.BinaryExpression: - switch ((parent).operatorToken.kind) { - case SyntaxKind.EqualsEqualsEqualsToken: - case SyntaxKind.ExclamationEqualsEqualsToken: - case SyntaxKind.EqualsEqualsToken: - case SyntaxKind.ExclamationEqualsToken: - return true; - } - break; - case SyntaxKind.ConditionalExpression: - return (node === (parent).whenTrue || - node === (parent).whenFalse) && - isLiteralTypeLocation(parent); - case SyntaxKind.ParenthesizedExpression: - return isLiteralTypeLocation(parent); - case SyntaxKind.CaseClause: - case SyntaxKind.LiteralType: - return true; - } - return false; - } - // If the given type is an object or union type, if that type has a single signature, and if // that signature is non-generic, return the signature. Otherwise return undefined. function getNonGenericSignature(type: Type): Signature { @@ -9974,7 +10064,7 @@ namespace ts { } } else { - const type = checkExpression(e, contextualMapper); + const type = checkExpressionForMutableLocation(e, contextualMapper); elementTypes.push(type); } hasSpreadElement = hasSpreadElement || e.kind === SyntaxKind.SpreadElementExpression; @@ -10031,6 +10121,10 @@ namespace ts { return isTypeAny(type) || isTypeOfKind(type, kind); } + function isInfinityOrNaNString(name: string): boolean { + return name === "Infinity" || name === "-Infinity" || name === "NaN"; + } + function isNumericLiteralName(name: string) { // The intent of numeric names is that // - they are names with text in a numeric form, and that @@ -10114,7 +10208,7 @@ namespace ts { } else { Debug.assert(memberDecl.kind === SyntaxKind.ShorthandPropertyAssignment); - type = checkExpression((memberDecl).name, contextualMapper); + type = checkExpressionForMutableLocation((memberDecl).name, contextualMapper); } typeFlags |= type.flags; const prop = createSymbol(SymbolFlags.Property | SymbolFlags.Transient | member.flags, member.name); @@ -10677,8 +10771,12 @@ namespace ts { return s.valueDeclaration ? s.valueDeclaration.kind : SyntaxKind.PropertyDeclaration; } - function getDeclarationFlagsFromSymbol(s: Symbol): NodeFlags { - return s.valueDeclaration ? getCombinedNodeFlags(s.valueDeclaration) : s.flags & SymbolFlags.Prototype ? NodeFlags.Public | NodeFlags.Static : 0; + function getDeclarationModifierFlagsFromSymbol(s: Symbol): ModifierFlags { + return s.valueDeclaration ? getCombinedModifierFlags(s.valueDeclaration) : s.flags & SymbolFlags.Prototype ? ModifierFlags.Public | ModifierFlags.Static : 0; + } + + function getDeclarationNodeFlagsFromSymbol(s: Symbol): NodeFlags { + return s.valueDeclaration ? getCombinedNodeFlags(s.valueDeclaration) : 0; } /** @@ -10690,7 +10788,7 @@ namespace ts { * @param prop The symbol for the right hand side of the property access. */ function checkClassPropertyAccess(node: PropertyAccessExpression | QualifiedName | VariableLikeDeclaration, left: Expression | QualifiedName, type: Type, prop: Symbol): boolean { - const flags = getDeclarationFlagsFromSymbol(prop); + const flags = getDeclarationModifierFlagsFromSymbol(prop); const declaringClass = getDeclaredTypeOfSymbol(getParentOfSymbol(prop)); const errorNode = node.kind === SyntaxKind.PropertyAccessExpression || node.kind === SyntaxKind.VariableDeclaration ? (node).name : @@ -10711,7 +10809,7 @@ namespace ts { return false; } - if (flags & NodeFlags.Abstract) { + if (flags & ModifierFlags.Abstract) { // A method cannot be accessed in a super property access if the method is abstract. // This error could mask a private property access error. But, a member // cannot simultaneously be private and abstract, so this will trigger an @@ -10723,14 +10821,14 @@ namespace ts { } // Public properties are otherwise accessible. - if (!(flags & (NodeFlags.Private | NodeFlags.Protected))) { + if (!(flags & ModifierFlags.NonPublicAccessibilityModifier)) { return true; } // Property is known to be private or protected at this point // Private property is accessible if the property is within the declaring class - if (flags & NodeFlags.Private) { + if (flags & ModifierFlags.Private) { const declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); if (!isNodeWithinClass(node, declaringClassDeclaration)) { error(errorNode, Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(declaringClass)); @@ -10758,7 +10856,7 @@ namespace ts { return false; } // No further restrictions for static properties - if (flags & NodeFlags.Static) { + if (flags & ModifierFlags.Static) { return true; } // An instance property must be accessed through an instance of the enclosing class @@ -10800,7 +10898,7 @@ namespace ts { function checkPropertyAccessExpressionOrQualifiedName(node: PropertyAccessExpression | QualifiedName, left: Expression | QualifiedName, right: Identifier) { const type = checkNonNullExpression(left); - if (isTypeAny(type)) { + if (isTypeAny(type) || type === silentNeverType) { return type; } @@ -10812,14 +10910,14 @@ namespace ts { const prop = getPropertyOfType(apparentType, right.text); if (!prop) { if (right.text && !checkAndReportErrorForExtendingInterface(node)) { - error(right, Diagnostics.Property_0_does_not_exist_on_type_1, declarationNameToString(right), typeToString(type.flags & TypeFlags.ThisType ? apparentType : type)); + reportNonexistentProperty(right, type.flags & TypeFlags.ThisType ? apparentType : type); } return unknownType; } if (noUnusedIdentifiers && (prop.flags & SymbolFlags.ClassMember) && - prop.valueDeclaration && (prop.valueDeclaration.flags & NodeFlags.Private)) { + prop.valueDeclaration && (getModifierFlags(prop.valueDeclaration) & ModifierFlags.Private)) { if (prop.flags & SymbolFlags.Instantiated) { getSymbolLinks(prop).target.isReferenced = true; @@ -10835,10 +10933,7 @@ namespace ts { checkClassPropertyAccess(node, left, apparentType, prop); } - let propType = getTypeOfSymbol(prop); - if (prop.flags & SymbolFlags.EnumMember && isLiteralContextForType(node, propType)) { - propType = getDeclaredTypeOfSymbol(prop); - } + const propType = getTypeOfSymbol(prop); // Only compute control flow type if this is a property access expression that isn't an // assignment target, and the referenced property was declared as a variable, property, @@ -10849,6 +10944,20 @@ namespace ts { return propType; } return getFlowTypeOfReference(node, propType, /*assumeInitialized*/ true, /*flowContainer*/ undefined); + + function reportNonexistentProperty(propNode: Identifier, containingType: Type) { + let errorInfo: DiagnosticMessageChain; + if (containingType.flags & TypeFlags.Union && !(containingType.flags & TypeFlags.Primitive)) { + for (const subtype of (containingType as UnionType).types) { + if (!getPropertyOfType(subtype, propNode.text)) { + errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Property_0_does_not_exist_on_type_1, declarationNameToString(propNode), typeToString(subtype)); + break; + } + } + } + errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Property_0_does_not_exist_on_type_1, declarationNameToString(propNode), typeToString(containingType)); + diagnostics.add(createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + } } function isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean { @@ -10936,8 +11045,8 @@ namespace ts { const objectType = getApparentType(checkNonNullExpression(node.expression)); const indexType = node.argumentExpression ? checkExpression(node.argumentExpression) : unknownType; - if (objectType === unknownType) { - return unknownType; + if (objectType === unknownType || objectType === silentNeverType) { + return objectType; } const isConstEnum = isConstEnumObjectType(objectType); @@ -11256,7 +11365,7 @@ namespace ts { // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) function instantiateSignatureInContextOf(signature: Signature, contextualSignature: Signature, contextualMapper: TypeMapper): Signature { - const context = createInferenceContext(signature.typeParameters, /*inferUnionTypes*/ true); + const context = createInferenceContext(signature, /*inferUnionTypes*/ true); forEachMatchingParameterType(contextualSignature, signature, (source, target) => { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type inferTypes(context, instantiateType(source, contextualMapper), target); @@ -11853,7 +11962,7 @@ namespace ts { else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { const typeArguments = (node).typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments, map(typeArguments, getTypeFromTypeNode), /*reportErrors*/ true, headMessage); + checkTypeArguments(candidateForTypeArgumentError, typeArguments, map(typeArguments, getTypeFromTypeNodeNoAlias), /*reportErrors*/ true, headMessage); } else { Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -11884,7 +11993,7 @@ namespace ts { for (let candidate of candidates) { if (hasCorrectArity(node, args, candidate)) { if (candidate.typeParameters && typeArguments) { - candidate = getSignatureInstantiation(candidate, map(typeArguments, getTypeFromTypeNode)); + candidate = getSignatureInstantiation(candidate, map(typeArguments, getTypeFromTypeNodeNoAlias)); } return candidate; } @@ -11912,7 +12021,7 @@ namespace ts { let candidate: Signature; let typeArgumentsAreValid: boolean; const inferenceContext = originalCandidate.typeParameters - ? createInferenceContext(originalCandidate.typeParameters, /*inferUnionTypes*/ false) + ? createInferenceContext(originalCandidate, /*inferUnionTypes*/ false) : undefined; while (true) { @@ -11920,7 +12029,7 @@ namespace ts { if (candidate.typeParameters) { let typeArgumentTypes: Type[]; if (typeArguments) { - typeArgumentTypes = map(typeArguments, getTypeFromTypeNode); + typeArgumentTypes = map(typeArguments, getTypeFromTypeNodeNoAlias); typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, /*reportErrors*/ false); } else { @@ -11987,6 +12096,9 @@ namespace ts { } const funcType = checkNonNullExpression(node.expression); + if (funcType === silentNeverType) { + return silentNeverSignature; + } const apparentType = getApparentType(funcType); if (apparentType === unknownType) { @@ -12020,7 +12132,7 @@ namespace ts { error(node, Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - error(node, Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature); + error(node, Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); } return resolveErrorCall(node); } @@ -12059,6 +12171,9 @@ namespace ts { } let expressionType = checkNonNullExpression(node.expression); + if (expressionType === silentNeverType) { + return silentNeverSignature; + } // If expressionType's apparent type(section 3.8.1) is an object type with one or // more construct signatures, the expression is processed in the same manner as a @@ -12076,7 +12191,7 @@ namespace ts { // In the case of a merged class-module or class-interface declaration, // only the class declaration node will have the Abstract flag set. const valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); - if (valueDecl && valueDecl.flags & NodeFlags.Abstract) { + if (valueDecl && getModifierFlags(valueDecl) & ModifierFlags.Abstract) { error(node, Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, declarationNameToString(valueDecl.name)); return resolveErrorCall(node); } @@ -12129,10 +12244,10 @@ namespace ts { } const declaration = signature.declaration; - const flags = declaration.flags; + const modifiers = getModifierFlags(declaration); // Public constructor is accessible. - if (!(flags & (NodeFlags.Private | NodeFlags.Protected))) { + if (!(modifiers & ModifierFlags.NonPublicAccessibilityModifier)) { return true; } @@ -12147,16 +12262,16 @@ namespace ts { const baseTypes = getBaseTypes(containingType); if (baseTypes.length) { const baseType = baseTypes[0]; - if (flags & NodeFlags.Protected && + if (modifiers & ModifierFlags.Protected && baseType.symbol === declaration.parent.symbol) { return true; } } } - if (flags & NodeFlags.Private) { + if (modifiers & ModifierFlags.Private) { error(node, Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); } - if (flags & NodeFlags.Protected) { + if (modifiers & ModifierFlags.Protected) { error(node, Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); } return false; @@ -12182,7 +12297,7 @@ namespace ts { } if (!callSignatures.length) { - error(node, Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature); + error(node, Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); return resolveErrorCall(node); } @@ -12230,7 +12345,7 @@ namespace ts { const headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); if (!callSignatures.length) { let errorInfo: DiagnosticMessageChain; - errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature); + errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); errorInfo = chainDiagnosticMessages(errorInfo, headMessage); diagnostics.add(createDiagnosticForNodeFromMessageChain(node, errorInfo)); return resolveErrorCall(node); @@ -12343,7 +12458,7 @@ namespace ts { } function checkAssertion(node: AssertionExpression) { - const exprType = getRegularTypeOfObjectLiteral(checkExpression(node.expression)); + const exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(node.expression))); checkSourceElement(node.type); const targetType = getTypeFromTypeNode(node.type); @@ -12403,7 +12518,7 @@ namespace ts { function assignBindingElementTypes(node: VariableLikeDeclaration) { if (isBindingPattern(node.name)) { for (const element of (node.name).elements) { - if (element.kind !== SyntaxKind.OmittedExpression) { + if (!isOmittedExpression(element)) { if (element.name.kind === SyntaxKind.Identifier) { getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); } @@ -12533,20 +12648,8 @@ namespace ts { return isAsync ? createPromiseReturnType(func, voidType) : voidType; } } - // When yield/return statements are contextually typed we allow the return type to be a union type. - // Otherwise we require the yield/return expressions to have a best common supertype. - type = contextualSignature ? getUnionType(types, /*subtypeReduction*/ true) : getCommonSupertype(types); - if (!type) { - if (funcIsGenerator) { - error(func, Diagnostics.No_best_common_type_exists_among_yield_expressions); - return createIterableIteratorType(unknownType); - } - else { - error(func, Diagnostics.No_best_common_type_exists_among_return_expressions); - // Defer to unioning the return types so we get a) downstream errors earlier and b) better Salsa experience - return isAsync ? createPromiseReturnType(func, getUnionType(types, /*subtypeReduction*/ true)) : getUnionType(types, /*subtypeReduction*/ true); - } - } + // Return a union of the return expression types. + type = getUnionType(types, /*subtypeReduction*/ true); if (funcIsGenerator) { type = createIterableIteratorType(type); @@ -12555,6 +12658,9 @@ namespace ts { if (!contextualSignature) { reportErrorsFromWidening(func, type); } + if (isUnitType(type) && !(contextualSignature && isLiteralContextualType(getReturnTypeOfSignature(contextualSignature)))) { + type = getBaseTypeOfLiteralType(type); + } const widenedType = getWidenedType(type); // From within an async function you can return either a non-promise value or a promise. Any @@ -12590,7 +12696,7 @@ namespace ts { return false; } const type = checkExpression(node.expression); - if (!isUnitUnionType(type)) { + if (!isLiteralType(type)) { return false; } const switchTypes = getSwitchClauseTypes(node); @@ -12627,7 +12733,7 @@ namespace ts { // the native Promise type by the caller. type = checkAwaitedType(type, func, Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); } - if (type === neverType) { + if (type.flags & TypeFlags.Never) { hasReturnOfTypeNever = true; } else if (!contains(aggregatedTypes, type)) { @@ -12677,7 +12783,7 @@ namespace ts { const hasExplicitReturn = func.flags & NodeFlags.HasExplicitReturn; - if (returnType === neverType) { + if (returnType && returnType.flags & TypeFlags.Never) { error(func.type, Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); } else if (returnType && !hasExplicitReturn) { @@ -12825,8 +12931,8 @@ namespace ts { // Enum members // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation) return symbol.isReadonly || - symbol.flags & SymbolFlags.Property && (getDeclarationFlagsFromSymbol(symbol) & NodeFlags.Readonly) !== 0 || - symbol.flags & SymbolFlags.Variable && (getDeclarationFlagsFromSymbol(symbol) & NodeFlags.Const) !== 0 || + symbol.flags & SymbolFlags.Property && (getDeclarationModifierFlagsFromSymbol(symbol) & ModifierFlags.Readonly) !== 0 || + symbol.flags & SymbolFlags.Variable && (getDeclarationNodeFlagsFromSymbol(symbol) & NodeFlags.Const) !== 0 || symbol.flags & SymbolFlags.Accessor && !(symbol.flags & SymbolFlags.SetAccessor) || (symbol.flags & SymbolFlags.EnumMember) !== 0; } @@ -12933,7 +13039,10 @@ namespace ts { function checkPrefixUnaryExpression(node: PrefixUnaryExpression): Type { const operandType = checkExpression(node.operand); - if (node.operator === SyntaxKind.MinusToken && node.operand.kind === SyntaxKind.NumericLiteral && isLiteralContextForType(node, numberType)) { + if (operandType === silentNeverType) { + return silentNeverType; + } + if (node.operator === SyntaxKind.MinusToken && node.operand.kind === SyntaxKind.NumericLiteral) { return getLiteralTypeForText(TypeFlags.NumberLiteral, "" + -(node.operand).text); } switch (node.operator) { @@ -12966,6 +13075,9 @@ namespace ts { function checkPostfixUnaryExpression(node: PostfixUnaryExpression): Type { const operandType = checkExpression(node.operand); + if (operandType === silentNeverType) { + return silentNeverType; + } const ok = checkArithmeticOperandType(node.operand, getNonNullableType(operandType), Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { @@ -13030,6 +13142,9 @@ namespace ts { } function checkInstanceOfExpression(left: Expression, right: Expression, leftType: Type, rightType: Type): Type { + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } // TypeScript 1.0 spec (April 2014): 4.15.4 // The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type, // and the right operand to be of type Any or a subtype of the 'Function' interface type. @@ -13046,6 +13161,9 @@ namespace ts { } function checkInExpression(left: Expression, right: Expression, leftType: Type, rightType: Type): Type { + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } // TypeScript 1.0 spec (April 2014): 4.15.5 // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, // and the right operand to be of type Any, an object type, or a type parameter type. @@ -13198,6 +13316,72 @@ namespace ts { return sourceType; } + /** + * This is a *shallow* check: An expression is side-effect-free if the + * evaluation of the expression *itself* cannot produce side effects. + * For example, x++ / 3 is side-effect free because the / operator + * does not have side effects. + * The intent is to "smell test" an expression for correctness in positions where + * its value is discarded (e.g. the left side of the comma operator). + */ + function isSideEffectFree(node: Node): boolean { + node = skipParentheses(node); + switch (node.kind) { + case SyntaxKind.Identifier: + case SyntaxKind.StringLiteral: + case SyntaxKind.RegularExpressionLiteral: + case SyntaxKind.TaggedTemplateExpression: + case SyntaxKind.TemplateExpression: + case SyntaxKind.NoSubstitutionTemplateLiteral: + case SyntaxKind.NumericLiteral: + case SyntaxKind.TrueKeyword: + case SyntaxKind.FalseKeyword: + case SyntaxKind.NullKeyword: + case SyntaxKind.UndefinedKeyword: + case SyntaxKind.FunctionExpression: + case SyntaxKind.ClassExpression: + case SyntaxKind.ArrowFunction: + case SyntaxKind.ArrayLiteralExpression: + case SyntaxKind.ObjectLiteralExpression: + case SyntaxKind.TypeOfExpression: + case SyntaxKind.NonNullExpression: + case SyntaxKind.JsxSelfClosingElement: + case SyntaxKind.JsxElement: + return true; + + case SyntaxKind.ConditionalExpression: + return isSideEffectFree((node as ConditionalExpression).whenTrue) && + isSideEffectFree((node as ConditionalExpression).whenFalse); + + case SyntaxKind.BinaryExpression: + if (isAssignmentOperator((node as BinaryExpression).operatorToken.kind)) { + return false; + } + return isSideEffectFree((node as BinaryExpression).left) && + isSideEffectFree((node as BinaryExpression).right); + + case SyntaxKind.PrefixUnaryExpression: + case SyntaxKind.PostfixUnaryExpression: + // Unary operators ~, !, +, and - have no side effects. + // The rest do. + switch ((node as PrefixUnaryExpression).operator) { + case SyntaxKind.ExclamationToken: + case SyntaxKind.PlusToken: + case SyntaxKind.MinusToken: + case SyntaxKind.TildeToken: + return true; + } + return false; + + // Some forms listed here for clarity + case SyntaxKind.VoidExpression: // Explicit opt-out + case SyntaxKind.TypeAssertionExpression: // Not SEF, but can produce useful type warnings + case SyntaxKind.AsExpression: // Not SEF, but can produce useful type warnings + default: + return false; + } + } + function isTypeEqualityComparableTo(source: Type, target: Type) { return (target.flags & TypeFlags.Nullable) !== 0 || isTypeComparableTo(source, target); } @@ -13244,6 +13428,9 @@ namespace ts { case SyntaxKind.CaretEqualsToken: case SyntaxKind.AmpersandToken: case SyntaxKind.AmpersandEqualsToken: + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } // TypeScript 1.0 spec (April 2014): 4.19.1 // These operators require their operands to be of type Any, the Number primitive type, // or an enum type. Operands of an enum type are treated @@ -13276,6 +13463,9 @@ namespace ts { return numberType; case SyntaxKind.PlusToken: case SyntaxKind.PlusEqualsToken: + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } // TypeScript 1.0 spec (April 2014): 4.19.2 // The binary + operator requires both operands to be of the Number primitive type or an enum type, // or at least one of the operands to be of type Any or the String primitive type. @@ -13333,11 +13523,11 @@ namespace ts { case SyntaxKind.ExclamationEqualsToken: case SyntaxKind.EqualsEqualsEqualsToken: case SyntaxKind.ExclamationEqualsEqualsToken: - const leftIsUnit = isUnitUnionType(leftType); - const rightIsUnit = isUnitUnionType(rightType); - if (!leftIsUnit || !rightIsUnit) { - leftType = leftIsUnit ? getBaseTypeOfUnitType(leftType) : leftType; - rightType = rightIsUnit ? getBaseTypeOfUnitType(rightType) : rightType; + const leftIsLiteral = isLiteralType(leftType); + const rightIsLiteral = isLiteralType(rightType); + if (!leftIsLiteral || !rightIsLiteral) { + leftType = leftIsLiteral ? getBaseTypeOfLiteralType(leftType) : leftType; + rightType = rightIsLiteral ? getBaseTypeOfLiteralType(rightType) : rightType; } if (!isTypeEqualityComparableTo(leftType, rightType) && !isTypeEqualityComparableTo(rightType, leftType)) { reportOperatorError(); @@ -13349,7 +13539,7 @@ namespace ts { return checkInExpression(left, right, leftType, rightType); case SyntaxKind.AmpersandAmpersandToken: return getTypeFacts(leftType) & TypeFacts.Truthy ? - includeFalsyTypes(rightType, getFalsyFlags(strictNullChecks ? leftType : getBaseTypeOfUnitType(rightType))) : + includeFalsyTypes(rightType, getFalsyFlags(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType))) : leftType; case SyntaxKind.BarBarToken: return getTypeFacts(leftType) & TypeFacts.Falsy ? @@ -13359,6 +13549,9 @@ namespace ts { checkAssignmentOperator(rightType); return getRegularTypeOfObjectLiteral(rightType); case SyntaxKind.CommaToken: + if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left)) { + error(left, Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); + } return rightType; } @@ -13483,64 +13676,18 @@ namespace ts { return getBestChoiceType(type1, type2); } - function typeContainsLiteralFromEnum(type: Type, enumType: EnumType) { - if (type.flags & TypeFlags.Union) { - for (const t of (type).types) { - if (t.flags & TypeFlags.EnumLiteral && (t).baseType === enumType) { - return true; - } - } - } - if (type.flags & TypeFlags.EnumLiteral) { - return (type).baseType === enumType; - } - return false; - } - - function isLiteralContextForType(node: Expression, type: Type) { - if (isLiteralTypeLocation(node)) { - return true; - } - let contextualType = getContextualType(node); - if (contextualType) { - if (contextualType.flags & TypeFlags.TypeParameter) { - const apparentType = getApparentTypeOfTypeParameter(contextualType); - // If the type parameter is constrained to the base primitive type we're checking for, - // consider this a literal context. For example, given a type parameter 'T extends string', - // this causes us to infer string literal types for T. - if (type === apparentType) { - return true; - } - contextualType = apparentType; - } - if (type.flags & TypeFlags.String) { - return maybeTypeOfKind(contextualType, TypeFlags.StringLiteral); - } - if (type.flags & TypeFlags.Number) { - return maybeTypeOfKind(contextualType, (TypeFlags.NumberLiteral | TypeFlags.EnumLiteral)); - } - if (type.flags & TypeFlags.Boolean) { - return maybeTypeOfKind(contextualType, TypeFlags.BooleanLiteral); - } - if (type.flags & TypeFlags.Enum) { - return typeContainsLiteralFromEnum(contextualType, type); - } - } - return false; - } - function checkLiteralExpression(node: Expression): Type { if (node.kind === SyntaxKind.NumericLiteral) { - checkGrammarNumericLiteral(node); + checkGrammarNumericLiteral(node); } switch (node.kind) { case SyntaxKind.StringLiteral: - return isLiteralContextForType(node, stringType) ? getLiteralTypeForText(TypeFlags.StringLiteral, (node).text) : stringType; + return getLiteralTypeForText(TypeFlags.StringLiteral, (node).text); case SyntaxKind.NumericLiteral: - return isLiteralContextForType(node, numberType) ? getLiteralTypeForText(TypeFlags.NumberLiteral, (node).text) : numberType; + return getLiteralTypeForText(TypeFlags.NumberLiteral, (node).text); case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: - return isLiteralContextForType(node, booleanType) ? node.kind === SyntaxKind.TrueKeyword ? trueType : falseType : booleanType; + return node.kind === SyntaxKind.TrueKeyword ? trueType : falseType; } } @@ -13579,6 +13726,40 @@ namespace ts { return links.resolvedType; } + function isTypeAssertion(node: Expression) { + node = skipParenthesizedNodes(node); + return node.kind === SyntaxKind.TypeAssertionExpression || node.kind === SyntaxKind.AsExpression; + } + + function checkDeclarationInitializer(declaration: VariableLikeDeclaration) { + const type = checkExpressionCached(declaration.initializer); + return getCombinedNodeFlags(declaration) & NodeFlags.Const || + getCombinedModifierFlags(declaration) & ModifierFlags.Readonly || + isTypeAssertion(declaration.initializer) ? type : getBaseTypeOfLiteralType(type); + } + + function isLiteralContextualType(contextualType: Type) { + if (contextualType) { + if (contextualType.flags & TypeFlags.TypeParameter) { + const apparentType = getApparentTypeOfTypeParameter(contextualType); + // If the type parameter is constrained to the base primitive type we're checking for, + // consider this a literal context. For example, given a type parameter 'T extends string', + // this causes us to infer string literal types for T. + if (apparentType.flags & (TypeFlags.String | TypeFlags.Number | TypeFlags.Boolean | TypeFlags.Enum)) { + return true; + } + contextualType = apparentType; + } + return maybeTypeOfKind(contextualType, TypeFlags.Literal); + } + return false; + } + + function checkExpressionForMutableLocation(node: Expression, contextualMapper?: TypeMapper): Type { + const type = checkExpression(node, contextualMapper); + return isTypeAssertion(node) || isLiteralContextualType(getContextualType(node)) ? type : getBaseTypeOfLiteralType(type); + } + function checkPropertyAssignment(node: PropertyAssignment, contextualMapper?: TypeMapper): Type { // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including @@ -13587,7 +13768,7 @@ namespace ts { checkComputedPropertyName(node.name); } - return checkExpression((node).initializer, contextualMapper); + return checkExpressionForMutableLocation((node).initializer, contextualMapper); } function checkObjectLiteralMethod(node: MethodDeclaration, contextualMapper?: TypeMapper): Type { @@ -13762,7 +13943,7 @@ namespace ts { checkVariableLikeDeclaration(node); let func = getContainingFunction(node); - if (node.flags & NodeFlags.ParameterPropertyModifier) { + if (getModifierFlags(node) & ModifierFlags.ParameterPropertyModifier) { func = getContainingFunction(node); if (!(func.kind === SyntaxKind.Constructor && nodeIsPresent(func.body))) { error(node, Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); @@ -13879,7 +14060,12 @@ namespace ts { pattern: BindingPattern, predicateVariableNode: Node, predicateVariableName: string) { - for (const { name } of pattern.elements) { + for (const element of pattern.elements) { + if (isOmittedExpression(element)) { + continue; + } + + const name = element.name; if (name.kind === SyntaxKind.Identifier && (name).text === predicateVariableName) { error(predicateVariableNode, @@ -14102,7 +14288,7 @@ namespace ts { // Abstract methods cannot have an implementation. // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node. - if (node.flags & NodeFlags.Abstract && node.body) { + if (getModifierFlags(node) & ModifierFlags.Abstract && node.body) { error(node, Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, declarationNameToString(node.name)); } } @@ -14161,7 +14347,7 @@ namespace ts { function isInstancePropertyWithInitializer(n: Node): boolean { return n.kind === SyntaxKind.PropertyDeclaration && - !(n.flags & NodeFlags.Static) && + !(getModifierFlags(n) & ModifierFlags.Static) && !!(n).initializer; } @@ -14184,7 +14370,7 @@ namespace ts { // or the containing class declares instance member variables with initializers. const superCallShouldBeFirst = forEach((node.parent).members, isInstancePropertyWithInitializer) || - forEach(node.parameters, p => p.flags & NodeFlags.ParameterPropertyModifier); + forEach(node.parameters, p => getModifierFlags(p) & ModifierFlags.ParameterPropertyModifier); // Skip past any prologue directives to find the first statement // to ensure that it was a super call. @@ -14238,10 +14424,10 @@ namespace ts { const otherKind = node.kind === SyntaxKind.GetAccessor ? SyntaxKind.SetAccessor : SyntaxKind.GetAccessor; const otherAccessor = getDeclarationOfKind(node.symbol, otherKind); if (otherAccessor) { - if (((node.flags & NodeFlags.AccessibilityModifier) !== (otherAccessor.flags & NodeFlags.AccessibilityModifier))) { + if ((getModifierFlags(node) & ModifierFlags.AccessibilityModifier) !== (getModifierFlags(otherAccessor) & ModifierFlags.AccessibilityModifier)) { error(node.name, Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); } - if (((node.flags & NodeFlags.Abstract) !== (otherAccessor.flags & NodeFlags.Abstract))) { + if (hasModifier(node, ModifierFlags.Abstract) !== hasModifier(otherAccessor, ModifierFlags.Abstract)) { error(node.name, Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); } @@ -14290,7 +14476,7 @@ namespace ts { const constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { if (!typeArguments) { - typeArguments = map(typeArgumentNodes, getTypeFromTypeNode); + typeArguments = map(typeArgumentNodes, getTypeFromTypeNodeNoAlias); mapper = createTypeMapper(typeParameters, typeArguments); } const typeArgument = typeArguments[i]; @@ -14356,11 +14542,11 @@ namespace ts { } function isPrivateWithinAmbient(node: Node): boolean { - return (node.flags & NodeFlags.Private) && isInAmbientContext(node); + return (getModifierFlags(node) & ModifierFlags.Private) && isInAmbientContext(node); } - function getEffectiveDeclarationFlags(n: Node, flagsToCheck: NodeFlags): NodeFlags { - let flags = getCombinedNodeFlags(n); + function getEffectiveDeclarationFlags(n: Node, flagsToCheck: ModifierFlags): ModifierFlags { + let flags = getCombinedModifierFlags(n); // children of classes (even ambient classes) should not be marked as ambient or export // because those flags have no useful semantics there. @@ -14368,11 +14554,11 @@ namespace ts { n.parent.kind !== SyntaxKind.ClassDeclaration && n.parent.kind !== SyntaxKind.ClassExpression && isInAmbientContext(n)) { - if (!(flags & NodeFlags.Ambient)) { + if (!(flags & ModifierFlags.Ambient)) { // It is nested in an ambient context, which means it is automatically exported - flags |= NodeFlags.Export; + flags |= ModifierFlags.Export; } - flags |= NodeFlags.Ambient; + flags |= ModifierFlags.Ambient; } return flags & flagsToCheck; @@ -14393,7 +14579,7 @@ namespace ts { return implementationSharesContainerWithFirstOverload ? implementation : overloads[0]; } - function checkFlagAgreementBetweenOverloads(overloads: Declaration[], implementation: FunctionLikeDeclaration, flagsToCheck: NodeFlags, someOverloadFlags: NodeFlags, allOverloadFlags: NodeFlags): void { + function checkFlagAgreementBetweenOverloads(overloads: Declaration[], implementation: FunctionLikeDeclaration, flagsToCheck: ModifierFlags, someOverloadFlags: ModifierFlags, allOverloadFlags: ModifierFlags): void { // Error if some overloads have a flag that is not shared by all overloads. To find the // deviations, we XOR someOverloadFlags with allOverloadFlags const someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags; @@ -14402,16 +14588,16 @@ namespace ts { forEach(overloads, o => { const deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags; - if (deviation & NodeFlags.Export) { + if (deviation & ModifierFlags.Export) { error(o.name, Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); } - else if (deviation & NodeFlags.Ambient) { + else if (deviation & ModifierFlags.Ambient) { error(o.name, Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); } - else if (deviation & (NodeFlags.Private | NodeFlags.Protected)) { + else if (deviation & (ModifierFlags.Private | ModifierFlags.Protected)) { error(o.name || o, Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } - else if (deviation & NodeFlags.Abstract) { + else if (deviation & ModifierFlags.Abstract) { error(o.name, Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); } }); @@ -14430,8 +14616,8 @@ namespace ts { } } - const flagsToCheck: NodeFlags = NodeFlags.Export | NodeFlags.Ambient | NodeFlags.Private | NodeFlags.Protected | NodeFlags.Abstract; - let someNodeFlags: NodeFlags = 0; + const flagsToCheck: ModifierFlags = ModifierFlags.Export | ModifierFlags.Ambient | ModifierFlags.Private | ModifierFlags.Protected | ModifierFlags.Abstract; + let someNodeFlags: ModifierFlags = ModifierFlags.None; let allNodeFlags = flagsToCheck; let someHaveQuestionToken = false; let allHaveQuestionToken = true; @@ -14466,13 +14652,13 @@ namespace ts { if (node.name && (subsequentNode).name && (node.name).text === ((subsequentNode).name).text) { const reportError = (node.kind === SyntaxKind.MethodDeclaration || node.kind === SyntaxKind.MethodSignature) && - (node.flags & NodeFlags.Static) !== (subsequentNode.flags & NodeFlags.Static); + (getModifierFlags(node) & ModifierFlags.Static) !== (getModifierFlags(subsequentNode) & ModifierFlags.Static); // we can get here in two cases // 1. mixed static and instance class members // 2. something with the same name was defined before the set of overloads that prevents them from merging // here we'll report error only for the first case since for second we should already report error in binder if (reportError) { - const diagnostic = node.flags & NodeFlags.Static ? Diagnostics.Function_overload_must_be_static : Diagnostics.Function_overload_must_not_be_static; + const diagnostic = getModifierFlags(node) & ModifierFlags.Static ? Diagnostics.Function_overload_must_be_static : Diagnostics.Function_overload_must_not_be_static; error(errorNode, diagnostic); } return; @@ -14490,7 +14676,7 @@ namespace ts { else { // Report different errors regarding non-consecutive blocks of declarations depending on whether // the node in question is abstract. - if (node.flags & NodeFlags.Abstract) { + if (getModifierFlags(node) & ModifierFlags.Abstract) { error(errorNode, Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); } else { @@ -14566,7 +14752,7 @@ namespace ts { // Abstract methods can't have an implementation -- in particular, they don't need one. if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && - !(lastSeenNonAmbientDeclaration.flags & NodeFlags.Abstract) && !lastSeenNonAmbientDeclaration.questionToken) { + !(getModifierFlags(lastSeenNonAmbientDeclaration) & ModifierFlags.Abstract) && !lastSeenNonAmbientDeclaration.questionToken) { reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } @@ -14616,10 +14802,10 @@ namespace ts { let defaultExportedDeclarationSpaces = SymbolFlags.None; for (const d of symbol.declarations) { const declarationSpaces = getDeclarationSpaces(d); - const effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, NodeFlags.Export | NodeFlags.Default); + const effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, ModifierFlags.Export | ModifierFlags.Default); - if (effectiveDeclarationFlags & NodeFlags.Export) { - if (effectiveDeclarationFlags & NodeFlags.Default) { + if (effectiveDeclarationFlags & ModifierFlags.Export) { + if (effectiveDeclarationFlags & ModifierFlags.Default) { defaultExportedDeclarationSpaces |= declarationSpaces; } else { @@ -14856,7 +15042,7 @@ namespace ts { * @param returnType The return type of a FunctionLikeDeclaration * @param location The node on which to report the error. */ - function checkCorrectPromiseType(returnType: Type, location: Node) { + function checkCorrectPromiseType(returnType: Type, location: Node, diagnostic: DiagnosticMessage, typeName?: string) { if (returnType === unknownType) { // The return type already had some other error, so we ignore and return // the unknown type. @@ -14875,7 +15061,7 @@ namespace ts { // The promise type was not a valid type reference to the global promise type, so we // report an error and return the unknown type. - error(location, Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + error(location, diagnostic, typeName); return unknownType; } @@ -14895,7 +15081,7 @@ namespace ts { function checkAsyncFunctionReturnType(node: FunctionLikeDeclaration): Type { if (languageVersion >= ScriptTarget.ES6) { const returnType = getTypeFromTypeNode(node.type); - return checkCorrectPromiseType(returnType, node.type); + return checkCorrectPromiseType(returnType, node.type, Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); } const globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(); @@ -14941,11 +15127,11 @@ namespace ts { const promiseConstructor = getNodeLinks(node.type).resolvedSymbol; if (!promiseConstructor || !symbolIsValue(promiseConstructor)) { + // try to fall back to global promise type. const typeName = promiseConstructor ? symbolToString(promiseConstructor) : typeToString(promiseType); - error(node, Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeName); - return unknownType; + return checkCorrectPromiseType(promiseType, node.type, Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeName); } // If the Promise constructor, resolved locally, is an alias symbol we should mark it as referenced. @@ -14953,7 +15139,7 @@ namespace ts { // Validate the promise constructor type. const promiseConstructorType = getTypeOfSymbol(promiseConstructor); - if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node, Diagnostics.Type_0_is_not_a_valid_async_function_return_type)) { + if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node.type, Diagnostics.Type_0_is_not_a_valid_async_function_return_type)) { return unknownType; } @@ -15274,13 +15460,13 @@ namespace ts { if (node.members) { for (const member of node.members) { if (member.kind === SyntaxKind.MethodDeclaration || member.kind === SyntaxKind.PropertyDeclaration) { - if (!member.symbol.isReferenced && member.flags & NodeFlags.Private) { + if (!member.symbol.isReferenced && getModifierFlags(member) & ModifierFlags.Private) { error(member.name, Diagnostics._0_is_declared_but_never_used, member.symbol.name); } } else if (member.kind === SyntaxKind.Constructor) { for (const parameter of (member).parameters) { - if (!parameter.symbol.isReferenced && parameter.flags & NodeFlags.Private) { + if (!parameter.symbol.isReferenced && getModifierFlags(parameter) & ModifierFlags.Private) { error(parameter.name, Diagnostics.Property_0_is_declared_but_never_used, parameter.symbol.name); } } @@ -15506,7 +15692,7 @@ namespace ts { if (localDeclarationSymbol && localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & SymbolFlags.BlockScopedVariable) { - if (getDeclarationFlagsFromSymbol(localDeclarationSymbol) & NodeFlags.BlockScoped) { + if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & NodeFlags.BlockScoped) { const varDeclList = getAncestor(localDeclarationSymbol.valueDeclaration, SyntaxKind.VariableDeclarationList); const container = varDeclList.parent.kind === SyntaxKind.VariableStatement && varDeclList.parent.parent @@ -15584,7 +15770,7 @@ namespace ts { // computed property names/initializers in instance property declaration of class like entities // are executed in constructor and thus deferred if (current.parent.kind === SyntaxKind.PropertyDeclaration && - !(current.parent.flags & NodeFlags.Static) && + !(hasModifier(current.parent, ModifierFlags.Static)) && isClassLike(current.parent.parent)) { return; } @@ -15699,14 +15885,14 @@ namespace ts { return false; } - const interestingFlags = NodeFlags.Private | - NodeFlags.Protected | - NodeFlags.Async | - NodeFlags.Abstract | - NodeFlags.Readonly | - NodeFlags.Static; + const interestingFlags = ModifierFlags.Private | + ModifierFlags.Protected | + ModifierFlags.Async | + ModifierFlags.Abstract | + ModifierFlags.Readonly | + ModifierFlags.Static; - return (left.flags & interestingFlags) === (right.flags & interestingFlags); + return (getModifierFlags(left) & interestingFlags) === (getModifierFlags(right) & interestingFlags); } function checkVariableDeclaration(node: VariableDeclaration) { @@ -16112,7 +16298,7 @@ namespace ts { // Now that we've removed all the StringLike types, if no constituents remain, then the entire // arrayOrStringType was a string. - if (arrayType === neverType) { + if (arrayType.flags & TypeFlags.Never) { return stringType; } } @@ -16173,7 +16359,7 @@ namespace ts { if (func) { const signature = getSignatureFromDeclaration(func); const returnType = getReturnTypeOfSignature(signature); - if (strictNullChecks || node.expression || returnType === neverType) { + if (strictNullChecks || node.expression || returnType.flags & TypeFlags.Never) { const exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; if (func.asteriskToken) { @@ -16362,7 +16548,7 @@ namespace ts { // Only process instance properties with computed names here. // Static properties cannot be in conflict with indexers, // and properties with literal names were already checked. - if (!(member.flags & NodeFlags.Static) && hasDynamicName(member)) { + if (!(getModifierFlags(member) & ModifierFlags.Static) && hasDynamicName(member)) { const propType = getTypeOfSymbol(member.symbol); checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, IndexKind.String); checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, IndexKind.Number); @@ -16492,7 +16678,7 @@ namespace ts { } function checkClassDeclaration(node: ClassDeclaration) { - if (!node.name && !(node.flags & NodeFlags.Default)) { + if (!node.name && !(getModifierFlags(node) & ModifierFlags.Default)) { grammarErrorOnFirstToken(node, Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } checkClassLikeDeclaration(node); @@ -16591,7 +16777,7 @@ namespace ts { const signatures = getSignaturesOfType(type, SignatureKind.Construct); if (signatures.length) { const declaration = signatures[0].declaration; - if (declaration && declaration.flags & NodeFlags.Private) { + if (declaration && getModifierFlags(declaration) & ModifierFlags.Private) { const typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); if (!isNodeWithinClass(node, typeClassDeclaration)) { error(node, Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, (node.expression).text); @@ -16636,7 +16822,7 @@ namespace ts { } const derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); - const baseDeclarationFlags = getDeclarationFlagsFromSymbol(base); + const baseDeclarationFlags = getDeclarationModifierFlagsFromSymbol(base); Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); @@ -16652,7 +16838,7 @@ namespace ts { // It is an error to inherit an abstract member without implementing it or being declared abstract. // If there is no declaration for the derived class (as in the case of class expressions), // then the class cannot be declared abstract. - if (baseDeclarationFlags & NodeFlags.Abstract && (!derivedClassDecl || !(derivedClassDecl.flags & NodeFlags.Abstract))) { + if (baseDeclarationFlags & ModifierFlags.Abstract && (!derivedClassDecl || !(getModifierFlags(derivedClassDecl) & ModifierFlags.Abstract))) { if (derivedClassDecl.kind === SyntaxKind.ClassExpression) { error(derivedClassDecl, Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); @@ -16665,13 +16851,13 @@ namespace ts { } else { // derived overrides base. - const derivedDeclarationFlags = getDeclarationFlagsFromSymbol(derived); - if ((baseDeclarationFlags & NodeFlags.Private) || (derivedDeclarationFlags & NodeFlags.Private)) { + const derivedDeclarationFlags = getDeclarationModifierFlagsFromSymbol(derived); + if ((baseDeclarationFlags & ModifierFlags.Private) || (derivedDeclarationFlags & ModifierFlags.Private)) { // either base or derived property is private - not override, skip it continue; } - if ((baseDeclarationFlags & NodeFlags.Static) !== (derivedDeclarationFlags & NodeFlags.Static)) { + if ((baseDeclarationFlags & ModifierFlags.Static) !== (derivedDeclarationFlags & ModifierFlags.Static)) { // value of 'static' is not the same for properties - not override, skip it continue; } @@ -16842,7 +17028,7 @@ namespace ts { } else { const text = getTextOfPropertyName(member.name); - if (isNumericLiteralName(text)) { + if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) { error(member.name, Diagnostics.An_enum_member_cannot_have_a_numeric_name); } } @@ -16943,7 +17129,7 @@ namespace ts { } return undefined; case SyntaxKind.NumericLiteral: - return +(e).text; + return +(e).text; case SyntaxKind.ParenthesizedExpression: return evalConstant((e).expression); case SyntaxKind.Identifier: @@ -17344,7 +17530,7 @@ namespace ts { // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & NodeFlags.Modifier)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && getModifierFlags(node) !== 0) { grammarErrorOnFirstToken(node, Diagnostics.An_import_declaration_cannot_have_modifiers); } if (checkExternalImportOrExportDeclaration(node)) { @@ -17374,7 +17560,7 @@ namespace ts { checkGrammarDecorators(node) || checkGrammarModifiers(node); if (isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { checkImportBinding(node); - if (node.flags & NodeFlags.Export) { + if (getModifierFlags(node) & ModifierFlags.Export) { markExportAsReferenced(node); } if (isInternalModuleImportEqualsDeclaration(node)) { @@ -17407,7 +17593,7 @@ namespace ts { return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & NodeFlags.Modifier)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && getModifierFlags(node) !== 0) { grammarErrorOnFirstToken(node, Diagnostics.An_export_declaration_cannot_have_modifiers); } @@ -17466,7 +17652,7 @@ namespace ts { return; } // Grammar checking - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & NodeFlags.Modifier)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && getModifierFlags(node) !== 0) { grammarErrorOnFirstToken(node, Diagnostics.An_export_assignment_cannot_have_modifiers); } if (node.expression.kind === SyntaxKind.Identifier) { @@ -17811,7 +17997,7 @@ namespace ts { function getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[] { const symbols = createMap(); - let memberFlags: NodeFlags = 0; + let memberFlags: ModifierFlags = ModifierFlags.None; if (isInsideWithStatementBody(location)) { // We cannot answer semantic questions within a with block, do not proceed any further @@ -17852,7 +18038,7 @@ namespace ts { // add the type parameters into the symbol table // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. // Note: that the memberFlags come from previous iteration. - if (!(memberFlags & NodeFlags.Static)) { + if (!(memberFlags & ModifierFlags.Static)) { copySymbols(getSymbolOfNode(location).members, meaning & SymbolFlags.Type); } break; @@ -17868,7 +18054,7 @@ namespace ts { copySymbol(argumentsSymbol, meaning); } - memberFlags = location.flags; + memberFlags = getModifierFlags(location); location = location.parent; } @@ -18030,7 +18216,7 @@ namespace ts { meaning |= SymbolFlags.Alias; return resolveEntityName(entityName, meaning); } - else if (isExpression(entityName)) { + else if (isPartOfExpression(entityName)) { if (nodeIsMissing(entityName)) { // Missing entity name. return undefined; @@ -18124,7 +18310,7 @@ namespace ts { // fallthrough case SyntaxKind.SuperKeyword: - const type = isExpression(node) ? checkExpression(node) : getTypeFromTypeNode(node); + const type = isPartOfExpression(node) ? checkExpression(node) : getTypeFromTypeNode(node); return type.symbol; case SyntaxKind.ThisType: @@ -18155,7 +18341,7 @@ namespace ts { if (objectType === unknownType) return undefined; const apparentType = getApparentType(objectType); if (apparentType === unknownType) return undefined; - return getPropertyOfType(apparentType, (node).text); + return getPropertyOfType(apparentType, (node).text); } break; } @@ -18185,11 +18371,11 @@ namespace ts { return unknownType; } - if (isTypeNode(node)) { + if (isPartOfTypeNode(node)) { return getTypeFromTypeNode(node); } - if (isExpression(node)) { + if (isPartOfExpression(node)) { return getTypeOfExpression(node); } @@ -18295,7 +18481,7 @@ namespace ts { */ function getParentTypeOfClassElement(node: ClassElement) { const classSymbol = getSymbolOfNode(node.parent); - return node.flags & NodeFlags.Static + return getModifierFlags(node) & ModifierFlags.Static ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } @@ -18343,7 +18529,14 @@ namespace ts { // Emitter support function isArgumentsLocalBinding(node: Identifier): boolean { - return getReferencedValueSymbol(node) === argumentsSymbol; + if (!isGeneratedIdentifier(node)) { + node = getParseTreeNode(node, isIdentifier); + if (node) { + return getReferencedValueSymbol(node) === argumentsSymbol; + } + } + + return false; } function moduleExportsSomeValue(moduleReferenceExpression: Expression): boolean { @@ -18375,32 +18568,45 @@ namespace ts { } } + function isNameOfModuleOrEnumDeclaration(node: Identifier) { + const parent = node.parent; + return isModuleOrEnumDeclaration(parent) && node === parent.name; + } + // When resolved as an expression identifier, if the given node references an exported entity, return the declaration // node of the exported entity's container. Otherwise, return undefined. - function getReferencedExportContainer(node: Identifier): SourceFile | ModuleDeclaration | EnumDeclaration { - let symbol = getReferencedValueSymbol(node); - if (symbol) { - if (symbol.flags & SymbolFlags.ExportValue) { - // If we reference an exported entity within the same module declaration, then whether - // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the - // kinds that we do NOT prefix. - const exportSymbol = getMergedSymbol(symbol.exportSymbol); - if (exportSymbol.flags & SymbolFlags.ExportHasLocal) { - return undefined; - } - symbol = exportSymbol; - } - const parentSymbol = getParentOfSymbol(symbol); - if (parentSymbol) { - if (parentSymbol.flags & SymbolFlags.ValueModule && parentSymbol.valueDeclaration.kind === SyntaxKind.SourceFile) { - // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. - if (parentSymbol.valueDeclaration === getSourceFileOfNode(node)) { - return parentSymbol.valueDeclaration; + function getReferencedExportContainer(node: Identifier, prefixLocals?: boolean): SourceFile | ModuleDeclaration | EnumDeclaration | undefined { + node = getParseTreeNode(node, isIdentifier); + if (node) { + // When resolving the export container for the name of a module or enum + // declaration, we need to start resolution at the declaration's container. + // Otherwise, we could incorrectly resolve the export container as the + // declaration if it contains an exported member with the same name. + let symbol = getReferencedValueSymbol(node, /*startInDeclarationContainer*/ isNameOfModuleOrEnumDeclaration(node)); + if (symbol) { + if (symbol.flags & SymbolFlags.ExportValue) { + // If we reference an exported entity within the same module declaration, then whether + // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the + // kinds that we do NOT prefix. + const exportSymbol = getMergedSymbol(symbol.exportSymbol); + if (!prefixLocals && exportSymbol.flags & SymbolFlags.ExportHasLocal) { + return undefined; } + symbol = exportSymbol; } - for (let n = node.parent; n; n = n.parent) { - if ((n.kind === SyntaxKind.ModuleDeclaration || n.kind === SyntaxKind.EnumDeclaration) && getSymbolOfNode(n) === parentSymbol) { - return n; + const parentSymbol = getParentOfSymbol(symbol); + if (parentSymbol) { + if (parentSymbol.flags & SymbolFlags.ValueModule && parentSymbol.valueDeclaration.kind === SyntaxKind.SourceFile) { + const symbolFile = parentSymbol.valueDeclaration; + const referenceFile = getSourceFileOfNode(node); + // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. + const symbolIsUmdExport = symbolFile !== referenceFile; + return symbolIsUmdExport ? undefined : symbolFile; + } + for (let n = node.parent; n; n = n.parent) { + if (isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol) { + return n; + } } } } @@ -18410,8 +18616,15 @@ namespace ts { // When resolved as an expression identifier, if the given node references an import, return the declaration of // that import. Otherwise, return undefined. function getReferencedImportDeclaration(node: Identifier): Declaration { - const symbol = getReferencedValueSymbol(node); - return symbol && symbol.flags & SymbolFlags.Alias ? getDeclarationOfAliasSymbol(symbol) : undefined; + node = getParseTreeNode(node, isIdentifier); + if (node) { + const symbol = getReferencedValueSymbol(node); + if (symbol && symbol.flags & SymbolFlags.Alias) { + return getDeclarationOfAliasSymbol(symbol); + } + } + + return undefined; } function isSymbolOfDeclarationWithCollidingName(symbol: Symbol): boolean { @@ -18461,35 +18674,62 @@ namespace ts { // a name that either hides an existing name or might hide it when compiled downlevel, // return the declaration of that entity. Otherwise, return undefined. function getReferencedDeclarationWithCollidingName(node: Identifier): Declaration { - const symbol = getReferencedValueSymbol(node); - return symbol && isSymbolOfDeclarationWithCollidingName(symbol) ? symbol.valueDeclaration : undefined; + if (!isGeneratedIdentifier(node)) { + node = getParseTreeNode(node, isIdentifier); + if (node) { + const symbol = getReferencedValueSymbol(node); + if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) { + return symbol.valueDeclaration; + } + } + } + + return undefined; } // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an // existing name or might hide a name when compiled downlevel function isDeclarationWithCollidingName(node: Declaration): boolean { - return isSymbolOfDeclarationWithCollidingName(getSymbolOfNode(node)); + node = getParseTreeNode(node, isDeclaration); + if (node) { + const symbol = getSymbolOfNode(node); + if (symbol) { + return isSymbolOfDeclarationWithCollidingName(symbol); + } + } + + return false; } function isValueAliasDeclaration(node: Node): boolean { + node = getParseTreeNode(node); + if (node === undefined) { + // A synthesized node comes from an emit transformation and is always a value. + return true; + } + switch (node.kind) { case SyntaxKind.ImportEqualsDeclaration: case SyntaxKind.ImportClause: case SyntaxKind.NamespaceImport: case SyntaxKind.ImportSpecifier: case SyntaxKind.ExportSpecifier: - return isAliasResolvedToValue(getSymbolOfNode(node)); + return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); case SyntaxKind.ExportDeclaration: const exportClause = (node).exportClause; return exportClause && forEach(exportClause.elements, isValueAliasDeclaration); case SyntaxKind.ExportAssignment: - return (node).expression && (node).expression.kind === SyntaxKind.Identifier ? isAliasResolvedToValue(getSymbolOfNode(node)) : true; + return (node).expression + && (node).expression.kind === SyntaxKind.Identifier + ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) + : true; } return false; } function isTopLevelValueImportEqualsWithEntityName(node: ImportEqualsDeclaration): boolean { - if (node.parent.kind !== SyntaxKind.SourceFile || !isInternalModuleImportEqualsDeclaration(node)) { + node = getParseTreeNode(node, isImportEqualsDeclaration); + if (node === undefined || node.parent.kind !== SyntaxKind.SourceFile || !isInternalModuleImportEqualsDeclaration(node)) { // parent is not source file or it is not reference to internal module return false; } @@ -18514,9 +18754,15 @@ namespace ts { } function isReferencedAliasDeclaration(node: Node, checkChildren?: boolean): boolean { + node = getParseTreeNode(node); + // Purely synthesized nodes are always emitted. + if (node === undefined) { + return true; + } + if (isAliasSymbolDeclaration(node)) { const symbol = getSymbolOfNode(node); - if (getSymbolLinks(symbol).referenced) { + if (symbol && getSymbolLinks(symbol).referenced) { return true; } } @@ -18549,7 +18795,8 @@ namespace ts { } function getNodeCheckFlags(node: Node): NodeCheckFlags { - return getNodeLinks(node).flags; + node = getParseTreeNode(node); + return node ? getNodeLinks(node).flags : undefined; } function getEnumMemberValue(node: EnumMember): number { @@ -18577,16 +18824,21 @@ namespace ts { return type.flags & TypeFlags.ObjectType && getSignaturesOfType(type, SignatureKind.Call).length > 0; } - function getTypeReferenceSerializationKind(typeName: EntityName): TypeReferenceSerializationKind { + function getTypeReferenceSerializationKind(typeName: EntityName, location?: Node): TypeReferenceSerializationKind { // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. - const valueSymbol = resolveEntityName(typeName, SymbolFlags.Value, /*ignoreErrors*/ true); + const valueSymbol = resolveEntityName(typeName, SymbolFlags.Value, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + const globalPromiseSymbol = tryGetGlobalPromiseConstructorSymbol(); + if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { + return TypeReferenceSerializationKind.Promise; + } + const constructorType = valueSymbol ? getTypeOfSymbol(valueSymbol) : undefined; if (constructorType && isConstructorType(constructorType)) { return TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue; } // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. - const typeSymbol = resolveEntityName(typeName, SymbolFlags.Type, /*ignoreErrors*/ true); + const typeSymbol = resolveEntityName(typeName, SymbolFlags.Type, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); // We might not be able to resolve type symbol so use unknown type in that case (eg error case) if (!typeSymbol) { return TypeReferenceSerializationKind.ObjectType; @@ -18598,8 +18850,8 @@ namespace ts { else if (type.flags & TypeFlags.Any) { return TypeReferenceSerializationKind.ObjectType; } - else if (isTypeOfKind(type, TypeFlags.Void)) { - return TypeReferenceSerializationKind.VoidType; + else if (isTypeOfKind(type, TypeFlags.Void | TypeFlags.Nullable | TypeFlags.Never)) { + return TypeReferenceSerializationKind.VoidNullableOrNeverType; } else if (isTypeOfKind(type, TypeFlags.BooleanLike)) { return TypeReferenceSerializationKind.BooleanType; @@ -18658,16 +18910,37 @@ namespace ts { return !!globals[name]; } - function getReferencedValueSymbol(reference: Identifier): Symbol { - return getNodeLinks(reference).resolvedSymbol || - resolveName(reference, reference.text, SymbolFlags.Value | SymbolFlags.ExportValue | SymbolFlags.Alias, - /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined); + function getReferencedValueSymbol(reference: Identifier, startInDeclarationContainer?: boolean): Symbol { + const resolvedSymbol = getNodeLinks(reference).resolvedSymbol; + if (resolvedSymbol) { + return resolvedSymbol; + } + + let location: Node = reference; + if (startInDeclarationContainer) { + // When resolving the name of a declaration as a value, we need to start resolution + // at a point outside of the declaration. + const parent = reference.parent; + if (isDeclaration(parent) && reference === parent.name) { + location = getDeclarationContainer(parent); + } + } + + return resolveName(location, reference.text, SymbolFlags.Value | SymbolFlags.ExportValue | SymbolFlags.Alias, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined); } function getReferencedValueDeclaration(reference: Identifier): Declaration { - Debug.assert(!nodeIsSynthesized(reference)); - const symbol = getReferencedValueSymbol(reference); - return symbol && getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; + if (!isGeneratedIdentifier(reference)) { + reference = getParseTreeNode(reference, isIdentifier); + if (reference) { + const symbol = getReferencedValueSymbol(reference); + if (symbol) { + return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; + } + } + } + + return undefined; } function createResolver(): EmitResolver { @@ -18684,9 +18957,6 @@ namespace ts { continue; } const file = host.getSourceFile(resolvedDirective.resolvedFileName); - if (!file) { - continue; - } fileToDirective.set(file.path, key); } } @@ -18806,20 +19076,21 @@ namespace ts { function initializeTypeChecker() { // Bind all source files and propagate errors - forEach(host.getSourceFiles(), file => { + for (const file of host.getSourceFiles()) { bindSourceFile(file, compilerOptions); - }); + } - let augmentations: LiteralExpression[][]; // Initialize global symbol table - forEach(host.getSourceFiles(), file => { + let augmentations: LiteralExpression[][]; + let requestedExternalEmitHelpers: NodeFlags = 0; + let firstFileRequestingExternalHelpers: SourceFile; + for (const file of host.getSourceFiles()) { if (!isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } if (file.patternAmbientModules && file.patternAmbientModules.length) { patternAmbientModules = concatenate(patternAmbientModules, file.patternAmbientModules); } - if (file.moduleAugmentations.length) { (augmentations || (augmentations = [])).push(file.moduleAugmentations); } @@ -18832,7 +19103,16 @@ namespace ts { } } } - }); + if ((compilerOptions.isolatedModules || isExternalModule(file)) && !file.isDeclarationFile) { + const fileRequestedExternalEmitHelpers = file.flags & NodeFlags.EmitHelperFlags; + if (fileRequestedExternalEmitHelpers) { + requestedExternalEmitHelpers |= fileRequestedExternalEmitHelpers; + if (firstFileRequestingExternalHelpers === undefined) { + firstFileRequestingExternalHelpers = file; + } + } + } + } if (augmentations) { // merge module augmentations. @@ -18872,6 +19152,7 @@ namespace ts { getGlobalPromiseLikeType = memoize(() => getGlobalType("PromiseLike", /*arity*/ 1)); getInstantiatedGlobalPromiseLikeType = memoize(createInstantiatedPromiseLikeType); getGlobalPromiseConstructorSymbol = memoize(() => getGlobalValueSymbol("Promise")); + tryGetGlobalPromiseConstructorSymbol = memoize(() => getGlobalSymbol("Promise", SymbolFlags.Value, /*diagnostic*/ undefined) && getGlobalPromiseConstructorSymbol()); getGlobalPromiseConstructorLikeType = memoize(() => getGlobalType("PromiseConstructorLike")); getGlobalThenableType = memoize(createThenableType); @@ -18895,6 +19176,51 @@ namespace ts { const symbol = getGlobalSymbol("ReadonlyArray", SymbolFlags.Type, /*diagnostic*/ undefined); globalReadonlyArrayType = symbol && getTypeOfGlobalSymbol(symbol, /*arity*/ 1); anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; + + // If we have specified that we are importing helpers, we should report global + // errors if we cannot resolve the helpers external module, or if it does not have + // the necessary helpers exported. + if (compilerOptions.importHelpers && firstFileRequestingExternalHelpers) { + // Find the first reference to the helpers module. + const helpersModule = resolveExternalModule( + firstFileRequestingExternalHelpers, + externalHelpersModuleNameText, + Diagnostics.Cannot_find_module_0, + /*errorNode*/ undefined); + + // If we found the module, report errors if it does not have the necessary exports. + if (helpersModule) { + const exports = helpersModule.exports; + if (requestedExternalEmitHelpers & NodeFlags.HasClassExtends && languageVersion < ScriptTarget.ES6) { + verifyHelperSymbol(exports, "__extends", SymbolFlags.Value); + } + if (requestedExternalEmitHelpers & NodeFlags.HasJsxSpreadAttributes && compilerOptions.jsx !== JsxEmit.Preserve) { + verifyHelperSymbol(exports, "__assign", SymbolFlags.Value); + } + if (requestedExternalEmitHelpers & NodeFlags.HasDecorators) { + verifyHelperSymbol(exports, "__decorate", SymbolFlags.Value); + if (compilerOptions.emitDecoratorMetadata) { + verifyHelperSymbol(exports, "__metadata", SymbolFlags.Value); + } + } + if (requestedExternalEmitHelpers & NodeFlags.HasParamDecorators) { + verifyHelperSymbol(exports, "__param", SymbolFlags.Value); + } + if (requestedExternalEmitHelpers & NodeFlags.HasAsyncFunctions) { + verifyHelperSymbol(exports, "__awaiter", SymbolFlags.Value); + if (languageVersion < ScriptTarget.ES6) { + verifyHelperSymbol(exports, "__generator", SymbolFlags.Value); + } + } + } + } + } + + function verifyHelperSymbol(symbols: SymbolTable, name: string, meaning: SymbolFlags) { + const symbol = getSymbol(symbols, escapeIdentifier(name), meaning); + if (!symbol) { + error(/*location*/ undefined, Diagnostics.Module_0_has_no_exported_member_1, externalHelpersModuleNameText, name); + } } function createInstantiatedPromiseLikeType(): ObjectType { @@ -18948,7 +19274,7 @@ namespace ts { } let lastStatic: Node, lastPrivate: Node, lastProtected: Node, lastDeclare: Node, lastAsync: Node, lastReadonly: Node; - let flags = 0; + let flags = ModifierFlags.None; for (const modifier of node.modifiers) { if (modifier.kind !== SyntaxKind.ReadonlyKeyword) { if (node.kind === SyntaxKind.PropertySignature || node.kind === SyntaxKind.MethodSignature) { @@ -18976,22 +19302,22 @@ namespace ts { lastPrivate = modifier; } - if (flags & NodeFlags.AccessibilityModifier) { + if (flags & ModifierFlags.AccessibilityModifier) { return grammarErrorOnNode(modifier, Diagnostics.Accessibility_modifier_already_seen); } - else if (flags & NodeFlags.Static) { + else if (flags & ModifierFlags.Static) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); } - else if (flags & NodeFlags.Readonly) { + else if (flags & ModifierFlags.Readonly) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly"); } - else if (flags & NodeFlags.Async) { + else if (flags & ModifierFlags.Async) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } else if (node.parent.kind === SyntaxKind.ModuleBlock || node.parent.kind === SyntaxKind.SourceFile) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); } - else if (flags & NodeFlags.Abstract) { + else if (flags & ModifierFlags.Abstract) { if (modifier.kind === SyntaxKind.PrivateKeyword) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); } @@ -19003,13 +19329,13 @@ namespace ts { break; case SyntaxKind.StaticKeyword: - if (flags & NodeFlags.Static) { + if (flags & ModifierFlags.Static) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "static"); } - else if (flags & NodeFlags.Readonly) { + else if (flags & ModifierFlags.Readonly) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly"); } - else if (flags & NodeFlags.Async) { + else if (flags & ModifierFlags.Async) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } else if (node.parent.kind === SyntaxKind.ModuleBlock || node.parent.kind === SyntaxKind.SourceFile) { @@ -19018,36 +19344,36 @@ namespace ts { else if (node.kind === SyntaxKind.Parameter) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } - else if (flags & NodeFlags.Abstract) { + else if (flags & ModifierFlags.Abstract) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } - flags |= NodeFlags.Static; + flags |= ModifierFlags.Static; lastStatic = modifier; break; case SyntaxKind.ReadonlyKeyword: - if (flags & NodeFlags.Readonly) { + if (flags & ModifierFlags.Readonly) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "readonly"); } else if (node.kind !== SyntaxKind.PropertyDeclaration && node.kind !== SyntaxKind.PropertySignature && node.kind !== SyntaxKind.IndexSignature && node.kind !== SyntaxKind.Parameter) { // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property. return grammarErrorOnNode(modifier, Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); } - flags |= NodeFlags.Readonly; + flags |= ModifierFlags.Readonly; lastReadonly = modifier; break; case SyntaxKind.ExportKeyword: - if (flags & NodeFlags.Export) { + if (flags & ModifierFlags.Export) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "export"); } - else if (flags & NodeFlags.Ambient) { + else if (flags & ModifierFlags.Ambient) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); } - else if (flags & NodeFlags.Abstract) { + else if (flags & ModifierFlags.Abstract) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract"); } - else if (flags & NodeFlags.Async) { + else if (flags & ModifierFlags.Async) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); } else if (node.parent.kind === SyntaxKind.ClassDeclaration) { @@ -19056,14 +19382,14 @@ namespace ts { else if (node.kind === SyntaxKind.Parameter) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } - flags |= NodeFlags.Export; + flags |= ModifierFlags.Export; break; case SyntaxKind.DeclareKeyword: - if (flags & NodeFlags.Ambient) { + if (flags & ModifierFlags.Ambient) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "declare"); } - else if (flags & NodeFlags.Async) { + else if (flags & ModifierFlags.Async) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } else if (node.parent.kind === SyntaxKind.ClassDeclaration) { @@ -19075,12 +19401,12 @@ namespace ts { else if (isInAmbientContext(node.parent) && node.parent.kind === SyntaxKind.ModuleBlock) { return grammarErrorOnNode(modifier, Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } - flags |= NodeFlags.Ambient; + flags |= ModifierFlags.Ambient; lastDeclare = modifier; break; case SyntaxKind.AbstractKeyword: - if (flags & NodeFlags.Abstract) { + if (flags & ModifierFlags.Abstract) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "abstract"); } if (node.kind !== SyntaxKind.ClassDeclaration) { @@ -19090,61 +19416,61 @@ namespace ts { node.kind !== SyntaxKind.SetAccessor) { return grammarErrorOnNode(modifier, Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === SyntaxKind.ClassDeclaration && node.parent.flags & NodeFlags.Abstract)) { + if (!(node.parent.kind === SyntaxKind.ClassDeclaration && getModifierFlags(node.parent) & ModifierFlags.Abstract)) { return grammarErrorOnNode(modifier, Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } - if (flags & NodeFlags.Static) { + if (flags & ModifierFlags.Static) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } - if (flags & NodeFlags.Private) { + if (flags & ModifierFlags.Private) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract"); } } - flags |= NodeFlags.Abstract; + flags |= ModifierFlags.Abstract; break; case SyntaxKind.AsyncKeyword: - if (flags & NodeFlags.Async) { + if (flags & ModifierFlags.Async) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "async"); } - else if (flags & NodeFlags.Ambient || isInAmbientContext(node.parent)) { + else if (flags & ModifierFlags.Ambient || isInAmbientContext(node.parent)) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } else if (node.kind === SyntaxKind.Parameter) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); } - flags |= NodeFlags.Async; + flags |= ModifierFlags.Async; lastAsync = modifier; break; } } if (node.kind === SyntaxKind.Constructor) { - if (flags & NodeFlags.Static) { + if (flags & ModifierFlags.Static) { return grammarErrorOnNode(lastStatic, Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } - if (flags & NodeFlags.Abstract) { + if (flags & ModifierFlags.Abstract) { return grammarErrorOnNode(lastStatic, Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); } - else if (flags & NodeFlags.Async) { + else if (flags & ModifierFlags.Async) { return grammarErrorOnNode(lastAsync, Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); } - else if (flags & NodeFlags.Readonly) { + else if (flags & ModifierFlags.Readonly) { return grammarErrorOnNode(lastReadonly, Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly"); } return; } - else if ((node.kind === SyntaxKind.ImportDeclaration || node.kind === SyntaxKind.ImportEqualsDeclaration) && flags & NodeFlags.Ambient) { + else if ((node.kind === SyntaxKind.ImportDeclaration || node.kind === SyntaxKind.ImportEqualsDeclaration) && flags & ModifierFlags.Ambient) { return grammarErrorOnNode(lastDeclare, Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === SyntaxKind.Parameter && (flags & NodeFlags.ParameterPropertyModifier) && isBindingPattern((node).name)) { + else if (node.kind === SyntaxKind.Parameter && (flags & ModifierFlags.ParameterPropertyModifier) && isBindingPattern((node).name)) { return grammarErrorOnNode(node, Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); } - else if (node.kind === SyntaxKind.Parameter && (flags & NodeFlags.ParameterPropertyModifier) && (node).dotDotDotToken) { + else if (node.kind === SyntaxKind.Parameter && (flags & ModifierFlags.ParameterPropertyModifier) && (node).dotDotDotToken) { return grammarErrorOnNode(node, Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } - if (flags & NodeFlags.Async) { + if (flags & ModifierFlags.Async) { return checkGrammarAsyncModifier(node, lastAsync); } } @@ -19205,10 +19531,6 @@ namespace ts { } function checkGrammarAsyncModifier(node: Node, asyncModifier: Node): boolean { - if (languageVersion < ScriptTarget.ES6) { - return grammarErrorOnNode(asyncModifier, Diagnostics.Async_functions_are_only_available_when_targeting_ECMAScript_2015_or_higher); - } - switch (node.kind) { case SyntaxKind.MethodDeclaration: case SyntaxKind.FunctionDeclaration: @@ -19312,7 +19634,7 @@ namespace ts { if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, Diagnostics.An_index_signature_cannot_have_a_rest_parameter); } - if (parameter.flags & NodeFlags.Modifier) { + if (getModifierFlags(parameter) !== 0) { return grammarErrorOnNode(parameter.name, Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); } if (parameter.questionToken) { @@ -19497,11 +19819,13 @@ namespace ts { } // Modifiers are never allowed on properties except for 'async' on a method declaration - forEach(prop.modifiers, mod => { - if (mod.kind !== SyntaxKind.AsyncKeyword || prop.kind !== SyntaxKind.MethodDeclaration) { - grammarErrorOnNode(mod, Diagnostics._0_modifier_cannot_be_used_here, getTextOfNode(mod)); + if (prop.modifiers) { + for (const mod of prop.modifiers) { + if (mod.kind !== SyntaxKind.AsyncKeyword || prop.kind !== SyntaxKind.MethodDeclaration) { + grammarErrorOnNode(mod, Diagnostics._0_modifier_cannot_be_used_here, getTextOfNode(mod)); + } } - }); + } // ECMA-262 11.1.5 Object Initializer // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true @@ -19516,7 +19840,7 @@ namespace ts { // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop, (prop).questionToken, Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === SyntaxKind.NumericLiteral) { - checkGrammarNumericLiteral(name); + checkGrammarNumericLiteral(name); } currentKind = Property; } @@ -19639,7 +19963,7 @@ namespace ts { else if (isInAmbientContext(accessor)) { return grammarErrorOnNode(accessor.name, Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); } - else if (accessor.body === undefined && !(accessor.flags & NodeFlags.Abstract)) { + else if (accessor.body === undefined && !(getModifierFlags(accessor) & ModifierFlags.Abstract)) { return grammarErrorAtPos(getSourceFileOfNode(accessor), accessor.end - 1, ";".length, Diagnostics._0_expected, "{"); } else if (accessor.typeParameters) { @@ -19850,7 +20174,7 @@ namespace ts { else { const elements = (name).elements; for (const element of elements) { - if (element.kind !== SyntaxKind.OmittedExpression) { + if (!isOmittedExpression(element)) { checkGrammarNameInLetOrConstDeclarations(element.name); } } @@ -19984,10 +20308,8 @@ namespace ts { node.kind === SyntaxKind.ExportDeclaration || node.kind === SyntaxKind.ExportAssignment || node.kind === SyntaxKind.NamespaceExportDeclaration || - (node.flags & NodeFlags.Ambient) || - (node.flags & (NodeFlags.Export | NodeFlags.Default))) { - - return false; + getModifierFlags(node) & (ModifierFlags.Ambient | ModifierFlags.Export | ModifierFlags.Default)) { + return false; } return grammarErrorOnFirstToken(node, Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); @@ -20040,7 +20362,7 @@ namespace ts { } } - function checkGrammarNumericLiteral(node: LiteralExpression): boolean { + function checkGrammarNumericLiteral(node: NumericLiteral): boolean { // Grammar checking if (node.isOctalLiteral && languageVersion >= ScriptTarget.ES5) { return grammarErrorOnNode(node, Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher); diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 825519bfb05..3dcca7cbb14 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -33,6 +33,7 @@ namespace ts { { name: "extendedDiagnostics", type: "boolean", + experimental: true }, { name: "emitBOM", @@ -296,6 +297,7 @@ namespace ts { "classic": ModuleResolutionKind.Classic, }), description: Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, + paramType: Diagnostics.STRATEGY, }, { name: "allowUnusedLabels", @@ -436,6 +438,11 @@ namespace ts { name: "strictNullChecks", type: "boolean", description: Diagnostics.Enable_strict_null_checks + }, + { + name: "importHelpers", + type: "boolean", + description: Diagnostics.Import_emit_helpers_from_tslib } ]; @@ -802,12 +809,45 @@ namespace ts { * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ - export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions: CompilerOptions = {}, configFileName?: string): ParsedCommandLine { + export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions: CompilerOptions = {}, configFileName?: string, resolutionStack: Path[] = []): ParsedCommandLine { const errors: Diagnostic[] = []; - const compilerOptions: CompilerOptions = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); - const options = extend(existingOptions, compilerOptions); + const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames); + const resolvedPath = toPath(configFileName || "", basePath, getCanonicalFileName); + if (resolutionStack.indexOf(resolvedPath) >= 0) { + return { + options: {}, + fileNames: [], + typingOptions: {}, + raw: json, + errors: [createCompilerDiagnostic(Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, [...resolutionStack, resolvedPath].join(" -> "))], + wildcardDirectories: {} + }; + } + + let options: CompilerOptions = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); const typingOptions: TypingOptions = convertTypingOptionsFromJsonWorker(json["typingOptions"], basePath, errors, configFileName); + if (json["extends"]) { + let [include, exclude, files, baseOptions]: [string[], string[], string[], CompilerOptions] = [undefined, undefined, undefined, {}]; + if (typeof json["extends"] === "string") { + [include, exclude, files, baseOptions] = (tryExtendsName(json["extends"]) || [include, exclude, files, baseOptions]); + } + else { + errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + } + if (include && !json["include"]) { + json["include"] = include; + } + if (exclude && !json["exclude"]) { + json["exclude"] = exclude; + } + if (files && !json["files"]) { + json["files"] = files; + } + options = assign({}, baseOptions, options); + } + + options = extend(existingOptions, options); options.configFilePath = configFileName; const { fileNames, wildcardDirectories } = getFileNames(errors); @@ -823,6 +863,39 @@ namespace ts { compileOnSave }; + function tryExtendsName(extendedConfig: string): [string[], string[], string[], CompilerOptions] { + // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) + if (!(isRootedDiskPath(extendedConfig) || startsWith(normalizeSlashes(extendedConfig), "./") || startsWith(normalizeSlashes(extendedConfig), "../"))) { + errors.push(createCompilerDiagnostic(Diagnostics.The_path_in_an_extends_options_must_be_relative_or_rooted)); + return; + } + let extendedConfigPath = toPath(extendedConfig, basePath, getCanonicalFileName); + if (!host.fileExists(extendedConfigPath) && !endsWith(extendedConfigPath, ".json")) { + extendedConfigPath = `${extendedConfigPath}.json` as Path; + if (!host.fileExists(extendedConfigPath)) { + errors.push(createCompilerDiagnostic(Diagnostics.File_0_does_not_exist, extendedConfig)); + return; + } + } + const extendedResult = readConfigFile(extendedConfigPath, path => host.readFile(path)); + if (extendedResult.error) { + errors.push(extendedResult.error); + return; + } + const extendedDirname = getDirectoryPath(extendedConfigPath); + const relativeDifference = convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + const updatePath: (path: string) => string = path => isRootedDiskPath(path) ? path : combinePaths(relativeDifference, path); + // Merge configs (copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios) + const result = parseJsonConfigFileContent(extendedResult.config, host, extendedDirname, /*existingOptions*/undefined, getBaseFileName(extendedConfigPath), resolutionStack.concat([resolvedPath])); + errors.push(...result.errors); + const [include, exclude, files] = map(["include", "exclude", "files"], key => { + if (!json[key] && extendedResult.config[key]) { + return map(extendedResult.config[key], updatePath); + } + }); + return [include, exclude, files, result.options]; + } + function getFileNames(errors: Diagnostic[]): ExpandResult { let fileNames: string[]; if (hasProperty(json, "files")) { @@ -857,14 +930,13 @@ namespace ts { errors.push(createCompilerDiagnostic(Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } else { - // By default, exclude common package folders + // By default, exclude common package folders and the outDir excludeSpecs = ["node_modules", "bower_components", "jspm_packages"]; - } - // Always exclude the output directory unless explicitly included - const outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; - if (outDir) { - excludeSpecs.push(outDir); + const outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; + if (outDir) { + excludeSpecs.push(outDir); + } } if (fileNames === undefined && includeSpecs === undefined) { diff --git a/src/compiler/comments.ts b/src/compiler/comments.ts new file mode 100644 index 00000000000..1bca13a4bdb --- /dev/null +++ b/src/compiler/comments.ts @@ -0,0 +1,352 @@ +/// + +/* @internal */ +namespace ts { + export interface CommentWriter { + reset(): void; + setSourceFile(sourceFile: SourceFile): void; + emitNodeWithComments(node: Node, emitCallback: (node: Node) => void): void; + emitBodyWithDetachedComments(node: Node, detachedRange: TextRange, emitCallback: (node: Node) => void): void; + emitTrailingCommentsOfPosition(pos: number): void; + } + + export function createCommentWriter(host: EmitHost, writer: EmitTextWriter, sourceMap: SourceMapWriter): CommentWriter { + const compilerOptions = host.getCompilerOptions(); + const extendedDiagnostics = compilerOptions.extendedDiagnostics; + const newLine = host.getNewLine(); + const { emitPos } = sourceMap; + + let containerPos = -1; + let containerEnd = -1; + let declarationListContainerEnd = -1; + let currentSourceFile: SourceFile; + let currentText: string; + let currentLineMap: number[]; + let detachedCommentsInfo: { nodePos: number, detachedCommentEndPos: number}[]; + let hasWrittenComment = false; + let disabled: boolean = compilerOptions.removeComments; + + return { + reset, + setSourceFile, + emitNodeWithComments, + emitBodyWithDetachedComments, + emitTrailingCommentsOfPosition, + }; + + function emitNodeWithComments(node: Node, emitCallback: (node: Node) => void) { + if (disabled) { + emitCallback(node); + return; + } + + if (node) { + const { pos, end } = node.commentRange || node; + const emitFlags = node.emitFlags; + if ((pos < 0 && end < 0) || (pos === end)) { + // Both pos and end are synthesized, so just emit the node without comments. + if (emitFlags & NodeEmitFlags.NoNestedComments) { + disableCommentsAndEmit(node, emitCallback); + } + else { + emitCallback(node); + } + } + else { + if (extendedDiagnostics) { + performance.mark("preEmitNodeWithComment"); + } + + const isEmittedNode = node.kind !== SyntaxKind.NotEmittedStatement; + const skipLeadingComments = pos < 0 || (emitFlags & NodeEmitFlags.NoLeadingComments) !== 0; + const skipTrailingComments = end < 0 || (emitFlags & NodeEmitFlags.NoTrailingComments) !== 0; + + // Emit leading comments if the position is not synthesized and the node + // has not opted out from emitting leading comments. + if (!skipLeadingComments) { + emitLeadingComments(pos, isEmittedNode); + } + + // Save current container state on the stack. + const savedContainerPos = containerPos; + const savedContainerEnd = containerEnd; + const savedDeclarationListContainerEnd = declarationListContainerEnd; + + if (!skipLeadingComments) { + containerPos = pos; + } + + if (!skipTrailingComments) { + containerEnd = end; + + // To avoid invalid comment emit in a down-level binding pattern, we + // keep track of the last declaration list container's end + if (node.kind === SyntaxKind.VariableDeclarationList) { + declarationListContainerEnd = end; + } + } + + if (extendedDiagnostics) { + performance.measure("commentTime", "preEmitNodeWithComment"); + } + + if (emitFlags & NodeEmitFlags.NoNestedComments) { + disableCommentsAndEmit(node, emitCallback); + } + else { + emitCallback(node); + } + + if (extendedDiagnostics) { + performance.mark("beginEmitNodeWithComment"); + } + + // Restore previous container state. + containerPos = savedContainerPos; + containerEnd = savedContainerEnd; + declarationListContainerEnd = savedDeclarationListContainerEnd; + + // Emit trailing comments if the position is not synthesized and the node + // has not opted out from emitting leading comments and is an emitted node. + if (!skipTrailingComments && isEmittedNode) { + emitTrailingComments(end); + } + + if (extendedDiagnostics) { + performance.measure("commentTime", "beginEmitNodeWithComment"); + } + } + } + } + + function emitBodyWithDetachedComments(node: Node, detachedRange: TextRange, emitCallback: (node: Node) => void) { + if (extendedDiagnostics) { + performance.mark("preEmitBodyWithDetachedComments"); + } + + const { pos, end } = detachedRange; + const emitFlags = node.emitFlags; + const skipLeadingComments = pos < 0 || (emitFlags & NodeEmitFlags.NoLeadingComments) !== 0; + const skipTrailingComments = disabled || end < 0 || (emitFlags & NodeEmitFlags.NoTrailingComments) !== 0; + + if (!skipLeadingComments) { + emitDetachedCommentsAndUpdateCommentsInfo(detachedRange); + } + + if (extendedDiagnostics) { + performance.measure("commentTime", "preEmitBodyWithDetachedComments"); + } + + if (emitFlags & NodeEmitFlags.NoNestedComments) { + disableCommentsAndEmit(node, emitCallback); + } + else { + emitCallback(node); + } + + if (extendedDiagnostics) { + performance.mark("beginEmitBodyWithDetachedCommetns"); + } + + if (!skipTrailingComments) { + emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true); + } + + if (extendedDiagnostics) { + performance.measure("commentTime", "beginEmitBodyWithDetachedCommetns"); + } + } + + function emitLeadingComments(pos: number, isEmittedNode: boolean) { + hasWrittenComment = false; + + if (isEmittedNode) { + forEachLeadingCommentToEmit(pos, emitLeadingComment); + } + else if (pos === 0) { + // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node, + // unless it is a triple slash comment at the top of the file. + // For Example: + // /// + // declare var x; + // /// + // interface F {} + // The first /// will NOT be removed while the second one will be removed even though both node will not be emitted + forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment); + } + } + + function emitTripleSlashLeadingComment(commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean, rangePos: number) { + if (isTripleSlashComment(commentPos, commentEnd)) { + emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); + } + } + + function emitLeadingComment(commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean, rangePos: number) { + if (!hasWrittenComment) { + emitNewLineBeforeLeadingCommentOfPosition(currentLineMap, writer, rangePos, commentPos); + hasWrittenComment = true; + } + + // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space + emitPos(commentPos); + writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + + if (hasTrailingNewLine) { + writer.writeLine(); + } + else { + writer.write(" "); + } + } + + function emitTrailingComments(pos: number) { + forEachTrailingCommentToEmit(pos, emitTrailingComment); + } + + function emitTrailingComment(commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean) { + // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/ + if (!writer.isAtStartOfLine()) { + writer.write(" "); + } + + emitPos(commentPos); + writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + + if (hasTrailingNewLine) { + writer.writeLine(); + } + } + + function emitTrailingCommentsOfPosition(pos: number) { + if (disabled) { + return; + } + + if (extendedDiagnostics) { + performance.mark("beforeEmitTrailingCommentsOfPosition"); + } + + forEachTrailingCommentToEmit(pos, emitTrailingCommentOfPosition); + + if (extendedDiagnostics) { + performance.measure("commentTime", "beforeEmitTrailingCommentsOfPosition"); + } + } + + function emitTrailingCommentOfPosition(commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean) { + // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space + + emitPos(commentPos); + writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + + if (hasTrailingNewLine) { + writer.writeLine(); + } + else { + writer.write(" "); + } + } + + function forEachLeadingCommentToEmit(pos: number, cb: (commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean, rangePos: number) => void) { + // Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments + if (containerPos === -1 || pos !== containerPos) { + if (hasDetachedComments(pos)) { + forEachLeadingCommentWithoutDetachedComments(cb); + } + else { + forEachLeadingCommentRange(currentText, pos, cb, /*state*/ pos); + } + } + } + + function forEachTrailingCommentToEmit(end: number, cb: (commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean) => void) { + // Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments + if (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd)) { + forEachTrailingCommentRange(currentText, end, cb); + } + } + + function reset() { + currentSourceFile = undefined; + currentText = undefined; + currentLineMap = undefined; + detachedCommentsInfo = undefined; + } + + function setSourceFile(sourceFile: SourceFile) { + currentSourceFile = sourceFile; + currentText = currentSourceFile.text; + currentLineMap = getLineStarts(currentSourceFile); + detachedCommentsInfo = undefined; + } + + function disableCommentsAndEmit(node: Node, emitCallback: (node: Node) => void): void { + if (disabled) { + emitCallback(node); + } + else { + disabled = true; + emitCallback(node); + disabled = false; + } + } + + function hasDetachedComments(pos: number) { + return detachedCommentsInfo !== undefined && lastOrUndefined(detachedCommentsInfo).nodePos === pos; + } + + function forEachLeadingCommentWithoutDetachedComments(cb: (commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean, rangePos: number) => void) { + // get the leading comments from detachedPos + const pos = lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos; + if (detachedCommentsInfo.length - 1) { + detachedCommentsInfo.pop(); + } + else { + detachedCommentsInfo = undefined; + } + + forEachLeadingCommentRange(currentText, pos, cb, /*state*/ pos); + } + + function emitDetachedCommentsAndUpdateCommentsInfo(range: TextRange) { + const currentDetachedCommentInfo = emitDetachedComments(currentText, currentLineMap, writer, writeComment, range, newLine, disabled); + if (currentDetachedCommentInfo) { + if (detachedCommentsInfo) { + detachedCommentsInfo.push(currentDetachedCommentInfo); + } + else { + detachedCommentsInfo = [currentDetachedCommentInfo]; + } + } + } + + function writeComment(text: string, lineMap: number[], writer: EmitTextWriter, commentPos: number, commentEnd: number, newLine: string) { + emitPos(commentPos); + writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + } + + /** + * Determine if the given comment is a triple-slash + * + * @return true if the comment is a triple-slash comment else false + **/ + function isTripleSlashComment(commentPos: number, commentEnd: number) { + // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text + // so that we don't end up computing comment string and doing match for all // comments + if (currentText.charCodeAt(commentPos + 1) === CharacterCodes.slash && + commentPos + 2 < commentEnd && + currentText.charCodeAt(commentPos + 2) === CharacterCodes.slash) { + const textSubStr = currentText.substring(commentPos, commentEnd); + return textSubStr.match(fullTripleSlashReferencePathRegEx) || + textSubStr.match(fullTripleSlashAMDReferencePathRegEx) ? + true : false; + } + return false; + } + } +} \ No newline at end of file diff --git a/src/compiler/core.ts b/src/compiler/core.ts index ea83e91867a..3967a867014 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -121,6 +121,23 @@ namespace ts { return undefined; } + /** + * Iterates through `array` by index and performs the callback on each element of array until the callback + * returns a falsey value, then returns false. + * If no such value is found, the callback is applied to each element of array and `true` is returned. + */ + export function every(array: T[], callback: (element: T, index: number) => boolean): boolean { + if (array) { + for (let i = 0, len = array.length; i < len; i++) { + if (!callback(array[i], i)) { + return false; + } + } + } + + return true; + } + /** Works like Array.prototype.find, returning `undefined` if no element satisfying the predicate is found. */ export function find(array: T[], predicate: (element: T, index: number) => boolean): T | undefined { for (let i = 0, len = array.length; i < len; i++) { @@ -177,11 +194,12 @@ namespace ts { return -1; } - export function countWhere(array: T[], predicate: (x: T) => boolean): number { + export function countWhere(array: T[], predicate: (x: T, i: number) => boolean): number { let count = 0; if (array) { - for (const v of array) { - if (predicate(v)) { + for (let i = 0; i < array.length; i++) { + const v = array[i]; + if (predicate(v, i)) { count++; } } @@ -193,6 +211,8 @@ namespace ts { * Filters an array by a predicate function. Returns the same array instance if the predicate is * true for all elements, otherwise returns a new array instance containing the filtered subset. */ + export function filter(array: T[], f: (x: T) => x is U): U[]; + export function filter(array: T[], f: (x: T) => boolean): T[] export function filter(array: T[], f: (x: T) => boolean): T[] { if (array) { const len = array.length; @@ -240,12 +260,140 @@ namespace ts { array.length = outIndex; } - export function map(array: T[], f: (x: T) => U): U[] { + export function map(array: T[], f: (x: T, i: number) => U): U[] { let result: U[]; + if (array) { + result = []; + for (let i = 0; i < array.length; i++) { + const v = array[i]; + result.push(f(v, i)); + } + } + return result; + } + + /** + * Flattens an array containing a mix of array or non-array elements. + * + * @param array The array to flatten. + */ + export function flatten(array: (T | T[])[]): T[] { + let result: T[]; if (array) { result = []; for (const v of array) { - result.push(f(v)); + if (v) { + if (isArray(v)) { + addRange(result, v); + } + else { + result.push(v); + } + } + } + } + + return result; + } + + /** + * Maps an array. If the mapped value is an array, it is spread into the result. + * + * @param array The array to map. + * @param mapfn The callback used to map the result into one or more values. + */ + export function flatMap(array: T[], mapfn: (x: T, i: number) => U | U[]): U[] { + let result: U[]; + if (array) { + result = []; + for (let i = 0; i < array.length; i++) { + const v = mapfn(array[i], i); + if (v) { + if (isArray(v)) { + addRange(result, v); + } + else { + result.push(v); + } + } + } + } + return result; + } + + /** + * Computes the first matching span of elements and returns a tuple of the first span + * and the remaining elements. + */ + export function span(array: T[], f: (x: T, i: number) => boolean): [T[], T[]] { + if (array) { + for (let i = 0; i < array.length; i++) { + if (!f(array[i], i)) { + return [array.slice(0, i), array.slice(i)]; + } + } + return [array.slice(0), []]; + } + + return undefined; + } + + /** + * Maps contiguous spans of values with the same key. + * + * @param array The array to map. + * @param keyfn A callback used to select the key for an element. + * @param mapfn A callback used to map a contiguous chunk of values to a single value. + */ + export function spanMap(array: T[], keyfn: (x: T, i: number) => K, mapfn: (chunk: T[], key: K, start: number, end: number) => U): U[] { + let result: U[]; + if (array) { + result = []; + const len = array.length; + let previousKey: K; + let key: K; + let start = 0; + let pos = 0; + while (start < len) { + while (pos < len) { + const value = array[pos]; + key = keyfn(value, pos); + if (pos === 0) { + previousKey = key; + } + else if (key !== previousKey) { + break; + } + + pos++; + } + + if (start < pos) { + const v = mapfn(array.slice(start, pos), previousKey, start, pos); + if (v) { + result.push(v); + } + + start = pos; + } + + previousKey = key; + pos++; + } + } + + return result; + } + + export function mapObject(object: MapLike, f: (key: string, x: T) => [string, U]): MapLike { + let result: MapLike; + if (object) { + result = {}; + for (const v of getOwnKeys(object)) { + const [key, value]: [string, U] = f(v, object[v]) || [undefined, undefined]; + if (key !== undefined) { + result[key] = value; + } } } return result; @@ -254,8 +402,7 @@ namespace ts { export function concatenate(array1: T[], array2: T[]): T[] { if (!array2 || !array2.length) return array1; if (!array1 || !array1.length) return array2; - - return array1.concat(array2); + return [...array1, ...array2]; } // TODO: fixme (N^2) - add optional comparer so collection can be sorted before deduplication. @@ -275,6 +422,27 @@ namespace ts { return result; } + /** + * Compacts an array, removing any falsey elements. + */ + export function compact(array: T[]): T[] { + let result: T[]; + if (array) { + for (let i = 0; i < array.length; i++) { + const v = array[i]; + if (result || !v) { + if (!result) { + result = array.slice(0, i); + } + if (v) { + result.push(v); + } + } + } + } + return result || array; + } + export function sum(array: any[], prop: string): number { let result = 0; for (const v of array) { @@ -286,7 +454,9 @@ namespace ts { export function addRange(to: T[], from: T[]): void { if (to && from) { for (const v of from) { - to.push(v); + if (v !== undefined) { + to.push(v); + } } } } @@ -301,15 +471,31 @@ namespace ts { return true; } + export function firstOrUndefined(array: T[]): T { + return array && array.length > 0 + ? array[0] + : undefined; + } + + export function singleOrUndefined(array: T[]): T { + return array && array.length === 1 + ? array[0] + : undefined; + } + + export function singleOrMany(array: T[]): T | T[] { + return array && array.length === 1 + ? array[0] + : array; + } + /** * Returns the last element of an array if non-empty, undefined otherwise. */ export function lastOrUndefined(array: T[]): T { - if (array.length === 0) { - return undefined; - } - - return array[array.length - 1]; + return array && array.length > 0 + ? array[array.length - 1] + : undefined; } /** @@ -348,14 +534,15 @@ namespace ts { return ~low; } - export function reduceLeft(array: T[], f: (a: T, x: T) => T): T; - export function reduceLeft(array: T[], f: (a: U, x: T) => U, initial: U): U; - export function reduceLeft(array: T[], f: (a: U, x: T) => U, initial?: U): U { - if (array) { - const count = array.length; - if (count > 0) { - let pos = 0; - let result: T | U; + export function reduceLeft(array: T[], f: (memo: U, value: T, i: number) => U, initial: U, start?: number, count?: number): U; + export function reduceLeft(array: T[], f: (memo: T, value: T, i: number) => T): T; + export function reduceLeft(array: T[], f: (memo: T, value: T, i: number) => T, initial?: T, start?: number, count?: number): T { + if (array && array.length > 0) { + const size = array.length; + if (size > 0) { + let pos = start === undefined || start < 0 ? 0 : start; + const end = count === undefined || pos + count > size - 1 ? size - 1 : pos + count; + let result: T; if (arguments.length <= 2) { result = array[pos]; pos++; @@ -363,23 +550,25 @@ namespace ts { else { result = initial; } - while (pos < count) { - result = f(result, array[pos]); + while (pos <= end) { + result = f(result, array[pos], pos); pos++; } - return result; + return result; } } return initial; } - export function reduceRight(array: T[], f: (a: T, x: T) => T): T; - export function reduceRight(array: T[], f: (a: U, x: T) => U, initial: U): U; - export function reduceRight(array: T[], f: (a: U, x: T) => U, initial?: U): U { + export function reduceRight(array: T[], f: (memo: U, value: T, i: number) => U, initial: U, start?: number, count?: number): U; + export function reduceRight(array: T[], f: (memo: T, value: T, i: number) => T): T; + export function reduceRight(array: T[], f: (memo: T, value: T, i: number) => T, initial?: T, start?: number, count?: number): T { if (array) { - let pos = array.length - 1; - if (pos >= 0) { - let result: T | U; + const size = array.length; + if (size > 0) { + let pos = start === undefined || start > size - 1 ? size - 1 : start; + const end = count === undefined || pos - count < 0 ? 0 : pos - count; + let result: T; if (arguments.length <= 2) { result = array[pos]; pos--; @@ -387,11 +576,11 @@ namespace ts { else { result = initial; } - while (pos >= 0) { - result = f(result, array[pos]); + while (pos >= end) { + result = f(result, array[pos], pos); pos--; } - return result; + return result; } } return initial; @@ -480,6 +669,18 @@ namespace ts { } } + export function assign, T2, T3>(t: T1, arg1: T2, arg2: T3): T1 & T2 & T3; + export function assign, T2>(t: T1, arg1: T2): T1 & T2; + export function assign>(t: T1, ...args: any[]): any; + export function assign>(t: T1, ...args: any[]) { + for (const arg of args) { + for (const p of getOwnKeys(arg)) { + t[p] = arg[p]; + } + } + return t; + } + /** * Reduce the properties of a map. * @@ -555,6 +756,15 @@ namespace ts { return result; } + export function isEmpty(map: Map) { + for (const id in map) { + if (hasProperty(map, id)) { + return false; + } + } + return true; + } + export function cloneMap(map: Map) { const clone = createMap(); copyProperties(map, clone); @@ -582,6 +792,36 @@ namespace ts { return result; } + /** + * Adds the value to an array of values associated with the key, and returns the array. + * Creates the array if it does not already exist. + */ + export function multiMapAdd(map: Map, key: string, value: V): V[] { + const values = map[key]; + if (values) { + values.push(value); + return values; + } + else { + return map[key] = [value]; + } + } + + /** + * Removes a value from an array of values associated with the key. + * Does not preserve the order of those values. + * Does nothing if `key` is not in `map`, or `value` is not in `map[key]`. + */ + export function multiMapRemove(map: Map, key: string, value: V): void { + const values = map[key]; + if (values) { + unorderedRemoveItem(values, value); + if (!values.length) { + delete map[key]; + } + } + } + /** * Tests whether a value is an array. */ @@ -820,7 +1060,8 @@ namespace ts { return 0; } - export let directorySeparator = "/"; + export const directorySeparator = "/"; + const directorySeparatorCharCode = CharacterCodes.slash; function getNormalizedParts(normalizedSlashedPath: string, rootLength: number) { const parts = normalizedSlashedPath.substr(rootLength).split(directorySeparator); const normalized: string[] = []; @@ -845,8 +1086,20 @@ namespace ts { export function normalizePath(path: string): string { path = normalizeSlashes(path); const rootLength = getRootLength(path); + const root = path.substr(0, rootLength); const normalized = getNormalizedParts(path, rootLength); - return path.substr(0, rootLength) + normalized.join(directorySeparator); + if (normalized.length) { + const joinedParts = root + normalized.join(directorySeparator); + return pathEndsWithDirectorySeparator(path) ? joinedParts + directorySeparator : joinedParts; + } + else { + return root; + } + } + + /** A path ending with '/' refers to a directory only, never a file. */ + export function pathEndsWithDirectorySeparator(path: string): boolean { + return path.charCodeAt(path.length - 1) === directorySeparatorCharCode; } export function getDirectoryPath(path: Path): Path; @@ -859,10 +1112,49 @@ namespace ts { return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; } + export function isExternalModuleNameRelative(moduleName: string): boolean { + // TypeScript 1.0 spec (April 2014): 11.2.1 + // An external module name is "relative" if the first term is "." or "..". + return /^\.\.?($|[\\/])/.test(moduleName); + } + + export function getEmitScriptTarget(compilerOptions: CompilerOptions) { + return compilerOptions.target || ScriptTarget.ES3; + } + + export function getEmitModuleKind(compilerOptions: CompilerOptions) { + return typeof compilerOptions.module === "number" ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) === ScriptTarget.ES6 ? ModuleKind.ES6 : ModuleKind.CommonJS; + } + + /* @internal */ + export function hasZeroOrOneAsteriskCharacter(str: string): boolean { + let seenAsterisk = false; + for (let i = 0; i < str.length; i++) { + if (str.charCodeAt(i) === CharacterCodes.asterisk) { + if (!seenAsterisk) { + seenAsterisk = true; + } + else { + // have already seen asterisk + return false; + } + } + } + return true; + } + export function isRootedDiskPath(path: string) { return getRootLength(path) !== 0; } + export function convertToRelativePath(absoluteOrRelativePath: string, basePath: string, getCanonicalFileName: (path: string) => string): string { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /* isAbsolutePathAnUrl */ false); + } + function normalizedPathComponents(path: string, rootLength: number) { const normalizedParts = getNormalizedParts(path, rootLength); return [path.substr(0, rootLength)].concat(normalizedParts); @@ -1477,11 +1769,16 @@ namespace ts { } function Node(this: Node, kind: SyntaxKind, pos: number, end: number) { + this.id = 0; this.kind = kind; this.pos = pos; this.end = end; this.flags = NodeFlags.None; + this.modifierFlagsCache = ModifierFlags.None; + this.transformFlags = TransformFlags.None; this.parent = undefined; + this.original = undefined; + this.transformId = 0; } export let objectAllocator: ObjectAllocator = { @@ -1502,10 +1799,13 @@ namespace ts { } export namespace Debug { - const currentAssertionLevel = AssertionLevel.None; + declare var process: any; + declare var require: any; + + let currentAssertionLevel: AssertionLevel; export function shouldAssert(level: AssertionLevel): boolean { - return currentAssertionLevel >= level; + return getCurrentAssertionLevel() >= level; } export function assert(expression: boolean, message?: string, verboseDebugInfo?: () => string): void { @@ -1522,97 +1822,76 @@ namespace ts { export function fail(message?: string): void { Debug.assert(/*expression*/ false, message); } + + function getCurrentAssertionLevel() { + if (currentAssertionLevel !== undefined) { + return currentAssertionLevel; + } + + if (sys === undefined) { + return AssertionLevel.None; + } + + const developmentMode = /^development$/i.test(getEnvironmentVariable("NODE_ENV")); + currentAssertionLevel = developmentMode + ? AssertionLevel.Normal + : AssertionLevel.None; + + return currentAssertionLevel; + } } - export function copyListRemovingItem(item: T, list: T[]) { - const copiedList: T[] = []; - for (const e of list) { - if (e !== item) { - copiedList.push(e); + export function getEnvironmentVariable(name: string, host?: CompilerHost) { + if (host && host.getEnvironmentVariable) { + return host.getEnvironmentVariable(name); + } + + if (sys && sys.getEnvironmentVariable) { + return sys.getEnvironmentVariable(name); + } + + return ""; + } + + /** Remove an item from an array, moving everything to its right one space left. */ + export function orderedRemoveItemAt(array: T[], index: number): void { + // This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`. + for (let i = index; i < array.length - 1; i++) { + array[i] = array[i + 1]; + } + array.pop(); + } + + export function unorderedRemoveItemAt(array: T[], index: number): void { + // Fill in the "hole" left at `index`. + array[index] = array[array.length - 1]; + array.pop(); + } + + /** Remove the *first* occurrence of `item` from the array. */ + export function unorderedRemoveItem(array: T[], item: T): void { + unorderedRemoveFirstItemWhere(array, element => element === item); + } + + /** Remove the *first* element satisfying `predicate`. */ + function unorderedRemoveFirstItemWhere(array: T[], predicate: (element: T) => boolean): void { + for (let i = 0; i < array.length; i++) { + if (predicate(array[i])) { + unorderedRemoveItemAt(array, i); + break; } } - return copiedList; } - export function createGetCanonicalFileName(useCaseSensitivefileNames: boolean): (fileName: string) => string { - return useCaseSensitivefileNames + export function createGetCanonicalFileName(useCaseSensitiveFileNames: boolean): (fileName: string) => string { + return useCaseSensitiveFileNames ? ((fileName) => fileName) : ((fileName) => fileName.toLowerCase()); } - - /* @internal */ - export function trace(host: ModuleResolutionHost, message: DiagnosticMessage, ...args: any[]): void; - export function trace(host: ModuleResolutionHost, message: DiagnosticMessage): void { - host.trace(formatMessage.apply(undefined, arguments)); - } - - /* @internal */ - export function isTraceEnabled(compilerOptions: CompilerOptions, host: ModuleResolutionHost): boolean { - return compilerOptions.traceResolution && host.trace !== undefined; - } - - /* @internal */ - export function hasZeroOrOneAsteriskCharacter(str: string): boolean { - let seenAsterisk = false; - for (let i = 0; i < str.length; i++) { - if (str.charCodeAt(i) === CharacterCodes.asterisk) { - if (!seenAsterisk) { - seenAsterisk = true; - } - else { - // have already seen asterisk - return false; - } - } - } - return true; - } - - /* @internal */ - export function createResolvedModule(resolvedFileName: string, isExternalLibraryImport: boolean, failedLookupLocations: string[]): ResolvedModuleWithFailedLookupLocations { - return { resolvedModule: resolvedFileName ? { resolvedFileName, isExternalLibraryImport } : undefined, failedLookupLocations }; - } - - /* @internal */ - export function isExternalModuleNameRelative(moduleName: string): boolean { - // TypeScript 1.0 spec (April 2014): 11.2.1 - // An external module name is "relative" if the first term is "." or "..". - return /^\.\.?($|[\\/])/.test(moduleName); - } - - /* @internal */ - export interface ModuleResolutionState { - host: ModuleResolutionHost; - compilerOptions: CompilerOptions; - traceEnabled: boolean; - // skip .tsx files if jsx is not enabled - skipTsx: boolean; - } - - - - /* @internal */ - export function readJson(path: string, host: ModuleResolutionHost): { typings?: string, types?: string, main?: string } { - try { - const jsonText = host.readFile(path); - return jsonText ? JSON.parse(jsonText) : {}; - } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - return {}; - } - } - - /* @internal */ - export function getEmitModuleKind(compilerOptions: CompilerOptions) { - return typeof compilerOptions.module === "number" ? - compilerOptions.module : - getEmitScriptTarget(compilerOptions) === ScriptTarget.ES6 ? ModuleKind.ES6 : ModuleKind.CommonJS; - } - - /* @internal */ - export function getEmitScriptTarget(compilerOptions: CompilerOptions) { - return compilerOptions.target || ScriptTarget.ES3; + export function positionIsSynthesized(pos: number): boolean { + // This is a fast way of testing the following conditions: + // pos === undefined || pos === null || isNaN(pos) || pos < 0; + return !(pos >= 0); } } diff --git a/src/compiler/declarationEmitter.ts b/src/compiler/declarationEmitter.ts index 5db6cd72bfb..a01a7e0414f 100644 --- a/src/compiler/declarationEmitter.ts +++ b/src/compiler/declarationEmitter.ts @@ -306,7 +306,7 @@ namespace ts { } function trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags) { - handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning)); + handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true)); recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); } @@ -374,7 +374,7 @@ namespace ts { const jsDocComments = getJsDocCommentsFromText(declaration, currentText); emitNewLineBeforeLeadingComments(currentLineMap, writer, declaration, jsDocComments); // jsDoc comments are emitted at /*leading comment1 */space/*leading comment*/space - emitComments(currentText, currentLineMap, writer, jsDocComments, /*trailingSeparator*/ true, newLine, writeCommentRange); + emitComments(currentText, currentLineMap, writer, jsDocComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeCommentRange); } } @@ -655,12 +655,13 @@ namespace ts { function emitModuleElementDeclarationFlags(node: Node) { // If the node is parented in the current source file we need to emit export declare or just export if (node.parent.kind === SyntaxKind.SourceFile) { + const modifiers = getModifierFlags(node); // If the node is exported - if (node.flags & NodeFlags.Export) { + if (modifiers & ModifierFlags.Export) { write("export "); } - if (node.flags & NodeFlags.Default) { + if (modifiers & ModifierFlags.Default) { write("default "); } else if (node.kind !== SyntaxKind.InterfaceDeclaration && !noDeclare) { @@ -669,21 +670,21 @@ namespace ts { } } - function emitClassMemberDeclarationFlags(flags: NodeFlags) { - if (flags & NodeFlags.Private) { + function emitClassMemberDeclarationFlags(flags: ModifierFlags) { + if (flags & ModifierFlags.Private) { write("private "); } - else if (flags & NodeFlags.Protected) { + else if (flags & ModifierFlags.Protected) { write("protected "); } - if (flags & NodeFlags.Static) { + if (flags & ModifierFlags.Static) { write("static "); } - if (flags & NodeFlags.Readonly) { + if (flags & ModifierFlags.Readonly) { write("readonly "); } - if (flags & NodeFlags.Abstract) { + if (flags & ModifierFlags.Abstract) { write("abstract "); } } @@ -692,7 +693,7 @@ namespace ts { // note usage of writer. methods instead of aliases created, just to make sure we are using // correct writer especially to handle asynchronous alias writing emitJsDocComments(node); - if (node.flags & NodeFlags.Export) { + if (hasModifier(node, ModifierFlags.Export)) { write("export "); } write("import "); @@ -731,7 +732,7 @@ namespace ts { function writeImportDeclaration(node: ImportDeclaration) { emitJsDocComments(node); - if (node.flags & NodeFlags.Export) { + if (hasModifier(node, ModifierFlags.Export)) { write("export "); } write("import "); @@ -926,7 +927,7 @@ namespace ts { } function isPrivateMethodTypeParameter(node: TypeParameterDeclaration) { - return node.parent.kind === SyntaxKind.MethodDeclaration && (node.parent.flags & NodeFlags.Private); + return node.parent.kind === SyntaxKind.MethodDeclaration && hasModifier(node.parent, ModifierFlags.Private); } function emitTypeParameters(typeParameters: TypeParameterDeclaration[]) { @@ -976,7 +977,7 @@ namespace ts { case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: - if (node.parent.flags & NodeFlags.Static) { + if (hasModifier(node.parent, ModifierFlags.Static)) { diagnosticMessage = Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } else if (node.parent.parent.kind === SyntaxKind.ClassDeclaration) { @@ -1055,7 +1056,7 @@ namespace ts { function emitParameterProperties(constructorDeclaration: ConstructorDeclaration) { if (constructorDeclaration) { forEach(constructorDeclaration.parameters, param => { - if (param.flags & NodeFlags.ParameterPropertyModifier) { + if (hasModifier(param, ModifierFlags.ParameterPropertyModifier)) { emitPropertyDeclaration(param); } }); @@ -1064,7 +1065,7 @@ namespace ts { emitJsDocComments(node); emitModuleElementDeclarationFlags(node); - if (node.flags & NodeFlags.Abstract) { + if (hasModifier(node, ModifierFlags.Abstract)) { write("abstract "); } @@ -1114,7 +1115,7 @@ namespace ts { } emitJsDocComments(node); - emitClassMemberDeclarationFlags(node.flags); + emitClassMemberDeclarationFlags(getModifierFlags(node)); emitVariableDeclaration(node); write(";"); writeLine(); @@ -1141,7 +1142,7 @@ namespace ts { if ((node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature) && node.parent.kind === SyntaxKind.TypeLiteral) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } - else if (!(node.flags & NodeFlags.Private)) { + else if (!hasModifier(node, ModifierFlags.Private)) { writeTypeOfDeclaration(node, node.type, getVariableDeclarationTypeVisibilityError); } } @@ -1158,7 +1159,7 @@ namespace ts { // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit else if (node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature) { // TODO(jfreeman): Deal with computed properties in error reporting. - if (node.flags & NodeFlags.Static) { + if (hasModifier(node, ModifierFlags.Static)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -1269,9 +1270,9 @@ namespace ts { if (node === accessors.firstAccessor) { emitJsDocComments(accessors.getAccessor); emitJsDocComments(accessors.setAccessor); - emitClassMemberDeclarationFlags(node.flags | (accessors.setAccessor ? 0 : NodeFlags.Readonly)); + emitClassMemberDeclarationFlags(getModifierFlags(node) | (accessors.setAccessor ? 0 : ModifierFlags.Readonly)); writeTextOfNode(currentText, node.name); - if (!(node.flags & NodeFlags.Private)) { + if (!hasModifier(node, ModifierFlags.Private)) { accessorWithTypeAnnotation = node; let type = getTypeAnnotationFromAccessor(node); if (!type) { @@ -1302,7 +1303,7 @@ namespace ts { let diagnosticMessage: DiagnosticMessage; if (accessorWithTypeAnnotation.kind === SyntaxKind.SetAccessor) { // Setters have to have type named and cannot infer it so, the type should always be named - if (accessorWithTypeAnnotation.parent.flags & NodeFlags.Static) { + if (hasModifier(accessorWithTypeAnnotation.parent, ModifierFlags.Static)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1; @@ -1320,7 +1321,7 @@ namespace ts { }; } else { - if (accessorWithTypeAnnotation.flags & NodeFlags.Static) { + if (hasModifier(accessorWithTypeAnnotation, ModifierFlags.Static)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -1356,7 +1357,7 @@ namespace ts { emitModuleElementDeclarationFlags(node); } else if (node.kind === SyntaxKind.MethodDeclaration || node.kind === SyntaxKind.Constructor) { - emitClassMemberDeclarationFlags(node.flags); + emitClassMemberDeclarationFlags(getModifierFlags(node)); } if (node.kind === SyntaxKind.FunctionDeclaration) { write("function "); @@ -1387,7 +1388,7 @@ namespace ts { if (node.kind === SyntaxKind.IndexSignature) { // Index signature can have readonly modifier - emitClassMemberDeclarationFlags(node.flags); + emitClassMemberDeclarationFlags(getModifierFlags(node)); write("["); } else { @@ -1428,7 +1429,7 @@ namespace ts { emitType(node.type); } } - else if (node.kind !== SyntaxKind.Constructor && !(node.flags & NodeFlags.Private)) { + else if (node.kind !== SyntaxKind.Constructor && !hasModifier(node, ModifierFlags.Private)) { writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); } @@ -1468,7 +1469,7 @@ namespace ts { case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: - if (node.flags & NodeFlags.Static) { + if (hasModifier(node, ModifierFlags.Static)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -1534,7 +1535,7 @@ namespace ts { node.parent.parent.kind === SyntaxKind.TypeLiteral) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } - else if (!(node.parent.flags & NodeFlags.Private)) { + else if (!hasModifier(node.parent, ModifierFlags.Private)) { writeTypeOfDeclaration(node, node.type, getParameterDeclarationTypeVisibilityError); } @@ -1570,7 +1571,7 @@ namespace ts { case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: - if (node.parent.flags & NodeFlags.Static) { + if (hasModifier(node.parent, ModifierFlags.Static)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 167985e184f..1699780a3cb 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -827,10 +827,6 @@ "category": "Error", "code": 1308 }, - "Async functions are only available when targeting ECMAScript 2015 or higher.": { - "category": "Error", - "code": 1311 - }, "'=' can only be used in an object literal property inside a destructuring assignment.": { "category": "Error", "code": 1312 @@ -1047,7 +1043,7 @@ "category": "Error", "code": 2348 }, - "Cannot invoke an expression whose type lacks a call signature.": { + "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures.": { "category": "Error", "code": 2349 }, @@ -1067,10 +1063,6 @@ "category": "Error", "code": 2353 }, - "No best common type exists among return expressions.": { - "category": "Error", - "code": 2354 - }, "A function whose declared type is neither 'void' nor 'any' must return a value.": { "category": "Error", "code": 2355 @@ -1635,10 +1627,6 @@ "category": "Error", "code": 2503 }, - "No best common type exists among yield expressions.": { - "category": "Error", - "code": 2504 - }, "A generator cannot have a 'void' type annotation.": { "category": "Error", "code": 2505 @@ -1703,7 +1691,7 @@ "category": "Error", "code": 2521 }, - "The 'arguments' object cannot be referenced in an async arrow function. Consider using a standard async function expression.": { + "The 'arguments' object cannot be referenced in an async function or method in ES3 and ES5. Consider using a standard function or method.": { "category": "Error", "code": 2522 }, @@ -1959,6 +1947,23 @@ "category": "Error", "code": 2692 }, + "'{0}' only refers to a type, but is being used as a value here.": { + "category": "Error", + "code": 2693 + }, + "Namespace '{0}' has no exported member '{1}'.": { + "category": "Error", + "code": 2694 + }, + "Left side of comma operator is unused and has no side effects.": { + "category": "Error", + "code": 2695 + }, + "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?": { + "category": "Error", + "code": 2696 + }, + "Import declaration '{0}' is using private name '{1}'.": { "category": "Error", "code": 4000 @@ -2476,6 +2481,10 @@ "category": "Message", "code": 6038 }, + "STRATEGY": { + "category": "Message", + "code": 6039 + }, "Compilation complete. Watching for file changes.": { "category": "Message", "code": 6042 @@ -2840,9 +2849,13 @@ "category": "Error", "code": 6138 }, + "Import emit helpers from 'tslib'.": { + "category": "Message", + "code": 6139 + }, "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'.": { "category": "Error", - "code": 6139 + "code": 6140 }, "Variable '{0}' implicitly has an '{1}' type.": { "category": "Error", @@ -2875,7 +2888,7 @@ "Element implicitly has an 'any' type because index expression is not of type 'number'.": { "category": "Error", "code": 7015 - }, + }, "Index signature of object type implicitly has an 'any' type.": { "category": "Error", "code": 7017 @@ -3051,5 +3064,14 @@ "Unknown typing option '{0}'.": { "category": "Error", "code": 17010 + }, + + "Circularity detected while resolving configuration: {0}": { + "category": "Error", + "code": 18000 + }, + "The path in an 'extends' options must be relative or rooted.": { + "category": "Error", + "code": 18001 } } diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 3c200aca931..03de307f2f3 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -1,285 +1,11 @@ -/// -/// +/// +/// /// +/// +/// /* @internal */ namespace ts { - export function getResolvedExternalModuleName(host: EmitHost, file: SourceFile): string { - return file.moduleName || getExternalModuleNameFromPath(host, file.fileName); - } - - export function getExternalModuleNameFromDeclaration(host: EmitHost, resolver: EmitResolver, declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration): string { - const file = resolver.getExternalModuleFileFromDeclaration(declaration); - if (!file || isDeclarationFile(file)) { - return undefined; - } - return getResolvedExternalModuleName(host, file); - } - - type DependencyGroup = Array; - - const enum Jump { - Break = 1 << 1, - Continue = 1 << 2, - Return = 1 << 3 - } - - const entities = createMap({ - "quot": 0x0022, - "amp": 0x0026, - "apos": 0x0027, - "lt": 0x003C, - "gt": 0x003E, - "nbsp": 0x00A0, - "iexcl": 0x00A1, - "cent": 0x00A2, - "pound": 0x00A3, - "curren": 0x00A4, - "yen": 0x00A5, - "brvbar": 0x00A6, - "sect": 0x00A7, - "uml": 0x00A8, - "copy": 0x00A9, - "ordf": 0x00AA, - "laquo": 0x00AB, - "not": 0x00AC, - "shy": 0x00AD, - "reg": 0x00AE, - "macr": 0x00AF, - "deg": 0x00B0, - "plusmn": 0x00B1, - "sup2": 0x00B2, - "sup3": 0x00B3, - "acute": 0x00B4, - "micro": 0x00B5, - "para": 0x00B6, - "middot": 0x00B7, - "cedil": 0x00B8, - "sup1": 0x00B9, - "ordm": 0x00BA, - "raquo": 0x00BB, - "frac14": 0x00BC, - "frac12": 0x00BD, - "frac34": 0x00BE, - "iquest": 0x00BF, - "Agrave": 0x00C0, - "Aacute": 0x00C1, - "Acirc": 0x00C2, - "Atilde": 0x00C3, - "Auml": 0x00C4, - "Aring": 0x00C5, - "AElig": 0x00C6, - "Ccedil": 0x00C7, - "Egrave": 0x00C8, - "Eacute": 0x00C9, - "Ecirc": 0x00CA, - "Euml": 0x00CB, - "Igrave": 0x00CC, - "Iacute": 0x00CD, - "Icirc": 0x00CE, - "Iuml": 0x00CF, - "ETH": 0x00D0, - "Ntilde": 0x00D1, - "Ograve": 0x00D2, - "Oacute": 0x00D3, - "Ocirc": 0x00D4, - "Otilde": 0x00D5, - "Ouml": 0x00D6, - "times": 0x00D7, - "Oslash": 0x00D8, - "Ugrave": 0x00D9, - "Uacute": 0x00DA, - "Ucirc": 0x00DB, - "Uuml": 0x00DC, - "Yacute": 0x00DD, - "THORN": 0x00DE, - "szlig": 0x00DF, - "agrave": 0x00E0, - "aacute": 0x00E1, - "acirc": 0x00E2, - "atilde": 0x00E3, - "auml": 0x00E4, - "aring": 0x00E5, - "aelig": 0x00E6, - "ccedil": 0x00E7, - "egrave": 0x00E8, - "eacute": 0x00E9, - "ecirc": 0x00EA, - "euml": 0x00EB, - "igrave": 0x00EC, - "iacute": 0x00ED, - "icirc": 0x00EE, - "iuml": 0x00EF, - "eth": 0x00F0, - "ntilde": 0x00F1, - "ograve": 0x00F2, - "oacute": 0x00F3, - "ocirc": 0x00F4, - "otilde": 0x00F5, - "ouml": 0x00F6, - "divide": 0x00F7, - "oslash": 0x00F8, - "ugrave": 0x00F9, - "uacute": 0x00FA, - "ucirc": 0x00FB, - "uuml": 0x00FC, - "yacute": 0x00FD, - "thorn": 0x00FE, - "yuml": 0x00FF, - "OElig": 0x0152, - "oelig": 0x0153, - "Scaron": 0x0160, - "scaron": 0x0161, - "Yuml": 0x0178, - "fnof": 0x0192, - "circ": 0x02C6, - "tilde": 0x02DC, - "Alpha": 0x0391, - "Beta": 0x0392, - "Gamma": 0x0393, - "Delta": 0x0394, - "Epsilon": 0x0395, - "Zeta": 0x0396, - "Eta": 0x0397, - "Theta": 0x0398, - "Iota": 0x0399, - "Kappa": 0x039A, - "Lambda": 0x039B, - "Mu": 0x039C, - "Nu": 0x039D, - "Xi": 0x039E, - "Omicron": 0x039F, - "Pi": 0x03A0, - "Rho": 0x03A1, - "Sigma": 0x03A3, - "Tau": 0x03A4, - "Upsilon": 0x03A5, - "Phi": 0x03A6, - "Chi": 0x03A7, - "Psi": 0x03A8, - "Omega": 0x03A9, - "alpha": 0x03B1, - "beta": 0x03B2, - "gamma": 0x03B3, - "delta": 0x03B4, - "epsilon": 0x03B5, - "zeta": 0x03B6, - "eta": 0x03B7, - "theta": 0x03B8, - "iota": 0x03B9, - "kappa": 0x03BA, - "lambda": 0x03BB, - "mu": 0x03BC, - "nu": 0x03BD, - "xi": 0x03BE, - "omicron": 0x03BF, - "pi": 0x03C0, - "rho": 0x03C1, - "sigmaf": 0x03C2, - "sigma": 0x03C3, - "tau": 0x03C4, - "upsilon": 0x03C5, - "phi": 0x03C6, - "chi": 0x03C7, - "psi": 0x03C8, - "omega": 0x03C9, - "thetasym": 0x03D1, - "upsih": 0x03D2, - "piv": 0x03D6, - "ensp": 0x2002, - "emsp": 0x2003, - "thinsp": 0x2009, - "zwnj": 0x200C, - "zwj": 0x200D, - "lrm": 0x200E, - "rlm": 0x200F, - "ndash": 0x2013, - "mdash": 0x2014, - "lsquo": 0x2018, - "rsquo": 0x2019, - "sbquo": 0x201A, - "ldquo": 0x201C, - "rdquo": 0x201D, - "bdquo": 0x201E, - "dagger": 0x2020, - "Dagger": 0x2021, - "bull": 0x2022, - "hellip": 0x2026, - "permil": 0x2030, - "prime": 0x2032, - "Prime": 0x2033, - "lsaquo": 0x2039, - "rsaquo": 0x203A, - "oline": 0x203E, - "frasl": 0x2044, - "euro": 0x20AC, - "image": 0x2111, - "weierp": 0x2118, - "real": 0x211C, - "trade": 0x2122, - "alefsym": 0x2135, - "larr": 0x2190, - "uarr": 0x2191, - "rarr": 0x2192, - "darr": 0x2193, - "harr": 0x2194, - "crarr": 0x21B5, - "lArr": 0x21D0, - "uArr": 0x21D1, - "rArr": 0x21D2, - "dArr": 0x21D3, - "hArr": 0x21D4, - "forall": 0x2200, - "part": 0x2202, - "exist": 0x2203, - "empty": 0x2205, - "nabla": 0x2207, - "isin": 0x2208, - "notin": 0x2209, - "ni": 0x220B, - "prod": 0x220F, - "sum": 0x2211, - "minus": 0x2212, - "lowast": 0x2217, - "radic": 0x221A, - "prop": 0x221D, - "infin": 0x221E, - "ang": 0x2220, - "and": 0x2227, - "or": 0x2228, - "cap": 0x2229, - "cup": 0x222A, - "int": 0x222B, - "there4": 0x2234, - "sim": 0x223C, - "cong": 0x2245, - "asymp": 0x2248, - "ne": 0x2260, - "equiv": 0x2261, - "le": 0x2264, - "ge": 0x2265, - "sub": 0x2282, - "sup": 0x2283, - "nsub": 0x2284, - "sube": 0x2286, - "supe": 0x2287, - "oplus": 0x2295, - "otimes": 0x2297, - "perp": 0x22A5, - "sdot": 0x22C5, - "lceil": 0x2308, - "rceil": 0x2309, - "lfloor": 0x230A, - "rfloor": 0x230B, - "lang": 0x2329, - "rang": 0x232A, - "loz": 0x25CA, - "spades": 0x2660, - "clubs": 0x2663, - "hearts": 0x2665, - "diams": 0x2666 - }); - // Flags enum to track count of temp variables and a few dedicated names const enum TempFlags { Auto = 0x00000000, // No preferred name @@ -287,56 +13,11 @@ namespace ts { _i = 0x10000000, // Use/preference flag for '_i' } - const enum CopyDirection { - ToOriginal, - ToOutParameter - } - - /** - * If loop contains block scoped binding captured in some function then loop body is converted to a function. - * Lexical bindings declared in loop initializer will be passed into the loop body function as parameters, - * however if this binding is modified inside the body - this new value should be propagated back to the original binding. - * This is done by declaring new variable (out parameter holder) outside of the loop for every binding that is reassigned inside the body. - * On every iteration this variable is initialized with value of corresponding binding. - * At every point where control flow leaves the loop either explicitly (break/continue) or implicitly (at the end of loop body) - * we copy the value inside the loop to the out parameter holder. - * - * for (let x;;) { - * let a = 1; - * let b = () => a; - * x++ - * if (...) break; - * ... - * } - * - * will be converted to - * - * var out_x; - * var loop = function(x) { - * var a = 1; - * var b = function() { return a; } - * x++; - * if (...) return out_x = x, "break"; - * ... - * out_x = x; - * } - * for (var x;;) { - * out_x = x; - * var state = loop(x); - * x = out_x; - * if (state === "break") break; - * } - * - * NOTE: values to out parameters are not copies if loop is abrupted with 'return' - in this case this will end the entire enclosing function - * so nobody can observe this new value. - */ - interface LoopOutParameter { - originalName: Identifier; - outParamName: string; - } - // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature export function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFile: SourceFile, emitOnlyDtsFiles?: boolean): EmitResult { + const delimiters = createDelimiterMap(); + const brackets = createBracketsMap(); + // emit output for the __extends helper function const extendsHelper = ` var __extends = (this && this.__extends) || function (d, b) { @@ -345,6 +26,9 @@ var __extends = (this && this.__extends) || function (d, b) { d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); };`; + // Emit output for the __assign helper function. + // This is typically used for JSX spread attributes, + // and can be used for object literal spread properties. const assignHelper = ` var __assign = (this && this.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { @@ -376,6 +60,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } };`; + // emit output for the __awaiter helper function const awaiterHelper = ` var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { @@ -386,17 +71,195 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }); };`; + // The __generator helper is used by down-level transformations to emulate the runtime + // semantics of an ES2015 generator function. When called, this helper returns an + // object that implements the Iterator protocol, in that it has `next`, `return`, and + // `throw` methods that step through the generator when invoked. + // + // parameters: + // thisArg The value to use as the `this` binding for the transformed generator body. + // body A function that acts as the transformed generator body. + // + // variables: + // _ Persistent state for the generator that is shared between the helper and the + // generator body. The state object has the following members: + // sent() - A method that returns or throws the current completion value. + // label - The next point at which to resume evaluation of the generator body. + // trys - A stack of protected regions (try/catch/finally blocks). + // ops - A stack of pending instructions when inside of a finally block. + // f A value indicating whether the generator is executing. + // y An iterator to delegate for a yield*. + // t A temporary variable that holds one of the following values (note that these + // cases do not overlap): + // - The completion value when resuming from a `yield` or `yield*`. + // - The error value for a catch block. + // - The current protected region (array of try/catch/finally/end labels). + // - The verb (`next`, `throw`, or `return` method) to delegate to the expression + // of a `yield*`. + // - The result of evaluating the verb delegated to the expression of a `yield*`. + // + // functions: + // verb(n) Creates a bound callback to the `step` function for opcode `n`. + // step(op) Evaluates opcodes in a generator body until execution is suspended or + // completed. + // + // The __generator helper understands a limited set of instructions: + // 0: next(value?) - Start or resume the generator with the specified value. + // 1: throw(error) - Resume the generator with an exception. If the generator is + // suspended inside of one or more protected regions, evaluates + // any intervening finally blocks between the current label and + // the nearest catch block or function boundary. If uncaught, the + // exception is thrown to the caller. + // 2: return(value?) - Resume the generator as if with a return. If the generator is + // suspended inside of one or more protected regions, evaluates any + // intervening finally blocks. + // 3: break(label) - Jump to the specified label. If the label is outside of the + // current protected region, evaluates any intervening finally + // blocks. + // 4: yield(value?) - Yield execution to the caller with an optional value. When + // resumed, the generator will continue at the next label. + // 5: yield*(value) - Delegates evaluation to the supplied iterator. When + // delegation completes, the generator will continue at the next + // label. + // 6: catch(error) - Handles an exception thrown from within the generator body. If + // the current label is inside of one or more protected regions, + // evaluates any intervening finally blocks between the current + // label and the nearest catch block or function boundary. If + // uncaught, the exception is thrown to the caller. + // 7: endfinally - Ends a finally block, resuming the last instruction prior to + // entering a finally block. + // + // For examples of how these are used, see the comments in ./transformers/generators.ts + const generatorHelper = ` +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; + return { next: verb(0), "throw": verb(1), "return": verb(2) }; + 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 = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [0, 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 }; + } +};`; + + // emit output for the __export helper function + const exportStarHelper = ` +function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +}`; + + // emit output for the UMD helper function. + const umdHelper = ` +(function (dependencies, factory) { + if (typeof module === 'object' && typeof module.exports === 'object') { + var v = factory(require, exports); if (v !== undefined) module.exports = v; + } + else if (typeof define === 'function' && define.amd) { + define(dependencies, factory); + } +})`; + + const superHelper = ` +const _super = name => super[name];`; + + const advancedSuperHelper = ` +const _super = (function (geti, seti) { + const cache = Object.create(null); + return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); +})(name => super[name], (name, value) => super[name] = value);`; + const compilerOptions = host.getCompilerOptions(); const languageVersion = getEmitScriptTarget(compilerOptions); - const modulekind = getEmitModuleKind(compilerOptions); + const moduleKind = getEmitModuleKind(compilerOptions); const sourceMapDataList: SourceMapData[] = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined; const emittedFilesList: string[] = compilerOptions.listEmittedFiles ? [] : undefined; const emitterDiagnostics = createDiagnosticCollection(); - let emitSkipped = false; const newLine = host.getNewLine(); + const transformers = getTransformers(compilerOptions); + const writer = createTextWriter(newLine); + const { + write, + writeLine, + increaseIndent, + decreaseIndent + } = writer; - const emitJavaScript = createFileEmitter(); - forEachExpectedEmitFile(host, emitFile, targetSourceFile, emitOnlyDtsFiles); + const sourceMap = createSourceMapWriter(host, writer); + const { + emitStart, + emitEnd, + emitTokenStart, + emitTokenEnd + } = sourceMap; + + const comments = createCommentWriter(host, writer, sourceMap); + const { + emitNodeWithComments, + emitBodyWithDetachedComments, + emitTrailingCommentsOfPosition + } = comments; + + let nodeIdToGeneratedName: string[]; + let autoGeneratedIdToGeneratedName: string[]; + let generatedNameSet: Map; + let tempFlags: TempFlags; + let currentSourceFile: SourceFile; + let currentText: string; + let currentFileIdentifiers: Map; + let extendsEmitted: boolean; + let assignEmitted: boolean; + let decorateEmitted: boolean; + let paramEmitted: boolean; + let awaiterEmitted: boolean; + let isOwnFileEmit: boolean; + let emitSkipped = false; + + performance.mark("beforeTransform"); + + // Transform the source files + const transformed = transformFiles( + resolver, + host, + getSourceFilesToEmit(host, targetSourceFile), + transformers); + + performance.measure("transformTime", "beforeTransform"); + + // Extract helpers from the result + const { + getTokenSourceMapRange, + isSubstitutionEnabled, + isEmitNotificationEnabled, + onSubstituteNode, + onEmitNode + } = transformed; + + performance.mark("beforePrint"); + + // Emit each output file + forEachTransformedEmitFile(host, transformed.getSourceFiles(), emitFile, emitOnlyDtsFiles); + + // Clean up after transformation + transformed.dispose(); + + performance.measure("printTime", "beforePrint"); return { emitSkipped, @@ -405,9 +268,2448 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge sourceMaps: sourceMapDataList }; + function emitFile(jsFilePath: string, sourceMapFilePath: string, declarationFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean) { + // Make sure not to write js file and source map file if any of them cannot be written + if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { + printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + } + else { + emitSkipped = true; + } + + if (declarationFilePath) { + emitSkipped = writeDeclarationFile(declarationFilePath, getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; + } + + if (!emitSkipped && emittedFilesList) { + emittedFilesList.push(jsFilePath); + if (sourceMapFilePath) { + emittedFilesList.push(sourceMapFilePath); + } + if (declarationFilePath) { + emittedFilesList.push(declarationFilePath); + } + } + } + + function printFile(jsFilePath: string, sourceMapFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean) { + sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + nodeIdToGeneratedName = []; + autoGeneratedIdToGeneratedName = []; + generatedNameSet = createMap(); + isOwnFileEmit = !isBundledEmit; + + // Emit helpers from all the files + if (isBundledEmit && moduleKind) { + for (const sourceFile of sourceFiles) { + emitEmitHelpers(sourceFile); + } + } + + // Print each transformed source file. + forEach(sourceFiles, printSourceFile); + + writeLine(); + + const sourceMappingURL = sourceMap.getSourceMappingURL(); + if (sourceMappingURL) { + write(`//# ${"sourceMappingURL"}=${sourceMappingURL}`); // Sometimes tools can sometimes see this line as a source mapping url comment + } + + // Write the source map + if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) { + writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), /*writeByteOrderMark*/ false); + } + + // Record source map data for the test harness. + if (sourceMapDataList) { + sourceMapDataList.push(sourceMap.getSourceMapData()); + } + + // Write the output file + writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM); + + // Reset state + sourceMap.reset(); + comments.reset(); + writer.reset(); + + tempFlags = TempFlags.Auto; + currentSourceFile = undefined; + currentText = undefined; + extendsEmitted = false; + assignEmitted = false; + decorateEmitted = false; + paramEmitted = false; + awaiterEmitted = false; + isOwnFileEmit = false; + } + + function printSourceFile(node: SourceFile) { + currentSourceFile = node; + currentText = node.text; + currentFileIdentifiers = node.identifiers; + sourceMap.setSourceFile(node); + comments.setSourceFile(node); + emitNodeWithNotification(node, emitWorker); + } + + /** + * Emits a node. + */ + function emit(node: Node) { + emitNodeWithNotification(node, emitWithComments); + } + + + /** + * Emits a node with comments. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from emit. + */ + function emitWithComments(node: Node) { + emitNodeWithComments(node, emitWithSourceMap); + } + + /** + * Emits a node with source maps. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from emitWithComments. + */ + function emitWithSourceMap(node: Node) { + emitNodeWithSourceMap(node, emitWorker); + } + + function emitIdentifierName(node: Identifier) { + if (node) { + emitNodeWithNotification(node, emitIdentifierNameWithComments); + } + } + + function emitIdentifierNameWithComments(node: Identifier) { + emitNodeWithComments(node, emitWorker); + } + + /** + * Emits an expression node. + */ + function emitExpression(node: Expression) { + emitNodeWithNotification(node, emitExpressionWithComments); + } + + /** + * Emits an expression with comments. + * + * NOTE: Do not call this method directly. It is part of the emitExpression pipeline + * and should only be called indirectly from emitExpression. + */ + function emitExpressionWithComments(node: Expression) { + emitNodeWithComments(node, emitExpressionWithSourceMap); + } + + /** + * Emits an expression with source maps. + * + * NOTE: Do not call this method directly. It is part of the emitExpression pipeline + * and should only be called indirectly from emitExpressionWithComments. + */ + function emitExpressionWithSourceMap(node: Expression) { + emitNodeWithSourceMap(node, emitExpressionWorker); + } + + /** + * Emits a node with emit notification if available. + */ + function emitNodeWithNotification(node: Node, emitCallback: (node: Node) => void) { + if (node) { + if (isEmitNotificationEnabled(node)) { + onEmitNode(node, emitCallback); + } + else { + emitCallback(node); + } + } + } + + function emitNodeWithSourceMap(node: Node, emitCallback: (node: Node) => void) { + if (node) { + emitStart(/*range*/ node, /*contextNode*/ node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); + emitCallback(node); + emitEnd(/*range*/ node, /*contextNode*/ node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); + } + } + + function getSourceMapRange(node: Node) { + return node.sourceMapRange || node; + } + + /** + * Determines whether to skip leading comment emit for a node. + * + * We do not emit comments for NotEmittedStatement nodes or any node that has + * NodeEmitFlags.NoLeadingComments. + * + * @param node A Node. + */ + function shouldSkipLeadingCommentsForNode(node: Node) { + return isNotEmittedStatement(node) + || (node.emitFlags & NodeEmitFlags.NoLeadingComments) !== 0; + } + + /** + * Determines whether to skip source map emit for the start position of a node. + * + * We do not emit source maps for NotEmittedStatement nodes or any node that + * has NodeEmitFlags.NoLeadingSourceMap. + * + * @param node A Node. + */ + function shouldSkipLeadingSourceMapForNode(node: Node) { + return isNotEmittedStatement(node) + || (node.emitFlags & NodeEmitFlags.NoLeadingSourceMap) !== 0; + } + + + /** + * Determines whether to skip source map emit for the end position of a node. + * + * We do not emit source maps for NotEmittedStatement nodes or any node that + * has NodeEmitFlags.NoTrailingSourceMap. + * + * @param node A Node. + */ + function shouldSkipTrailingSourceMapForNode(node: Node) { + return isNotEmittedStatement(node) + || (node.emitFlags & NodeEmitFlags.NoTrailingSourceMap) !== 0; + } + + /** + * Determines whether to skip source map emit for a node and its children. + * + * We do not emit source maps for a node that has NodeEmitFlags.NoNestedSourceMaps. + */ + function shouldSkipSourceMapForChildren(node: Node) { + return (node.emitFlags & NodeEmitFlags.NoNestedSourceMaps) !== 0; + } + + function emitWorker(node: Node): void { + if (tryEmitSubstitute(node, emitWorker, /*isExpression*/ false)) { + return; + } + + const kind = node.kind; + switch (kind) { + // Pseudo-literals + case SyntaxKind.TemplateHead: + case SyntaxKind.TemplateMiddle: + case SyntaxKind.TemplateTail: + return emitLiteral(node); + + // Identifiers + case SyntaxKind.Identifier: + return emitIdentifier(node); + + // Reserved words + case SyntaxKind.ConstKeyword: + case SyntaxKind.DefaultKeyword: + case SyntaxKind.ExportKeyword: + case SyntaxKind.VoidKeyword: + + // Strict mode reserved words + case SyntaxKind.PrivateKeyword: + case SyntaxKind.ProtectedKeyword: + case SyntaxKind.PublicKeyword: + case SyntaxKind.StaticKeyword: + + // Contextual keywords + case SyntaxKind.AbstractKeyword: + case SyntaxKind.AnyKeyword: + case SyntaxKind.AsyncKeyword: + case SyntaxKind.BooleanKeyword: + case SyntaxKind.DeclareKeyword: + case SyntaxKind.NumberKeyword: + case SyntaxKind.ReadonlyKeyword: + case SyntaxKind.StringKeyword: + case SyntaxKind.SymbolKeyword: + case SyntaxKind.GlobalKeyword: + return writeTokenNode(node); + + // Parse tree nodes + + // Names + case SyntaxKind.QualifiedName: + return emitQualifiedName(node); + case SyntaxKind.ComputedPropertyName: + return emitComputedPropertyName(node); + + // Signature elements + case SyntaxKind.TypeParameter: + return emitTypeParameter(node); + case SyntaxKind.Parameter: + return emitParameter(node); + case SyntaxKind.Decorator: + return emitDecorator(node); + + // Type members + case SyntaxKind.PropertySignature: + return emitPropertySignature(node); + case SyntaxKind.PropertyDeclaration: + return emitPropertyDeclaration(node); + case SyntaxKind.MethodSignature: + return emitMethodSignature(node); + case SyntaxKind.MethodDeclaration: + return emitMethodDeclaration(node); + case SyntaxKind.Constructor: + return emitConstructor(node); + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + return emitAccessorDeclaration(node); + case SyntaxKind.CallSignature: + return emitCallSignature(node); + case SyntaxKind.ConstructSignature: + return emitConstructSignature(node); + case SyntaxKind.IndexSignature: + return emitIndexSignature(node); + + // Types + case SyntaxKind.TypePredicate: + return emitTypePredicate(node); + case SyntaxKind.TypeReference: + return emitTypeReference(node); + case SyntaxKind.FunctionType: + return emitFunctionType(node); + case SyntaxKind.ConstructorType: + return emitConstructorType(node); + case SyntaxKind.TypeQuery: + return emitTypeQuery(node); + case SyntaxKind.TypeLiteral: + return emitTypeLiteral(node); + case SyntaxKind.ArrayType: + return emitArrayType(node); + case SyntaxKind.TupleType: + return emitTupleType(node); + case SyntaxKind.UnionType: + return emitUnionType(node); + case SyntaxKind.IntersectionType: + return emitIntersectionType(node); + case SyntaxKind.ParenthesizedType: + return emitParenthesizedType(node); + case SyntaxKind.ExpressionWithTypeArguments: + return emitExpressionWithTypeArguments(node); + case SyntaxKind.ThisType: + return emitThisType(node); + case SyntaxKind.LiteralType: + return emitLiteralType(node); + + // Binding patterns + case SyntaxKind.ObjectBindingPattern: + return emitObjectBindingPattern(node); + case SyntaxKind.ArrayBindingPattern: + return emitArrayBindingPattern(node); + case SyntaxKind.BindingElement: + return emitBindingElement(node); + + // Misc + case SyntaxKind.TemplateSpan: + return emitTemplateSpan(node); + case SyntaxKind.SemicolonClassElement: + return emitSemicolonClassElement(node); + + // Statements + case SyntaxKind.Block: + return emitBlock(node); + case SyntaxKind.VariableStatement: + return emitVariableStatement(node); + case SyntaxKind.EmptyStatement: + return emitEmptyStatement(node); + case SyntaxKind.ExpressionStatement: + return emitExpressionStatement(node); + case SyntaxKind.IfStatement: + return emitIfStatement(node); + case SyntaxKind.DoStatement: + return emitDoStatement(node); + case SyntaxKind.WhileStatement: + return emitWhileStatement(node); + case SyntaxKind.ForStatement: + return emitForStatement(node); + case SyntaxKind.ForInStatement: + return emitForInStatement(node); + case SyntaxKind.ForOfStatement: + return emitForOfStatement(node); + case SyntaxKind.ContinueStatement: + return emitContinueStatement(node); + case SyntaxKind.BreakStatement: + return emitBreakStatement(node); + case SyntaxKind.ReturnStatement: + return emitReturnStatement(node); + case SyntaxKind.WithStatement: + return emitWithStatement(node); + case SyntaxKind.SwitchStatement: + return emitSwitchStatement(node); + case SyntaxKind.LabeledStatement: + return emitLabeledStatement(node); + case SyntaxKind.ThrowStatement: + return emitThrowStatement(node); + case SyntaxKind.TryStatement: + return emitTryStatement(node); + case SyntaxKind.DebuggerStatement: + return emitDebuggerStatement(node); + + // Declarations + case SyntaxKind.VariableDeclaration: + return emitVariableDeclaration(node); + case SyntaxKind.VariableDeclarationList: + return emitVariableDeclarationList(node); + case SyntaxKind.FunctionDeclaration: + return emitFunctionDeclaration(node); + case SyntaxKind.ClassDeclaration: + return emitClassDeclaration(node); + case SyntaxKind.InterfaceDeclaration: + return emitInterfaceDeclaration(node); + case SyntaxKind.TypeAliasDeclaration: + return emitTypeAliasDeclaration(node); + case SyntaxKind.EnumDeclaration: + return emitEnumDeclaration(node); + case SyntaxKind.ModuleDeclaration: + return emitModuleDeclaration(node); + case SyntaxKind.ModuleBlock: + return emitModuleBlock(node); + case SyntaxKind.CaseBlock: + return emitCaseBlock(node); + case SyntaxKind.ImportEqualsDeclaration: + return emitImportEqualsDeclaration(node); + case SyntaxKind.ImportDeclaration: + return emitImportDeclaration(node); + case SyntaxKind.ImportClause: + return emitImportClause(node); + case SyntaxKind.NamespaceImport: + return emitNamespaceImport(node); + case SyntaxKind.NamedImports: + return emitNamedImports(node); + case SyntaxKind.ImportSpecifier: + return emitImportSpecifier(node); + case SyntaxKind.ExportAssignment: + return emitExportAssignment(node); + case SyntaxKind.ExportDeclaration: + return emitExportDeclaration(node); + case SyntaxKind.NamedExports: + return emitNamedExports(node); + case SyntaxKind.ExportSpecifier: + return emitExportSpecifier(node); + case SyntaxKind.MissingDeclaration: + return; + + // Module references + case SyntaxKind.ExternalModuleReference: + return emitExternalModuleReference(node); + + // JSX (non-expression) + case SyntaxKind.JsxText: + return emitJsxText(node); + case SyntaxKind.JsxOpeningElement: + return emitJsxOpeningElement(node); + case SyntaxKind.JsxClosingElement: + return emitJsxClosingElement(node); + case SyntaxKind.JsxAttribute: + return emitJsxAttribute(node); + case SyntaxKind.JsxSpreadAttribute: + return emitJsxSpreadAttribute(node); + case SyntaxKind.JsxExpression: + return emitJsxExpression(node); + + // Clauses + case SyntaxKind.CaseClause: + return emitCaseClause(node); + case SyntaxKind.DefaultClause: + return emitDefaultClause(node); + case SyntaxKind.HeritageClause: + return emitHeritageClause(node); + case SyntaxKind.CatchClause: + return emitCatchClause(node); + + // Property assignments + case SyntaxKind.PropertyAssignment: + return emitPropertyAssignment(node); + case SyntaxKind.ShorthandPropertyAssignment: + return emitShorthandPropertyAssignment(node); + + // Enum + case SyntaxKind.EnumMember: + return emitEnumMember(node); + + // Top-level nodes + case SyntaxKind.SourceFile: + return emitSourceFile(node); + + // JSDoc nodes (ignored) + + // Transformation nodes (ignored) + } + + if (isExpression(node)) { + return emitExpressionWorker(node); + } + } + + function emitExpressionWorker(node: Node) { + if (tryEmitSubstitute(node, emitExpressionWorker, /*isExpression*/ true)) { + return; + } + + const kind = node.kind; + switch (kind) { + // Literals + case SyntaxKind.NumericLiteral: + return emitNumericLiteral(node); + + case SyntaxKind.StringLiteral: + case SyntaxKind.RegularExpressionLiteral: + case SyntaxKind.NoSubstitutionTemplateLiteral: + return emitLiteral(node); + + // Identifiers + case SyntaxKind.Identifier: + return emitIdentifier(node); + + // Reserved words + case SyntaxKind.FalseKeyword: + case SyntaxKind.NullKeyword: + case SyntaxKind.SuperKeyword: + case SyntaxKind.TrueKeyword: + case SyntaxKind.ThisKeyword: + return writeTokenNode(node); + + // Expressions + case SyntaxKind.ArrayLiteralExpression: + return emitArrayLiteralExpression(node); + case SyntaxKind.ObjectLiteralExpression: + return emitObjectLiteralExpression(node); + case SyntaxKind.PropertyAccessExpression: + return emitPropertyAccessExpression(node); + case SyntaxKind.ElementAccessExpression: + return emitElementAccessExpression(node); + case SyntaxKind.CallExpression: + return emitCallExpression(node); + case SyntaxKind.NewExpression: + return emitNewExpression(node); + case SyntaxKind.TaggedTemplateExpression: + return emitTaggedTemplateExpression(node); + case SyntaxKind.TypeAssertionExpression: + return emitTypeAssertionExpression(node); + case SyntaxKind.ParenthesizedExpression: + return emitParenthesizedExpression(node); + case SyntaxKind.FunctionExpression: + return emitFunctionExpression(node); + case SyntaxKind.ArrowFunction: + return emitArrowFunction(node); + case SyntaxKind.DeleteExpression: + return emitDeleteExpression(node); + case SyntaxKind.TypeOfExpression: + return emitTypeOfExpression(node); + case SyntaxKind.VoidExpression: + return emitVoidExpression(node); + case SyntaxKind.AwaitExpression: + return emitAwaitExpression(node); + case SyntaxKind.PrefixUnaryExpression: + return emitPrefixUnaryExpression(node); + case SyntaxKind.PostfixUnaryExpression: + return emitPostfixUnaryExpression(node); + case SyntaxKind.BinaryExpression: + return emitBinaryExpression(node); + case SyntaxKind.ConditionalExpression: + return emitConditionalExpression(node); + case SyntaxKind.TemplateExpression: + return emitTemplateExpression(node); + case SyntaxKind.YieldExpression: + return emitYieldExpression(node); + case SyntaxKind.SpreadElementExpression: + return emitSpreadElementExpression(node); + case SyntaxKind.ClassExpression: + return emitClassExpression(node); + case SyntaxKind.OmittedExpression: + return; + case SyntaxKind.AsExpression: + return emitAsExpression(node); + case SyntaxKind.NonNullExpression: + return emitNonNullExpression(node); + + // JSX + case SyntaxKind.JsxElement: + return emitJsxElement(node); + case SyntaxKind.JsxSelfClosingElement: + return emitJsxSelfClosingElement(node); + + // Transformation nodes + case SyntaxKind.PartiallyEmittedExpression: + return emitPartiallyEmittedExpression(node); + } + } + + // + // Literals/Pseudo-literals + // + + // SyntaxKind.NumericLiteral + function emitNumericLiteral(node: NumericLiteral) { + emitLiteral(node); + if (node.trailingComment) { + write(` /*${node.trailingComment}*/`); + } + } + + // SyntaxKind.StringLiteral + // SyntaxKind.RegularExpressionLiteral + // SyntaxKind.NoSubstitutionTemplateLiteral + // SyntaxKind.TemplateHead + // SyntaxKind.TemplateMiddle + // SyntaxKind.TemplateTail + function emitLiteral(node: LiteralLikeNode) { + const text = getLiteralTextOfNode(node); + if ((compilerOptions.sourceMap || compilerOptions.inlineSourceMap) + && (node.kind === SyntaxKind.StringLiteral || isTemplateLiteralKind(node.kind))) { + writer.writeLiteral(text); + } + else { + write(text); + } + } + + // + // Identifiers + // + + function emitIdentifier(node: Identifier) { + if (node.emitFlags & NodeEmitFlags.UMDDefine) { + writeLines(umdHelper); + } + else { + write(getTextOfNode(node, /*includeTrivia*/ false)); + } + } + + // + // Names + // + + function emitQualifiedName(node: QualifiedName) { + emitEntityName(node.left); + write("."); + emit(node.right); + } + + function emitEntityName(node: EntityName) { + if (node.kind === SyntaxKind.Identifier) { + emitExpression(node); + } + else { + emit(node); + } + } + + function emitComputedPropertyName(node: ComputedPropertyName) { + write("["); + emitExpression(node.expression); + write("]"); + } + + // + // Signature elements + // + + function emitTypeParameter(node: TypeParameterDeclaration) { + emit(node.name); + emitWithPrefix(" extends ", node.constraint); + } + + function emitParameter(node: ParameterDeclaration) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeIfPresent(node.dotDotDotToken, "..."); + emit(node.name); + writeIfPresent(node.questionToken, "?"); + emitExpressionWithPrefix(" = ", node.initializer); + emitWithPrefix(": ", node.type); + } + + function emitDecorator(decorator: Decorator) { + write("@"); + emitExpression(decorator.expression); + } + + // + // Type members + // + + function emitPropertySignature(node: PropertySignature) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.name); + writeIfPresent(node.questionToken, "?"); + emitWithPrefix(": ", node.type); + write(";"); + } + + function emitPropertyDeclaration(node: PropertyDeclaration) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.name); + emitWithPrefix(": ", node.type); + emitExpressionWithPrefix(" = ", node.initializer); + write(";"); + } + + function emitMethodSignature(node: MethodSignature) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emit(node.name); + writeIfPresent(node.questionToken, "?"); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitWithPrefix(": ", node.type); + write(";"); + } + + function emitMethodDeclaration(node: MethodDeclaration) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + writeIfPresent(node.asteriskToken, "*"); + emit(node.name); + emitSignatureAndBody(node, emitSignatureHead); + } + + function emitConstructor(node: ConstructorDeclaration) { + emitModifiers(node, node.modifiers); + write("constructor"); + emitSignatureAndBody(node, emitSignatureHead); + } + + function emitAccessorDeclaration(node: AccessorDeclaration) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + write(node.kind === SyntaxKind.GetAccessor ? "get " : "set "); + emit(node.name); + emitSignatureAndBody(node, emitSignatureHead); + } + + function emitCallSignature(node: CallSignatureDeclaration) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitWithPrefix(": ", node.type); + write(";"); + } + + function emitConstructSignature(node: ConstructSignatureDeclaration) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + write("new "); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitWithPrefix(": ", node.type); + write(";"); + } + + function emitIndexSignature(node: IndexSignatureDeclaration) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitParametersForIndexSignature(node, node.parameters); + emitWithPrefix(": ", node.type); + write(";"); + } + + function emitSemicolonClassElement(node: SemicolonClassElement) { + write(";"); + } + + // + // Types + // + + function emitTypePredicate(node: TypePredicateNode) { + emit(node.parameterName); + write(" is "); + emit(node.type); + } + + function emitTypeReference(node: TypeReferenceNode) { + emit(node.typeName); + emitTypeArguments(node, node.typeArguments); + } + + function emitFunctionType(node: FunctionTypeNode) { + emitTypeParameters(node, node.typeParameters); + emitParametersForArrow(node, node.parameters); + write(" => "); + emit(node.type); + } + + function emitConstructorType(node: ConstructorTypeNode) { + write("new "); + emitTypeParameters(node, node.typeParameters); + emitParametersForArrow(node, node.parameters); + write(" => "); + emit(node.type); + } + + function emitTypeQuery(node: TypeQueryNode) { + write("typeof "); + emit(node.exprName); + } + + function emitTypeLiteral(node: TypeLiteralNode) { + write("{"); + emitList(node, node.members, ListFormat.TypeLiteralMembers); + write("}"); + } + + function emitArrayType(node: ArrayTypeNode) { + emit(node.elementType); + write("[]"); + } + + function emitTupleType(node: TupleTypeNode) { + write("["); + emitList(node, node.elementTypes, ListFormat.TupleTypeElements); + write("]"); + } + + function emitUnionType(node: UnionTypeNode) { + emitList(node, node.types, ListFormat.UnionTypeConstituents); + } + + function emitIntersectionType(node: IntersectionTypeNode) { + emitList(node, node.types, ListFormat.IntersectionTypeConstituents); + } + + function emitParenthesizedType(node: ParenthesizedTypeNode) { + write("("); + emit(node.type); + write(")"); + } + + function emitThisType(node: ThisTypeNode) { + write("this"); + } + + function emitLiteralType(node: LiteralTypeNode) { + emitExpression(node.literal); + } + + // + // Binding patterns + // + + function emitObjectBindingPattern(node: ObjectBindingPattern) { + const elements = node.elements; + if (elements.length === 0) { + write("{}"); + } + else { + write("{"); + emitList(node, elements, ListFormat.ObjectBindingPatternElements); + write("}"); + } + } + + function emitArrayBindingPattern(node: ArrayBindingPattern) { + const elements = node.elements; + if (elements.length === 0) { + write("[]"); + } + else { + write("["); + emitList(node, node.elements, ListFormat.ArrayBindingPatternElements); + write("]"); + } + } + + function emitBindingElement(node: BindingElement) { + emitWithSuffix(node.propertyName, ": "); + writeIfPresent(node.dotDotDotToken, "..."); + emit(node.name); + emitExpressionWithPrefix(" = ", node.initializer); + } + + // + // Expressions + // + + function emitArrayLiteralExpression(node: ArrayLiteralExpression) { + const elements = node.elements; + if (elements.length === 0) { + write("[]"); + } + else { + const preferNewLine = node.multiLine ? ListFormat.PreferNewLine : ListFormat.None; + emitExpressionList(node, elements, ListFormat.ArrayLiteralExpressionElements | preferNewLine); + } + } + + function emitObjectLiteralExpression(node: ObjectLiteralExpression) { + const properties = node.properties; + if (properties.length === 0) { + write("{}"); + } + else { + const indentedFlag = node.emitFlags & NodeEmitFlags.Indented; + if (indentedFlag) { + increaseIndent(); + } + + const preferNewLine = node.multiLine ? ListFormat.PreferNewLine : ListFormat.None; + const allowTrailingComma = languageVersion >= ScriptTarget.ES5 ? ListFormat.AllowTrailingComma : ListFormat.None; + emitList(node, properties, ListFormat.ObjectLiteralExpressionProperties | allowTrailingComma | preferNewLine); + + if (indentedFlag) { + decreaseIndent(); + } + } + } + + function emitPropertyAccessExpression(node: PropertyAccessExpression) { + if (tryEmitConstantValue(node)) { + return; + } + + let indentBeforeDot = false; + let indentAfterDot = false; + if (!(node.emitFlags & NodeEmitFlags.NoIndentation)) { + const dotRangeStart = node.expression.end; + const dotRangeEnd = skipTrivia(currentText, node.expression.end) + 1; + const dotToken = { kind: SyntaxKind.DotToken, pos: dotRangeStart, end: dotRangeEnd }; + indentBeforeDot = needsIndentation(node, node.expression, dotToken); + indentAfterDot = needsIndentation(node, dotToken, node.name); + } + const shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); + + emitExpression(node.expression); + increaseIndentIf(indentBeforeDot); + write(shouldEmitDotDot ? ".." : "."); + increaseIndentIf(indentAfterDot); + emit(node.name); + decreaseIndentIf(indentBeforeDot, indentAfterDot); + } + + // 1..toString is a valid property access, emit a dot after the literal + // Also emit a dot if expression is a integer const enum value - it will appear in generated code as numeric literal + function needsDotDotForPropertyAccess(expression: Expression) { + if (expression.kind === SyntaxKind.NumericLiteral) { + // check if numeric literal was originally written with a dot + const text = getLiteralTextOfNode(expression); + return text.indexOf(tokenToString(SyntaxKind.DotToken)) < 0; + } + else { + // check if constant enum value is integer + const constantValue = tryGetConstEnumValue(expression); + // isFinite handles cases when constantValue is undefined + return isFinite(constantValue) && Math.floor(constantValue) === constantValue; + } + } + + function emitElementAccessExpression(node: ElementAccessExpression) { + if (tryEmitConstantValue(node)) { + return; + } + + emitExpression(node.expression); + write("["); + emitExpression(node.argumentExpression); + write("]"); + } + + function emitCallExpression(node: CallExpression) { + emitExpression(node.expression); + emitExpressionList(node, node.arguments, ListFormat.CallExpressionArguments); + } + + function emitNewExpression(node: NewExpression) { + write("new "); + emitExpression(node.expression); + emitExpressionList(node, node.arguments, ListFormat.NewExpressionArguments); + } + + function emitTaggedTemplateExpression(node: TaggedTemplateExpression) { + emitExpression(node.tag); + write(" "); + emitExpression(node.template); + } + + function emitTypeAssertionExpression(node: TypeAssertion) { + if (node.type) { + write("<"); + emit(node.type); + write(">"); + } + + emitExpression(node.expression); + } + + function emitParenthesizedExpression(node: ParenthesizedExpression) { + write("("); + emitExpression(node.expression); + write(")"); + } + + function emitFunctionExpression(node: FunctionExpression) { + emitFunctionDeclarationOrExpression(node); + } + + function emitArrowFunction(node: ArrowFunction) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + emitSignatureAndBody(node, emitArrowFunctionHead); + } + + function emitArrowFunctionHead(node: ArrowFunction) { + emitTypeParameters(node, node.typeParameters); + emitParametersForArrow(node, node.parameters); + emitWithPrefix(": ", node.type); + write(" =>"); + } + + function emitDeleteExpression(node: DeleteExpression) { + write("delete "); + emitExpression(node.expression); + } + + function emitTypeOfExpression(node: TypeOfExpression) { + write("typeof "); + emitExpression(node.expression); + } + + function emitVoidExpression(node: VoidExpression) { + write("void "); + emitExpression(node.expression); + } + + function emitAwaitExpression(node: AwaitExpression) { + write("await "); + emitExpression(node.expression); + } + + function emitPrefixUnaryExpression(node: PrefixUnaryExpression) { + writeTokenText(node.operator); + if (shouldEmitWhitespaceBeforeOperand(node)) { + write(" "); + } + emitExpression(node.operand); + } + + function shouldEmitWhitespaceBeforeOperand(node: PrefixUnaryExpression) { + // In some cases, we need to emit a space between the operator and the operand. One obvious case + // is when the operator is an identifier, like delete or typeof. We also need to do this for plus + // and minus expressions in certain cases. Specifically, consider the following two cases (parens + // are just for clarity of exposition, and not part of the source code): + // + // (+(+1)) + // (+(++1)) + // + // We need to emit a space in both cases. In the first case, the absence of a space will make + // the resulting expression a prefix increment operation. And in the second, it will make the resulting + // expression a prefix increment whose operand is a plus expression - (++(+x)) + // The same is true of minus of course. + const operand = node.operand; + return operand.kind === SyntaxKind.PrefixUnaryExpression + && ((node.operator === SyntaxKind.PlusToken && ((operand).operator === SyntaxKind.PlusToken || (operand).operator === SyntaxKind.PlusPlusToken)) + || (node.operator === SyntaxKind.MinusToken && ((operand).operator === SyntaxKind.MinusToken || (operand).operator === SyntaxKind.MinusMinusToken))); + } + + function emitPostfixUnaryExpression(node: PostfixUnaryExpression) { + emitExpression(node.operand); + writeTokenText(node.operator); + } + + function emitBinaryExpression(node: BinaryExpression) { + const isCommaOperator = node.operatorToken.kind !== SyntaxKind.CommaToken; + const indentBeforeOperator = needsIndentation(node, node.left, node.operatorToken); + const indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); + + emitExpression(node.left); + increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); + writeTokenText(node.operatorToken.kind); + increaseIndentIf(indentAfterOperator, " "); + emitExpression(node.right); + decreaseIndentIf(indentBeforeOperator, indentAfterOperator); + } + + function emitConditionalExpression(node: ConditionalExpression) { + const indentBeforeQuestion = needsIndentation(node, node.condition, node.questionToken); + const indentAfterQuestion = needsIndentation(node, node.questionToken, node.whenTrue); + const indentBeforeColon = needsIndentation(node, node.whenTrue, node.colonToken); + const indentAfterColon = needsIndentation(node, node.colonToken, node.whenFalse); + + emitExpression(node.condition); + increaseIndentIf(indentBeforeQuestion, " "); + write("?"); + increaseIndentIf(indentAfterQuestion, " "); + emitExpression(node.whenTrue); + decreaseIndentIf(indentBeforeQuestion, indentAfterQuestion); + + increaseIndentIf(indentBeforeColon, " "); + write(":"); + increaseIndentIf(indentAfterColon, " "); + emitExpression(node.whenFalse); + decreaseIndentIf(indentBeforeColon, indentAfterColon); + } + + function emitTemplateExpression(node: TemplateExpression) { + emit(node.head); + emitList(node, node.templateSpans, ListFormat.TemplateExpressionSpans); + } + + function emitYieldExpression(node: YieldExpression) { + write(node.asteriskToken ? "yield*" : "yield"); + emitExpressionWithPrefix(" ", node.expression); + } + + function emitSpreadElementExpression(node: SpreadElementExpression) { + write("..."); + emitExpression(node.expression); + } + + function emitClassExpression(node: ClassExpression) { + emitClassDeclarationOrExpression(node); + } + + function emitExpressionWithTypeArguments(node: ExpressionWithTypeArguments) { + emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); + } + + function emitAsExpression(node: AsExpression) { + emitExpression(node.expression); + if (node.type) { + write(" as "); + emit(node.type); + } + } + + function emitNonNullExpression(node: NonNullExpression) { + emitExpression(node.expression); + write("!"); + } + + // + // Misc + // + + function emitTemplateSpan(node: TemplateSpan) { + emitExpression(node.expression); + emit(node.literal); + } + + // + // Statements + // + + function emitBlock(node: Block, format?: ListFormat) { + if (isSingleLineEmptyBlock(node)) { + writeToken(SyntaxKind.OpenBraceToken, node.pos, /*contextNode*/ node); + write(" "); + writeToken(SyntaxKind.CloseBraceToken, node.statements.end, /*contextNode*/ node); + } + else { + writeToken(SyntaxKind.OpenBraceToken, node.pos, /*contextNode*/ node); + emitBlockStatements(node); + writeToken(SyntaxKind.CloseBraceToken, node.statements.end, /*contextNode*/ node); + } + } + + function emitBlockStatements(node: Block) { + if (node.emitFlags & NodeEmitFlags.SingleLine) { + emitList(node, node.statements, ListFormat.SingleLineBlockStatements); + } + else { + emitList(node, node.statements, ListFormat.MultiLineBlockStatements); + } + } + + function emitVariableStatement(node: VariableStatement) { + emitModifiers(node, node.modifiers); + emit(node.declarationList); + write(";"); + } + + function emitEmptyStatement(node: EmptyStatement) { + write(";"); + } + + function emitExpressionStatement(node: ExpressionStatement) { + emitExpression(node.expression); + write(";"); + } + + function emitIfStatement(node: IfStatement) { + const openParenPos = writeToken(SyntaxKind.IfKeyword, node.pos, node); + write(" "); + writeToken(SyntaxKind.OpenParenToken, openParenPos, node); + emitExpression(node.expression); + writeToken(SyntaxKind.CloseParenToken, node.expression.end, node); + emitEmbeddedStatement(node.thenStatement); + if (node.elseStatement) { + writeLine(); + writeToken(SyntaxKind.ElseKeyword, node.thenStatement.end, node); + if (node.elseStatement.kind === SyntaxKind.IfStatement) { + write(" "); + emit(node.elseStatement); + } + else { + emitEmbeddedStatement(node.elseStatement); + } + } + } + + function emitDoStatement(node: DoStatement) { + write("do"); + emitEmbeddedStatement(node.statement); + if (isBlock(node.statement)) { + write(" "); + } + else { + writeLine(); + } + + write("while ("); + emitExpression(node.expression); + write(");"); + } + + function emitWhileStatement(node: WhileStatement) { + write("while ("); + emitExpression(node.expression); + write(")"); + emitEmbeddedStatement(node.statement); + } + + function emitForStatement(node: ForStatement) { + const openParenPos = writeToken(SyntaxKind.ForKeyword, node.pos); + write(" "); + writeToken(SyntaxKind.OpenParenToken, openParenPos, /*contextNode*/ node); + emitForBinding(node.initializer); + write(";"); + emitExpressionWithPrefix(" ", node.condition); + write(";"); + emitExpressionWithPrefix(" ", node.incrementor); + write(")"); + emitEmbeddedStatement(node.statement); + } + + function emitForInStatement(node: ForInStatement) { + const openParenPos = writeToken(SyntaxKind.ForKeyword, node.pos); + write(" "); + writeToken(SyntaxKind.OpenParenToken, openParenPos); + emitForBinding(node.initializer); + write(" in "); + emitExpression(node.expression); + writeToken(SyntaxKind.CloseParenToken, node.expression.end); + emitEmbeddedStatement(node.statement); + } + + function emitForOfStatement(node: ForOfStatement) { + const openParenPos = writeToken(SyntaxKind.ForKeyword, node.pos); + write(" "); + writeToken(SyntaxKind.OpenParenToken, openParenPos); + emitForBinding(node.initializer); + write(" of "); + emitExpression(node.expression); + writeToken(SyntaxKind.CloseParenToken, node.expression.end); + emitEmbeddedStatement(node.statement); + } + + function emitForBinding(node: VariableDeclarationList | Expression) { + if (node !== undefined) { + if (node.kind === SyntaxKind.VariableDeclarationList) { + emit(node); + } + else { + emitExpression(node); + } + } + } + + function emitContinueStatement(node: ContinueStatement) { + writeToken(SyntaxKind.ContinueKeyword, node.pos); + emitWithPrefix(" ", node.label); + write(";"); + } + + function emitBreakStatement(node: BreakStatement) { + writeToken(SyntaxKind.BreakKeyword, node.pos); + emitWithPrefix(" ", node.label); + write(";"); + } + + function emitReturnStatement(node: ReturnStatement) { + writeToken(SyntaxKind.ReturnKeyword, node.pos, /*contextNode*/ node); + emitExpressionWithPrefix(" ", node.expression); + write(";"); + } + + function emitWithStatement(node: WithStatement) { + write("with ("); + emitExpression(node.expression); + write(")"); + emitEmbeddedStatement(node.statement); + } + + function emitSwitchStatement(node: SwitchStatement) { + const openParenPos = writeToken(SyntaxKind.SwitchKeyword, node.pos); + write(" "); + writeToken(SyntaxKind.OpenParenToken, openParenPos); + emitExpression(node.expression); + writeToken(SyntaxKind.CloseParenToken, node.expression.end); + write(" "); + emit(node.caseBlock); + } + + function emitLabeledStatement(node: LabeledStatement) { + emit(node.label); + write(": "); + emit(node.statement); + } + + function emitThrowStatement(node: ThrowStatement) { + write("throw"); + emitExpressionWithPrefix(" ", node.expression); + write(";"); + } + + function emitTryStatement(node: TryStatement) { + write("try "); + emit(node.tryBlock); + emit(node.catchClause); + if (node.finallyBlock) { + writeLine(); + write("finally "); + emit(node.finallyBlock); + } + } + + function emitDebuggerStatement(node: DebuggerStatement) { + writeToken(SyntaxKind.DebuggerKeyword, node.pos); + write(";"); + } + + // + // Declarations + // + + function emitVariableDeclaration(node: VariableDeclaration) { + emit(node.name); + emitExpressionWithPrefix(" = ", node.initializer); + } + + function emitVariableDeclarationList(node: VariableDeclarationList) { + write(isLet(node) ? "let " : isConst(node) ? "const " : "var "); + emitList(node, node.declarations, ListFormat.VariableDeclarationList); + } + + function emitFunctionDeclaration(node: FunctionDeclaration) { + emitFunctionDeclarationOrExpression(node); + } + + function emitFunctionDeclarationOrExpression(node: FunctionDeclaration | FunctionExpression) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + write(node.asteriskToken ? "function* " : "function "); + emitIdentifierName(node.name); + emitSignatureAndBody(node, emitSignatureHead); + } + + function emitSignatureAndBody(node: FunctionLikeDeclaration, emitSignatureHead: (node: SignatureDeclaration) => void) { + const body = node.body; + if (body) { + if (isBlock(body)) { + const indentedFlag = node.emitFlags & NodeEmitFlags.Indented; + if (indentedFlag) { + increaseIndent(); + } + + if (node.emitFlags & NodeEmitFlags.ReuseTempVariableScope) { + emitSignatureHead(node); + emitBlockFunctionBody(node, body); + } + else { + const savedTempFlags = tempFlags; + tempFlags = 0; + emitSignatureHead(node); + emitBlockFunctionBody(node, body); + tempFlags = savedTempFlags; + } + + if (indentedFlag) { + decreaseIndent(); + } + } + else { + emitSignatureHead(node); + write(" "); + emitExpression(body); + } + } + else { + emitSignatureHead(node); + write(";"); + } + + } + + function emitSignatureHead(node: FunctionDeclaration | FunctionExpression | MethodDeclaration | AccessorDeclaration | ConstructorDeclaration) { + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitWithPrefix(": ", node.type); + } + + function shouldEmitBlockFunctionBodyOnSingleLine(parentNode: Node, body: Block) { + // We must emit a function body as a single-line body in the following case: + // * The body has NodeEmitFlags.SingleLine specified. + + // We must emit a function body as a multi-line body in the following cases: + // * The body is explicitly marked as multi-line. + // * A non-synthesized body's start and end position are on different lines. + // * Any statement in the body starts on a new line. + + if (body.emitFlags & NodeEmitFlags.SingleLine) { + return true; + } + + if (body.multiLine) { + return false; + } + + if (!nodeIsSynthesized(body) && !rangeIsOnSingleLine(body, currentSourceFile)) { + return false; + } + + if (shouldWriteLeadingLineTerminator(body, body.statements, ListFormat.PreserveLines) + || shouldWriteClosingLineTerminator(body, body.statements, ListFormat.PreserveLines)) { + return false; + } + + let previousStatement: Statement; + for (const statement of body.statements) { + if (shouldWriteSeparatingLineTerminator(previousStatement, statement, ListFormat.PreserveLines)) { + return false; + } + + previousStatement = statement; + } + + return true; + } + + function emitBlockFunctionBody(parentNode: Node, body: Block) { + write(" {"); + increaseIndent(); + + emitBodyWithDetachedComments(body, body.statements, + shouldEmitBlockFunctionBodyOnSingleLine(parentNode, body) + ? emitBlockFunctionBodyOnSingleLine + : emitBlockFunctionBodyWorker); + + decreaseIndent(); + writeToken(SyntaxKind.CloseBraceToken, body.statements.end, body); + } + + function emitBlockFunctionBodyOnSingleLine(body: Block) { + emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true); + } + + function emitBlockFunctionBodyWorker(body: Block, emitBlockFunctionBodyOnSingleLine?: boolean) { + // Emit all the prologue directives (like "use strict"). + const statementOffset = emitPrologueDirectives(body.statements, /*startWithNewLine*/ true); + const helpersEmitted = emitHelpers(body); + + if (statementOffset === 0 && !helpersEmitted && emitBlockFunctionBodyOnSingleLine) { + decreaseIndent(); + emitList(body, body.statements, ListFormat.SingleLineFunctionBodyStatements); + increaseIndent(); + } + else { + emitList(body, body.statements, ListFormat.MultiLineFunctionBodyStatements, statementOffset); + } + } + + function emitClassDeclaration(node: ClassDeclaration) { + emitClassDeclarationOrExpression(node); + } + + function emitClassDeclarationOrExpression(node: ClassDeclaration | ClassExpression) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + write("class"); + emitNodeWithPrefix(" ", node.name, emitIdentifierName); + + const indentedFlag = node.emitFlags & NodeEmitFlags.Indented; + if (indentedFlag) { + increaseIndent(); + } + + emitTypeParameters(node, node.typeParameters); + emitList(node, node.heritageClauses, ListFormat.ClassHeritageClauses); + + const savedTempFlags = tempFlags; + tempFlags = 0; + + write(" {"); + emitList(node, node.members, ListFormat.ClassMembers); + write("}"); + + if (indentedFlag) { + decreaseIndent(); + } + + tempFlags = savedTempFlags; + } + + function emitInterfaceDeclaration(node: InterfaceDeclaration) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + write("interface "); + emit(node.name); + emitTypeParameters(node, node.typeParameters); + emitList(node, node.heritageClauses, ListFormat.HeritageClauses); + write(" {"); + emitList(node, node.members, ListFormat.InterfaceMembers); + write("}"); + } + + function emitTypeAliasDeclaration(node: TypeAliasDeclaration) { + emitDecorators(node, node.decorators); + emitModifiers(node, node.modifiers); + write("type "); + emit(node.name); + emitTypeParameters(node, node.typeParameters); + write(" = "); + emit(node.type); + write(";"); + } + + function emitEnumDeclaration(node: EnumDeclaration) { + emitModifiers(node, node.modifiers); + write("enum "); + emit(node.name); + + const savedTempFlags = tempFlags; + tempFlags = 0; + + write(" {"); + emitList(node, node.members, ListFormat.EnumMembers); + write("}"); + tempFlags = savedTempFlags; + } + + function emitModuleDeclaration(node: ModuleDeclaration) { + emitModifiers(node, node.modifiers); + write(node.flags & NodeFlags.Namespace ? "namespace " : "module "); + emit(node.name); + + let body = node.body; + while (body.kind === SyntaxKind.ModuleDeclaration) { + write("."); + emit((body).name); + body = (body).body; + } + + write(" "); + emit(body); + } + + function emitModuleBlock(node: ModuleBlock) { + if (isSingleLineEmptyBlock(node)) { + write("{ }"); + } + else { + const savedTempFlags = tempFlags; + tempFlags = 0; + write("{"); + increaseIndent(); + emitBlockStatements(node); + write("}"); + tempFlags = savedTempFlags; + } + } + + function emitCaseBlock(node: CaseBlock) { + writeToken(SyntaxKind.OpenBraceToken, node.pos); + emitList(node, node.clauses, ListFormat.CaseBlockClauses); + writeToken(SyntaxKind.CloseBraceToken, node.clauses.end); + } + + function emitImportEqualsDeclaration(node: ImportEqualsDeclaration) { + emitModifiers(node, node.modifiers); + write("import "); + emit(node.name); + write(" = "); + emitModuleReference(node.moduleReference); + write(";"); + } + + function emitModuleReference(node: ModuleReference) { + if (node.kind === SyntaxKind.Identifier) { + emitExpression(node); + } + else { + emit(node); + } + } + + function emitImportDeclaration(node: ImportDeclaration) { + emitModifiers(node, node.modifiers); + write("import "); + if (node.importClause) { + emit(node.importClause); + write(" from "); + } + emitExpression(node.moduleSpecifier); + write(";"); + } + + function emitImportClause(node: ImportClause) { + emit(node.name); + if (node.name && node.namedBindings) { + write(", "); + } + emit(node.namedBindings); + } + + function emitNamespaceImport(node: NamespaceImport) { + write("* as "); + emit(node.name); + } + + function emitNamedImports(node: NamedImports) { + emitNamedImportsOrExports(node); + } + + function emitImportSpecifier(node: ImportSpecifier) { + emitImportOrExportSpecifier(node); + } + + function emitExportAssignment(node: ExportAssignment) { + write(node.isExportEquals ? "export = " : "export default "); + emitExpression(node.expression); + write(";"); + } + + function emitExportDeclaration(node: ExportDeclaration) { + write("export "); + if (node.exportClause) { + emit(node.exportClause); + } + else { + write("*"); + } + if (node.moduleSpecifier) { + write(" from "); + emitExpression(node.moduleSpecifier); + } + write(";"); + } + + function emitNamedExports(node: NamedExports) { + emitNamedImportsOrExports(node); + } + + function emitExportSpecifier(node: ExportSpecifier) { + emitImportOrExportSpecifier(node); + } + + function emitNamedImportsOrExports(node: NamedImportsOrExports) { + write("{"); + emitList(node, node.elements, ListFormat.NamedImportsOrExportsElements); + write("}"); + } + + function emitImportOrExportSpecifier(node: ImportOrExportSpecifier) { + if (node.propertyName) { + emit(node.propertyName); + write(" as "); + } + + emit(node.name); + } + + // + // Module references + // + + function emitExternalModuleReference(node: ExternalModuleReference) { + write("require("); + emitExpression(node.expression); + write(")"); + } + + // + // JSX + // + + function emitJsxElement(node: JsxElement) { + emit(node.openingElement); + emitList(node, node.children, ListFormat.JsxElementChildren); + emit(node.closingElement); + } + + function emitJsxSelfClosingElement(node: JsxSelfClosingElement) { + write("<"); + emitJsxTagName(node.tagName); + write(" "); + emitList(node, node.attributes, ListFormat.JsxElementAttributes); + write("/>"); + } + + function emitJsxOpeningElement(node: JsxOpeningElement) { + write("<"); + emitJsxTagName(node.tagName); + writeIfAny(node.attributes, " "); + emitList(node, node.attributes, ListFormat.JsxElementAttributes); + write(">"); + } + + function emitJsxText(node: JsxText) { + writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true)); + } + + function emitJsxClosingElement(node: JsxClosingElement) { + write(""); + } + + function emitJsxAttribute(node: JsxAttribute) { + emit(node.name); + emitWithPrefix("=", node.initializer); + } + + function emitJsxSpreadAttribute(node: JsxSpreadAttribute) { + write("{..."); + emitExpression(node.expression); + write("}"); + } + + function emitJsxExpression(node: JsxExpression) { + if (node.expression) { + write("{"); + emitExpression(node.expression); + write("}"); + } + } + + function emitJsxTagName(node: JsxTagNameExpression) { + if (node.kind === SyntaxKind.Identifier) { + emitExpression(node); + } + else { + emit(node); + } + } + + // + // Clauses + // + + function emitCaseClause(node: CaseClause) { + write("case "); + emitExpression(node.expression); + write(":"); + + emitCaseOrDefaultClauseStatements(node, node.statements); + } + + function emitDefaultClause(node: DefaultClause) { + write("default:"); + emitCaseOrDefaultClauseStatements(node, node.statements); + } + + function emitCaseOrDefaultClauseStatements(parentNode: Node, statements: NodeArray) { + const emitAsSingleStatement = + statements.length === 1 && + ( + // treat synthesized nodes as located on the same line for emit purposes + nodeIsSynthesized(parentNode) || + nodeIsSynthesized(statements[0]) || + rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile) + ); + + if (emitAsSingleStatement) { + write(" "); + emit(statements[0]); + } + else { + emitList(parentNode, statements, ListFormat.CaseOrDefaultClauseStatements); + } + } + + function emitHeritageClause(node: HeritageClause) { + write(" "); + writeTokenText(node.token); + write(" "); + emitList(node, node.types, ListFormat.HeritageClauseTypes); + } + + function emitCatchClause(node: CatchClause) { + writeLine(); + const openParenPos = writeToken(SyntaxKind.CatchKeyword, node.pos); + write(" "); + writeToken(SyntaxKind.OpenParenToken, openParenPos); + emit(node.variableDeclaration); + writeToken(SyntaxKind.CloseParenToken, node.variableDeclaration ? node.variableDeclaration.end : openParenPos); + write(" "); + emit(node.block); + } + + // + // Property assignments + // + + function emitPropertyAssignment(node: PropertyAssignment) { + emit(node.name); + write(": "); + // This is to ensure that we emit comment in the following case: + // For example: + // obj = { + // id: /*comment1*/ ()=>void + // } + // "comment1" is not considered to be leading comment for node.initializer + // but rather a trailing comment on the previous node. + const initializer = node.initializer; + if (!shouldSkipLeadingCommentsForNode(initializer)) { + const commentRange = initializer.commentRange || initializer; + emitTrailingCommentsOfPosition(commentRange.pos); + } + + emitExpression(initializer); + } + + function emitShorthandPropertyAssignment(node: ShorthandPropertyAssignment) { + emit(node.name); + if (node.objectAssignmentInitializer) { + write(" = "); + emitExpression(node.objectAssignmentInitializer); + } + } + + // + // Enum + // + + function emitEnumMember(node: EnumMember) { + emit(node.name); + emitExpressionWithPrefix(" = ", node.initializer); + } + + // + // Top-level nodes + // + + function emitSourceFile(node: SourceFile) { + writeLine(); + emitShebang(); + emitBodyWithDetachedComments(node, node.statements, emitSourceFileWorker); + } + + function emitSourceFileWorker(node: SourceFile) { + const statements = node.statements; + const statementOffset = emitPrologueDirectives(statements); + const savedTempFlags = tempFlags; + tempFlags = 0; + emitHelpers(node); + emitList(node, statements, ListFormat.MultiLine, statementOffset); + tempFlags = savedTempFlags; + } + + // Transformation nodes + + function emitPartiallyEmittedExpression(node: PartiallyEmittedExpression) { + emitExpression(node.expression); + } + + /** + * Emits any prologue directives at the start of a Statement list, returning the + * number of prologue directives written to the output. + */ + function emitPrologueDirectives(statements: Node[], startWithNewLine?: boolean): number { + for (let i = 0; i < statements.length; i++) { + if (isPrologueDirective(statements[i])) { + if (startWithNewLine || i > 0) { + writeLine(); + } + emit(statements[i]); + } + else { + // return index of the first non prologue directive + return i; + } + } + + return statements.length; + } + + function emitHelpers(node: Node) { + const emitFlags = node.emitFlags; + let helpersEmitted = false; + if (emitFlags & NodeEmitFlags.EmitEmitHelpers) { + helpersEmitted = emitEmitHelpers(currentSourceFile); + } + + if (emitFlags & NodeEmitFlags.EmitExportStar) { + writeLines(exportStarHelper); + helpersEmitted = true; + } + + if (emitFlags & NodeEmitFlags.EmitSuperHelper) { + writeLines(superHelper); + helpersEmitted = true; + } + + if (emitFlags & NodeEmitFlags.EmitAdvancedSuperHelper) { + writeLines(advancedSuperHelper); + helpersEmitted = true; + } + + return helpersEmitted; + } + + function emitEmitHelpers(node: SourceFile) { + // Only emit helpers if the user did not say otherwise. + if (compilerOptions.noEmitHelpers) { + return false; + } + + // Don't emit helpers if we can import them. + if (compilerOptions.importHelpers + && (isExternalModule(node) || compilerOptions.isolatedModules)) { + return false; + } + + let helpersEmitted = false; + + // Only Emit __extends function when target ES5. + // For target ES6 and above, we can emit classDeclaration as is. + if ((languageVersion < ScriptTarget.ES6) && (!extendsEmitted && node.flags & NodeFlags.HasClassExtends)) { + writeLines(extendsHelper); + extendsEmitted = true; + helpersEmitted = true; + } + + if (compilerOptions.jsx !== JsxEmit.Preserve && !assignEmitted && (node.flags & NodeFlags.HasJsxSpreadAttributes)) { + writeLines(assignHelper); + assignEmitted = true; + } + + if (!decorateEmitted && node.flags & NodeFlags.HasDecorators) { + writeLines(decorateHelper); + if (compilerOptions.emitDecoratorMetadata) { + writeLines(metadataHelper); + } + + decorateEmitted = true; + helpersEmitted = true; + } + + if (!paramEmitted && node.flags & NodeFlags.HasParamDecorators) { + writeLines(paramHelper); + paramEmitted = true; + helpersEmitted = true; + } + + if (!awaiterEmitted && node.flags & NodeFlags.HasAsyncFunctions) { + writeLines(awaiterHelper); + if (languageVersion < ScriptTarget.ES6) { + writeLines(generatorHelper); + } + + awaiterEmitted = true; + helpersEmitted = true; + } + + if (helpersEmitted) { + writeLine(); + } + + return helpersEmitted; + } + + function writeLines(text: string): void { + const lines = text.split(/\r\n|\r|\n/g); + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + if (line.length) { + if (i > 0) { + writeLine(); + } + write(line); + } + } + } + + // + // Helpers + // + + function emitShebang() { + const shebang = getShebang(currentText); + if (shebang) { + write(shebang); + writeLine(); + } + } + + function emitModifiers(node: Node, modifiers: NodeArray) { + if (modifiers && modifiers.length) { + emitList(node, modifiers, ListFormat.Modifiers); + write(" "); + } + } + + function emitWithPrefix(prefix: string, node: Node) { + emitNodeWithPrefix(prefix, node, emit); + } + + function emitExpressionWithPrefix(prefix: string, node: Node) { + emitNodeWithPrefix(prefix, node, emitExpression); + } + + function emitNodeWithPrefix(prefix: string, node: Node, emit: (node: Node) => void) { + if (node) { + write(prefix); + emit(node); + } + } + + function emitWithSuffix(node: Node, suffix: string) { + if (node) { + emit(node); + write(suffix); + } + } + + function tryEmitSubstitute(node: Node, emitNode: (node: Node) => void, isExpression: boolean) { + if (isSubstitutionEnabled(node) && (node.emitFlags & NodeEmitFlags.NoSubstitution) === 0) { + const substitute = onSubstituteNode(node, isExpression); + if (substitute !== node) { + substitute.emitFlags |= NodeEmitFlags.NoSubstitution; + emitNode(substitute); + return true; + } + } + + return false; + } + + function tryEmitConstantValue(node: PropertyAccessExpression | ElementAccessExpression): boolean { + const constantValue = tryGetConstEnumValue(node); + if (constantValue !== undefined) { + write(String(constantValue)); + if (!compilerOptions.removeComments) { + const propertyName = isPropertyAccessExpression(node) + ? declarationNameToString(node.name) + : getTextOfNode(node.argumentExpression); + write(` /* ${propertyName} */`); + } + + return true; + } + + return false; + } + + function emitEmbeddedStatement(node: Statement) { + if (isBlock(node)) { + write(" "); + emit(node); + } + else { + writeLine(); + increaseIndent(); + emit(node); + decreaseIndent(); + } + } + + function emitDecorators(parentNode: Node, decorators: NodeArray) { + emitList(parentNode, decorators, ListFormat.Decorators); + } + + function emitTypeArguments(parentNode: Node, typeArguments: NodeArray) { + emitList(parentNode, typeArguments, ListFormat.TypeArguments); + } + + function emitTypeParameters(parentNode: Node, typeParameters: NodeArray) { + emitList(parentNode, typeParameters, ListFormat.TypeParameters); + } + + function emitParameters(parentNode: Node, parameters: NodeArray) { + emitList(parentNode, parameters, ListFormat.Parameters); + } + + function emitParametersForArrow(parentNode: Node, parameters: NodeArray) { + if (parameters && + parameters.length === 1 && + parameters[0].type === undefined && + parameters[0].pos === parentNode.pos) { + emit(parameters[0]); + } + else { + emitParameters(parentNode, parameters); + } + } + + function emitParametersForIndexSignature(parentNode: Node, parameters: NodeArray) { + emitList(parentNode, parameters, ListFormat.IndexSignatureParameters); + } + + function emitList(parentNode: Node, children: NodeArray, format: ListFormat, start?: number, count?: number) { + emitNodeList(emit, parentNode, children, format, start, count); + } + + function emitExpressionList(parentNode: Node, children: NodeArray, format: ListFormat, start?: number, count?: number) { + emitNodeList(emitExpression, parentNode, children, format, start, count); + } + + function emitNodeList(emit: (node: Node) => void, parentNode: Node, children: NodeArray, format: ListFormat, start = 0, count = children ? children.length - start : 0) { + const isUndefined = children === undefined; + if (isUndefined && format & ListFormat.OptionalIfUndefined) { + return; + } + + const isEmpty = isUndefined || children.length === 0 || start >= children.length || count === 0; + if (isEmpty && format & ListFormat.OptionalIfEmpty) { + return; + } + + if (format & ListFormat.BracketsMask) { + write(getOpeningBracket(format)); + } + + if (isEmpty) { + // Write a line terminator if the parent node was multi-line + if (format & ListFormat.MultiLine) { + writeLine(); + } + else if (format & ListFormat.SpaceBetweenBraces) { + write(" "); + } + } + else { + // Write the opening line terminator or leading whitespace. + const mayEmitInterveningComments = (format & ListFormat.NoInterveningComments) === 0; + let shouldEmitInterveningComments = mayEmitInterveningComments; + if (shouldWriteLeadingLineTerminator(parentNode, children, format)) { + writeLine(); + shouldEmitInterveningComments = false; + } + else if (format & ListFormat.SpaceBetweenBraces) { + write(" "); + } + + // Increase the indent, if requested. + if (format & ListFormat.Indented) { + increaseIndent(); + } + + // Emit each child. + let previousSibling: Node; + let shouldDecreaseIndentAfterEmit: boolean; + const delimiter = getDelimiter(format); + for (let i = 0; i < count; i++) { + const child = children[start + i]; + + // Write the delimiter if this is not the first node. + if (previousSibling) { + write(delimiter); + + // Write either a line terminator or whitespace to separate the elements. + if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) { + // If a synthesized node in a single-line list starts on a new + // line, we should increase the indent. + if ((format & (ListFormat.LinesMask | ListFormat.Indented)) === ListFormat.SingleLine) { + increaseIndent(); + shouldDecreaseIndentAfterEmit = true; + } + + writeLine(); + shouldEmitInterveningComments = false; + } + else if (previousSibling && format & ListFormat.SpaceBetweenSiblings) { + write(" "); + } + } + + if (shouldEmitInterveningComments) { + const commentRange = child.commentRange || child; + emitTrailingCommentsOfPosition(commentRange.pos); + } + else { + shouldEmitInterveningComments = mayEmitInterveningComments; + } + + // Emit this child. + emit(child); + + if (shouldDecreaseIndentAfterEmit) { + decreaseIndent(); + shouldDecreaseIndentAfterEmit = false; + } + + previousSibling = child; + } + + // Write a trailing comma, if requested. + const hasTrailingComma = (format & ListFormat.AllowTrailingComma) && children.hasTrailingComma; + if (format & ListFormat.CommaDelimited && hasTrailingComma) { + write(","); + } + + // Decrease the indent, if requested. + if (format & ListFormat.Indented) { + decreaseIndent(); + } + + // Write the closing line terminator or closing whitespace. + if (shouldWriteClosingLineTerminator(parentNode, children, format)) { + writeLine(); + } + else if (format & ListFormat.SpaceBetweenBraces) { + write(" "); + } + } + + if (format & ListFormat.BracketsMask) { + write(getClosingBracket(format)); + } + } + + function writeIfAny(nodes: NodeArray, text: string) { + if (nodes && nodes.length > 0) { + write(text); + } + } + + function writeIfPresent(node: Node, text: string) { + if (node !== undefined) { + write(text); + } + } + + function writeToken(token: SyntaxKind, pos: number, contextNode?: Node) { + const tokenStartPos = emitTokenStart(token, pos, contextNode, shouldSkipLeadingSourceMapForToken, getTokenSourceMapRange); + const tokenEndPos = writeTokenText(token, tokenStartPos); + return emitTokenEnd(token, tokenEndPos, contextNode, shouldSkipTrailingSourceMapForToken, getTokenSourceMapRange); + } + + function shouldSkipLeadingSourceMapForToken(contextNode: Node) { + return (contextNode.emitFlags & NodeEmitFlags.NoTokenLeadingSourceMaps) !== 0; + } + + function shouldSkipTrailingSourceMapForToken(contextNode: Node) { + return (contextNode.emitFlags & NodeEmitFlags.NoTokenTrailingSourceMaps) !== 0; + } + + function writeTokenText(token: SyntaxKind, pos?: number) { + const tokenString = tokenToString(token); + write(tokenString); + return positionIsSynthesized(pos) ? -1 : pos + tokenString.length; + } + + function writeTokenNode(node: Node) { + if (node) { + emitStart(/*range*/ node, /*contextNode*/ node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); + writeTokenText(node.kind); + emitEnd(/*range*/ node, /*contextNode*/ node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); + } + } + + function increaseIndentIf(value: boolean, valueToWriteWhenNotIndenting?: string) { + if (value) { + increaseIndent(); + writeLine(); + } + else if (valueToWriteWhenNotIndenting) { + write(valueToWriteWhenNotIndenting); + } + } + + // Helper function to decrease the indent if we previously indented. Allows multiple + // previous indent values to be considered at a time. This also allows caller to just + // call this once, passing in all their appropriate indent values, instead of needing + // to call this helper function multiple times. + function decreaseIndentIf(value1: boolean, value2?: boolean) { + if (value1) { + decreaseIndent(); + } + if (value2) { + decreaseIndent(); + } + } + + function shouldWriteLeadingLineTerminator(parentNode: Node, children: NodeArray, format: ListFormat) { + if (format & ListFormat.MultiLine) { + return true; + } + + if (format & ListFormat.PreserveLines) { + if (format & ListFormat.PreferNewLine) { + return true; + } + + const firstChild = children[0]; + if (firstChild === undefined) { + return !rangeIsOnSingleLine(parentNode, currentSourceFile); + } + else if (positionIsSynthesized(parentNode.pos) || nodeIsSynthesized(firstChild)) { + return synthesizedNodeStartsOnNewLine(firstChild, format); + } + else { + return !rangeStartPositionsAreOnSameLine(parentNode, firstChild, currentSourceFile); + } + } + else { + return false; + } + } + + function shouldWriteSeparatingLineTerminator(previousNode: Node, nextNode: Node, format: ListFormat) { + if (format & ListFormat.MultiLine) { + return true; + } + else if (format & ListFormat.PreserveLines) { + if (previousNode === undefined || nextNode === undefined) { + return false; + } + else if (nodeIsSynthesized(previousNode) || nodeIsSynthesized(nextNode)) { + return synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format); + } + else { + return !rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile); + } + } + else { + return nextNode.startsOnNewLine; + } + } + + function shouldWriteClosingLineTerminator(parentNode: Node, children: NodeArray, format: ListFormat) { + if (format & ListFormat.MultiLine) { + return (format & ListFormat.NoTrailingNewLine) === 0; + } + else if (format & ListFormat.PreserveLines) { + if (format & ListFormat.PreferNewLine) { + return true; + } + + const lastChild = lastOrUndefined(children); + if (lastChild === undefined) { + return !rangeIsOnSingleLine(parentNode, currentSourceFile); + } + else if (positionIsSynthesized(parentNode.pos) || nodeIsSynthesized(lastChild)) { + return synthesizedNodeStartsOnNewLine(lastChild, format); + } + else { + return !rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile); + } + } + else { + return false; + } + } + + function synthesizedNodeStartsOnNewLine(node: Node, format?: ListFormat) { + if (nodeIsSynthesized(node)) { + const startsOnNewLine = node.startsOnNewLine; + if (startsOnNewLine === undefined) { + return (format & ListFormat.PreferNewLine) !== 0; + } + + return startsOnNewLine; + } + + return (format & ListFormat.PreferNewLine) !== 0; + } + + function needsIndentation(parent: Node, node1: Node, node2: Node): boolean { + parent = skipSynthesizedParentheses(parent); + node1 = skipSynthesizedParentheses(node1); + node2 = skipSynthesizedParentheses(node2); + + // Always use a newline for synthesized code if the synthesizer desires it. + if (node2.startsOnNewLine) { + return true; + } + + return !nodeIsSynthesized(parent) + && !nodeIsSynthesized(node1) + && !nodeIsSynthesized(node2) + && !rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile); + } + + function skipSynthesizedParentheses(node: Node) { + while (node.kind === SyntaxKind.ParenthesizedExpression && nodeIsSynthesized(node)) { + node = (node).expression; + } + + return node; + } + + function getTextOfNode(node: Node, includeTrivia?: boolean): string { + if (isGeneratedIdentifier(node)) { + return getGeneratedIdentifier(node); + } + else if (isIdentifier(node) && (nodeIsSynthesized(node) || !node.parent)) { + return unescapeIdentifier(node.text); + } + else if (node.kind === SyntaxKind.StringLiteral && (node).textSourceNode) { + return getTextOfNode((node).textSourceNode, includeTrivia); + } + else if (isLiteralExpression(node) && (nodeIsSynthesized(node) || !node.parent)) { + return node.text; + } + + return getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); + } + + function getLiteralTextOfNode(node: LiteralLikeNode): string { + if (node.kind === SyntaxKind.StringLiteral && (node).textSourceNode) { + const textSourceNode = (node).textSourceNode; + if (isIdentifier(textSourceNode)) { + return "\"" + escapeNonAsciiCharacters(escapeString(getTextOfNode(textSourceNode))) + "\""; + } + else { + return getLiteralTextOfNode(textSourceNode); + } + } + + return getLiteralText(node, currentSourceFile, languageVersion); + } + + function tryGetConstEnumValue(node: Node): number { + if (compilerOptions.isolatedModules) { + return undefined; + } + + return isPropertyAccessExpression(node) || isElementAccessExpression(node) + ? resolver.getConstantValue(node) + : undefined; + } + + function isSingleLineEmptyBlock(block: Block) { + return !block.multiLine + && block.statements.length === 0 + && rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); + } + + function isUniqueName(name: string): boolean { + return !resolver.hasGlobalName(name) && + !hasProperty(currentFileIdentifiers, name) && + !hasProperty(generatedNameSet, name); + } + function isUniqueLocalName(name: string, container: Node): boolean { - for (let node = container; isNodeDescendentOf(node, container); node = node.nextContainer) { - if (node.locals && name in node.locals) { + for (let node = container; isNodeDescendantOf(node, container); node = node.nextContainer) { + if (node.locals && hasProperty(node.locals, name)) { // We conservatively include alias symbols to cover cases where they're emitted as locals if (node.locals[name].flags & (SymbolFlags.Value | SymbolFlags.ExportValue | SymbolFlags.Alias)) { return false; @@ -417,7984 +2719,270 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge return true; } - interface ConvertedLoopState { - /* - * set of labels that occurred inside the converted loop - * used to determine if labeled jump can be emitted as is or it should be dispatched to calling code - */ - labels?: Map; - /* - * collection of labeled jumps that transfer control outside the converted loop. - * maps store association 'label -> labelMarker' where - * - label - value of label as it appear in code - * - label marker - return value that should be interpreted by calling code as 'jump to