Merge branch 'master' into no_ts_extension

This commit is contained in:
Andy Hanson committed 2016-08-15 07:18:34 -07:00
commit 3de8c22196
205 files changed
+5527 -842

No files matched your search

+9
View File
@@ -7,12 +7,18 @@ node_js:
sudo: false
env:
- workerCount=3
matrix:
fast_finish: true
include:
- os: osx
node_js: stable
osx_image: xcode7.3
env: workerCount=2
allow_failures:
- os: osx
branches:
only:
@@ -28,3 +34,6 @@ install:
cache:
directories:
- node_modules
git:
depth: 1
+5 -2
View File
@@ -35,6 +35,7 @@ import merge2 = require("merge2");
import intoStream = require("into-stream");
import * as os from "os";
import Linter = require("tslint");
import fold = require("travis-fold");
const gulp = helpMaker(originalGulp);
const mochaParallel = require("./scripts/mocha-parallel.js");
const {runTestsInParallel} = mochaParallel;
@@ -449,7 +450,7 @@ gulp.task(tsserverLibraryFile, false, [servicesFile], (done) => {
});
gulp.task("lssl", "Builds language service server library", [tsserverLibraryFile]);
gulp.task("local", "Builds the full compiler and services", [builtLocalCompiler, servicesFile, serverFile, builtGeneratedDiagnosticMessagesJSON]);
gulp.task("local", "Builds the full compiler and services", [builtLocalCompiler, servicesFile, serverFile, builtGeneratedDiagnosticMessagesJSON, tsserverLibraryFile]);
gulp.task("tsc", "Builds only the compiler", [builtLocalCompiler]);
@@ -503,7 +504,7 @@ gulp.task("VerifyLKG", false, [], () => {
return gulp.src(expectedFiles).pipe(gulp.dest(LKGDirectory));
});
gulp.task("LKGInternal", false, ["lib", "local", "lssl"]);
gulp.task("LKGInternal", false, ["lib", "local"]);
gulp.task("LKG", "Makes a new LKG out of the built js files", ["clean", "dontUseDebugMode"], () => {
return runSequence("LKGInternal", "VerifyLKG");
@@ -964,6 +965,7 @@ gulp.task("lint", "Runs tslint on the compiler sources. Optional arguments are:
const fileMatcher = RegExp(cmdLineOptions["files"]);
const lintOptions = getLinterOptions();
let failed = 0;
if (fold.isTravis()) console.log(fold.start("lint"));
return gulp.src(lintTargets)
.pipe(insert.transform((contents, file) => {
if (!fileMatcher.test(file.path)) return contents;
@@ -975,6 +977,7 @@ gulp.task("lint", "Runs tslint on the compiler sources. Optional arguments are:
return contents; // TODO (weswig): Automatically apply fixes? :3
}))
.on("end", () => {
if (fold.isTravis()) console.log(fold.end("lint"));
if (failed > 0) {
console.error("Linter errors.");
process.exit(1);
+59 -5
View File
@@ -5,6 +5,7 @@ var os = require("os");
var path = require("path");
var child_process = require("child_process");
var Linter = require("tslint");
var fold = require("travis-fold");
var runTestsInParallel = require("./scripts/mocha-parallel").runTestsInParallel;
// Variables
@@ -32,6 +33,28 @@ if (process.env.path !== undefined) {
process.env.PATH = nodeModulesPathPrefix + process.env.PATH;
}
function toNs(diff) {
return diff[0] * 1e9 + diff[1];
}
function mark() {
if (!fold.isTravis()) return;
var stamp = process.hrtime();
var id = Math.floor(Math.random() * 0xFFFFFFFF).toString(16);
console.log("travis_time:start:" + id + "\r");
return {
stamp: stamp,
id: id
};
}
function measure(marker) {
if (!fold.isTravis()) return;
var diff = process.hrtime(marker.stamp);
var total = [marker.stamp[0] + diff[0], marker.stamp[1] + diff[1]];
console.log("travis_time:end:" + marker.id + ":start=" + toNs(marker.stamp) + ",finish=" + toNs(total) + ",duration=" + toNs(diff) + "\r");
}
var compilerSources = [
"core.ts",
"performance.ts",
@@ -285,6 +308,7 @@ var builtLocalCompiler = path.join(builtLocalDirectory, compilerFilename);
*/
function compileFile(outFile, sources, prereqs, prefixes, useBuiltCompiler, opts, callback) {
file(outFile, prereqs, function() {
var startCompileTime = mark();
opts = opts || {};
var compilerPath = useBuiltCompiler ? builtLocalCompiler : LKGCompiler;
var options = "--noImplicitAny --noImplicitThis --noEmitOnError --types "
@@ -361,11 +385,13 @@ function compileFile(outFile, sources, prereqs, prefixes, useBuiltCompiler, opts
callback();
}
measure(startCompileTime);
complete();
});
ex.addListener("error", function() {
fs.unlinkSync(outFile);
fail("Compilation of " + outFile + " unsuccessful");
measure(startCompileTime);
});
ex.run();
}, {async: true});
@@ -551,7 +577,7 @@ var tsserverLibraryDefinitionFile = path.join(builtLocalDirectory, "tsserverlibr
compileFile(
tsserverLibraryFile,
languageServiceLibrarySources,
[builtLocalDirectory, copyright].concat(languageServiceLibrarySources),
[builtLocalDirectory, copyright, builtLocalCompiler].concat(languageServiceLibrarySources).concat(libraryTargets),
/*prefixes*/ [copyright],
/*useBuiltCompiler*/ true,
{ noOutFile: false, generateDeclarations: true });
@@ -560,9 +586,19 @@ compileFile(
desc("Builds language service server library");
task("lssl", [tsserverLibraryFile, tsserverLibraryDefinitionFile]);
desc("Emit the start of the build fold");
task("build-fold-start", [] , function() {
if (fold.isTravis()) console.log(fold.start("build"));
});
desc("Emit the end of the build fold");
task("build-fold-end", [] , function() {
if (fold.isTravis()) console.log(fold.end("build"));
});
// Local target to build the compiler and services
desc("Builds the full compiler and services");
task("local", ["generate-diagnostics", "lib", tscFile, servicesFile, nodeDefinitionsFile, serverFile, builtGeneratedDiagnosticMessagesJSON]);
task("local", ["build-fold-start", "generate-diagnostics", "lib", tscFile, servicesFile, nodeDefinitionsFile, serverFile, builtGeneratedDiagnosticMessagesJSON, "lssl", "build-fold-end"]);
// Local target to build only tsc.js
desc("Builds only the compiler");
@@ -617,7 +653,7 @@ task("generate-spec", [specMd]);
// Makes a new LKG. This target does not build anything, but errors if not all the outputs are present in the built/local directory
desc("Makes a new LKG out of the built js files");
task("LKG", ["clean", "release", "local", "lssl"].concat(libraryTargets), function() {
task("LKG", ["clean", "release", "local"].concat(libraryTargets), function() {
var expectedFiles = [tscFile, servicesFile, serverFile, nodePackageFile, nodeDefinitionsFile, standaloneDefinitionsFile, tsserverLibraryFile, tsserverLibraryDefinitionFile].concat(libraryTargets);
var missingFiles = expectedFiles.filter(function (f) {
return !fs.existsSync(f);
@@ -758,6 +794,7 @@ function runConsoleTests(defaultReporter, runInParallel) {
// timeout normally isn't necessary but Travis-CI has been timing out on compiler baselines occasionally
// default timeout is 2sec which really should be enough, but maybe we just need a small amount longer
if(!runInParallel) {
var startTime = mark();
tests = tests ? ' -g "' + tests + '"' : '';
var cmd = "mocha" + (debug ? " --debug-brk" : "") + " -R " + reporter + tests + colors + bail + ' -t ' + testTimeout + ' ' + run;
console.log(cmd);
@@ -766,10 +803,12 @@ function runConsoleTests(defaultReporter, runInParallel) {
process.env.NODE_ENV = "development";
exec(cmd, function () {
process.env.NODE_ENV = savedNodeEnv;
measure(startTime);
runLinter();
finish();
}, function(e, status) {
process.env.NODE_ENV = savedNodeEnv;
measure(startTime);
finish(status);
});
@@ -777,9 +816,10 @@ function runConsoleTests(defaultReporter, runInParallel) {
else {
var savedNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "development";
var startTime = mark();
runTestsInParallel(taskConfigsFolder, run, { testTimeout: testTimeout, noColors: colors === " --no-colors " }, function (err) {
process.env.NODE_ENV = savedNodeEnv;
measure(startTime);
// last worker clean everything and runs linter in case if there were no errors
deleteTemporaryProjectOutput();
jake.rmRf(taskConfigsFolder);
@@ -998,12 +1038,22 @@ var tslintRulesOutFiles = tslintRules.map(function(p) {
return path.join(builtLocalDirectory, "tslint", p + ".js");
});
desc("Compiles tslint rules to js");
task("build-rules", tslintRulesOutFiles);
task("build-rules", ["build-rules-start"].concat(tslintRulesOutFiles).concat(["build-rules-end"]));
tslintRulesFiles.forEach(function(ruleFile, i) {
compileFile(tslintRulesOutFiles[i], [ruleFile], [ruleFile], [], /*useBuiltCompiler*/ false,
{ noOutFile: true, generateDeclarations: false, outDir: path.join(builtLocalDirectory, "tslint")});
});
desc("Emit the start of the build-rules fold");
task("build-rules-start", [] , function() {
if (fold.isTravis()) console.log(fold.start("build-rules"));
});
desc("Emit the end of the build-rules fold");
task("build-rules-end", [] , function() {
if (fold.isTravis()) console.log(fold.end("build-rules"));
});
function getLinterOptions() {
return {
configuration: require("./tslint.json"),
@@ -1047,6 +1097,8 @@ var lintTargets = compilerSources
desc("Runs tslint on the compiler sources. Optional arguments are: f[iles]=regex");
task("lint", ["build-rules"], function() {
if (fold.isTravis()) console.log(fold.start("lint"));
var startTime = mark();
var lintOptions = getLinterOptions();
var failed = 0;
var fileMatcher = RegExp(process.env.f || process.env.file || process.env.files || "");
@@ -1062,6 +1114,8 @@ task("lint", ["build-rules"], function() {
done[target] = true;
}
}
measure(startTime);
if (fold.isTravis()) console.log(fold.end("lint"));
if (failed > 0) {
fail('Linter errors.', failed);
}
+3 -2
View File
@@ -30,8 +30,8 @@
},
"devDependencies": {
"@types/browserify": "latest",
"@types/convert-source-map": "latest",
"@types/chai": "latest",
"@types/convert-source-map": "latest",
"@types/del": "latest",
"@types/glob": "latest",
"@types/gulp": "latest",
@@ -72,13 +72,14 @@
"run-sequence": "latest",
"sorcery": "latest",
"through2": "latest",
"travis-fold": "latest",
"ts-node": "latest",
"tslint": "next",
"typescript": "next"
},
"scripts": {
"pretest": "jake tests",
"test": "jake runtests",
"test": "jake runtests-parallel",
"build": "npm run build:compiler && npm run build:tests",
"build:compiler": "jake local",
"build:tests": "jake tests",
+1 -1
View File
@@ -69,7 +69,7 @@ function checkForUniqueCodes(messages: string[], diagnosticTable: InputDiagnosti
}
function buildUniqueNameMap(names: string[]): ts.Map<string> {
var nameMap: ts.Map<string> = {};
var nameMap = ts.createMap<string>();
var uniqueNames = NameGenerator.ensureUniqueness(names, /* isCaseSensitive */ false, /* isFixed */ undefined);
+6 -7
View File
@@ -1,7 +1,6 @@
import * as Lint from "tslint/lib/lint";
import * as ts from "typescript";
export class Rule extends Lint.Rules.AbstractRule {
public static FAILURE_STRING_FACTORY = (identifier: string) => `Identifier '${identifier}' never appears on the LHS of an assignment - use const instead of let for its declaration.`;
@@ -64,7 +63,7 @@ interface DeclarationUsages {
}
class PreferConstWalker extends Lint.RuleWalker {
private inScopeLetDeclarations: ts.Map<DeclarationUsages>[] = [];
private inScopeLetDeclarations: ts.MapLike<DeclarationUsages>[] = [];
private errors: Lint.RuleFailure[] = [];
private markAssignment(identifier: ts.Identifier) {
const name = identifier.text;
@@ -172,7 +171,7 @@ class PreferConstWalker extends Lint.RuleWalker {
}
private visitAnyForStatement(node: ts.ForOfStatement | ts.ForInStatement) {
const names: ts.Map<DeclarationUsages> = {};
const names: ts.MapLike<DeclarationUsages> = {};
if (isLet(node.initializer)) {
if (node.initializer.kind === ts.SyntaxKind.VariableDeclarationList) {
this.collectLetIdentifiers(node.initializer as ts.VariableDeclarationList, names);
@@ -194,7 +193,7 @@ class PreferConstWalker extends Lint.RuleWalker {
}
visitBlock(node: ts.Block) {
const names: ts.Map<DeclarationUsages> = {};
const names: ts.MapLike<DeclarationUsages> = {};
for (const statement of node.statements) {
if (statement.kind === ts.SyntaxKind.VariableStatement) {
this.collectLetIdentifiers((statement as ts.VariableStatement).declarationList, names);
@@ -205,7 +204,7 @@ class PreferConstWalker extends Lint.RuleWalker {
this.popDeclarations();
}
private collectLetIdentifiers(list: ts.VariableDeclarationList, ret: ts.Map<DeclarationUsages>) {
private collectLetIdentifiers(list: ts.VariableDeclarationList, ret: ts.MapLike<DeclarationUsages>) {
for (const node of list.declarations) {
if (isLet(node) && !isExported(node)) {
this.collectNameIdentifiers(node, node.name, ret);
@@ -213,7 +212,7 @@ class PreferConstWalker extends Lint.RuleWalker {
}
}
private collectNameIdentifiers(declaration: ts.VariableDeclaration, node: ts.Identifier | ts.BindingPattern, table: ts.Map<DeclarationUsages>) {
private collectNameIdentifiers(declaration: ts.VariableDeclaration, node: ts.Identifier | ts.BindingPattern, table: ts.MapLike<DeclarationUsages>) {
if (node.kind === ts.SyntaxKind.Identifier) {
table[(node as ts.Identifier).text] = { declaration, usages: 0 };
}
@@ -222,7 +221,7 @@ class PreferConstWalker extends Lint.RuleWalker {
}
}
private collectBindingPatternIdentifiers(value: ts.VariableDeclaration, pattern: ts.BindingPattern, table: ts.Map<DeclarationUsages>) {
private collectBindingPatternIdentifiers(value: ts.VariableDeclaration, pattern: ts.BindingPattern, table: ts.MapLike<DeclarationUsages>) {
for (const element of pattern.elements) {
this.collectNameIdentifiers(value, element.name, table);
}
+1
View File
@@ -22,3 +22,4 @@ declare module "into-stream" {
}
declare module "sorcery";
declare module "travis-fold";
+19 -21
View File
@@ -135,7 +135,7 @@ namespace ts {
options = opts;
languageVersion = getEmitScriptTarget(options);
inStrictMode = !!file.externalModuleIndicator;
classifiableNames = {};
classifiableNames = createMap<string>();
symbolCount = 0;
Symbol = objectAllocator.getSymbolConstructor();
@@ -183,11 +183,11 @@ namespace ts {
symbol.declarations.push(node);
if (symbolFlags & SymbolFlags.HasExports && !symbol.exports) {
symbol.exports = {};
symbol.exports = createMap<Symbol>();
}
if (symbolFlags & SymbolFlags.HasMembers && !symbol.members) {
symbol.members = {};
symbol.members = createMap<Symbol>();
}
if (symbolFlags & SymbolFlags.Value) {
@@ -318,9 +318,7 @@ namespace 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 = hasProperty(symbolTable, name)
? symbolTable[name]
: (symbolTable[name] = createSymbol(SymbolFlags.None, name));
symbol = symbolTable[name] || (symbolTable[name] = createSymbol(SymbolFlags.None, name));
if (name && (includes & SymbolFlags.Classifiable)) {
classifiableNames[name] = name;
@@ -434,7 +432,7 @@ namespace ts {
if (containerFlags & ContainerFlags.IsContainer) {
container = blockScopeContainer = node;
if (containerFlags & ContainerFlags.HasLocals) {
container.locals = {};
container.locals = createMap<Symbol>();
}
addToContainerChain(container);
}
@@ -1399,7 +1397,8 @@ namespace ts {
const typeLiteralSymbol = createSymbol(SymbolFlags.TypeLiteral, "__type");
addDeclarationToSymbol(typeLiteralSymbol, node, SymbolFlags.TypeLiteral);
typeLiteralSymbol.members = { [symbol.name]: symbol };
typeLiteralSymbol.members = createMap<Symbol>();
typeLiteralSymbol.members[symbol.name] = symbol;
}
function bindObjectLiteralExpression(node: ObjectLiteralExpression) {
@@ -1409,7 +1408,7 @@ namespace ts {
}
if (inStrictMode) {
const seen: Map<ElementKind> = {};
const seen = createMap<ElementKind>();
for (const prop of node.properties) {
if (prop.name.kind !== SyntaxKind.Identifier) {
@@ -1465,7 +1464,7 @@ namespace ts {
// fall through.
default:
if (!blockScopeContainer.locals) {
blockScopeContainer.locals = {};
blockScopeContainer.locals = createMap<Symbol>();
addToContainerChain(blockScopeContainer);
}
declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes);
@@ -1887,18 +1886,17 @@ namespace ts {
}
function bindExportAssignment(node: ExportAssignment | BinaryExpression) {
const boundExpression = node.kind === SyntaxKind.ExportAssignment ? (<ExportAssignment>node).expression : (<BinaryExpression>node).right;
if (!container.symbol || !container.symbol.exports) {
// Export assignment in some sort of block construct
bindAnonymousDeclaration(node, SymbolFlags.Alias, getDeclarationName(node));
}
else if (boundExpression.kind === SyntaxKind.Identifier && node.kind === SyntaxKind.ExportAssignment) {
// An export default clause with an identifier exports all meanings of that identifier
declareSymbol(container.symbol.exports, container.symbol, node, SymbolFlags.Alias, SymbolFlags.PropertyExcludes | SymbolFlags.AliasExcludes);
}
else {
// An export default clause with an expression exports a value
declareSymbol(container.symbol.exports, container.symbol, node, SymbolFlags.Property, SymbolFlags.PropertyExcludes | SymbolFlags.AliasExcludes);
const flags = node.kind === SyntaxKind.ExportAssignment && exportAssignmentIsAlias(<ExportAssignment>node)
// An export default clause with an EntityNameExpression exports all meanings of that identifier
? SymbolFlags.Alias
// An export default clause with any other expression exports a value
: SymbolFlags.Property;
declareSymbol(container.symbol.exports, container.symbol, node, flags, SymbolFlags.PropertyExcludes | SymbolFlags.AliasExcludes);
}
}
@@ -1925,7 +1923,7 @@ namespace ts {
}
}
file.symbol.globalExports = file.symbol.globalExports || {};
file.symbol.globalExports = file.symbol.globalExports || createMap<Symbol>();
declareSymbol(file.symbol.globalExports, file.symbol, node, SymbolFlags.Alias, SymbolFlags.AliasExcludes);
}
@@ -1978,7 +1976,7 @@ namespace ts {
else {
return;
}
assignee.symbol.members = assignee.symbol.members || {};
assignee.symbol.members = assignee.symbol.members || createMap<Symbol>();
// It's acceptable for multiple 'this' assignments of the same identifier to occur
declareSymbol(assignee.symbol.members, assignee.symbol, node, SymbolFlags.Property, SymbolFlags.PropertyExcludes & ~SymbolFlags.Property);
}
@@ -2004,7 +2002,7 @@ namespace ts {
// Set up the members collection if it doesn't exist already
if (!funcSymbol.members) {
funcSymbol.members = {};
funcSymbol.members = createMap<Symbol>();
}
// Declare the method/property
@@ -2053,7 +2051,7 @@ namespace 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.
const prototypeSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Prototype, "prototype");
if (hasProperty(symbol.exports, prototypeSymbol.name)) {
if (symbol.exports[prototypeSymbol.name]) {
if (node.name) {
node.name.parent = node;
}
+459 -335
View File
File diff suppressed because it is too large. Load diff
+5 -5
View File
@@ -470,8 +470,8 @@ namespace ts {
return optionNameMapCache;
}
const optionNameMap: Map<CommandLineOption> = {};
const shortOptionNames: Map<string> = {};
const optionNameMap = createMap<CommandLineOption>();
const shortOptionNames = createMap<string>();
forEach(optionDeclarations, option => {
optionNameMap[option.name.toLowerCase()] = option;
if (option.shortName) {
@@ -958,12 +958,12 @@ namespace 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.
const literalFileMap: Map<string> = {};
const literalFileMap = createMap<string>();
// 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.
const wildcardFileMap: Map<string> = {};
const wildcardFileMap = createMap<string>();
if (include) {
include = validateSpecs(include, errors, /*allowTrailingRecursion*/ false);
@@ -1063,7 +1063,7 @@ namespace ts {
// /a/b/a?z - Watch /a/b directly to catch any new file matching a?z
const rawExcludeRegex = getRegularExpressionForWildcard(exclude, path, "exclude");
const excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i");
const wildcardDirectories: Map<WatchDirectoryFlags> = {};
const wildcardDirectories = createMap<WatchDirectoryFlags>();
if (include !== undefined) {
const recursiveKeys: string[] = [];
for (const file of include) {
+67 -26
View File
@@ -19,8 +19,24 @@ namespace ts {
True = -1
}
const createObject = Object.create;
export function createMap<T>(): Map<T> {
/* tslint:disable:no-null-keyword */
const map: Map<T> = createObject(null);
/* tslint:enable: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["__"];
return map;
}
export function createFileMap<T>(keyMapper?: (key: string) => string): FileMap<T> {
let files: Map<T> = {};
let files = createMap<T>();
return {
get,
set,
@@ -55,7 +71,7 @@ namespace ts {
}
function clear() {
files = {};
files = createMap<T>();
}
function toKey(path: Path): string {
@@ -81,7 +97,7 @@ namespace ts {
* returns a truthy value, then returns that value.
* If no such value is found, the callback is applied to each element of array and undefined is returned.
*/
export function forEach<T, U>(array: T[], callback: (element: T, index: number) => U): U {
export function forEach<T, U>(array: T[] | undefined, callback: (element: T, index: number) => U | undefined): U | undefined {
if (array) {
for (let i = 0, len = array.length; i < len; i++) {
const result = callback(array[i], i);
@@ -93,8 +109,8 @@ namespace ts {
return undefined;
}
/** Works like Array.prototype.find. */
export function find<T>(array: T[], predicate: (element: T, index: number) => boolean): T | undefined {
/** Works like Array.prototype.find, returning `undefined` if no element satisfying the predicate is found. */
export function tryFind<T>(array: T[], predicate: (element: T, index: number) => boolean): T | undefined {
for (let i = 0, len = array.length; i < len; i++) {
const value = array[i];
if (predicate(value, i)) {
@@ -104,6 +120,17 @@ namespace ts {
return undefined;
}
/** Like `forEach`, but assumes existence of array and fails if no truthy value is found. */
export function find<T, U>(array: T[], callback: (element: T, index: number) => U | undefined): U {
for (let i = 0, len = array.length; i < len; i++) {
const result = callback(array[i], i);
if (result) {
return result;
}
}
Debug.fail();
}
export function contains<T>(array: T[], value: T): boolean {
if (array) {
for (const v of array) {
@@ -147,17 +174,29 @@ namespace ts {
return count;
}
/**
* 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<T>(array: T[], f: (x: T) => boolean): T[] {
let result: T[];
if (array) {
result = [];
for (const item of array) {
if (f(item)) {
result.push(item);
const len = array.length;
let i = 0;
while (i < len && f(array[i])) i++;
if (i < len) {
const result = array.slice(0, i);
i++;
while (i < len) {
const item = array[i];
if (f(item)) {
result.push(item);
}
i++;
}
return result;
}
}
return result;
return array;
}
export function filterMutate<T>(array: T[], f: (x: T) => boolean): void {
@@ -322,11 +361,11 @@ namespace ts {
const hasOwnProperty = Object.prototype.hasOwnProperty;
export function hasProperty<T>(map: Map<T>, key: string): boolean {
export function hasProperty<T>(map: MapLike<T>, key: string): boolean {
return hasOwnProperty.call(map, key);
}
export function getKeys<T>(map: Map<T>): string[] {
export function getKeys<T>(map: MapLike<T>): string[] {
const keys: string[] = [];
for (const key in map) {
keys.push(key);
@@ -334,11 +373,15 @@ namespace ts {
return keys;
}
export function getProperty<T>(map: Map<T>, key: string): T {
return hasOwnProperty.call(map, key) ? map[key] : undefined;
export function getProperty<T>(map: MapLike<T>, key: string): T | undefined {
return hasProperty(map, key) ? map[key] : undefined;
}
export function isEmpty<T>(map: Map<T>) {
export function getOrUpdateProperty<T>(map: MapLike<T>, key: string, makeValue: () => T): T {
return hasProperty(map, key) ? map[key] : map[key] = makeValue();
}
export function isEmpty<T>(map: MapLike<T>) {
for (const id in map) {
if (hasProperty(map, id)) {
return false;
@@ -355,7 +398,7 @@ namespace ts {
return <T>result;
}
export function extend<T1 extends Map<{}>, T2 extends Map<{}>>(first: T1 , second: T2): T1 & T2 {
export function extend<T1 extends MapLike<{}>, T2 extends MapLike<{}>>(first: T1 , second: T2): T1 & T2 {
const result: T1 & T2 = <any>{};
for (const id in first) {
(result as any)[id] = first[id];
@@ -368,7 +411,7 @@ namespace ts {
return result;
}
export function forEachValue<T, U>(map: Map<T>, callback: (value: T) => U): U {
export function forEachValue<T, U>(map: MapLike<T>, callback: (value: T) => U): U {
let result: U;
for (const id in map) {
if (result = callback(map[id])) break;
@@ -376,7 +419,7 @@ namespace ts {
return result;
}
export function forEachKey<T, U>(map: Map<T>, callback: (key: string) => U): U {
export function forEachKey<T, U>(map: MapLike<T>, callback: (key: string) => U): U {
let result: U;
for (const id in map) {
if (result = callback(id)) break;
@@ -384,11 +427,11 @@ namespace ts {
return result;
}
export function lookUp<T>(map: Map<T>, key: string): T {
export function lookUp<T>(map: MapLike<T>, key: string): T {
return hasProperty(map, key) ? map[key] : undefined;
}
export function copyMap<T>(source: Map<T>, target: Map<T>): void {
export function copyMap<T>(source: MapLike<T>, target: MapLike<T>): void {
for (const p in source) {
target[p] = source[p];
}
@@ -405,7 +448,7 @@ namespace ts {
* index in the array will be the one associated with the produced key.
*/
export function arrayToMap<T>(array: T[], makeKey: (value: T) => string): Map<T> {
const result: Map<T> = {};
const result = createMap<T>();
forEach(array, value => {
result[makeKey(value)] = value;
@@ -421,7 +464,7 @@ namespace ts {
* @param callback An aggregation function that is called for each entry in the map
* @param initial The initial value for the reduction.
*/
export function reduceProperties<T, U>(map: Map<T>, callback: (aggregate: U, value: T, key: string) => U, initial: U): U {
export function reduceProperties<T, U>(map: MapLike<T>, callback: (aggregate: U, value: T, key: string) => U, initial: U): U {
let result = initial;
if (map) {
for (const key in map) {
@@ -461,9 +504,7 @@ namespace ts {
export let localizedDiagnosticMessages: Map<string> = undefined;
export function getLocaleSpecificMessage(message: DiagnosticMessage) {
return localizedDiagnosticMessages && localizedDiagnosticMessages[message.key]
? localizedDiagnosticMessages[message.key]
: message.message;
return localizedDiagnosticMessages && localizedDiagnosticMessages[message.key] || message.message;
}
export function createFileDiagnostic(file: SourceFile, start: number, length: number, message: DiagnosticMessage, ...args: any[]): Diagnostic;
+5 -5
View File
@@ -269,7 +269,7 @@ namespace ts {
}
if (!usedTypeDirectiveReferences) {
usedTypeDirectiveReferences = {};
usedTypeDirectiveReferences = createMap<string>();
}
for (const directive of typeReferenceDirectives) {
if (!hasProperty(usedTypeDirectiveReferences, directive)) {
@@ -441,7 +441,7 @@ namespace ts {
}
}
function emitEntityName(entityName: EntityName | PropertyAccessExpression) {
function emitEntityName(entityName: EntityNameOrEntityNameExpression) {
const visibilityResult = resolver.isEntityNameVisible(entityName,
// Aliases can be written asynchronously so use correct enclosing declaration
entityName.parent.kind === SyntaxKind.ImportEqualsDeclaration ? entityName.parent : enclosingDeclaration);
@@ -452,9 +452,9 @@ namespace ts {
}
function emitExpressionWithTypeArguments(node: ExpressionWithTypeArguments) {
if (isSupportedExpressionWithTypeArguments(node)) {
if (isEntityNameExpression(node.expression)) {
Debug.assert(node.expression.kind === SyntaxKind.Identifier || node.expression.kind === SyntaxKind.PropertyAccessExpression);
emitEntityName(<Identifier | PropertyAccessExpression>node.expression);
emitEntityName(node.expression);
if (node.typeArguments) {
write("<");
emitCommaList(node.typeArguments, emitType);
@@ -1019,7 +1019,7 @@ namespace ts {
}
function emitTypeOfTypeReference(node: ExpressionWithTypeArguments) {
if (isSupportedExpressionWithTypeArguments(node)) {
if (isEntityNameExpression(node.expression)) {
emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError);
}
else if (!isImplementsList && node.expression.kind === SyntaxKind.NullKeyword) {
+13 -13
View File
@@ -24,7 +24,7 @@ namespace ts {
Return = 1 << 3
}
const entities: Map<number> = {
const entities: MapLike<number> = {
"quot": 0x0022,
"amp": 0x0026,
"apos": 0x0027,
@@ -489,13 +489,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
function setLabeledJump(state: ConvertedLoopState, isBreak: boolean, labelText: string, labelMarker: string): void {
if (isBreak) {
if (!state.labeledNonLocalBreaks) {
state.labeledNonLocalBreaks = {};
state.labeledNonLocalBreaks = createMap<string>();
}
state.labeledNonLocalBreaks[labelText] = labelMarker;
}
else {
if (!state.labeledNonLocalContinues) {
state.labeledNonLocalContinues = {};
state.labeledNonLocalContinues = createMap<string>();
}
state.labeledNonLocalContinues[labelText] = labelMarker;
}
@@ -531,7 +531,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
let currentText: string;
let currentLineMap: number[];
let currentFileIdentifiers: Map<string>;
let renamedDependencies: Map<string>;
let renamedDependencies: MapLike<string>;
let isEs6Module: boolean;
let isCurrentFileExternalModule: boolean;
@@ -577,7 +577,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
const setSourceMapWriterEmit = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? changeSourceMapEmit : function (writer: SourceMapWriter) { };
const moduleEmitDelegates: Map<(node: SourceFile, emitRelativePathAsModuleName?: boolean) => void> = {
const moduleEmitDelegates: MapLike<(node: SourceFile, emitRelativePathAsModuleName?: boolean) => void> = {
[ModuleKind.ES6]: emitES6Module,
[ModuleKind.AMD]: emitAMDModule,
[ModuleKind.System]: emitSystemModule,
@@ -585,7 +585,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
[ModuleKind.CommonJS]: emitCommonJSModule,
};
const bundleEmitDelegates: Map<(node: SourceFile, emitRelativePathAsModuleName?: boolean) => void> = {
const bundleEmitDelegates: MapLike<(node: SourceFile, emitRelativePathAsModuleName?: boolean) => void> = {
[ModuleKind.ES6]() {},
[ModuleKind.AMD]: emitAMDModule,
[ModuleKind.System]: emitSystemModule,
@@ -597,7 +597,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
function doEmit(jsFilePath: string, sourceMapFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean) {
sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit);
generatedNameSet = {};
generatedNameSet = createMap<string>();
nodeToGeneratedName = [];
decoratedClassAliases = [];
isOwnFileEmit = !isBundledEmit;
@@ -3257,7 +3257,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
// 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 = {};
seen = createMap<string>();
}
else {
write(", ");
@@ -3856,7 +3856,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
if (convertedLoopState) {
if (!convertedLoopState.labels) {
convertedLoopState.labels = {};
convertedLoopState.labels = createMap<string>();
}
convertedLoopState.labels[node.label.text] = node.label.text;
}
@@ -6803,7 +6803,7 @@ const _super = (function (geti, seti) {
function collectExternalModuleInfo(sourceFile: SourceFile) {
externalImports = [];
exportSpecifiers = {};
exportSpecifiers = createMap<ExportSpecifier[]>();
exportEquals = undefined;
hasExportStarsToExportValues = false;
for (const node of sourceFile.statements) {
@@ -6842,7 +6842,7 @@ const _super = (function (geti, seti) {
// export { x, y }
for (const specifier of (<ExportDeclaration>node).exportClause.elements) {
const name = (specifier.propertyName || specifier.name).text;
(exportSpecifiers[name] || (exportSpecifiers[name] = [])).push(specifier);
getOrUpdateProperty(exportSpecifiers, name, () => []).push(specifier);
}
}
break;
@@ -7081,7 +7081,7 @@ const _super = (function (geti, seti) {
if (hoistedVars) {
writeLine();
write("var ");
const seen: Map<string> = {};
const seen = createMap<string>();
for (let i = 0; i < hoistedVars.length; i++) {
const local = hoistedVars[i];
const name = local.kind === SyntaxKind.Identifier
@@ -7447,7 +7447,7 @@ const _super = (function (geti, seti) {
writeModuleName(node, emitRelativePathAsModuleName);
write("[");
const groupIndices: Map<number> = {};
const groupIndices = createMap<number>();
const dependencyGroups: DependencyGroup[] = [];
for (let i = 0; i < externalImports.length; i++) {
+2 -2
View File
@@ -595,7 +595,7 @@ namespace ts {
parseDiagnostics = [];
parsingContext = 0;
identifiers = {};
identifiers = createMap<string>();
identifierCount = 0;
nodeCount = 0;
@@ -1084,7 +1084,7 @@ namespace ts {
function internIdentifier(text: string): string {
text = escapeIdentifier(text);
return hasProperty(identifiers, text) ? identifiers[text] : (identifiers[text] = text);
return identifiers[text] || (identifiers[text] = text);
}
// An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues
+2 -2
View File
@@ -10,8 +10,8 @@ namespace ts.performance {
/** Performance measurements for the compiler. */
declare const onProfilerEvent: { (markName: string): void; profiler: boolean; };
let profilerEvent: (markName: string) => void;
let counters: Map<number>;
let measures: Map<number>;
let counters: MapLike<number>;
let measures: MapLike<number>;
/**
* Emit a performance event if ts-profiler is connected. This is primarily used
+61 -59
View File
@@ -119,49 +119,31 @@ namespace ts {
}
function tryReadTypesSection(packageJsonPath: string, baseDirectory: string, state: ModuleResolutionState): string {
let jsonContent: { typings?: string, types?: string, main?: string };
try {
const jsonText = state.host.readFile(packageJsonPath);
jsonContent = jsonText ? <{ typings?: string, types?: string, main?: string }>JSON.parse(jsonText) : {};
}
catch (e) {
// gracefully handle if readFile fails or returns not JSON
jsonContent = {};
const jsonContent = readJson(packageJsonPath, state.host);
function tryReadFromField(fieldName: string) {
if (hasProperty(jsonContent, fieldName)) {
const typesFile = (<any>jsonContent)[fieldName];
if (typeof typesFile === "string") {
const typesFilePath = normalizePath(combinePaths(baseDirectory, typesFile));
if (state.traceEnabled) {
trace(state.host, Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath);
}
return typesFilePath;
}
else {
if (state.traceEnabled) {
trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile);
}
}
}
}
let typesFile: string;
let fieldName: string;
// 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, 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, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, "types", typeof jsonContent.types);
}
}
}
if (typesFile) {
const typesFilePath = normalizePath(combinePaths(baseDirectory, typesFile));
if (state.traceEnabled) {
trace(state.host, Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath);
}
const 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) {
@@ -173,6 +155,17 @@ namespace ts {
return undefined;
}
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 {};
}
}
const typeReferenceExtensions = [".d.ts"];
function getEffectiveTypeRoots(options: CompilerOptions, host: ModuleResolutionHost) {
@@ -718,7 +711,7 @@ namespace ts {
}
function loadNodeModuleFromDirectory(extensions: string[], candidate: string, failedLookupLocation: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): string {
const packageJsonPath = combinePaths(candidate, "package.json");
const packageJsonPath = pathToPackageJson(candidate);
const directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host);
if (directoryExists && state.host.fileExists(packageJsonPath)) {
if (state.traceEnabled) {
@@ -750,6 +743,10 @@ namespace ts {
return loadModuleFromFile(combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state);
}
function pathToPackageJson(directory: string): string {
return combinePaths(directory, "package.json");
}
function loadModuleFromNodeModulesFolder(moduleName: string, directory: string, failedLookupLocations: string[], state: ModuleResolutionState): string {
const nodeModulesFolder = combinePaths(directory, "node_modules");
const nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host);
@@ -849,7 +846,7 @@ namespace ts {
}
export function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost {
const existingDirectories: Map<boolean> = {};
const existingDirectories = createMap<boolean>();
function getCanonicalFileName(fileName: string): string {
// if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form.
@@ -902,7 +899,7 @@ namespace ts {
function writeFileIfUpdated(fileName: string, data: string, writeByteOrderMark: boolean): void {
if (!outputFingerprints) {
outputFingerprints = {};
outputFingerprints = createMap<OutputFingerprint>();
}
const hash = sys.createHash(data);
@@ -1043,7 +1040,7 @@ namespace ts {
return [];
}
const resolutions: T[] = [];
const cache: Map<T> = {};
const cache = createMap<T>();
for (const name of names) {
let result: T;
if (hasProperty(cache, name)) {
@@ -1058,32 +1055,37 @@ namespace ts {
return resolutions;
}
function getInferredTypesRoot(options: CompilerOptions, rootFiles: string[], host: CompilerHost) {
return computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), f => host.getCanonicalFileName(f));
}
/**
* Given a set of options and a set of root files, returns the set of type directive names
* Given a set of options, 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.
*/
export function getAutomaticTypeDirectiveNames(options: CompilerOptions, rootFiles: string[], host: CompilerHost): string[] {
export function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[] {
// Use explicit type list from tsconfig.json
if (options.types) {
return options.types;
}
// Walk the primary type lookup locations
let result: string[] = [];
const result: string[] = [];
if (host.directoryExists && host.getDirectories) {
const typeRoots = getEffectiveTypeRoots(options, host);
if (typeRoots) {
for (const root of typeRoots) {
if (host.directoryExists(root)) {
result = result.concat(host.getDirectories(root));
for (const typeDirectivePath of host.getDirectories(root)) {
const normalized = normalizePath(typeDirectivePath);
const packageJsonPath = pathToPackageJson(combinePaths(root, normalized));
// tslint:disable-next-line:no-null-keyword
const isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null;
if (!isNotNeededPackage) {
// Return just the type directive names
result.push(getBaseFileName(normalized));
}
}
}
}
}
@@ -1099,7 +1101,7 @@ namespace ts {
let noDiagnosticsTypeChecker: TypeChecker;
let classifiableNames: Map<string>;
let resolvedTypeReferenceDirectives: Map<ResolvedTypeReferenceDirective> = {};
let resolvedTypeReferenceDirectives = createMap<ResolvedTypeReferenceDirective>();
let fileProcessingDiagnostics = createDiagnosticCollection();
// The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules.
@@ -1114,10 +1116,10 @@ namespace ts {
// 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.
const modulesWithElidedImports: Map<boolean> = {};
const modulesWithElidedImports = createMap<boolean>();
// Track source files that are source files found by searching under node_modules, as these shouldn't be compiled.
const sourceFilesFoundSearchingNodeModules: Map<boolean> = {};
const sourceFilesFoundSearchingNodeModules = createMap<boolean>();
const start = performance.mark();
@@ -1158,11 +1160,11 @@ namespace ts {
forEach(rootNames, name => processRootFile(name, /*isDefaultLib*/ false));
// load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders
const typeReferences: string[] = getAutomaticTypeDirectiveNames(options, rootNames, host);
const typeReferences: string[] = getAutomaticTypeDirectiveNames(options, host);
if (typeReferences) {
const inferredRoot = getInferredTypesRoot(options, rootNames, host);
const containingFilename = combinePaths(inferredRoot, "__inferred type names__.ts");
// This containingFilename needs to match with the one used in managed-side
const containingFilename = combinePaths(host.getCurrentDirectory(), "__inferred type names__.ts");
const resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename);
for (let i = 0; i < typeReferences.length; i++) {
processTypeReferenceDirective(typeReferences[i], resolutions[i]);
@@ -1245,7 +1247,7 @@ namespace ts {
if (!classifiableNames) {
// Initialize a checker so that all our files are bound.
getTypeChecker();
classifiableNames = {};
classifiableNames = createMap<string>();
for (const sourceFile of files) {
copyMap(sourceFile.classifiableNames, classifiableNames);
@@ -2086,7 +2088,7 @@ namespace ts {
function processImportedModules(file: SourceFile, basePath: string) {
collectExternalModuleReferences(file);
if (file.imports.length || file.moduleAugmentations.length) {
file.resolvedModules = {};
file.resolvedModules = createMap<ResolvedModule>();
const moduleNames = map(concatenate(file.imports, file.moduleAugmentations), getTextOfLiteral);
const resolutions = resolveModuleNamesWorker(moduleNames, getNormalizedAbsolutePath(file.fileName, currentDirectory));
for (let i = 0; i < moduleNames.length; i++) {
+2 -2
View File
@@ -55,7 +55,7 @@ namespace ts {
tryScan<T>(callback: () => T): T;
}
const textToToken: Map<SyntaxKind> = {
const textToToken: MapLike<SyntaxKind> = {
"abstract": SyntaxKind.AbstractKeyword,
"any": SyntaxKind.AnyKeyword,
"as": SyntaxKind.AsKeyword,
@@ -271,7 +271,7 @@ namespace ts {
lookupInUnicodeMap(code, unicodeES3IdentifierPart);
}
function makeReverseMap(source: Map<number>): string[] {
function makeReverseMap(source: MapLike<number>): string[] {
const result: string[] = [];
for (const name in source) {
if (source.hasOwnProperty(name)) {
+12 -17
View File
@@ -233,15 +233,15 @@ namespace ts {
const useNonPollingWatchers = process.env["TSC_NONPOLLING_WATCHER"];
function createWatchedFileSet() {
const dirWatchers: Map<DirectoryWatcher> = {};
const dirWatchers = createMap<DirectoryWatcher>();
// One file can have multiple watchers
const fileWatcherCallbacks: Map<FileWatcherCallback[]> = {};
const fileWatcherCallbacks = createMap<FileWatcherCallback[]>();
return { addFile, removeFile };
function reduceDirWatcherRefCountForFile(fileName: string) {
const dirName = getDirectoryPath(fileName);
if (hasProperty(dirWatchers, dirName)) {
const watcher = dirWatchers[dirName];
const watcher = dirWatchers[dirName];
if (watcher) {
watcher.referenceCount -= 1;
if (watcher.referenceCount <= 0) {
watcher.close();
@@ -251,13 +251,12 @@ namespace ts {
}
function addDirWatcher(dirPath: string): void {
if (hasProperty(dirWatchers, dirPath)) {
const watcher = dirWatchers[dirPath];
let watcher = dirWatchers[dirPath];
if (watcher) {
watcher.referenceCount += 1;
return;
}
const watcher: DirectoryWatcher = _fs.watch(
watcher = _fs.watch(
dirPath,
{ persistent: true },
(eventName: string, relativeFileName: string) => fileEventHandler(eventName, relativeFileName, dirPath)
@@ -268,12 +267,7 @@ namespace ts {
}
function addFileWatcherCallback(filePath: string, callback: FileWatcherCallback): void {
if (hasProperty(fileWatcherCallbacks, filePath)) {
fileWatcherCallbacks[filePath].push(callback);
}
else {
fileWatcherCallbacks[filePath] = [callback];
}
(fileWatcherCallbacks[filePath] || (fileWatcherCallbacks[filePath] = [])).push(callback);
}
function addFile(fileName: string, callback: FileWatcherCallback): WatchedFile {
@@ -289,8 +283,9 @@ namespace ts {
}
function removeFileWatcherCallback(filePath: string, callback: FileWatcherCallback) {
if (hasProperty(fileWatcherCallbacks, filePath)) {
const newCallbacks = copyListRemovingItem(callback, fileWatcherCallbacks[filePath]);
const callbacks = fileWatcherCallbacks[filePath];
if (callbacks) {
const newCallbacks = copyListRemovingItem(callback, callbacks);
if (newCallbacks.length === 0) {
delete fileWatcherCallbacks[filePath];
}
@@ -306,7 +301,7 @@ namespace ts {
? undefined
: ts.getNormalizedAbsolutePath(relativeFileName, baseDirPath);
// Some applications save a working file via rename operations
if ((eventName === "change" || eventName === "rename") && hasProperty(fileWatcherCallbacks, fileName)) {
if ((eventName === "change" || eventName === "rename") && fileWatcherCallbacks[fileName]) {
for (const fileCallback of fileWatcherCallbacks[fileName]) {
fileCallback(fileName);
}
+4 -4
View File
@@ -122,7 +122,7 @@ namespace ts {
const gutterSeparator = " ";
const resetEscapeSequence = "\u001b[0m";
const ellipsis = "...";
const categoryFormatMap: Map<string> = {
const categoryFormatMap: MapLike<string> = {
[DiagnosticCategory.Warning]: yellowForegroundEscapeSequence,
[DiagnosticCategory.Error]: redForegroundEscapeSequence,
[DiagnosticCategory.Message]: blueForegroundEscapeSequence,
@@ -432,7 +432,7 @@ namespace ts {
}
// reset the cache of existing files
cachedExistingFiles = {};
cachedExistingFiles = createMap<boolean>();
const compileResult = compile(rootFileNames, compilerOptions, compilerHost);
@@ -676,7 +676,7 @@ namespace ts {
const usageColumn: string[] = []; // Things like "-d, --declaration" go in here.
const descriptionColumn: string[] = [];
const optionsDescriptionMap: Map<string[]> = {}; // Map between option.description and list of option.type if it is a kind
const optionsDescriptionMap = createMap<string[]>(); // Map between option.description and list of option.type if it is a kind
for (let i = 0; i < optsList.length; i++) {
const option = optsList[i];
@@ -786,7 +786,7 @@ namespace ts {
return;
function serializeCompilerOptions(options: CompilerOptions): Map<string | number | boolean> {
const result: Map<string | number | boolean> = {};
const result = createMap<string | number | boolean>();
const optionsNameMap = getOptionNameMap().optionNameMap;
for (const name in options) {
+37 -15
View File
@@ -1,9 +1,13 @@
namespace ts {
export interface Map<T> {
export interface MapLike<T> {
[index: string]: T;
}
export interface Map<T> extends MapLike<T> {
__mapBrand: any;
}
// branded string type used to store absolute, normalized and canonicalized paths
// arbitrary file name can be converted to Path via toPath function
export type Path = string & { __pathBrand: any };
@@ -982,13 +986,19 @@ namespace ts {
multiLine?: boolean;
}
export type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression;
export type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression;
// @kind(SyntaxKind.PropertyAccessExpression)
export interface PropertyAccessExpression extends MemberExpression, Declaration {
expression: LeftHandSideExpression;
name: Identifier;
}
export type IdentifierOrPropertyAccess = Identifier | PropertyAccessExpression;
/** Brand for a PropertyAccessExpression which, like a QualifiedName, consists of a sequence of identifiers separated by dots. */
export interface PropertyAccessEntityNameExpression extends PropertyAccessExpression {
_propertyAccessExpressionLikeQualifiedNameBrand?: any;
expression: EntityNameExpression;
}
// @kind(SyntaxKind.ElementAccessExpression)
export interface ElementAccessExpression extends MemberExpression {
@@ -1606,6 +1616,16 @@ namespace ts {
antecedent: FlowNode;
}
export type FlowType = Type | IncompleteType;
// Incomplete types occur during control flow analysis of loops. An IncompleteType
// is distinguished from a regular type by a flags value of zero. Incomplete type
// objects are internal to the getFlowTypeOfRefecence function and never escape it.
export interface IncompleteType {
flags: TypeFlags; // No flags set
type: Type; // The type marked incomplete
}
export interface AmdDependency {
path: string;
name: string;
@@ -1630,7 +1650,7 @@ namespace ts {
// this map is used by transpiler to supply alternative names for dependencies (i.e. in case of bundling)
/* @internal */
renamedDependencies?: Map<string>;
renamedDependencies?: MapLike<string>;
/**
* lib.d.ts should have a reference comment like
@@ -2021,7 +2041,7 @@ 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: EntityName | Expression, enclosingDeclaration: Node): SymbolVisibilityResult;
isEntityNameVisible(entityName: EntityNameOrEntityNameExpression, enclosingDeclaration: Node): SymbolVisibilityResult;
// Returns the constant value this property access resolves to, or 'undefined' for a non-constant
getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number;
getReferencedValueDeclaration(reference: Identifier): Declaration;
@@ -2030,7 +2050,7 @@ namespace ts {
moduleExportsSomeValue(moduleReferenceExpression: Expression): boolean;
isArgumentsLocalBinding(node: Identifier): boolean;
getExternalModuleFileFromDeclaration(declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration | ModuleDeclaration): SourceFile;
getTypeReferenceDirectivesForEntityName(name: EntityName | PropertyAccessExpression): string[];
getTypeReferenceDirectivesForEntityName(name: EntityNameOrEntityNameExpression): string[];
getTypeReferenceDirectivesForSymbol(symbol: Symbol, meaning?: SymbolFlags): string[];
}
@@ -2150,6 +2170,8 @@ namespace ts {
mapper?: TypeMapper; // Type mapper for instantiation alias
referenced?: boolean; // True if alias symbol has been referenced as a value
containingType?: UnionOrIntersectionType; // Containing union or intersection type for synthetic property
hasCommonType?: boolean; // True if constituents of synthetic property all have same type
isDiscriminantProperty?: boolean; // True if discriminant synthetic property
resolvedExports?: SymbolTable; // Resolved exports of module
exportsChecked?: boolean; // True if exports of external module have been checked
isDeclarationWithCollidingName?: boolean; // True if symbol is block scoped redeclaration
@@ -2160,9 +2182,7 @@ namespace ts {
/* @internal */
export interface TransientSymbol extends Symbol, SymbolLinks { }
export interface SymbolTable {
[index: string]: Symbol;
}
export type SymbolTable = Map<Symbol>;
/** Represents a "prefix*suffix" pattern. */
/* @internal */
@@ -2359,6 +2379,7 @@ namespace ts {
export interface TupleType extends ObjectType {
elementTypes: Type[]; // Element types
thisType?: Type; // This-type of tuple (only needed for tuples that are constraints of type parameters)
}
export interface UnionOrIntersectionType extends Type {
@@ -2545,7 +2566,7 @@ namespace ts {
}
export type RootPaths = string[];
export type PathSubstitutions = Map<string[]>;
export type PathSubstitutions = MapLike<string[]>;
export type TsConfigOnlyOptions = RootPaths | PathSubstitutions;
export type CompilerOptionsValue = string | number | boolean | (string | number)[] | TsConfigOnlyOptions;
@@ -2705,7 +2726,7 @@ namespace ts {
fileNames: string[];
raw?: any;
errors: Diagnostic[];
wildcardDirectories?: Map<WatchDirectoryFlags>;
wildcardDirectories?: MapLike<WatchDirectoryFlags>;
}
export const enum WatchDirectoryFlags {
@@ -2715,13 +2736,13 @@ namespace ts {
export interface ExpandResult {
fileNames: string[];
wildcardDirectories: Map<WatchDirectoryFlags>;
wildcardDirectories: MapLike<WatchDirectoryFlags>;
}
/* @internal */
export interface CommandLineOptionBase {
name: string;
type: "string" | "number" | "boolean" | "object" | "list" | Map<number | string>; // a value of a primitive type, or an object literal mapping named values to actual values
type: "string" | "number" | "boolean" | "object" | "list" | MapLike<number | string>; // a value of a primitive type, or an object literal mapping named values to actual values
isFilePath?: boolean; // True if option value is a path or fileName
shortName?: string; // A short mnemonic for convenience - for instance, 'h' can be used in place of 'help'
description?: DiagnosticMessage; // The message describing what the command line switch does
@@ -2737,7 +2758,7 @@ namespace ts {
/* @internal */
export interface CommandLineOptionOfCustomType extends CommandLineOptionBase {
type: Map<number | string>; // an object literal mapping named values to actual values
type: MapLike<number | string>; // an object literal mapping named values to actual values
}
/* @internal */
@@ -2900,6 +2921,7 @@ namespace ts {
directoryExists?(directoryName: string): boolean;
realpath?(path: string): string;
getCurrentDirectory?(): string;
getDirectories?(path: string): string[];
}
export interface ResolvedModule {
+30 -43
View File
@@ -87,14 +87,14 @@ namespace ts {
return node.end - node.pos;
}
export function mapIsEqualTo<T>(map1: Map<T>, map2: Map<T>): boolean {
export function mapIsEqualTo<T>(map1: MapLike<T>, map2: MapLike<T>): boolean {
if (!map1 || !map2) {
return map1 === map2;
}
return containsAll(map1, map2) && containsAll(map2, map1);
}
function containsAll<T>(map: Map<T>, other: Map<T>): boolean {
function containsAll<T>(map: MapLike<T>, other: MapLike<T>): boolean {
for (const key in map) {
if (!hasProperty(map, key)) {
continue;
@@ -126,7 +126,7 @@ namespace ts {
}
export function hasResolvedModule(sourceFile: SourceFile, moduleNameText: string): boolean {
return sourceFile.resolvedModules && hasProperty(sourceFile.resolvedModules, moduleNameText);
return !!(sourceFile.resolvedModules && sourceFile.resolvedModules[moduleNameText]);
}
export function getResolvedModule(sourceFile: SourceFile, moduleNameText: string): ResolvedModule {
@@ -135,7 +135,7 @@ namespace ts {
export function setResolvedModule(sourceFile: SourceFile, moduleNameText: string, resolvedModule: ResolvedModule): void {
if (!sourceFile.resolvedModules) {
sourceFile.resolvedModules = {};
sourceFile.resolvedModules = createMap<ResolvedModule>();
}
sourceFile.resolvedModules[moduleNameText] = resolvedModule;
@@ -143,7 +143,7 @@ namespace ts {
export function setResolvedTypeReferenceDirective(sourceFile: SourceFile, typeReferenceDirectiveName: string, resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective): void {
if (!sourceFile.resolvedTypeReferenceDirectiveNames) {
sourceFile.resolvedTypeReferenceDirectiveNames = {};
sourceFile.resolvedTypeReferenceDirectiveNames = createMap<ResolvedTypeReferenceDirective>();
}
sourceFile.resolvedTypeReferenceDirectiveNames[typeReferenceDirectiveName] = resolvedTypeReferenceDirective;
@@ -166,7 +166,7 @@ namespace ts {
}
for (let i = 0; i < names.length; i++) {
const newResolution = newResolutions[i];
const oldResolution = oldResolutions && hasProperty(oldResolutions, names[i]) ? oldResolutions[names[i]] : undefined;
const oldResolution = oldResolutions && oldResolutions[names[i]];
const changed =
oldResolution
? !newResolution || !comparer(oldResolution, newResolution)
@@ -1033,14 +1033,14 @@ namespace ts {
&& (<PropertyAccessExpression | ElementAccessExpression>node).expression.kind === SyntaxKind.SuperKeyword;
}
export function getEntityNameFromTypeNode(node: TypeNode): EntityName | Expression {
export function getEntityNameFromTypeNode(node: TypeNode): EntityNameOrEntityNameExpression {
if (node) {
switch (node.kind) {
case SyntaxKind.TypeReference:
return (<TypeReferenceNode>node).typeName;
case SyntaxKind.ExpressionWithTypeArguments:
return (<ExpressionWithTypeArguments>node).expression;
Debug.assert(isEntityNameExpression((<ExpressionWithTypeArguments>node).expression));
return <EntityNameExpression>(<ExpressionWithTypeArguments>node).expression;
case SyntaxKind.Identifier:
case SyntaxKind.QualifiedName:
return (<EntityName><Node>node);
@@ -1569,6 +1569,7 @@ namespace ts {
case SyntaxKind.MethodSignature:
case SyntaxKind.ModuleDeclaration:
case SyntaxKind.NamespaceImport:
case SyntaxKind.NamespaceExportDeclaration:
case SyntaxKind.Parameter:
case SyntaxKind.PropertyAssignment:
case SyntaxKind.PropertyDeclaration:
@@ -1693,8 +1694,8 @@ namespace ts {
// import * as <symbol> from ...
// import { x as <symbol> } from ...
// export { x as <symbol> } from ...
// export = ...
// export default ...
// export = <EntityNameExpression>
// export default <EntityNameExpression>
export function isAliasSymbolDeclaration(node: Node): boolean {
return node.kind === SyntaxKind.ImportEqualsDeclaration ||
node.kind === SyntaxKind.NamespaceExportDeclaration ||
@@ -1702,7 +1703,11 @@ namespace ts {
node.kind === SyntaxKind.NamespaceImport ||
node.kind === SyntaxKind.ImportSpecifier ||
node.kind === SyntaxKind.ExportSpecifier ||
node.kind === SyntaxKind.ExportAssignment && (<ExportAssignment>node).expression.kind === SyntaxKind.Identifier;
node.kind === SyntaxKind.ExportAssignment && exportAssignmentIsAlias(<ExportAssignment>node);
}
export function exportAssignmentIsAlias(node: ExportAssignment): boolean {
return isEntityNameExpression(node.expression);
}
export function getClassExtendsHeritageClauseElement(node: ClassLikeDeclaration | InterfaceDeclaration) {
@@ -1965,7 +1970,7 @@ namespace ts {
export function createDiagnosticCollection(): DiagnosticCollection {
let nonFileDiagnostics: Diagnostic[] = [];
const fileDiagnostics: Map<Diagnostic[]> = {};
const fileDiagnostics = createMap<Diagnostic[]>();
let diagnosticsModified = false;
let modificationCount = 0;
@@ -1983,12 +1988,11 @@ namespace ts {
}
function reattachFileDiagnostics(newFile: SourceFile): void {
if (!hasProperty(fileDiagnostics, newFile.fileName)) {
return;
}
for (const diagnostic of fileDiagnostics[newFile.fileName]) {
diagnostic.file = newFile;
const diagnostics = fileDiagnostics[newFile.fileName];
if (diagnostics) {
for (const diagnostic of diagnostics) {
diagnostic.file = newFile;
}
}
}
@@ -2029,9 +2033,7 @@ namespace ts {
forEach(nonFileDiagnostics, pushDiagnostic);
for (const key in fileDiagnostics) {
if (hasProperty(fileDiagnostics, key)) {
forEach(fileDiagnostics[key], pushDiagnostic);
}
forEach(fileDiagnostics[key], pushDiagnostic);
}
return sortAndDeduplicateDiagnostics(allDiagnostics);
@@ -2046,9 +2048,7 @@ namespace ts {
nonFileDiagnostics = sortAndDeduplicateDiagnostics(nonFileDiagnostics);
for (const key in fileDiagnostics) {
if (hasProperty(fileDiagnostics, key)) {
fileDiagnostics[key] = sortAndDeduplicateDiagnostics(fileDiagnostics[key]);
}
fileDiagnostics[key] = sortAndDeduplicateDiagnostics(fileDiagnostics[key]);
}
}
}
@@ -2059,7 +2059,7 @@ namespace 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.
const escapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
const escapedCharsMap: Map<string> = {
const escapedCharsMap: MapLike<string> = {
"\0": "\\0",
"\t": "\\t",
"\v": "\\v",
@@ -2680,22 +2680,9 @@ namespace ts {
isClassLike(node.parent.parent);
}
// Returns false if this heritage clause element's expression contains something unsupported
// (i.e. not a name or dotted name).
export function isSupportedExpressionWithTypeArguments(node: ExpressionWithTypeArguments): boolean {
return isSupportedExpressionWithTypeArgumentsRest(node.expression);
}
function isSupportedExpressionWithTypeArgumentsRest(node: Expression): boolean {
if (node.kind === SyntaxKind.Identifier) {
return true;
}
else if (isPropertyAccessExpression(node)) {
return isSupportedExpressionWithTypeArgumentsRest(node.expression);
}
else {
return false;
}
export function isEntityNameExpression(node: Expression): node is EntityNameExpression {
return node.kind === SyntaxKind.Identifier ||
node.kind === SyntaxKind.PropertyAccessExpression && isEntityNameExpression((<PropertyAccessExpression>node).expression);
}
export function isRightSideOfQualifiedNameOrPropertyAccess(node: Node) {
@@ -2728,7 +2715,7 @@ namespace ts {
/** Return ".ts" or ".tsx" if that is the extension. */
export function tryExtractTypeScriptExtension(fileName: string): string | undefined {
return find(supportedTypescriptExtensionsWithDtsFirst, extension => fileExtensionIs(fileName, extension));
return tryFind(supportedTypescriptExtensionsWithDtsFirst, extension => fileExtensionIs(fileName, extension));
}
// Must have '.d.ts' first because if '.ts' goes first, that will be detected as the extension instead of '.d.ts'.
const supportedTypescriptExtensionsWithDtsFirst = supportedTypeScriptExtensions.slice().reverse();
+4 -4
View File
@@ -52,7 +52,7 @@ class CompilerBaselineRunner extends RunnerBase {
private makeUnitName(name: string, root: string) {
const path = ts.toPath(name, root, (fileName) => Harness.Compiler.getCanonicalFileName(fileName));
const pathStart = ts.toPath(Harness.IO.getCurrentDirectory(), "", (fileName) => Harness.Compiler.getCanonicalFileName(fileName));
return pathStart === "" ? path : path.replace(pathStart, "/");
return pathStart ? path.replace(pathStart, "/") : path;
};
public checkTestCodeOutput(fileName: string) {
@@ -291,8 +291,8 @@ class CompilerBaselineRunner extends RunnerBase {
const fullWalker = new TypeWriterWalker(program, /*fullTypeCheck*/ true);
const fullResults: ts.Map<TypeWriterResult[]> = {};
const pullResults: ts.Map<TypeWriterResult[]> = {};
const fullResults: ts.MapLike<TypeWriterResult[]> = {};
const pullResults: ts.MapLike<TypeWriterResult[]> = {};
for (const sourceFile of allFiles) {
fullResults[sourceFile.unitName] = fullWalker.getTypeAndSymbols(sourceFile.unitName);
@@ -338,7 +338,7 @@ class CompilerBaselineRunner extends RunnerBase {
}
}
function generateBaseLine(typeWriterResults: ts.Map<TypeWriterResult[]>, isSymbolBaseline: boolean): string {
function generateBaseLine(typeWriterResults: ts.MapLike<TypeWriterResult[]>, isSymbolBaseline: boolean): string {
const typeLines: string[] = [];
const typeMap: { [fileName: string]: { [lineNum: number]: string[]; } } = {};
+43 -77
View File
@@ -95,7 +95,7 @@ namespace FourSlash {
export import IndentStyle = ts.IndentStyle;
const entityMap: ts.Map<string> = {
const entityMap: ts.MapLike<string> = {
"&": "&amp;",
"\"": "&quot;",
"'": "&#39;",
@@ -204,7 +204,7 @@ namespace FourSlash {
public formatCodeOptions: ts.FormatCodeOptions;
private inputFiles: ts.Map<string> = {}; // Map between inputFile's fileName and its content for easily looking up when resolving references
private inputFiles: ts.MapLike<string> = {}; // Map between inputFile's fileName and its content for easily looking up when resolving references
// Add input file which has matched file name with the given reference-file path.
// This is necessary when resolveReference flag is specified
@@ -249,6 +249,7 @@ namespace FourSlash {
if (compilationOptions.typeRoots) {
compilationOptions.typeRoots = compilationOptions.typeRoots.map(p => ts.getNormalizedAbsolutePath(p, this.basePath));
}
compilationOptions.skipDefaultLibCheck = true;
const languageServiceAdapter = this.getLanguageServiceAdapter(testType, this.cancellationToken, compilationOptions);
this.languageServiceAdapterHost = languageServiceAdapter.getHost();
@@ -376,7 +377,7 @@ namespace FourSlash {
public verifyErrorExistsBetweenMarkers(startMarkerName: string, endMarkerName: string, negative: boolean) {
const startMarker = this.getMarkerByName(startMarkerName);
const endMarker = this.getMarkerByName(endMarkerName);
const predicate = function (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) {
const predicate = function(errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) {
return ((errorMinChar === startPos) && (errorLimChar === endPos)) ? true : false;
};
@@ -428,12 +429,12 @@ namespace FourSlash {
let predicate: (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) => boolean;
if (after) {
predicate = function (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) {
predicate = function(errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) {
return ((errorMinChar >= startPos) && (errorLimChar >= startPos)) ? true : false;
};
}
else {
predicate = function (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) {
predicate = function(errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) {
return ((errorMinChar <= startPos) && (errorLimChar <= startPos)) ? true : false;
};
}
@@ -458,7 +459,7 @@ namespace FourSlash {
endPos = endMarker.position;
}
errors.forEach(function (error: ts.Diagnostic) {
errors.forEach(function(error: ts.Diagnostic) {
if (predicate(error.start, error.start + error.length, startPos, endPos)) {
exists = true;
}
@@ -475,7 +476,7 @@ namespace FourSlash {
Harness.IO.log("Unexpected error(s) found. Error list is:");
}
errors.forEach(function (error: ts.Diagnostic) {
errors.forEach(function(error: ts.Diagnostic) {
Harness.IO.log(" minChar: " + error.start +
", limChar: " + (error.start + error.length) +
", message: " + ts.flattenDiagnosticMessageText(error.messageText, Harness.IO.newLine()) + "\n");
@@ -593,7 +594,7 @@ namespace FourSlash {
public noItemsWithSameNameButDifferentKind(): void {
const completions = this.getCompletionListAtCaret();
const uniqueItems: ts.Map<string> = {};
const uniqueItems: ts.MapLike<string> = {};
for (const item of completions.entries) {
if (!ts.hasProperty(uniqueItems, item.name)) {
uniqueItems[item.name] = item.kind;
@@ -1348,14 +1349,7 @@ namespace FourSlash {
}
// Enters lines of text at the current caret position
public type(text: string) {
return this.typeHighFidelity(text);
}
// Enters lines of text at the current caret position, invoking
// language service APIs to mimic Visual Studio's behavior
// as much as possible
private typeHighFidelity(text: string) {
public type(text: string, highFidelity = false) {
let offset = this.currentCaretPosition;
const prevChar = " ";
const checkCadence = (text.length >> 2) + 1;
@@ -1364,24 +1358,26 @@ namespace FourSlash {
// Make the edit
const ch = text.charAt(i);
this.languageServiceAdapterHost.editScript(this.activeFile.fileName, offset, offset, ch);
this.languageService.getBraceMatchingAtPosition(this.activeFile.fileName, offset);
if (highFidelity) {
this.languageService.getBraceMatchingAtPosition(this.activeFile.fileName, offset);
}
this.updateMarkersForEdit(this.activeFile.fileName, offset, offset, ch);
offset++;
if (ch === "(" || ch === ",") {
/* Signature help*/
this.languageService.getSignatureHelpItems(this.activeFile.fileName, offset);
}
else if (prevChar === " " && /A-Za-z_/.test(ch)) {
/* Completions */
this.languageService.getCompletionsAtPosition(this.activeFile.fileName, offset);
}
if (highFidelity) {
if (ch === "(" || ch === ",") {
/* Signature help*/
this.languageService.getSignatureHelpItems(this.activeFile.fileName, offset);
}
else if (prevChar === " " && /A-Za-z_/.test(ch)) {
/* Completions */
this.languageService.getCompletionsAtPosition(this.activeFile.fileName, offset);
}
if (i % checkCadence === 0) {
this.checkPostEditInvariants();
// this.languageService.getSyntacticDiagnostics(this.activeFile.fileName);
// this.languageService.getSemanticDiagnostics(this.activeFile.fileName);
if (i % checkCadence === 0) {
this.checkPostEditInvariants();
}
}
// Handle post-keystroke formatting
@@ -1389,14 +1385,12 @@ namespace FourSlash {
const edits = this.languageService.getFormattingEditsAfterKeystroke(this.activeFile.fileName, offset, ch, this.formatCodeOptions);
if (edits.length) {
offset += this.applyEdits(this.activeFile.fileName, edits, /*isFormattingEdit*/ true);
// this.checkPostEditInvariants();
}
}
}
// Move the caret to wherever we ended up
this.currentCaretPosition = offset;
this.fixCaretPosition();
this.checkPostEditInvariants();
}
@@ -1415,7 +1409,6 @@ namespace FourSlash {
const edits = this.languageService.getFormattingEditsForRange(this.activeFile.fileName, start, offset, this.formatCodeOptions);
if (edits.length) {
offset += this.applyEdits(this.activeFile.fileName, edits, /*isFormattingEdit*/ true);
this.checkPostEditInvariants();
}
}
@@ -1638,8 +1631,8 @@ namespace FourSlash {
return this.testData.ranges;
}
public rangesByText(): ts.Map<Range[]> {
const result: ts.Map<Range[]> = {};
public rangesByText(): ts.MapLike<Range[]> {
const result: ts.MapLike<Range[]> = {};
for (const range of this.getRanges()) {
const text = this.rangeText(range);
(ts.getProperty(result, text) || (result[text] = [])).push(range);
@@ -1897,7 +1890,7 @@ namespace FourSlash {
public verifyBraceCompletionAtPosition(negative: boolean, openingBrace: string) {
const openBraceMap: ts.Map<ts.CharacterCodes> = {
const openBraceMap: ts.MapLike<ts.CharacterCodes> = {
"(": ts.CharacterCodes.openParen,
"{": ts.CharacterCodes.openBrace,
"[": ts.CharacterCodes.openBracket,
@@ -2269,40 +2262,12 @@ namespace FourSlash {
export function runFourSlashTestContent(basePath: string, testType: FourSlashTestType, content: string, fileName: string): void {
// Parse out the files and their metadata
const testData = parseTestData(basePath, content, fileName);
const state = new TestState(basePath, testType, testData);
let result = "";
const fourslashFile: Harness.Compiler.TestFile = {
unitName: Harness.Compiler.fourslashFileName,
content: undefined,
};
const testFile: Harness.Compiler.TestFile = {
unitName: fileName,
content: content
};
const host = Harness.Compiler.createCompilerHost(
[fourslashFile, testFile],
(fn, contents) => result = contents,
ts.ScriptTarget.Latest,
Harness.IO.useCaseSensitiveFileNames(),
Harness.IO.getCurrentDirectory());
const program = ts.createProgram([Harness.Compiler.fourslashFileName, fileName], { outFile: "fourslashTestOutput.js", noResolve: true, target: ts.ScriptTarget.ES3 }, host);
const sourceFile = host.getSourceFile(fileName, ts.ScriptTarget.ES3);
const diagnostics = ts.getPreEmitDiagnostics(program, sourceFile);
if (diagnostics.length > 0) {
throw new Error(`Error compiling ${fileName}: ` +
diagnostics.map(e => ts.flattenDiagnosticMessageText(e.messageText, Harness.IO.newLine())).join("\r\n"));
const output = ts.transpileModule(content, { reportDiagnostics: true });
if (output.diagnostics.length > 0) {
throw new Error(`Syntax error in ${basePath}: ${output.diagnostics[0].messageText}`);
}
program.emit(sourceFile);
ts.Debug.assert(!!result);
runCode(result, state);
runCode(output.outputText, state);
}
function runCode(code: string, state: TestState): void {
@@ -2395,13 +2360,14 @@ ${code}
// Comment line, check for global/file @options and record them
const match = optionRegex.exec(line.substr(2));
if (match) {
const fileMetadataNamesIndex = fileMetadataNames.indexOf(match[1]);
const [key, value] = match.slice(1);
const fileMetadataNamesIndex = fileMetadataNames.indexOf(key);
if (fileMetadataNamesIndex === -1) {
// Check if the match is already existed in the global options
if (globalOptions[match[1]] !== undefined) {
throw new Error("Global Option : '" + match[1] + "' is already existed");
if (globalOptions[key] !== undefined) {
throw new Error(`Global option '${key}' already exists`);
}
globalOptions[match[1]] = match[2];
globalOptions[key] = value;
}
else {
if (fileMetadataNamesIndex === fileMetadataNames.indexOf(metadataOptionNames.fileName)) {
@@ -2416,12 +2382,12 @@ ${code}
resetLocalData();
}
currentFileName = basePath + "/" + match[2];
currentFileOptions[match[1]] = match[2];
currentFileName = basePath + "/" + value;
currentFileOptions[key] = value;
}
else {
// Add other fileMetadata flag
currentFileOptions[match[1]] = match[2];
currentFileOptions[key] = value;
}
}
}
@@ -2509,7 +2475,7 @@ ${code}
}
const marker: Marker = {
fileName: fileName,
fileName,
position: location.position,
data: markerValue
};
@@ -2526,7 +2492,7 @@ ${code}
function recordMarker(fileName: string, location: LocationInformation, name: string, markerMap: MarkerMap, markers: Marker[]): Marker {
const marker: Marker = {
fileName: fileName,
fileName,
position: location.position
};
@@ -2772,7 +2738,7 @@ namespace FourSlashInterface {
return this.state.getRanges();
}
public rangesByText(): ts.Map<FourSlash.Range[]> {
public rangesByText(): ts.MapLike<FourSlash.Range[]> {
return this.state.rangesByText();
}
+3 -3
View File
@@ -750,7 +750,7 @@ namespace Harness {
export function readDirectory(path: string, extension?: string[], exclude?: string[], include?: string[]) {
const fs = new Utils.VirtualFileSystem(path, useCaseSensitiveFileNames());
for (const file in listFiles(path)) {
for (const file of listFiles(path)) {
fs.addFile(file);
}
return ts.matchFiles(path, extension, exclude, include, useCaseSensitiveFileNames(), getCurrentDirectory(), path => {
@@ -848,7 +848,7 @@ namespace Harness {
export const defaultLibFileName = "lib.d.ts";
export const es2015DefaultLibFileName = "lib.es2015.d.ts";
const libFileNameSourceFileMap: ts.Map<ts.SourceFile> = {
const libFileNameSourceFileMap: ts.MapLike<ts.SourceFile> = {
[defaultLibFileName]: createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + "lib.es5.d.ts"), /*languageVersion*/ ts.ScriptTarget.Latest)
};
@@ -1002,7 +1002,7 @@ namespace Harness {
{ name: "symlink", type: "string" }
];
let optionsIndex: ts.Map<ts.CommandLineOption>;
let optionsIndex: ts.MapLike<ts.CommandLineOption>;
function getCommandLineOption(name: string): ts.CommandLineOption {
if (!optionsIndex) {
optionsIndex = {};
+3 -3
View File
@@ -123,7 +123,7 @@ namespace Harness.LanguageService {
}
export class LanguageServiceAdapterHost {
protected fileNameToScript: ts.Map<ScriptInfo> = {};
protected fileNameToScript: ts.MapLike<ScriptInfo> = {};
constructor(protected cancellationToken = DefaultHostCancellationToken.Instance,
protected settings = ts.getDefaultCompilerOptions()) {
@@ -235,7 +235,7 @@ namespace Harness.LanguageService {
this.getModuleResolutionsForFile = (fileName) => {
const scriptInfo = this.getScriptInfo(fileName);
const preprocessInfo = ts.preProcessFile(scriptInfo.content, /*readImportFiles*/ true);
const imports: ts.Map<string> = {};
const imports: ts.MapLike<string> = {};
for (const module of preprocessInfo.importedFiles) {
const resolutionInfo = ts.resolveModuleName(module.fileName, fileName, compilerOptions, moduleResolutionHost);
if (resolutionInfo.resolvedModule) {
@@ -248,7 +248,7 @@ namespace Harness.LanguageService {
const scriptInfo = this.getScriptInfo(fileName);
if (scriptInfo) {
const preprocessInfo = ts.preProcessFile(scriptInfo.content, /*readImportFiles*/ false);
const resolutions: ts.Map<ts.ResolvedTypeReferenceDirective> = {};
const resolutions: ts.MapLike<ts.ResolvedTypeReferenceDirective> = {};
const settings = this.nativeHost.getCompilationSettings();
for (const typeReferenceDirective of preprocessInfo.typeReferenceDirectives) {
const resolutionInfo = ts.resolveTypeReferenceDirective(typeReferenceDirective.fileName, fileName, settings, moduleResolutionHost);
+1 -1
View File
@@ -253,7 +253,7 @@ class ProjectRunner extends RunnerBase {
moduleResolution: ts.ModuleResolutionKind.Classic, // currently all tests use classic module resolution kind, this will change in the future
};
// Set the values specified using json
const optionNameMap: ts.Map<ts.CommandLineOption> = {};
const optionNameMap: ts.MapLike<ts.CommandLineOption> = {};
ts.forEach(ts.optionDeclarations, option => {
optionNameMap[option.name] = option;
});
@@ -6,8 +6,8 @@ namespace ts {
content: string;
}
function createDefaultServerHost(fileMap: Map<File>): server.ServerHost {
const existingDirectories: Map<boolean> = {};
function createDefaultServerHost(fileMap: MapLike<File>): server.ServerHost {
const existingDirectories: MapLike<boolean> = {};
forEachValue(fileMap, v => {
let dir = getDirectoryPath(v.name);
let previous: string;
@@ -193,7 +193,7 @@ namespace ts {
content: `export var y = 1`
};
const fileMap: Map<File> = { [root.name]: root };
const fileMap: MapLike<File> = { [root.name]: root };
const serverHost = createDefaultServerHost(fileMap);
const originalFileExists = serverHost.fileExists;
+15 -15
View File
@@ -10,7 +10,7 @@ namespace ts {
const map = arrayToMap(files, f => f.name);
if (hasDirectoryExists) {
const directories: Map<string> = {};
const directories: MapLike<string> = {};
for (const f of files) {
let name = getDirectoryPath(f.name);
while (true) {
@@ -282,7 +282,7 @@ namespace ts {
});
describe("Module resolution - relative imports", () => {
function test(files: Map<string>, currentDirectory: string, rootFiles: string[], expectedFilesCount: number, relativeNamesToCheck: string[]) {
function test(files: MapLike<string>, currentDirectory: string, rootFiles: string[], expectedFilesCount: number, relativeNamesToCheck: string[]) {
const options: CompilerOptions = { module: ModuleKind.CommonJS };
const host: CompilerHost = {
getSourceFile: (fileName: string, languageVersion: ScriptTarget) => {
@@ -318,7 +318,7 @@ namespace ts {
}
it("should find all modules", () => {
const files: Map<string> = {
const files: MapLike<string> = {
"/a/b/c/first/shared.ts": `
class A {}
export = A`,
@@ -337,7 +337,7 @@ export = C;
});
it("should find modules in node_modules", () => {
const files: Map<string> = {
const files: MapLike<string> = {
"/parent/node_modules/mod/index.d.ts": "export var x",
"/parent/app/myapp.ts": `import {x} from "mod"`
};
@@ -345,7 +345,7 @@ export = C;
});
it("should find file referenced via absolute and relative names", () => {
const files: Map<string> = {
const files: MapLike<string> = {
"/a/b/c.ts": `/// <reference path="b.ts"/>`,
"/a/b/b.ts": "var x"
};
@@ -355,10 +355,10 @@ export = C;
describe("Files with different casing", () => {
const library = createSourceFile("lib.d.ts", "", ScriptTarget.ES5);
function test(files: Map<string>, options: CompilerOptions, currentDirectory: string, useCaseSensitiveFileNames: boolean, rootFiles: string[], diagnosticCodes: number[]): void {
function test(files: MapLike<string>, options: CompilerOptions, currentDirectory: string, useCaseSensitiveFileNames: boolean, rootFiles: string[], diagnosticCodes: number[]): void {
const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames);
if (!useCaseSensitiveFileNames) {
const f: Map<string> = {};
const f: MapLike<string> = {};
for (const fileName in files) {
f[getCanonicalFileName(fileName)] = files[fileName];
}
@@ -395,7 +395,7 @@ export = C;
}
it("should succeed when the same file is referenced using absolute and relative names", () => {
const files: Map<string> = {
const files: MapLike<string> = {
"/a/b/c.ts": `/// <reference path="d.ts"/>`,
"/a/b/d.ts": "var x"
};
@@ -403,7 +403,7 @@ export = C;
});
it("should fail when two files used in program differ only in casing (tripleslash references)", () => {
const files: Map<string> = {
const files: MapLike<string> = {
"/a/b/c.ts": `/// <reference path="D.ts"/>`,
"/a/b/d.ts": "var x"
};
@@ -411,7 +411,7 @@ export = C;
});
it("should fail when two files used in program differ only in casing (imports)", () => {
const files: Map<string> = {
const files: MapLike<string> = {
"/a/b/c.ts": `import {x} from "D"`,
"/a/b/d.ts": "export var x"
};
@@ -419,7 +419,7 @@ export = C;
});
it("should fail when two files used in program differ only in casing (imports, relative module names)", () => {
const files: Map<string> = {
const files: MapLike<string> = {
"moduleA.ts": `import {x} from "./ModuleB"`,
"moduleB.ts": "export var x"
};
@@ -427,7 +427,7 @@ export = C;
});
it("should fail when two files exist on disk that differs only in casing", () => {
const files: Map<string> = {
const files: MapLike<string> = {
"/a/b/c.ts": `import {x} from "D"`,
"/a/b/D.ts": "export var x",
"/a/b/d.ts": "export var y"
@@ -436,7 +436,7 @@ export = C;
});
it("should fail when module name in 'require' calls has inconsistent casing", () => {
const files: Map<string> = {
const files: MapLike<string> = {
"moduleA.ts": `import a = require("./ModuleC")`,
"moduleB.ts": `import a = require("./moduleC")`,
"moduleC.ts": "export var x"
@@ -445,7 +445,7 @@ export = C;
});
it("should fail when module names in 'require' calls has inconsistent casing and current directory has uppercase chars", () => {
const files: Map<string> = {
const files: MapLike<string> = {
"/a/B/c/moduleA.ts": `import a = require("./ModuleC")`,
"/a/B/c/moduleB.ts": `import a = require("./moduleC")`,
"/a/B/c/moduleC.ts": "export var x",
@@ -457,7 +457,7 @@ import b = require("./moduleB");
test(files, { module: ts.ModuleKind.CommonJS, forceConsistentCasingInFileNames: true }, "/a/B/c", /*useCaseSensitiveFileNames*/ false, ["moduleD.ts"], [1149]);
});
it("should not fail when module names in 'require' calls has consistent casing and current directory has uppercase chars", () => {
const files: Map<string> = {
const files: MapLike<string> = {
"/a/B/c/moduleA.ts": `import a = require("./moduleC")`,
"/a/B/c/moduleB.ts": `import a = require("./moduleC")`,
"/a/B/c/moduleC.ts": "export var x",
@@ -96,7 +96,7 @@ namespace ts {
}
function createTestCompilerHost(texts: NamedSourceText[], target: ScriptTarget): CompilerHost {
const files: Map<SourceFileWithText> = {};
const files: MapLike<SourceFileWithText> = {};
for (const t of texts) {
const file = <SourceFileWithText>createSourceFile(t.name, t.text.getFullText(), target);
file.sourceText = t.text;
@@ -152,7 +152,7 @@ namespace ts {
return program;
}
function getSizeOfMap(map: Map<any>): number {
function getSizeOfMap(map: MapLike<any>): number {
let size = 0;
for (const id in map) {
if (hasProperty(map, id)) {
@@ -174,7 +174,7 @@ namespace ts {
assert.isTrue(expected.primary === actual.primary, `'primary': expected '${expected.primary}' to be equal to '${actual.primary}'`);
}
function checkCache<T>(caption: string, program: Program, fileName: string, expectedContent: Map<T>, getCache: (f: SourceFile) => Map<T>, entryChecker: (expected: T, original: T) => void): void {
function checkCache<T>(caption: string, program: Program, fileName: string, expectedContent: MapLike<T>, getCache: (f: SourceFile) => MapLike<T>, entryChecker: (expected: T, original: T) => void): void {
const file = program.getSourceFile(fileName);
assert.isTrue(file !== undefined, `cannot find file ${fileName}`);
const cache = getCache(file);
@@ -203,11 +203,11 @@ namespace ts {
}
}
function checkResolvedModulesCache(program: Program, fileName: string, expectedContent: Map<ResolvedModule>): void {
function checkResolvedModulesCache(program: Program, fileName: string, expectedContent: MapLike<ResolvedModule>): void {
checkCache("resolved modules", program, fileName, expectedContent, f => f.resolvedModules, checkResolvedModule);
}
function checkResolvedTypeDirectivesCache(program: Program, fileName: string, expectedContent: Map<ResolvedTypeReferenceDirective>): void {
function checkResolvedTypeDirectivesCache(program: Program, fileName: string, expectedContent: MapLike<ResolvedTypeReferenceDirective>): void {
checkCache("resolved type directives", program, fileName, expectedContent, f => f.resolvedTypeReferenceDirectiveNames, checkResolvedTypeDirective);
}
+3 -3
View File
@@ -106,7 +106,7 @@ namespace ts.server {
describe("onMessage", () => {
it("should not throw when commands are executed with invalid arguments", () => {
let i = 0;
for (name in CommandNames) {
for (const name in CommandNames) {
if (!Object.prototype.hasOwnProperty.call(CommandNames, name)) {
continue;
}
@@ -362,8 +362,8 @@ namespace ts.server {
class InProcClient {
private server: InProcSession;
private seq = 0;
private callbacks: ts.Map<(resp: protocol.Response) => void> = {};
private eventHandlers: ts.Map<(args: any) => void> = {};
private callbacks: ts.MapLike<(resp: protocol.Response) => void> = {};
private eventHandlers: ts.MapLike<(args: any) => void> = {};
handle(msg: protocol.Message): void {
if (msg.type === "response") {
@@ -68,7 +68,7 @@ namespace ts {
return entry;
}
function sizeOfMap(map: Map<any>): number {
function sizeOfMap(map: MapLike<any>): number {
let n = 0;
for (const name in map) {
if (hasProperty(map, name)) {
@@ -78,7 +78,7 @@ namespace ts {
return n;
}
function checkMapKeys(caption: string, map: Map<any>, expectedKeys: string[]) {
function checkMapKeys(caption: string, map: MapLike<any>, expectedKeys: string[]) {
assert.equal(sizeOfMap(map), expectedKeys.length, `${caption}: incorrect size of map`);
for (const name of expectedKeys) {
assert.isTrue(hasProperty(map, name), `${caption} is expected to contain ${name}, actual keys: ${getKeys(map)}`);
@@ -126,8 +126,8 @@ namespace ts {
private getCanonicalFileName: (s: string) => string;
private toPath: (f: string) => Path;
private callbackQueue: TimeOutCallback[] = [];
readonly watchedDirectories: Map<{ cb: DirectoryWatcherCallback, recursive: boolean }[]> = {};
readonly watchedFiles: Map<FileWatcherCallback[]> = {};
readonly watchedDirectories: MapLike<{ cb: DirectoryWatcherCallback, recursive: boolean }[]> = {};
readonly watchedFiles: MapLike<FileWatcherCallback[]> = {};
constructor(public useCaseSensitiveFileNames: boolean, private executingFilePath: string, private currentDirectory: string, fileOrFolderList: FileOrFolder[]) {
this.getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames);
+24
View File
@@ -343,6 +343,30 @@ interface ObjectConstructor {
defineProperty(o: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): any;
}
interface ReadonlyArray<T> {
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: T, index: number, obj: ReadonlyArray<T>) => boolean, thisArg?: any): T | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: T) => boolean, thisArg?: any): number;
}
interface RegExp {
/**
* Returns a string indicating the flags of the regular expression in question. This field is read-only.
+20
View File
@@ -63,6 +63,26 @@ interface ArrayConstructor {
from<T>(iterable: Iterable<T>): Array<T>;
}
interface ReadonlyArray<T> {
/** Iterator */
[Symbol.iterator](): IterableIterator<T>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, T]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<T>;
}
interface IArguments {
/** Iterator */
[Symbol.iterator](): IterableIterator<any>;
+5
View File
@@ -1108,6 +1108,11 @@ interface Array<T> {
* Removes the last element from an array and returns it.
*/
pop(): T | undefined;
/**
* Combines two or more arrays.
* @param items Additional items to add to the end of array1.
*/
concat(...items: T[][]): T[];
/**
* Combines two or more arrays.
* @param items Additional items to add to the end of array1.
+1 -1
View File
@@ -21,7 +21,7 @@ namespace ts.server {
export class SessionClient implements LanguageService {
private sequence: number = 0;
private lineMaps: ts.Map<number[]> = {};
private lineMaps: ts.Map<number[]> = ts.createMap<number[]>();
private messages: string[] = [];
private lastRenameEntry: RenameEntry;
+8 -8
View File
@@ -130,7 +130,7 @@ namespace ts.server {
const path = toPath(containingFile, this.host.getCurrentDirectory(), this.getCanonicalFileName);
const currentResolutionsInFile = cache.get(path);
const newResolutions: Map<T> = {};
const newResolutions = createMap<T>();
const resolvedModules: R[] = [];
const compilerOptions = this.getCompilationSettings();
@@ -378,7 +378,7 @@ namespace ts.server {
export interface ProjectOptions {
// these fields can be present in the project file
files?: string[];
wildcardDirectories?: ts.Map<ts.WatchDirectoryFlags>;
wildcardDirectories?: ts.MapLike<ts.WatchDirectoryFlags>;
compilerOptions?: ts.CompilerOptions;
}
@@ -391,7 +391,7 @@ namespace ts.server {
// Used to keep track of what directories are watched for this project
directoriesWatchedForTsconfig: string[] = [];
program: ts.Program;
filenameToSourceFile: ts.Map<ts.SourceFile> = {};
filenameToSourceFile = ts.createMap<ts.SourceFile>();
updateGraphSeq = 0;
/** Used for configured projects which may have multiple open roots */
openRefCount = 0;
@@ -504,7 +504,7 @@ namespace ts.server {
return;
}
this.filenameToSourceFile = {};
this.filenameToSourceFile = createMap<SourceFile>();
const sourceFiles = this.program.getSourceFiles();
for (let i = 0, len = sourceFiles.length; i < len; i++) {
const normFilename = ts.normalizePath(sourceFiles[i].fileName);
@@ -613,7 +613,7 @@ namespace ts.server {
}
export class ProjectService {
filenameToScriptInfo: ts.Map<ScriptInfo> = {};
filenameToScriptInfo = ts.createMap<ScriptInfo>();
// open, non-configured root files
openFileRoots: ScriptInfo[] = [];
// projects built from openFileRoots
@@ -625,12 +625,12 @@ namespace ts.server {
// open files that are roots of a configured project
openFileRootsConfigured: ScriptInfo[] = [];
// a path to directory watcher map that detects added tsconfig files
directoryWatchersForTsconfig: ts.Map<FileWatcher> = {};
directoryWatchersForTsconfig = ts.createMap<FileWatcher>();
// count of how many projects are using the directory watcher. If the
// number becomes 0 for a watcher, then we should close it.
directoryWatchersRefCount: ts.Map<number> = {};
directoryWatchersRefCount = ts.createMap<number>();
hostConfiguration: HostConfiguration;
timerForDetectingProjectFileListChanges: Map<any> = {};
timerForDetectingProjectFileListChanges = createMap<any>();
constructor(public host: ServerHost, public psLogger: Logger, public eventHandler?: ProjectServiceEventHandler) {
// ts.disableIncrementalParsing = true;
+1 -1
View File
@@ -1061,7 +1061,7 @@ namespace ts.server {
return { response, responseRequired: true };
}
private handlers: Map<(request: protocol.Request) => { response?: any, responseRequired?: boolean }> = {
private handlers: MapLike<(request: protocol.Request) => { response?: any, responseRequired?: boolean }> = {
[CommandNames.Exit]: () => {
this.exit();
return { responseRequired: false };
+2
View File
@@ -10,6 +10,8 @@
"types": []
},
"files": [
"../services/shims.ts",
"../services/utilities.ts",
"editorServices.ts",
"protocol.d.ts",
"session.ts"
+2 -2
View File
@@ -47,7 +47,7 @@ namespace ts.JsTyping {
{ cachedTypingPaths: string[], newTypingNames: string[], filesToWatch: string[] } {
// A typing name to typing file path mapping
const inferredTypings: Map<string> = {};
const inferredTypings = createMap<string>();
if (!typingOptions || !typingOptions.enableAutoDiscovery) {
return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] };
@@ -62,7 +62,7 @@ namespace ts.JsTyping {
safeList = result.config;
}
else {
safeList = {};
safeList = createMap<string>();
};
}
+1 -1
View File
@@ -234,7 +234,7 @@ namespace ts.NavigationBar {
/** Merge declarations of the same kind. */
function mergeChildren(children: NavigationBarNode[]): void {
const nameToItems: Map<NavigationBarNode | NavigationBarNode[]> = {};
const nameToItems = createMap<NavigationBarNode | NavigationBarNode[]>();
filterMutate(children, child => {
const decl = <Declaration>child.node;
const name = decl.name && nodeText(decl.name);
+1 -1
View File
@@ -113,7 +113,7 @@ namespace 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.
const stringToWordSpans: Map<TextSpan[]> = {};
const stringToWordSpans = createMap<TextSpan[]>();
pattern = pattern.trim();
+20 -13
View File
@@ -975,7 +975,7 @@ namespace ts {
}
private computeNamedDeclarations(): Map<Declaration[]> {
const result: Map<Declaration[]> = {};
const result = createMap<Declaration[]>();
forEachChild(this, visit);
@@ -1886,7 +1886,7 @@ namespace ts {
};
}
// Cache host information about scrip Should be refreshed
// Cache host information about script should be refreshed
// at each language service public entry point, since we don't know when
// set of scripts handled by the host changes.
class HostCache {
@@ -2025,7 +2025,7 @@ namespace ts {
fileName?: string;
reportDiagnostics?: boolean;
moduleName?: string;
renamedDependencies?: Map<string>;
renamedDependencies?: MapLike<string>;
}
export interface TranspileOutput {
@@ -2243,7 +2243,7 @@ namespace ts {
export function createDocumentRegistry(useCaseSensitiveFileNames?: boolean, currentDirectory = ""): DocumentRegistry {
// Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have
// for those settings.
const buckets: Map<FileMap<DocumentRegistryEntry>> = {};
const buckets = createMap<FileMap<DocumentRegistryEntry>>();
const getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames);
function getKeyForCompilationSettings(settings: CompilerOptions): DocumentRegistryBucketKey {
@@ -4102,7 +4102,7 @@ namespace ts {
* do not occur at the current position and have not otherwise been typed.
*/
function filterNamedImportOrExportCompletionItems(exportsOfModule: Symbol[], namedImportsOrExports: ImportOrExportSpecifier[]): Symbol[] {
const existingImportsOrExports: Map<boolean> = {};
const existingImportsOrExports = createMap<boolean>();
for (const element of namedImportsOrExports) {
// If this is the current item we are editing right now, do not filter it out
@@ -4132,7 +4132,7 @@ namespace ts {
return contextualMemberSymbols;
}
const existingMemberNames: Map<boolean> = {};
const existingMemberNames = createMap<boolean>();
for (const m of existingMembers) {
// Ignore omitted expressions for missing members
if (m.kind !== SyntaxKind.PropertyAssignment &&
@@ -4175,7 +4175,7 @@ namespace ts {
* do not occur at the current position and have not otherwise been typed.
*/
function filterJsxAttributes(symbols: Symbol[], attributes: NodeArray<JsxAttribute | JsxSpreadAttribute>): Symbol[] {
const seenNames: Map<boolean> = {};
const seenNames = createMap<boolean>();
for (const attr of attributes) {
// If this is the current item we are editing right now, do not filter it out
if (attr.getStart() <= position && position <= attr.getEnd()) {
@@ -4317,7 +4317,7 @@ namespace ts {
function getCompletionEntriesFromSymbols(symbols: Symbol[], entries: CompletionEntry[], location: Node, performCharacterChecks: boolean): Map<string> {
const start = timestamp();
const uniqueNames: Map<string> = {};
const uniqueNames = createMap<string>();
if (symbols) {
for (const symbol of symbols) {
const entry = createCompletionEntry(symbol, location, performCharacterChecks);
@@ -4830,7 +4830,14 @@ namespace ts {
}
if (symbolFlags & SymbolFlags.Alias) {
addNewLineIfDisplayPartsExist();
displayParts.push(keywordPart(SyntaxKind.ImportKeyword));
if (symbol.declarations[0].kind === SyntaxKind.NamespaceExportDeclaration) {
displayParts.push(keywordPart(SyntaxKind.ExportKeyword));
displayParts.push(spacePart());
displayParts.push(keywordPart(SyntaxKind.NamespaceKeyword));
}
else {
displayParts.push(keywordPart(SyntaxKind.ImportKeyword));
}
displayParts.push(spacePart());
addFullSymbolName(symbol);
ts.forEach(symbol.declarations, declaration => {
@@ -5311,7 +5318,7 @@ namespace ts {
return undefined;
}
const fileNameToDocumentHighlights: Map<DocumentHighlights> = {};
const fileNameToDocumentHighlights = createMap<DocumentHighlights>();
const result: DocumentHighlights[] = [];
for (const referencedSymbol of referencedSymbols) {
for (const referenceEntry of referencedSymbol.references) {
@@ -6706,7 +6713,7 @@ namespace ts {
// Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions
if (rootSymbol.parent && rootSymbol.parent.flags & (SymbolFlags.Class | SymbolFlags.Interface)) {
getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, /*previousIterationSymbolsCache*/ {});
getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, /*previousIterationSymbolsCache*/ createMap<Symbol>());
}
});
@@ -6827,7 +6834,7 @@ namespace ts {
// see if any is in the list
if (rootSymbol.parent && rootSymbol.parent.flags & (SymbolFlags.Class | SymbolFlags.Interface)) {
const result: Symbol[] = [];
getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, /*previousIterationSymbolsCache*/ {});
getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, /*previousIterationSymbolsCache*/ createMap<Symbol>());
return forEach(result, s => searchSymbols.indexOf(s) >= 0 ? s : undefined);
}
@@ -8311,7 +8318,7 @@ namespace ts {
}
function initializeNameTable(sourceFile: SourceFile): void {
const nameTable: Map<number> = {};
const nameTable = createMap<number>();
walk(sourceFile);
sourceFile.nameTable = nameTable;
+30 -5
View File
@@ -72,8 +72,13 @@ namespace ts {
directoryExists(directoryName: string): boolean;
}
/** Public interface of the the of a config service shim instance.*/
export interface CoreServicesShimHost extends Logger, ModuleResolutionHost {
/** Public interface of the core-services host instance used in managed side */
export interface CoreServicesShimHost extends Logger {
directoryExists(directoryName: string): boolean;
fileExists(fileName: string): boolean;
getCurrentDirectory(): string;
getDirectories(path: string): string;
/**
* Returns a JSON-encoded value of the type: string[]
*
@@ -81,9 +86,14 @@ namespace ts {
* when enumerating the directory.
*/
readDirectory(rootDir: string, extension: string, basePaths?: string, excludeEx?: string, includeFileEx?: string, includeDirEx?: string, depth?: number): string;
useCaseSensitiveFileNames?(): boolean;
getCurrentDirectory(): string;
/**
* Read arbitary text files on disk, i.e. when resolution procedure needs the content of 'package.json' to determine location of bundled typings for node modules
*/
readFile(fileName: string): string;
realpath?(path: string): string;
trace(s: string): void;
useCaseSensitiveFileNames?(): boolean;
}
///
@@ -240,6 +250,7 @@ namespace ts {
}
export interface CoreServicesShim extends Shim {
getAutomaticTypeDirectiveNames(compilerOptionsJson: string): string;
getPreProcessedFileInfo(fileName: string, sourceText: IScriptSnapshot): string;
getTSConfigFileInfo(fileName: string, sourceText: IScriptSnapshot): string;
getDefaultCompilationSettings(): string;
@@ -492,6 +503,10 @@ namespace ts {
private readDirectoryFallback(rootDir: string, extension: string, exclude: string[]) {
return JSON.parse(this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude)));
}
public getDirectories(path: string): string[] {
return JSON.parse(this.shimHost.getDirectories(path));
}
}
function simpleForwardCall(logger: Logger, actionDescription: string, action: () => any, logPerformance: boolean): any {
@@ -1003,7 +1018,7 @@ namespace ts {
public getPreProcessedFileInfo(fileName: string, sourceTextSnapshot: IScriptSnapshot): string {
return this.forwardJSONCall(
"getPreProcessedFileInfo('" + fileName + "')",
`getPreProcessedFileInfo('${fileName}')`,
() => {
// for now treat files as JavaScript
const result = preProcessFile(sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()), /* readImportFiles */ true, /* detectJavaScriptImports */ true);
@@ -1017,6 +1032,16 @@ namespace ts {
});
}
public getAutomaticTypeDirectiveNames(compilerOptionsJson: string): string {
return this.forwardJSONCall(
`getAutomaticTypeDirectiveNames('${compilerOptionsJson}')`,
() => {
const compilerOptions = <CompilerOptions>JSON.parse(compilerOptionsJson);
return getAutomaticTypeDirectiveNames(compilerOptions, this.host);
}
);
}
private convertFileReferences(refs: FileReference[]): IFileReference[] {
if (!refs) {
return undefined;
@@ -20,7 +20,7 @@ declare var path: any;
import * as ts from "typescript";
function watch(rootFileNames: string[], options: ts.CompilerOptions) {
const files: ts.Map<{ version: number }> = {};
const files: ts.MapLike<{ version: number }> = {};
// initialize the list of files
rootFileNames.forEach(fileName => {
@@ -0,0 +1,17 @@
tests/cases/compiler/a.ts(2,5): error TS2339: Property 'default' does not exist on type 'typeof "tests/cases/compiler/b"'.
tests/cases/compiler/a.ts(3,5): error TS2339: Property 'default' does not exist on type 'typeof "tests/cases/compiler/b"'.
==== tests/cases/compiler/a.ts (2 errors) ====
import Foo = require("./b");
Foo.default.bar();
~~~~~~~
!!! error TS2339: Property 'default' does not exist on type 'typeof "tests/cases/compiler/b"'.
Foo.default.default.foo();
~~~~~~~
!!! error TS2339: Property 'default' does not exist on type 'typeof "tests/cases/compiler/b"'.
==== tests/cases/compiler/b.d.ts (0 errors) ====
export function foo();
export function bar();
@@ -0,0 +1,17 @@
//// [tests/cases/compiler/allowSyntheticDefaultImports10.ts] ////
//// [b.d.ts]
export function foo();
export function bar();
//// [a.ts]
import Foo = require("./b");
Foo.default.bar();
Foo.default.default.foo();
//// [a.js]
"use strict";
var Foo = require("./b");
Foo.default.bar();
Foo.default.default.foo();
@@ -0,0 +1,28 @@
//// [tests/cases/compiler/allowSyntheticDefaultImports7.ts] ////
//// [b.d.ts]
export function foo();
export function bar();
//// [a.ts]
import { default as Foo } from "./b";
Foo.bar();
Foo.foo();
//// [a.js]
System.register(["./b"], function(exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
var b_1;
return {
setters:[
function (b_1_1) {
b_1 = b_1_1;
}],
execute: function() {
b_1["default"].bar();
b_1["default"].foo();
}
}
});
@@ -0,0 +1,22 @@
=== tests/cases/compiler/b.d.ts ===
export function foo();
>foo : Symbol(foo, Decl(b.d.ts, 0, 0))
export function bar();
>bar : Symbol(bar, Decl(b.d.ts, 0, 22))
=== tests/cases/compiler/a.ts ===
import { default as Foo } from "./b";
>default : Symbol(Foo, Decl(a.ts, 0, 8))
>Foo : Symbol(Foo, Decl(a.ts, 0, 8))
Foo.bar();
>Foo.bar : Symbol(Foo.bar, Decl(b.d.ts, 0, 22))
>Foo : Symbol(Foo, Decl(a.ts, 0, 8))
>bar : Symbol(Foo.bar, Decl(b.d.ts, 0, 22))
Foo.foo();
>Foo.foo : Symbol(Foo.foo, Decl(b.d.ts, 0, 0))
>Foo : Symbol(Foo, Decl(a.ts, 0, 8))
>foo : Symbol(Foo.foo, Decl(b.d.ts, 0, 0))
@@ -0,0 +1,24 @@
=== tests/cases/compiler/b.d.ts ===
export function foo();
>foo : () => any
export function bar();
>bar : () => any
=== tests/cases/compiler/a.ts ===
import { default as Foo } from "./b";
>default : typeof Foo
>Foo : typeof Foo
Foo.bar();
>Foo.bar() : any
>Foo.bar : () => any
>Foo : typeof Foo
>bar : () => any
Foo.foo();
>Foo.foo() : any
>Foo.foo : () => any
>Foo : typeof Foo
>foo : () => any
@@ -0,0 +1,14 @@
tests/cases/compiler/a.ts(1,10): error TS2305: Module '"tests/cases/compiler/b"' has no exported member 'default'.
==== tests/cases/compiler/b.d.ts (0 errors) ====
export function foo();
export function bar();
==== tests/cases/compiler/a.ts (1 errors) ====
import { default as Foo } from "./b";
~~~~~~~
!!! error TS2305: Module '"tests/cases/compiler/b"' has no exported member 'default'.
Foo.bar();
Foo.foo();
@@ -0,0 +1,28 @@
//// [tests/cases/compiler/allowSyntheticDefaultImports8.ts] ////
//// [b.d.ts]
export function foo();
export function bar();
//// [a.ts]
import { default as Foo } from "./b";
Foo.bar();
Foo.foo();
//// [a.js]
System.register(["./b"], function(exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
var b_1;
return {
setters:[
function (b_1_1) {
b_1 = b_1_1;
}],
execute: function() {
b_1["default"].bar();
b_1["default"].foo();
}
}
});
@@ -0,0 +1,17 @@
//// [tests/cases/compiler/allowSyntheticDefaultImports9.ts] ////
//// [b.d.ts]
export function foo();
export function bar();
//// [a.ts]
import { default as Foo } from "./b";
Foo.bar();
Foo.foo();
//// [a.js]
"use strict";
var b_1 = require("./b");
b_1["default"].bar();
b_1["default"].foo();
@@ -0,0 +1,22 @@
=== tests/cases/compiler/b.d.ts ===
export function foo();
>foo : Symbol(foo, Decl(b.d.ts, 0, 0))
export function bar();
>bar : Symbol(bar, Decl(b.d.ts, 0, 22))
=== tests/cases/compiler/a.ts ===
import { default as Foo } from "./b";
>default : Symbol(Foo, Decl(a.ts, 0, 8))
>Foo : Symbol(Foo, Decl(a.ts, 0, 8))
Foo.bar();
>Foo.bar : Symbol(Foo.bar, Decl(b.d.ts, 0, 22))
>Foo : Symbol(Foo, Decl(a.ts, 0, 8))
>bar : Symbol(Foo.bar, Decl(b.d.ts, 0, 22))
Foo.foo();
>Foo.foo : Symbol(Foo.foo, Decl(b.d.ts, 0, 0))
>Foo : Symbol(Foo, Decl(a.ts, 0, 8))
>foo : Symbol(Foo.foo, Decl(b.d.ts, 0, 0))
@@ -0,0 +1,24 @@
=== tests/cases/compiler/b.d.ts ===
export function foo();
>foo : () => any
export function bar();
>bar : () => any
=== tests/cases/compiler/a.ts ===
import { default as Foo } from "./b";
>default : typeof Foo
>Foo : typeof Foo
Foo.bar();
>Foo.bar() : any
>Foo.bar : () => any
>Foo : typeof Foo
>bar : () => any
Foo.foo();
>Foo.foo() : any
>Foo.foo : () => any
>Foo : typeof Foo
>foo : () => any
@@ -3,21 +3,21 @@ var a: string[] = [];
>a : Symbol(a, Decl(arrayConcat2.ts, 0, 3))
a.concat("hello", 'world');
>a.concat : Symbol(Array.concat, Decl(lib.d.ts, --, --))
>a.concat : Symbol(Array.concat, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>a : Symbol(a, Decl(arrayConcat2.ts, 0, 3))
>concat : Symbol(Array.concat, Decl(lib.d.ts, --, --))
>concat : Symbol(Array.concat, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
a.concat('Hello');
>a.concat : Symbol(Array.concat, Decl(lib.d.ts, --, --))
>a.concat : Symbol(Array.concat, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>a : Symbol(a, Decl(arrayConcat2.ts, 0, 3))
>concat : Symbol(Array.concat, Decl(lib.d.ts, --, --))
>concat : Symbol(Array.concat, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
var b = new Array<string>();
>b : Symbol(b, Decl(arrayConcat2.ts, 5, 3))
>Array : Symbol(Array, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
b.concat('hello');
>b.concat : Symbol(Array.concat, Decl(lib.d.ts, --, --))
>b.concat : Symbol(Array.concat, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>b : Symbol(b, Decl(arrayConcat2.ts, 5, 3))
>concat : Symbol(Array.concat, Decl(lib.d.ts, --, --))
>concat : Symbol(Array.concat, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
+6 -6
View File
@@ -5,17 +5,17 @@ var a: string[] = [];
a.concat("hello", 'world');
>a.concat("hello", 'world') : string[]
>a.concat : (...items: (string | string[])[]) => string[]
>a.concat : { (...items: string[][]): string[]; (...items: (string | string[])[]): string[]; }
>a : string[]
>concat : (...items: (string | string[])[]) => string[]
>concat : { (...items: string[][]): string[]; (...items: (string | string[])[]): string[]; }
>"hello" : string
>'world' : string
a.concat('Hello');
>a.concat('Hello') : string[]
>a.concat : (...items: (string | string[])[]) => string[]
>a.concat : { (...items: string[][]): string[]; (...items: (string | string[])[]): string[]; }
>a : string[]
>concat : (...items: (string | string[])[]) => string[]
>concat : { (...items: string[][]): string[]; (...items: (string | string[])[]): string[]; }
>'Hello' : string
var b = new Array<string>();
@@ -25,8 +25,8 @@ var b = new Array<string>();
b.concat('hello');
>b.concat('hello') : string[]
>b.concat : (...items: (string | string[])[]) => string[]
>b.concat : { (...items: string[][]): string[]; (...items: (string | string[])[]): string[]; }
>b : string[]
>concat : (...items: (string | string[])[]) => string[]
>concat : { (...items: string[][]): string[]; (...items: (string | string[])[]): string[]; }
>'hello' : string
@@ -2,8 +2,8 @@
var x = [].concat([{ a: 1 }], [{ a: 2 }])
>x : Symbol(x, Decl(arrayConcatMap.ts, 0, 3))
>[].concat([{ a: 1 }], [{ a: 2 }]) .map : Symbol(Array.map, Decl(lib.d.ts, --, --))
>[].concat : Symbol(Array.concat, Decl(lib.d.ts, --, --))
>concat : Symbol(Array.concat, Decl(lib.d.ts, --, --))
>[].concat : Symbol(Array.concat, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>concat : Symbol(Array.concat, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>a : Symbol(a, Decl(arrayConcatMap.ts, 0, 20))
>a : Symbol(a, Decl(arrayConcatMap.ts, 0, 32))
@@ -4,9 +4,9 @@ var x = [].concat([{ a: 1 }], [{ a: 2 }])
>[].concat([{ a: 1 }], [{ a: 2 }]) .map(b => b.a) : any[]
>[].concat([{ a: 1 }], [{ a: 2 }]) .map : <U>(callbackfn: (value: any, index: number, array: any[]) => U, thisArg?: any) => U[]
>[].concat([{ a: 1 }], [{ a: 2 }]) : any[]
>[].concat : (...items: any[]) => any[]
>[].concat : { (...items: any[][]): any[]; (...items: any[]): any[]; }
>[] : undefined[]
>concat : (...items: any[]) => any[]
>concat : { (...items: any[][]): any[]; (...items: any[]): any[]; }
>[{ a: 1 }] : { a: number; }[]
>{ a: 1 } : { a: number; }
>a : number
@@ -14,15 +14,15 @@ var fa: number[];
fa = fa.concat([0]);
>fa : Symbol(fa, Decl(concatError.ts, 8, 3))
>fa.concat : Symbol(Array.concat, Decl(lib.d.ts, --, --))
>fa.concat : Symbol(Array.concat, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>fa : Symbol(fa, Decl(concatError.ts, 8, 3))
>concat : Symbol(Array.concat, Decl(lib.d.ts, --, --))
>concat : Symbol(Array.concat, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
fa = fa.concat(0);
>fa : Symbol(fa, Decl(concatError.ts, 8, 3))
>fa.concat : Symbol(Array.concat, Decl(lib.d.ts, --, --))
>fa.concat : Symbol(Array.concat, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>fa : Symbol(fa, Decl(concatError.ts, 8, 3))
>concat : Symbol(Array.concat, Decl(lib.d.ts, --, --))
>concat : Symbol(Array.concat, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
+4 -4
View File
@@ -16,9 +16,9 @@ fa = fa.concat([0]);
>fa = fa.concat([0]) : number[]
>fa : number[]
>fa.concat([0]) : number[]
>fa.concat : (...items: (number | number[])[]) => number[]
>fa.concat : { (...items: number[][]): number[]; (...items: (number | number[])[]): number[]; }
>fa : number[]
>concat : (...items: (number | number[])[]) => number[]
>concat : { (...items: number[][]): number[]; (...items: (number | number[])[]): number[]; }
>[0] : number[]
>0 : number
@@ -26,9 +26,9 @@ fa = fa.concat(0);
>fa = fa.concat(0) : number[]
>fa : number[]
>fa.concat(0) : number[]
>fa.concat : (...items: (number | number[])[]) => number[]
>fa.concat : { (...items: number[][]): number[]; (...items: (number | number[])[]): number[]; }
>fa : number[]
>concat : (...items: (number | number[])[]) => number[]
>concat : { (...items: number[][]): number[]; (...items: (number | number[])[]): number[]; }
>0 : number
@@ -0,0 +1,8 @@
//// [concatTuples.ts]
let ijs: [number, number][] = [[1, 2]];
ijs = ijs.concat([[3, 4], [5, 6]]);
//// [concatTuples.js]
var ijs = [[1, 2]];
ijs = ijs.concat([[3, 4], [5, 6]]);
@@ -0,0 +1,10 @@
=== tests/cases/compiler/concatTuples.ts ===
let ijs: [number, number][] = [[1, 2]];
>ijs : Symbol(ijs, Decl(concatTuples.ts, 0, 3))
ijs = ijs.concat([[3, 4], [5, 6]]);
>ijs : Symbol(ijs, Decl(concatTuples.ts, 0, 3))
>ijs.concat : Symbol(Array.concat, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>ijs : Symbol(ijs, Decl(concatTuples.ts, 0, 3))
>concat : Symbol(Array.concat, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
@@ -0,0 +1,23 @@
=== tests/cases/compiler/concatTuples.ts ===
let ijs: [number, number][] = [[1, 2]];
>ijs : [number, number][]
>[[1, 2]] : [number, number][]
>[1, 2] : [number, number]
>1 : number
>2 : number
ijs = ijs.concat([[3, 4], [5, 6]]);
>ijs = ijs.concat([[3, 4], [5, 6]]) : [number, number][]
>ijs : [number, number][]
>ijs.concat([[3, 4], [5, 6]]) : [number, number][]
>ijs.concat : { (...items: [number, number][][]): [number, number][]; (...items: ([number, number] | [number, number][])[]): [number, number][]; }
>ijs : [number, number][]
>concat : { (...items: [number, number][][]): [number, number][]; (...items: ([number, number] | [number, number][])[]): [number, number][]; }
>[[3, 4], [5, 6]] : [number, number][]
>[3, 4] : [number, number]
>3 : number
>4 : number
>[5, 6] : [number, number]
>5 : number
>6 : number
@@ -64,9 +64,9 @@ if (isNodeList(sourceObj)) {
>sourceObj : Symbol(sourceObj, Decl(controlFlowBinaryOrExpression.ts, 23, 3))
sourceObj.length;
>sourceObj.length : Symbol(length, Decl(controlFlowBinaryOrExpression.ts, 10, 27), Decl(controlFlowBinaryOrExpression.ts, 14, 33))
>sourceObj.length : Symbol(NodeList.length, Decl(controlFlowBinaryOrExpression.ts, 10, 27))
>sourceObj : Symbol(sourceObj, Decl(controlFlowBinaryOrExpression.ts, 23, 3))
>length : Symbol(length, Decl(controlFlowBinaryOrExpression.ts, 10, 27), Decl(controlFlowBinaryOrExpression.ts, 14, 33))
>length : Symbol(NodeList.length, Decl(controlFlowBinaryOrExpression.ts, 10, 27))
}
if (isHTMLCollection(sourceObj)) {
@@ -74,9 +74,9 @@ if (isHTMLCollection(sourceObj)) {
>sourceObj : Symbol(sourceObj, Decl(controlFlowBinaryOrExpression.ts, 23, 3))
sourceObj.length;
>sourceObj.length : Symbol(length, Decl(controlFlowBinaryOrExpression.ts, 10, 27), Decl(controlFlowBinaryOrExpression.ts, 14, 33))
>sourceObj.length : Symbol(HTMLCollection.length, Decl(controlFlowBinaryOrExpression.ts, 14, 33))
>sourceObj : Symbol(sourceObj, Decl(controlFlowBinaryOrExpression.ts, 23, 3))
>length : Symbol(length, Decl(controlFlowBinaryOrExpression.ts, 10, 27), Decl(controlFlowBinaryOrExpression.ts, 14, 33))
>length : Symbol(HTMLCollection.length, Decl(controlFlowBinaryOrExpression.ts, 14, 33))
}
if (isNodeList(sourceObj) || isHTMLCollection(sourceObj)) {
@@ -80,7 +80,7 @@ if (isNodeList(sourceObj)) {
sourceObj.length;
>sourceObj.length : number
>sourceObj : NodeList | HTMLCollection
>sourceObj : NodeList
>length : number
}
@@ -91,7 +91,7 @@ if (isHTMLCollection(sourceObj)) {
sourceObj.length;
>sourceObj.length : number
>sourceObj : NodeList | HTMLCollection
>sourceObj : HTMLCollection
>length : number
}
@@ -102,11 +102,11 @@ if (isNodeList(sourceObj) || isHTMLCollection(sourceObj)) {
>sourceObj : EventTargetLike
>isHTMLCollection(sourceObj) : boolean
>isHTMLCollection : (sourceObj: any) => sourceObj is HTMLCollection
>sourceObj : { a: string; }
>sourceObj : HTMLCollection | { a: string; }
sourceObj.length;
>sourceObj.length : number
>sourceObj : NodeList | HTMLCollection | ({ a: string; } & HTMLCollection)
>sourceObj : NodeList | HTMLCollection
>length : number
}
@@ -35,6 +35,22 @@ function b() {
}
x; // string
}
function c<T>(data: string | T): T {
if (typeof data === 'string') {
return JSON.parse(data);
}
else {
return data;
}
}
function d<T extends string>(data: string | T): never {
if (typeof data === 'string') {
throw new Error('will always happen');
}
else {
return data;
}
}
//// [controlFlowIfStatement.js]
@@ -72,3 +88,19 @@ function b() {
}
x; // string
}
function c(data) {
if (typeof data === 'string') {
return JSON.parse(data);
}
else {
return data;
}
}
function d(data) {
if (typeof data === 'string') {
throw new Error('will always happen');
}
else {
return data;
}
}
@@ -71,4 +71,42 @@ function b() {
x; // string
>x : Symbol(x, Decl(controlFlowIfStatement.ts, 26, 7))
}
function c<T>(data: string | T): T {
>c : Symbol(c, Decl(controlFlowIfStatement.ts, 35, 1))
>T : Symbol(T, Decl(controlFlowIfStatement.ts, 36, 11))
>data : Symbol(data, Decl(controlFlowIfStatement.ts, 36, 14))
>T : Symbol(T, Decl(controlFlowIfStatement.ts, 36, 11))
>T : Symbol(T, Decl(controlFlowIfStatement.ts, 36, 11))
if (typeof data === 'string') {
>data : Symbol(data, Decl(controlFlowIfStatement.ts, 36, 14))
return JSON.parse(data);
>JSON.parse : Symbol(JSON.parse, Decl(lib.d.ts, --, --))
>JSON : Symbol(JSON, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>parse : Symbol(JSON.parse, Decl(lib.d.ts, --, --))
>data : Symbol(data, Decl(controlFlowIfStatement.ts, 36, 14))
}
else {
return data;
>data : Symbol(data, Decl(controlFlowIfStatement.ts, 36, 14))
}
}
function d<T extends string>(data: string | T): never {
>d : Symbol(d, Decl(controlFlowIfStatement.ts, 43, 1))
>T : Symbol(T, Decl(controlFlowIfStatement.ts, 44, 11))
>data : Symbol(data, Decl(controlFlowIfStatement.ts, 44, 29))
>T : Symbol(T, Decl(controlFlowIfStatement.ts, 44, 11))
if (typeof data === 'string') {
>data : Symbol(data, Decl(controlFlowIfStatement.ts, 44, 29))
throw new Error('will always happen');
>Error : Symbol(Error, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
}
else {
return data;
>data : Symbol(data, Decl(controlFlowIfStatement.ts, 44, 29))
}
}
@@ -90,4 +90,51 @@ function b() {
x; // string
>x : string
}
function c<T>(data: string | T): T {
>c : <T>(data: string | T) => T
>T : T
>data : string | T
>T : T
>T : T
if (typeof data === 'string') {
>typeof data === 'string' : boolean
>typeof data : string
>data : string | T
>'string' : "string"
return JSON.parse(data);
>JSON.parse(data) : any
>JSON.parse : (text: string, reviver?: (key: any, value: any) => any) => any
>JSON : JSON
>parse : (text: string, reviver?: (key: any, value: any) => any) => any
>data : string
}
else {
return data;
>data : T
}
}
function d<T extends string>(data: string | T): never {
>d : <T extends string>(data: string | T) => never
>T : T
>data : string | T
>T : T
if (typeof data === 'string') {
>typeof data === 'string' : boolean
>typeof data : string
>data : string | T
>'string' : "string"
throw new Error('will always happen');
>new Error('will always happen') : Error
>Error : ErrorConstructor
>'will always happen' : string
}
else {
return data;
>data : never
}
}
@@ -0,0 +1,184 @@
//// [controlFlowInstanceof.ts]
// Repros from #10167
function f1(s: Set<string> | Set<number>) {
s = new Set<number>();
s; // Set<number>
if (s instanceof Set) {
s; // Set<number>
}
s; // Set<number>
s.add(42);
}
function f2(s: Set<string> | Set<number>) {
s = new Set<number>();
s; // Set<number>
if (s instanceof Promise) {
s; // Set<number> & Promise<any>
}
s; // Set<number>
s.add(42);
}
function f3(s: Set<string> | Set<number>) {
s; // Set<string> | Set<number>
if (s instanceof Set) {
s; // Set<string> | Set<number>
}
else {
s; // never
}
}
function f4(s: Set<string> | Set<number>) {
s = new Set<number>();
s; // Set<number>
if (s instanceof Set) {
s; // Set<number>
}
else {
s; // never
}
}
// More tests
class A { a: string }
class B extends A { b: string }
class C extends A { c: string }
function foo(x: A | undefined) {
x; // A | undefined
if (x instanceof B || x instanceof C) {
x; // B | C
}
x; // A | undefined
if (x instanceof B && x instanceof C) {
x; // B & C
}
x; // A | undefined
if (!x) {
return;
}
x; // A
if (x instanceof B) {
x; // B
if (x instanceof C) {
x; // B & C
}
else {
x; // B
}
x; // B
}
else {
x; // A
}
x; // A
}
// X is neither assignable to Y nor a subtype of Y
// Y is assignable to X, but not a subtype of X
interface X {
x?: string;
}
class Y {
y: string;
}
function goo(x: X) {
x;
if (x instanceof Y) {
x.y;
}
x;
}
//// [controlFlowInstanceof.js]
// Repros from #10167
function f1(s) {
s = new Set();
s; // Set<number>
if (s instanceof Set) {
s; // Set<number>
}
s; // Set<number>
s.add(42);
}
function f2(s) {
s = new Set();
s; // Set<number>
if (s instanceof Promise) {
s; // Set<number> & Promise<any>
}
s; // Set<number>
s.add(42);
}
function f3(s) {
s; // Set<string> | Set<number>
if (s instanceof Set) {
s; // Set<string> | Set<number>
}
else {
s; // never
}
}
function f4(s) {
s = new Set();
s; // Set<number>
if (s instanceof Set) {
s; // Set<number>
}
else {
s; // never
}
}
// More tests
class A {
}
class B extends A {
}
class C extends A {
}
function foo(x) {
x; // A | undefined
if (x instanceof B || x instanceof C) {
x; // B | C
}
x; // A | undefined
if (x instanceof B && x instanceof C) {
x; // B & C
}
x; // A | undefined
if (!x) {
return;
}
x; // A
if (x instanceof B) {
x; // B
if (x instanceof C) {
x; // B & C
}
else {
x; // B
}
x; // B
}
else {
x; // A
}
x; // A
}
class Y {
}
function goo(x) {
x;
if (x instanceof Y) {
x.y;
}
x;
}
@@ -0,0 +1,232 @@
=== tests/cases/compiler/controlFlowInstanceof.ts ===
// Repros from #10167
function f1(s: Set<string> | Set<number>) {
>f1 : Symbol(f1, Decl(controlFlowInstanceof.ts, 0, 0))
>s : Symbol(s, Decl(controlFlowInstanceof.ts, 3, 12))
>Set : Symbol(Set, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --))
>Set : Symbol(Set, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --))
s = new Set<number>();
>s : Symbol(s, Decl(controlFlowInstanceof.ts, 3, 12))
>Set : Symbol(Set, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --))
s; // Set<number>
>s : Symbol(s, Decl(controlFlowInstanceof.ts, 3, 12))
if (s instanceof Set) {
>s : Symbol(s, Decl(controlFlowInstanceof.ts, 3, 12))
>Set : Symbol(Set, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --))
s; // Set<number>
>s : Symbol(s, Decl(controlFlowInstanceof.ts, 3, 12))
}
s; // Set<number>
>s : Symbol(s, Decl(controlFlowInstanceof.ts, 3, 12))
s.add(42);
>s.add : Symbol(Set.add, Decl(lib.es2015.collection.d.ts, --, --))
>s : Symbol(s, Decl(controlFlowInstanceof.ts, 3, 12))
>add : Symbol(Set.add, Decl(lib.es2015.collection.d.ts, --, --))
}
function f2(s: Set<string> | Set<number>) {
>f2 : Symbol(f2, Decl(controlFlowInstanceof.ts, 11, 1))
>s : Symbol(s, Decl(controlFlowInstanceof.ts, 13, 12))
>Set : Symbol(Set, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --))
>Set : Symbol(Set, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --))
s = new Set<number>();
>s : Symbol(s, Decl(controlFlowInstanceof.ts, 13, 12))
>Set : Symbol(Set, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --))
s; // Set<number>
>s : Symbol(s, Decl(controlFlowInstanceof.ts, 13, 12))
if (s instanceof Promise) {
>s : Symbol(s, Decl(controlFlowInstanceof.ts, 13, 12))
>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --))
s; // Set<number> & Promise<any>
>s : Symbol(s, Decl(controlFlowInstanceof.ts, 13, 12))
}
s; // Set<number>
>s : Symbol(s, Decl(controlFlowInstanceof.ts, 13, 12))
s.add(42);
>s.add : Symbol(Set.add, Decl(lib.es2015.collection.d.ts, --, --))
>s : Symbol(s, Decl(controlFlowInstanceof.ts, 13, 12))
>add : Symbol(Set.add, Decl(lib.es2015.collection.d.ts, --, --))
}
function f3(s: Set<string> | Set<number>) {
>f3 : Symbol(f3, Decl(controlFlowInstanceof.ts, 21, 1))
>s : Symbol(s, Decl(controlFlowInstanceof.ts, 23, 12))
>Set : Symbol(Set, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --))
>Set : Symbol(Set, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --))
s; // Set<string> | Set<number>
>s : Symbol(s, Decl(controlFlowInstanceof.ts, 23, 12))
if (s instanceof Set) {
>s : Symbol(s, Decl(controlFlowInstanceof.ts, 23, 12))
>Set : Symbol(Set, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --))
s; // Set<string> | Set<number>
>s : Symbol(s, Decl(controlFlowInstanceof.ts, 23, 12))
}
else {
s; // never
>s : Symbol(s, Decl(controlFlowInstanceof.ts, 23, 12))
}
}
function f4(s: Set<string> | Set<number>) {
>f4 : Symbol(f4, Decl(controlFlowInstanceof.ts, 31, 1))
>s : Symbol(s, Decl(controlFlowInstanceof.ts, 33, 12))
>Set : Symbol(Set, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --))
>Set : Symbol(Set, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --))
s = new Set<number>();
>s : Symbol(s, Decl(controlFlowInstanceof.ts, 33, 12))
>Set : Symbol(Set, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --))
s; // Set<number>
>s : Symbol(s, Decl(controlFlowInstanceof.ts, 33, 12))
if (s instanceof Set) {
>s : Symbol(s, Decl(controlFlowInstanceof.ts, 33, 12))
>Set : Symbol(Set, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --))
s; // Set<number>
>s : Symbol(s, Decl(controlFlowInstanceof.ts, 33, 12))
}
else {
s; // never
>s : Symbol(s, Decl(controlFlowInstanceof.ts, 33, 12))
}
}
// More tests
class A { a: string }
>A : Symbol(A, Decl(controlFlowInstanceof.ts, 42, 1))
>a : Symbol(A.a, Decl(controlFlowInstanceof.ts, 46, 9))
class B extends A { b: string }
>B : Symbol(B, Decl(controlFlowInstanceof.ts, 46, 21))
>A : Symbol(A, Decl(controlFlowInstanceof.ts, 42, 1))
>b : Symbol(B.b, Decl(controlFlowInstanceof.ts, 47, 19))
class C extends A { c: string }
>C : Symbol(C, Decl(controlFlowInstanceof.ts, 47, 31))
>A : Symbol(A, Decl(controlFlowInstanceof.ts, 42, 1))
>c : Symbol(C.c, Decl(controlFlowInstanceof.ts, 48, 19))
function foo(x: A | undefined) {
>foo : Symbol(foo, Decl(controlFlowInstanceof.ts, 48, 31))
>x : Symbol(x, Decl(controlFlowInstanceof.ts, 50, 13))
>A : Symbol(A, Decl(controlFlowInstanceof.ts, 42, 1))
x; // A | undefined
>x : Symbol(x, Decl(controlFlowInstanceof.ts, 50, 13))
if (x instanceof B || x instanceof C) {
>x : Symbol(x, Decl(controlFlowInstanceof.ts, 50, 13))
>B : Symbol(B, Decl(controlFlowInstanceof.ts, 46, 21))
>x : Symbol(x, Decl(controlFlowInstanceof.ts, 50, 13))
>C : Symbol(C, Decl(controlFlowInstanceof.ts, 47, 31))
x; // B | C
>x : Symbol(x, Decl(controlFlowInstanceof.ts, 50, 13))
}
x; // A | undefined
>x : Symbol(x, Decl(controlFlowInstanceof.ts, 50, 13))
if (x instanceof B && x instanceof C) {
>x : Symbol(x, Decl(controlFlowInstanceof.ts, 50, 13))
>B : Symbol(B, Decl(controlFlowInstanceof.ts, 46, 21))
>x : Symbol(x, Decl(controlFlowInstanceof.ts, 50, 13))
>C : Symbol(C, Decl(controlFlowInstanceof.ts, 47, 31))
x; // B & C
>x : Symbol(x, Decl(controlFlowInstanceof.ts, 50, 13))
}
x; // A | undefined
>x : Symbol(x, Decl(controlFlowInstanceof.ts, 50, 13))
if (!x) {
>x : Symbol(x, Decl(controlFlowInstanceof.ts, 50, 13))
return;
}
x; // A
>x : Symbol(x, Decl(controlFlowInstanceof.ts, 50, 13))
if (x instanceof B) {
>x : Symbol(x, Decl(controlFlowInstanceof.ts, 50, 13))
>B : Symbol(B, Decl(controlFlowInstanceof.ts, 46, 21))
x; // B
>x : Symbol(x, Decl(controlFlowInstanceof.ts, 50, 13))
if (x instanceof C) {
>x : Symbol(x, Decl(controlFlowInstanceof.ts, 50, 13))
>C : Symbol(C, Decl(controlFlowInstanceof.ts, 47, 31))
x; // B & C
>x : Symbol(x, Decl(controlFlowInstanceof.ts, 50, 13))
}
else {
x; // B
>x : Symbol(x, Decl(controlFlowInstanceof.ts, 50, 13))
}
x; // B
>x : Symbol(x, Decl(controlFlowInstanceof.ts, 50, 13))
}
else {
x; // A
>x : Symbol(x, Decl(controlFlowInstanceof.ts, 50, 13))
}
x; // A
>x : Symbol(x, Decl(controlFlowInstanceof.ts, 50, 13))
}
// X is neither assignable to Y nor a subtype of Y
// Y is assignable to X, but not a subtype of X
interface X {
>X : Symbol(X, Decl(controlFlowInstanceof.ts, 78, 1))
x?: string;
>x : Symbol(X.x, Decl(controlFlowInstanceof.ts, 83, 13))
}
class Y {
>Y : Symbol(Y, Decl(controlFlowInstanceof.ts, 85, 1))
y: string;
>y : Symbol(Y.y, Decl(controlFlowInstanceof.ts, 87, 9))
}
function goo(x: X) {
>goo : Symbol(goo, Decl(controlFlowInstanceof.ts, 89, 1))
>x : Symbol(x, Decl(controlFlowInstanceof.ts, 91, 13))
>X : Symbol(X, Decl(controlFlowInstanceof.ts, 78, 1))
x;
>x : Symbol(x, Decl(controlFlowInstanceof.ts, 91, 13))
if (x instanceof Y) {
>x : Symbol(x, Decl(controlFlowInstanceof.ts, 91, 13))
>Y : Symbol(Y, Decl(controlFlowInstanceof.ts, 85, 1))
x.y;
>x.y : Symbol(Y.y, Decl(controlFlowInstanceof.ts, 87, 9))
>x : Symbol(x, Decl(controlFlowInstanceof.ts, 91, 13))
>y : Symbol(Y.y, Decl(controlFlowInstanceof.ts, 87, 9))
}
x;
>x : Symbol(x, Decl(controlFlowInstanceof.ts, 91, 13))
}
@@ -0,0 +1,256 @@
=== tests/cases/compiler/controlFlowInstanceof.ts ===
// Repros from #10167
function f1(s: Set<string> | Set<number>) {
>f1 : (s: Set<string> | Set<number>) => void
>s : Set<string> | Set<number>
>Set : Set<T>
>Set : Set<T>
s = new Set<number>();
>s = new Set<number>() : Set<number>
>s : Set<string> | Set<number>
>new Set<number>() : Set<number>
>Set : SetConstructor
s; // Set<number>
>s : Set<number>
if (s instanceof Set) {
>s instanceof Set : boolean
>s : Set<number>
>Set : SetConstructor
s; // Set<number>
>s : Set<number>
}
s; // Set<number>
>s : Set<number>
s.add(42);
>s.add(42) : Set<number>
>s.add : (value: number) => Set<number>
>s : Set<number>
>add : (value: number) => Set<number>
>42 : number
}
function f2(s: Set<string> | Set<number>) {
>f2 : (s: Set<string> | Set<number>) => void
>s : Set<string> | Set<number>
>Set : Set<T>
>Set : Set<T>
s = new Set<number>();
>s = new Set<number>() : Set<number>
>s : Set<string> | Set<number>
>new Set<number>() : Set<number>
>Set : SetConstructor
s; // Set<number>
>s : Set<number>
if (s instanceof Promise) {
>s instanceof Promise : boolean
>s : Set<number>
>Promise : PromiseConstructor
s; // Set<number> & Promise<any>
>s : Set<number> & Promise<any>
}
s; // Set<number>
>s : Set<number>
s.add(42);
>s.add(42) : Set<number>
>s.add : (value: number) => Set<number>
>s : Set<number>
>add : (value: number) => Set<number>
>42 : number
}
function f3(s: Set<string> | Set<number>) {
>f3 : (s: Set<string> | Set<number>) => void
>s : Set<string> | Set<number>
>Set : Set<T>
>Set : Set<T>
s; // Set<string> | Set<number>
>s : Set<string> | Set<number>
if (s instanceof Set) {
>s instanceof Set : boolean
>s : Set<string> | Set<number>
>Set : SetConstructor
s; // Set<string> | Set<number>
>s : Set<string> | Set<number>
}
else {
s; // never
>s : never
}
}
function f4(s: Set<string> | Set<number>) {
>f4 : (s: Set<string> | Set<number>) => void
>s : Set<string> | Set<number>
>Set : Set<T>
>Set : Set<T>
s = new Set<number>();
>s = new Set<number>() : Set<number>
>s : Set<string> | Set<number>
>new Set<number>() : Set<number>
>Set : SetConstructor
s; // Set<number>
>s : Set<number>
if (s instanceof Set) {
>s instanceof Set : boolean
>s : Set<number>
>Set : SetConstructor
s; // Set<number>
>s : Set<number>
}
else {
s; // never
>s : never
}
}
// More tests
class A { a: string }
>A : A
>a : string
class B extends A { b: string }
>B : B
>A : A
>b : string
class C extends A { c: string }
>C : C
>A : A
>c : string
function foo(x: A | undefined) {
>foo : (x: A) => void
>x : A
>A : A
x; // A | undefined
>x : A
if (x instanceof B || x instanceof C) {
>x instanceof B || x instanceof C : boolean
>x instanceof B : boolean
>x : A
>B : typeof B
>x instanceof C : boolean
>x : A
>C : typeof C
x; // B | C
>x : B | C
}
x; // A | undefined
>x : A
if (x instanceof B && x instanceof C) {
>x instanceof B && x instanceof C : boolean
>x instanceof B : boolean
>x : A
>B : typeof B
>x instanceof C : boolean
>x : B
>C : typeof C
x; // B & C
>x : B & C
}
x; // A | undefined
>x : A
if (!x) {
>!x : boolean
>x : A
return;
}
x; // A
>x : A
if (x instanceof B) {
>x instanceof B : boolean
>x : A
>B : typeof B
x; // B
>x : B
if (x instanceof C) {
>x instanceof C : boolean
>x : B
>C : typeof C
x; // B & C
>x : B & C
}
else {
x; // B
>x : B
}
x; // B
>x : B
}
else {
x; // A
>x : A
}
x; // A
>x : A
}
// X is neither assignable to Y nor a subtype of Y
// Y is assignable to X, but not a subtype of X
interface X {
>X : X
x?: string;
>x : string
}
class Y {
>Y : Y
y: string;
>y : string
}
function goo(x: X) {
>goo : (x: X) => void
>x : X
>X : X
x;
>x : X
if (x instanceof Y) {
>x instanceof Y : boolean
>x : X
>Y : typeof Y
x.y;
>x.y : string
>x : Y
>y : string
}
x;
>x : X
}
@@ -0,0 +1,77 @@
tests/cases/compiler/discriminantPropertyCheck.ts(30,9): error TS2532: Object is possibly 'undefined'.
tests/cases/compiler/discriminantPropertyCheck.ts(66,9): error TS2532: Object is possibly 'undefined'.
==== tests/cases/compiler/discriminantPropertyCheck.ts (2 errors) ====
type Item = Item1 | Item2;
interface Base {
bar: boolean;
}
interface Item1 extends Base {
kind: "A";
foo: string | undefined;
baz: boolean;
qux: true;
}
interface Item2 extends Base {
kind: "B";
foo: string | undefined;
baz: boolean;
qux: false;
}
function goo1(x: Item) {
if (x.kind === "A" && x.foo !== undefined) {
x.foo.length;
}
}
function goo2(x: Item) {
if (x.foo !== undefined && x.kind === "A") {
x.foo.length; // Error, intervening discriminant guard
~~~~~
!!! error TS2532: Object is possibly 'undefined'.
}
}
function foo1(x: Item) {
if (x.bar && x.foo !== undefined) {
x.foo.length;
}
}
function foo2(x: Item) {
if (x.foo !== undefined && x.bar) {
x.foo.length;
}
}
function foo3(x: Item) {
if (x.baz && x.foo !== undefined) {
x.foo.length;
}
}
function foo4(x: Item) {
if (x.foo !== undefined && x.baz) {
x.foo.length;
}
}
function foo5(x: Item) {
if (x.qux && x.foo !== undefined) {
x.foo.length;
}
}
function foo6(x: Item) {
if (x.foo !== undefined && x.qux) {
x.foo.length; // Error, intervening discriminant guard
~~~~~
!!! error TS2532: Object is possibly 'undefined'.
}
}
@@ -0,0 +1,111 @@
//// [discriminantPropertyCheck.ts]
type Item = Item1 | Item2;
interface Base {
bar: boolean;
}
interface Item1 extends Base {
kind: "A";
foo: string | undefined;
baz: boolean;
qux: true;
}
interface Item2 extends Base {
kind: "B";
foo: string | undefined;
baz: boolean;
qux: false;
}
function goo1(x: Item) {
if (x.kind === "A" && x.foo !== undefined) {
x.foo.length;
}
}
function goo2(x: Item) {
if (x.foo !== undefined && x.kind === "A") {
x.foo.length; // Error, intervening discriminant guard
}
}
function foo1(x: Item) {
if (x.bar && x.foo !== undefined) {
x.foo.length;
}
}
function foo2(x: Item) {
if (x.foo !== undefined && x.bar) {
x.foo.length;
}
}
function foo3(x: Item) {
if (x.baz && x.foo !== undefined) {
x.foo.length;
}
}
function foo4(x: Item) {
if (x.foo !== undefined && x.baz) {
x.foo.length;
}
}
function foo5(x: Item) {
if (x.qux && x.foo !== undefined) {
x.foo.length;
}
}
function foo6(x: Item) {
if (x.foo !== undefined && x.qux) {
x.foo.length; // Error, intervening discriminant guard
}
}
//// [discriminantPropertyCheck.js]
function goo1(x) {
if (x.kind === "A" && x.foo !== undefined) {
x.foo.length;
}
}
function goo2(x) {
if (x.foo !== undefined && x.kind === "A") {
x.foo.length; // Error, intervening discriminant guard
}
}
function foo1(x) {
if (x.bar && x.foo !== undefined) {
x.foo.length;
}
}
function foo2(x) {
if (x.foo !== undefined && x.bar) {
x.foo.length;
}
}
function foo3(x) {
if (x.baz && x.foo !== undefined) {
x.foo.length;
}
}
function foo4(x) {
if (x.foo !== undefined && x.baz) {
x.foo.length;
}
}
function foo5(x) {
if (x.qux && x.foo !== undefined) {
x.foo.length;
}
}
function foo6(x) {
if (x.foo !== undefined && x.qux) {
x.foo.length; // Error, intervening discriminant guard
}
}
@@ -0,0 +1,44 @@
//// [discriminantsAndNullOrUndefined.ts]
// Repro from #10228
interface A { kind: 'A'; }
interface B { kind: 'B'; }
type C = A | B | undefined;
function never(_: never): never {
throw new Error();
}
function useA(_: A): void { }
function useB(_: B): void { }
declare var c: C;
if (c !== undefined) {
switch (c.kind) {
case 'A': useA(c); break;
case 'B': useB(c); break;
default: never(c);
}
}
//// [discriminantsAndNullOrUndefined.js]
// Repro from #10228
function never(_) {
throw new Error();
}
function useA(_) { }
function useB(_) { }
if (c !== undefined) {
switch (c.kind) {
case 'A':
useA(c);
break;
case 'B':
useB(c);
break;
default: never(c);
}
}
@@ -0,0 +1,61 @@
=== tests/cases/compiler/discriminantsAndNullOrUndefined.ts ===
// Repro from #10228
interface A { kind: 'A'; }
>A : Symbol(A, Decl(discriminantsAndNullOrUndefined.ts, 0, 0))
>kind : Symbol(A.kind, Decl(discriminantsAndNullOrUndefined.ts, 3, 13))
interface B { kind: 'B'; }
>B : Symbol(B, Decl(discriminantsAndNullOrUndefined.ts, 3, 26))
>kind : Symbol(B.kind, Decl(discriminantsAndNullOrUndefined.ts, 4, 13))
type C = A | B | undefined;
>C : Symbol(C, Decl(discriminantsAndNullOrUndefined.ts, 4, 26))
>A : Symbol(A, Decl(discriminantsAndNullOrUndefined.ts, 0, 0))
>B : Symbol(B, Decl(discriminantsAndNullOrUndefined.ts, 3, 26))
function never(_: never): never {
>never : Symbol(never, Decl(discriminantsAndNullOrUndefined.ts, 6, 27))
>_ : Symbol(_, Decl(discriminantsAndNullOrUndefined.ts, 8, 15))
throw new Error();
>Error : Symbol(Error, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
}
function useA(_: A): void { }
>useA : Symbol(useA, Decl(discriminantsAndNullOrUndefined.ts, 10, 1))
>_ : Symbol(_, Decl(discriminantsAndNullOrUndefined.ts, 12, 14))
>A : Symbol(A, Decl(discriminantsAndNullOrUndefined.ts, 0, 0))
function useB(_: B): void { }
>useB : Symbol(useB, Decl(discriminantsAndNullOrUndefined.ts, 12, 29))
>_ : Symbol(_, Decl(discriminantsAndNullOrUndefined.ts, 13, 14))
>B : Symbol(B, Decl(discriminantsAndNullOrUndefined.ts, 3, 26))
declare var c: C;
>c : Symbol(c, Decl(discriminantsAndNullOrUndefined.ts, 15, 11))
>C : Symbol(C, Decl(discriminantsAndNullOrUndefined.ts, 4, 26))
if (c !== undefined) {
>c : Symbol(c, Decl(discriminantsAndNullOrUndefined.ts, 15, 11))
>undefined : Symbol(undefined)
switch (c.kind) {
>c.kind : Symbol(kind, Decl(discriminantsAndNullOrUndefined.ts, 3, 13), Decl(discriminantsAndNullOrUndefined.ts, 4, 13))
>c : Symbol(c, Decl(discriminantsAndNullOrUndefined.ts, 15, 11))
>kind : Symbol(kind, Decl(discriminantsAndNullOrUndefined.ts, 3, 13), Decl(discriminantsAndNullOrUndefined.ts, 4, 13))
case 'A': useA(c); break;
>useA : Symbol(useA, Decl(discriminantsAndNullOrUndefined.ts, 10, 1))
>c : Symbol(c, Decl(discriminantsAndNullOrUndefined.ts, 15, 11))
case 'B': useB(c); break;
>useB : Symbol(useB, Decl(discriminantsAndNullOrUndefined.ts, 12, 29))
>c : Symbol(c, Decl(discriminantsAndNullOrUndefined.ts, 15, 11))
default: never(c);
>never : Symbol(never, Decl(discriminantsAndNullOrUndefined.ts, 6, 27))
>c : Symbol(c, Decl(discriminantsAndNullOrUndefined.ts, 15, 11))
}
}
@@ -0,0 +1,68 @@
=== tests/cases/compiler/discriminantsAndNullOrUndefined.ts ===
// Repro from #10228
interface A { kind: 'A'; }
>A : A
>kind : "A"
interface B { kind: 'B'; }
>B : B
>kind : "B"
type C = A | B | undefined;
>C : C
>A : A
>B : B
function never(_: never): never {
>never : (_: never) => never
>_ : never
throw new Error();
>new Error() : Error
>Error : ErrorConstructor
}
function useA(_: A): void { }
>useA : (_: A) => void
>_ : A
>A : A
function useB(_: B): void { }
>useB : (_: B) => void
>_ : B
>B : B
declare var c: C;
>c : C
>C : C
if (c !== undefined) {
>c !== undefined : boolean
>c : C
>undefined : undefined
switch (c.kind) {
>c.kind : "A" | "B"
>c : A | B
>kind : "A" | "B"
case 'A': useA(c); break;
>'A' : "A"
>useA(c) : void
>useA : (_: A) => void
>c : A
case 'B': useB(c); break;
>'B' : "B"
>useB(c) : void
>useB : (_: B) => void
>c : B
default: never(c);
>never(c) : never
>never : (_: never) => never
>c : never
}
}
@@ -0,0 +1,84 @@
//// [discriminantsAndPrimitives.ts]
// Repro from #10257 plus other tests
interface Foo {
kind: "foo";
name: string;
}
interface Bar {
kind: "bar";
length: string;
}
function f1(x: Foo | Bar | string) {
if (typeof x !== 'string') {
switch(x.kind) {
case 'foo':
x.name;
}
}
}
function f2(x: Foo | Bar | string | undefined) {
if (typeof x === "object") {
switch(x.kind) {
case 'foo':
x.name;
}
}
}
function f3(x: Foo | Bar | string | null) {
if (x && typeof x !== "string") {
switch(x.kind) {
case 'foo':
x.name;
}
}
}
function f4(x: Foo | Bar | string | number | null) {
if (x && typeof x === "object") {
switch(x.kind) {
case 'foo':
x.name;
}
}
}
//// [discriminantsAndPrimitives.js]
// Repro from #10257 plus other tests
function f1(x) {
if (typeof x !== 'string') {
switch (x.kind) {
case 'foo':
x.name;
}
}
}
function f2(x) {
if (typeof x === "object") {
switch (x.kind) {
case 'foo':
x.name;
}
}
}
function f3(x) {
if (x && typeof x !== "string") {
switch (x.kind) {
case 'foo':
x.name;
}
}
}
function f4(x) {
if (x && typeof x === "object") {
switch (x.kind) {
case 'foo':
x.name;
}
}
}
@@ -0,0 +1,117 @@
=== tests/cases/compiler/discriminantsAndPrimitives.ts ===
// Repro from #10257 plus other tests
interface Foo {
>Foo : Symbol(Foo, Decl(discriminantsAndPrimitives.ts, 0, 0))
kind: "foo";
>kind : Symbol(Foo.kind, Decl(discriminantsAndPrimitives.ts, 3, 15))
name: string;
>name : Symbol(Foo.name, Decl(discriminantsAndPrimitives.ts, 4, 16))
}
interface Bar {
>Bar : Symbol(Bar, Decl(discriminantsAndPrimitives.ts, 6, 1))
kind: "bar";
>kind : Symbol(Bar.kind, Decl(discriminantsAndPrimitives.ts, 8, 15))
length: string;
>length : Symbol(Bar.length, Decl(discriminantsAndPrimitives.ts, 9, 16))
}
function f1(x: Foo | Bar | string) {
>f1 : Symbol(f1, Decl(discriminantsAndPrimitives.ts, 11, 1))
>x : Symbol(x, Decl(discriminantsAndPrimitives.ts, 13, 12))
>Foo : Symbol(Foo, Decl(discriminantsAndPrimitives.ts, 0, 0))
>Bar : Symbol(Bar, Decl(discriminantsAndPrimitives.ts, 6, 1))
if (typeof x !== 'string') {
>x : Symbol(x, Decl(discriminantsAndPrimitives.ts, 13, 12))
switch(x.kind) {
>x.kind : Symbol(kind, Decl(discriminantsAndPrimitives.ts, 3, 15), Decl(discriminantsAndPrimitives.ts, 8, 15))
>x : Symbol(x, Decl(discriminantsAndPrimitives.ts, 13, 12))
>kind : Symbol(kind, Decl(discriminantsAndPrimitives.ts, 3, 15), Decl(discriminantsAndPrimitives.ts, 8, 15))
case 'foo':
x.name;
>x.name : Symbol(Foo.name, Decl(discriminantsAndPrimitives.ts, 4, 16))
>x : Symbol(x, Decl(discriminantsAndPrimitives.ts, 13, 12))
>name : Symbol(Foo.name, Decl(discriminantsAndPrimitives.ts, 4, 16))
}
}
}
function f2(x: Foo | Bar | string | undefined) {
>f2 : Symbol(f2, Decl(discriminantsAndPrimitives.ts, 20, 1))
>x : Symbol(x, Decl(discriminantsAndPrimitives.ts, 22, 12))
>Foo : Symbol(Foo, Decl(discriminantsAndPrimitives.ts, 0, 0))
>Bar : Symbol(Bar, Decl(discriminantsAndPrimitives.ts, 6, 1))
if (typeof x === "object") {
>x : Symbol(x, Decl(discriminantsAndPrimitives.ts, 22, 12))
switch(x.kind) {
>x.kind : Symbol(kind, Decl(discriminantsAndPrimitives.ts, 3, 15), Decl(discriminantsAndPrimitives.ts, 8, 15))
>x : Symbol(x, Decl(discriminantsAndPrimitives.ts, 22, 12))
>kind : Symbol(kind, Decl(discriminantsAndPrimitives.ts, 3, 15), Decl(discriminantsAndPrimitives.ts, 8, 15))
case 'foo':
x.name;
>x.name : Symbol(Foo.name, Decl(discriminantsAndPrimitives.ts, 4, 16))
>x : Symbol(x, Decl(discriminantsAndPrimitives.ts, 22, 12))
>name : Symbol(Foo.name, Decl(discriminantsAndPrimitives.ts, 4, 16))
}
}
}
function f3(x: Foo | Bar | string | null) {
>f3 : Symbol(f3, Decl(discriminantsAndPrimitives.ts, 29, 1))
>x : Symbol(x, Decl(discriminantsAndPrimitives.ts, 31, 12))
>Foo : Symbol(Foo, Decl(discriminantsAndPrimitives.ts, 0, 0))
>Bar : Symbol(Bar, Decl(discriminantsAndPrimitives.ts, 6, 1))
if (x && typeof x !== "string") {
>x : Symbol(x, Decl(discriminantsAndPrimitives.ts, 31, 12))
>x : Symbol(x, Decl(discriminantsAndPrimitives.ts, 31, 12))
switch(x.kind) {
>x.kind : Symbol(kind, Decl(discriminantsAndPrimitives.ts, 3, 15), Decl(discriminantsAndPrimitives.ts, 8, 15))
>x : Symbol(x, Decl(discriminantsAndPrimitives.ts, 31, 12))
>kind : Symbol(kind, Decl(discriminantsAndPrimitives.ts, 3, 15), Decl(discriminantsAndPrimitives.ts, 8, 15))
case 'foo':
x.name;
>x.name : Symbol(Foo.name, Decl(discriminantsAndPrimitives.ts, 4, 16))
>x : Symbol(x, Decl(discriminantsAndPrimitives.ts, 31, 12))
>name : Symbol(Foo.name, Decl(discriminantsAndPrimitives.ts, 4, 16))
}
}
}
function f4(x: Foo | Bar | string | number | null) {
>f4 : Symbol(f4, Decl(discriminantsAndPrimitives.ts, 38, 1))
>x : Symbol(x, Decl(discriminantsAndPrimitives.ts, 40, 12))
>Foo : Symbol(Foo, Decl(discriminantsAndPrimitives.ts, 0, 0))
>Bar : Symbol(Bar, Decl(discriminantsAndPrimitives.ts, 6, 1))
if (x && typeof x === "object") {
>x : Symbol(x, Decl(discriminantsAndPrimitives.ts, 40, 12))
>x : Symbol(x, Decl(discriminantsAndPrimitives.ts, 40, 12))
switch(x.kind) {
>x.kind : Symbol(kind, Decl(discriminantsAndPrimitives.ts, 3, 15), Decl(discriminantsAndPrimitives.ts, 8, 15))
>x : Symbol(x, Decl(discriminantsAndPrimitives.ts, 40, 12))
>kind : Symbol(kind, Decl(discriminantsAndPrimitives.ts, 3, 15), Decl(discriminantsAndPrimitives.ts, 8, 15))
case 'foo':
x.name;
>x.name : Symbol(Foo.name, Decl(discriminantsAndPrimitives.ts, 4, 16))
>x : Symbol(x, Decl(discriminantsAndPrimitives.ts, 40, 12))
>name : Symbol(Foo.name, Decl(discriminantsAndPrimitives.ts, 4, 16))
}
}
}
@@ -0,0 +1,141 @@
=== tests/cases/compiler/discriminantsAndPrimitives.ts ===
// Repro from #10257 plus other tests
interface Foo {
>Foo : Foo
kind: "foo";
>kind : "foo"
name: string;
>name : string
}
interface Bar {
>Bar : Bar
kind: "bar";
>kind : "bar"
length: string;
>length : string
}
function f1(x: Foo | Bar | string) {
>f1 : (x: string | Foo | Bar) => void
>x : string | Foo | Bar
>Foo : Foo
>Bar : Bar
if (typeof x !== 'string') {
>typeof x !== 'string' : boolean
>typeof x : string
>x : string | Foo | Bar
>'string' : "string"
switch(x.kind) {
>x.kind : "foo" | "bar"
>x : Foo | Bar
>kind : "foo" | "bar"
case 'foo':
>'foo' : "foo"
x.name;
>x.name : string
>x : Foo
>name : string
}
}
}
function f2(x: Foo | Bar | string | undefined) {
>f2 : (x: string | Foo | Bar | undefined) => void
>x : string | Foo | Bar | undefined
>Foo : Foo
>Bar : Bar
if (typeof x === "object") {
>typeof x === "object" : boolean
>typeof x : string
>x : string | Foo | Bar | undefined
>"object" : "object"
switch(x.kind) {
>x.kind : "foo" | "bar"
>x : Foo | Bar
>kind : "foo" | "bar"
case 'foo':
>'foo' : "foo"
x.name;
>x.name : string
>x : Foo
>name : string
}
}
}
function f3(x: Foo | Bar | string | null) {
>f3 : (x: string | Foo | Bar | null) => void
>x : string | Foo | Bar | null
>Foo : Foo
>Bar : Bar
>null : null
if (x && typeof x !== "string") {
>x && typeof x !== "string" : boolean | "" | null
>x : string | Foo | Bar | null
>typeof x !== "string" : boolean
>typeof x : string
>x : string | Foo | Bar
>"string" : "string"
switch(x.kind) {
>x.kind : "foo" | "bar"
>x : Foo | Bar
>kind : "foo" | "bar"
case 'foo':
>'foo' : "foo"
x.name;
>x.name : string
>x : Foo
>name : string
}
}
}
function f4(x: Foo | Bar | string | number | null) {
>f4 : (x: string | number | Foo | Bar | null) => void
>x : string | number | Foo | Bar | null
>Foo : Foo
>Bar : Bar
>null : null
if (x && typeof x === "object") {
>x && typeof x === "object" : boolean | "" | 0 | null
>x : string | number | Foo | Bar | null
>typeof x === "object" : boolean
>typeof x : string
>x : string | number | Foo | Bar
>"object" : "object"
switch(x.kind) {
>x.kind : "foo" | "bar"
>x : Foo | Bar
>kind : "foo" | "bar"
case 'foo':
>'foo' : "foo"
x.name;
>x.name : string
>x : Foo
>name : string
}
}
}
@@ -0,0 +1,59 @@
//// [discriminantsAndTypePredicates.ts]
// Repro from #10145
interface A { type: 'A' }
interface B { type: 'B' }
function isA(x: A | B): x is A { return x.type === 'A'; }
function isB(x: A | B): x is B { return x.type === 'B'; }
function foo1(x: A | B): any {
x; // A | B
if (isA(x)) {
return x; // A
}
x; // B
if (isB(x)) {
return x; // B
}
x; // never
}
function foo2(x: A | B): any {
x; // A | B
if (x.type === 'A') {
return x; // A
}
x; // B
if (x.type === 'B') {
return x; // B
}
x; // never
}
//// [discriminantsAndTypePredicates.js]
// Repro from #10145
function isA(x) { return x.type === 'A'; }
function isB(x) { return x.type === 'B'; }
function foo1(x) {
x; // A | B
if (isA(x)) {
return x; // A
}
x; // B
if (isB(x)) {
return x; // B
}
x; // never
}
function foo2(x) {
x; // A | B
if (x.type === 'A') {
return x; // A
}
x; // B
if (x.type === 'B') {
return x; // B
}
x; // never
}
@@ -0,0 +1,94 @@
=== tests/cases/compiler/discriminantsAndTypePredicates.ts ===
// Repro from #10145
interface A { type: 'A' }
>A : Symbol(A, Decl(discriminantsAndTypePredicates.ts, 0, 0))
>type : Symbol(A.type, Decl(discriminantsAndTypePredicates.ts, 2, 13))
interface B { type: 'B' }
>B : Symbol(B, Decl(discriminantsAndTypePredicates.ts, 2, 25))
>type : Symbol(B.type, Decl(discriminantsAndTypePredicates.ts, 3, 13))
function isA(x: A | B): x is A { return x.type === 'A'; }
>isA : Symbol(isA, Decl(discriminantsAndTypePredicates.ts, 3, 25))
>x : Symbol(x, Decl(discriminantsAndTypePredicates.ts, 5, 13))
>A : Symbol(A, Decl(discriminantsAndTypePredicates.ts, 0, 0))
>B : Symbol(B, Decl(discriminantsAndTypePredicates.ts, 2, 25))
>x : Symbol(x, Decl(discriminantsAndTypePredicates.ts, 5, 13))
>A : Symbol(A, Decl(discriminantsAndTypePredicates.ts, 0, 0))
>x.type : Symbol(type, Decl(discriminantsAndTypePredicates.ts, 2, 13), Decl(discriminantsAndTypePredicates.ts, 3, 13))
>x : Symbol(x, Decl(discriminantsAndTypePredicates.ts, 5, 13))
>type : Symbol(type, Decl(discriminantsAndTypePredicates.ts, 2, 13), Decl(discriminantsAndTypePredicates.ts, 3, 13))
function isB(x: A | B): x is B { return x.type === 'B'; }
>isB : Symbol(isB, Decl(discriminantsAndTypePredicates.ts, 5, 57))
>x : Symbol(x, Decl(discriminantsAndTypePredicates.ts, 6, 13))
>A : Symbol(A, Decl(discriminantsAndTypePredicates.ts, 0, 0))
>B : Symbol(B, Decl(discriminantsAndTypePredicates.ts, 2, 25))
>x : Symbol(x, Decl(discriminantsAndTypePredicates.ts, 6, 13))
>B : Symbol(B, Decl(discriminantsAndTypePredicates.ts, 2, 25))
>x.type : Symbol(type, Decl(discriminantsAndTypePredicates.ts, 2, 13), Decl(discriminantsAndTypePredicates.ts, 3, 13))
>x : Symbol(x, Decl(discriminantsAndTypePredicates.ts, 6, 13))
>type : Symbol(type, Decl(discriminantsAndTypePredicates.ts, 2, 13), Decl(discriminantsAndTypePredicates.ts, 3, 13))
function foo1(x: A | B): any {
>foo1 : Symbol(foo1, Decl(discriminantsAndTypePredicates.ts, 6, 57))
>x : Symbol(x, Decl(discriminantsAndTypePredicates.ts, 8, 14))
>A : Symbol(A, Decl(discriminantsAndTypePredicates.ts, 0, 0))
>B : Symbol(B, Decl(discriminantsAndTypePredicates.ts, 2, 25))
x; // A | B
>x : Symbol(x, Decl(discriminantsAndTypePredicates.ts, 8, 14))
if (isA(x)) {
>isA : Symbol(isA, Decl(discriminantsAndTypePredicates.ts, 3, 25))
>x : Symbol(x, Decl(discriminantsAndTypePredicates.ts, 8, 14))
return x; // A
>x : Symbol(x, Decl(discriminantsAndTypePredicates.ts, 8, 14))
}
x; // B
>x : Symbol(x, Decl(discriminantsAndTypePredicates.ts, 8, 14))
if (isB(x)) {
>isB : Symbol(isB, Decl(discriminantsAndTypePredicates.ts, 5, 57))
>x : Symbol(x, Decl(discriminantsAndTypePredicates.ts, 8, 14))
return x; // B
>x : Symbol(x, Decl(discriminantsAndTypePredicates.ts, 8, 14))
}
x; // never
>x : Symbol(x, Decl(discriminantsAndTypePredicates.ts, 8, 14))
}
function foo2(x: A | B): any {
>foo2 : Symbol(foo2, Decl(discriminantsAndTypePredicates.ts, 18, 1))
>x : Symbol(x, Decl(discriminantsAndTypePredicates.ts, 20, 14))
>A : Symbol(A, Decl(discriminantsAndTypePredicates.ts, 0, 0))
>B : Symbol(B, Decl(discriminantsAndTypePredicates.ts, 2, 25))
x; // A | B
>x : Symbol(x, Decl(discriminantsAndTypePredicates.ts, 20, 14))
if (x.type === 'A') {
>x.type : Symbol(type, Decl(discriminantsAndTypePredicates.ts, 2, 13), Decl(discriminantsAndTypePredicates.ts, 3, 13))
>x : Symbol(x, Decl(discriminantsAndTypePredicates.ts, 20, 14))
>type : Symbol(type, Decl(discriminantsAndTypePredicates.ts, 2, 13), Decl(discriminantsAndTypePredicates.ts, 3, 13))
return x; // A
>x : Symbol(x, Decl(discriminantsAndTypePredicates.ts, 20, 14))
}
x; // B
>x : Symbol(x, Decl(discriminantsAndTypePredicates.ts, 20, 14))
if (x.type === 'B') {
>x.type : Symbol(B.type, Decl(discriminantsAndTypePredicates.ts, 3, 13))
>x : Symbol(x, Decl(discriminantsAndTypePredicates.ts, 20, 14))
>type : Symbol(B.type, Decl(discriminantsAndTypePredicates.ts, 3, 13))
return x; // B
>x : Symbol(x, Decl(discriminantsAndTypePredicates.ts, 20, 14))
}
x; // never
>x : Symbol(x, Decl(discriminantsAndTypePredicates.ts, 20, 14))
}
@@ -0,0 +1,104 @@
=== tests/cases/compiler/discriminantsAndTypePredicates.ts ===
// Repro from #10145
interface A { type: 'A' }
>A : A
>type : "A"
interface B { type: 'B' }
>B : B
>type : "B"
function isA(x: A | B): x is A { return x.type === 'A'; }
>isA : (x: A | B) => x is A
>x : A | B
>A : A
>B : B
>x : any
>A : A
>x.type === 'A' : boolean
>x.type : "A" | "B"
>x : A | B
>type : "A" | "B"
>'A' : "A"
function isB(x: A | B): x is B { return x.type === 'B'; }
>isB : (x: A | B) => x is B
>x : A | B
>A : A
>B : B
>x : any
>B : B
>x.type === 'B' : boolean
>x.type : "A" | "B"
>x : A | B
>type : "A" | "B"
>'B' : "B"
function foo1(x: A | B): any {
>foo1 : (x: A | B) => any
>x : A | B
>A : A
>B : B
x; // A | B
>x : A | B
if (isA(x)) {
>isA(x) : boolean
>isA : (x: A | B) => x is A
>x : A | B
return x; // A
>x : A
}
x; // B
>x : B
if (isB(x)) {
>isB(x) : boolean
>isB : (x: A | B) => x is B
>x : B
return x; // B
>x : B
}
x; // never
>x : never
}
function foo2(x: A | B): any {
>foo2 : (x: A | B) => any
>x : A | B
>A : A
>B : B
x; // A | B
>x : A | B
if (x.type === 'A') {
>x.type === 'A' : boolean
>x.type : "A" | "B"
>x : A | B
>type : "A" | "B"
>'A' : "A"
return x; // A
>x : A
}
x; // B
>x : B
if (x.type === 'B') {
>x.type === 'B' : boolean
>x.type : "B"
>x : B
>type : "B"
>'B' : "B"
return x; // B
>x : B
}
x; // never
>x : never
}
@@ -0,0 +1,13 @@
tests/cases/compiler/emitCapturingThisInTupleDestructuring1.ts(3,17): error TS2493: Tuple type '[any]' with length '1' cannot be assigned to tuple with length '3'.
tests/cases/compiler/emitCapturingThisInTupleDestructuring1.ts(3,29): error TS2493: Tuple type '[any]' with length '1' cannot be assigned to tuple with length '3'.
==== tests/cases/compiler/emitCapturingThisInTupleDestructuring1.ts (2 errors) ====
declare function wrapper(x: any);
wrapper((array: [any]) => {
[this.test, this.test1, this.test2] = array; // even though there is a compiler error, we should still emit lexical capture for "this"
~~~~~~~~~~
!!! error TS2493: Tuple type '[any]' with length '1' cannot be assigned to tuple with length '3'.
~~~~~~~~~~
!!! error TS2493: Tuple type '[any]' with length '1' cannot be assigned to tuple with length '3'.
});
@@ -0,0 +1,11 @@
//// [emitCapturingThisInTupleDestructuring1.ts]
declare function wrapper(x: any);
wrapper((array: [any]) => {
[this.test, this.test1, this.test2] = array; // even though there is a compiler error, we should still emit lexical capture for "this"
});
//// [emitCapturingThisInTupleDestructuring1.js]
var _this = this;
wrapper(function (array) {
_this.test = array[0], _this.test1 = array[1], _this.test2 = array[2]; // even though there is a compiler error, we should still emit lexical capture for "this"
});
@@ -0,0 +1,16 @@
tests/cases/compiler/emitCapturingThisInTupleDestructuring2.ts(8,39): error TS2493: Tuple type '[number, number]' with length '2' cannot be assigned to tuple with length '3'.
==== tests/cases/compiler/emitCapturingThisInTupleDestructuring2.ts (1 errors) ====
var array1: [number, number] = [1, 2];
class B {
test: number;
test1: any;
test2: any;
method() {
() => [this.test, this.test1, this.test2] = array1; // even though there is a compiler error, we should still emit lexical capture for "this"
~~~~~~~~~~
!!! error TS2493: Tuple type '[number, number]' with length '2' cannot be assigned to tuple with length '3'.
}
}
@@ -0,0 +1,23 @@
//// [emitCapturingThisInTupleDestructuring2.ts]
var array1: [number, number] = [1, 2];
class B {
test: number;
test1: any;
test2: any;
method() {
() => [this.test, this.test1, this.test2] = array1; // even though there is a compiler error, we should still emit lexical capture for "this"
}
}
//// [emitCapturingThisInTupleDestructuring2.js]
var array1 = [1, 2];
var B = (function () {
function B() {
}
B.prototype.method = function () {
var _this = this;
(function () { return (_this.test = array1[0], _this.test1 = array1[1], _this.test2 = array1[2], array1); }); // even though there is a compiler error, we should still emit lexical capture for "this"
};
return B;
}());
@@ -15,9 +15,9 @@ function rebase(fn: (base: any, ...args: any[]) => any): (...args: any[]) => any
>fn : Symbol(fn, Decl(emitSkipsThisWithRestParameter.ts, 0, 16))
>apply : Symbol(Function.apply, Decl(lib.d.ts, --, --))
>this : Symbol(this, Decl(emitSkipsThisWithRestParameter.ts, 1, 20))
>[ this ].concat : Symbol(Array.concat, Decl(lib.d.ts, --, --))
>[ this ].concat : Symbol(Array.concat, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>this : Symbol(this, Decl(emitSkipsThisWithRestParameter.ts, 1, 20))
>concat : Symbol(Array.concat, Decl(lib.d.ts, --, --))
>concat : Symbol(Array.concat, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>args : Symbol(args, Decl(emitSkipsThisWithRestParameter.ts, 1, 30))
};
@@ -18,10 +18,10 @@ function rebase(fn: (base: any, ...args: any[]) => any): (...args: any[]) => any
>apply : (this: Function, thisArg: any, argArray?: any) => any
>this : any
>[ this ].concat(args) : any[]
>[ this ].concat : (...items: any[]) => any[]
>[ this ].concat : { (...items: any[][]): any[]; (...items: any[]): any[]; }
>[ this ] : any[]
>this : any
>concat : (...items: any[]) => any[]
>concat : { (...items: any[][]): any[]; (...items: any[]): any[]; }
>args : any[]
};
@@ -0,0 +1,76 @@
//// [tests/cases/compiler/exportDefaultProperty.ts] ////
//// [declarations.d.ts]
// This test is just like exportEqualsProperty, but with `export default`.
declare namespace foo.bar {
export type X = number;
export const X: number;
}
declare module "foobar" {
export default foo.bar;
}
declare module "foobarx" {
export default foo.bar.X;
}
//// [a.ts]
namespace A {
export class B { constructor(b: number) {} }
export namespace B { export const b: number = 0; }
}
export default A.B;
//// [b.ts]
export default "foo".length;
//// [index.ts]
/// <reference path="declarations.d.ts" />
import fooBar from "foobar";
import X = fooBar.X;
import X2 from "foobarx";
const x: X = X;
const x2: X2 = X2;
import B from "./a";
const b: B = new B(B.b);
import fooLength from "./b";
fooLength + 1;
//// [a.js]
"use strict";
var A;
(function (A) {
var B = (function () {
function B(b) {
}
return B;
}());
A.B = B;
var B;
(function (B) {
B.b = 0;
})(B = A.B || (A.B = {}));
})(A || (A = {}));
exports.__esModule = true;
exports["default"] = A.B;
//// [b.js]
"use strict";
exports.__esModule = true;
exports["default"] = "foo".length;
//// [index.js]
"use strict";
/// <reference path="declarations.d.ts" />
var foobar_1 = require("foobar");
var X = foobar_1["default"].X;
var foobarx_1 = require("foobarx");
var x = X;
var x2 = foobarx_1["default"];
var a_1 = require("./a");
var b = new a_1["default"](a_1["default"].b);
var b_1 = require("./b");
b_1["default"] + 1;
@@ -0,0 +1,92 @@
=== tests/cases/compiler/index.ts ===
/// <reference path="declarations.d.ts" />
import fooBar from "foobar";
>fooBar : Symbol(fooBar, Decl(index.ts, 1, 6))
import X = fooBar.X;
>X : Symbol(X, Decl(index.ts, 1, 28))
>fooBar : Symbol(fooBar, Decl(index.ts, 1, 6))
>X : Symbol(fooBar.X, Decl(declarations.d.ts, 2, 27), Decl(declarations.d.ts, 4, 16))
import X2 from "foobarx";
>X2 : Symbol(X2, Decl(index.ts, 3, 6))
const x: X = X;
>x : Symbol(x, Decl(index.ts, 4, 5))
>X : Symbol(X, Decl(index.ts, 1, 28))
>X : Symbol(X, Decl(index.ts, 1, 28))
const x2: X2 = X2;
>x2 : Symbol(x2, Decl(index.ts, 5, 5))
>X2 : Symbol(X2, Decl(index.ts, 3, 6))
>X2 : Symbol(X2, Decl(index.ts, 3, 6))
import B from "./a";
>B : Symbol(B, Decl(index.ts, 7, 6))
const b: B = new B(B.b);
>b : Symbol(b, Decl(index.ts, 8, 5))
>B : Symbol(B, Decl(index.ts, 7, 6))
>B : Symbol(B, Decl(index.ts, 7, 6))
>B.b : Symbol(B.b, Decl(a.ts, 2, 37))
>B : Symbol(B, Decl(index.ts, 7, 6))
>b : Symbol(B.b, Decl(a.ts, 2, 37))
import fooLength from "./b";
>fooLength : Symbol(fooLength, Decl(index.ts, 10, 6))
fooLength + 1;
>fooLength : Symbol(fooLength, Decl(index.ts, 10, 6))
=== tests/cases/compiler/declarations.d.ts ===
// This test is just like exportEqualsProperty, but with `export default`.
declare namespace foo.bar {
>foo : Symbol(foo, Decl(declarations.d.ts, 0, 0))
>bar : Symbol(bar, Decl(declarations.d.ts, 2, 22))
export type X = number;
>X : Symbol(X, Decl(declarations.d.ts, 2, 27), Decl(declarations.d.ts, 4, 16))
export const X: number;
>X : Symbol(X, Decl(declarations.d.ts, 2, 27), Decl(declarations.d.ts, 4, 16))
}
declare module "foobar" {
export default foo.bar;
>foo.bar : Symbol(default, Decl(declarations.d.ts, 2, 22))
>foo : Symbol(foo, Decl(declarations.d.ts, 0, 0))
>bar : Symbol(default, Decl(declarations.d.ts, 2, 22))
}
declare module "foobarx" {
export default foo.bar.X;
>foo.bar.X : Symbol(default, Decl(declarations.d.ts, 2, 27), Decl(declarations.d.ts, 4, 16))
>foo.bar : Symbol(foo.bar, Decl(declarations.d.ts, 2, 22))
>foo : Symbol(foo, Decl(declarations.d.ts, 0, 0))
>bar : Symbol(foo.bar, Decl(declarations.d.ts, 2, 22))
>X : Symbol(default, Decl(declarations.d.ts, 2, 27), Decl(declarations.d.ts, 4, 16))
}
=== tests/cases/compiler/a.ts ===
namespace A {
>A : Symbol(A, Decl(a.ts, 0, 0))
export class B { constructor(b: number) {} }
>B : Symbol(B, Decl(a.ts, 0, 13), Decl(a.ts, 1, 48))
>b : Symbol(b, Decl(a.ts, 1, 33))
export namespace B { export const b: number = 0; }
>B : Symbol(B, Decl(a.ts, 0, 13), Decl(a.ts, 1, 48))
>b : Symbol(b, Decl(a.ts, 2, 37))
}
export default A.B;
>A.B : Symbol(default, Decl(a.ts, 0, 13), Decl(a.ts, 1, 48))
>A : Symbol(A, Decl(a.ts, 0, 0))
>B : Symbol(default, Decl(a.ts, 0, 13), Decl(a.ts, 1, 48))
=== tests/cases/compiler/b.ts ===
export default "foo".length;
>"foo".length : Symbol(String.length, Decl(lib.d.ts, --, --))
>length : Symbol(String.length, Decl(lib.d.ts, --, --))
@@ -0,0 +1,97 @@
=== tests/cases/compiler/index.ts ===
/// <reference path="declarations.d.ts" />
import fooBar from "foobar";
>fooBar : typeof fooBar
import X = fooBar.X;
>X : number
>fooBar : typeof fooBar
>X : number
import X2 from "foobarx";
>X2 : number
const x: X = X;
>x : number
>X : number
>X : number
const x2: X2 = X2;
>x2 : number
>X2 : number
>X2 : number
import B from "./a";
>B : typeof B
const b: B = new B(B.b);
>b : B
>B : B
>new B(B.b) : B
>B : typeof B
>B.b : number
>B : typeof B
>b : number
import fooLength from "./b";
>fooLength : number
fooLength + 1;
>fooLength + 1 : number
>fooLength : number
>1 : number
=== tests/cases/compiler/declarations.d.ts ===
// This test is just like exportEqualsProperty, but with `export default`.
declare namespace foo.bar {
>foo : typeof foo
>bar : typeof bar
export type X = number;
>X : number
export const X: number;
>X : number
}
declare module "foobar" {
export default foo.bar;
>foo.bar : typeof default
>foo : typeof foo
>bar : typeof default
}
declare module "foobarx" {
export default foo.bar.X;
>foo.bar.X : number
>foo.bar : typeof foo.bar
>foo : typeof foo
>bar : typeof foo.bar
>X : number
}
=== tests/cases/compiler/a.ts ===
namespace A {
>A : typeof A
export class B { constructor(b: number) {} }
>B : B
>b : number
export namespace B { export const b: number = 0; }
>B : typeof B
>b : number
>0 : number
}
export default A.B;
>A.B : typeof default
>A : typeof A
>B : typeof default
=== tests/cases/compiler/b.ts ===
export default "foo".length;
>"foo".length : number
>"foo" : string
>length : number
@@ -0,0 +1,72 @@
//// [tests/cases/compiler/exportEqualsProperty.ts] ////
//// [declarations.d.ts]
// This test is just like exportDefaultProperty, but with `export =`.
declare namespace foo.bar {
export type X = number;
export const X: number;
}
declare module "foobar" {
export = foo.bar;
}
declare module "foobarx" {
export = foo.bar.X;
}
//// [a.ts]
namespace A {
export class B { constructor(b: number) {} }
export namespace B { export const b: number = 0; }
}
export = A.B;
//// [b.ts]
export = "foo".length;
//// [index.ts]
/// <reference path="declarations.d.ts" />
import { X } from "foobar";
import X2 = require("foobarx");
const x: X = X;
const x2: X2 = X2;
import B = require("./a");
const b: B = new B(B.b);
import fooLength = require("./b");
fooLength + 1;
//// [a.js]
"use strict";
var A;
(function (A) {
var B = (function () {
function B(b) {
}
return B;
}());
A.B = B;
var B;
(function (B) {
B.b = 0;
})(B = A.B || (A.B = {}));
})(A || (A = {}));
module.exports = A.B;
//// [b.js]
"use strict";
module.exports = "foo".length;
//// [index.js]
"use strict";
/// <reference path="declarations.d.ts" />
var foobar_1 = require("foobar");
var X2 = require("foobarx");
var x = foobar_1.X;
var x2 = X2;
var B = require("./a");
var b = new B(B.b);
var fooLength = require("./b");
fooLength + 1;
@@ -0,0 +1,87 @@
=== tests/cases/compiler/index.ts ===
/// <reference path="declarations.d.ts" />
import { X } from "foobar";
>X : Symbol(X, Decl(index.ts, 1, 8))
import X2 = require("foobarx");
>X2 : Symbol(X2, Decl(index.ts, 1, 27))
const x: X = X;
>x : Symbol(x, Decl(index.ts, 3, 5))
>X : Symbol(X, Decl(index.ts, 1, 8))
>X : Symbol(X, Decl(index.ts, 1, 8))
const x2: X2 = X2;
>x2 : Symbol(x2, Decl(index.ts, 4, 5))
>X2 : Symbol(X2, Decl(index.ts, 1, 27))
>X2 : Symbol(X2, Decl(index.ts, 1, 27))
import B = require("./a");
>B : Symbol(B, Decl(index.ts, 4, 18))
const b: B = new B(B.b);
>b : Symbol(b, Decl(index.ts, 7, 5))
>B : Symbol(B, Decl(index.ts, 4, 18))
>B : Symbol(B, Decl(index.ts, 4, 18))
>B.b : Symbol(B.b, Decl(a.ts, 2, 37))
>B : Symbol(B, Decl(index.ts, 4, 18))
>b : Symbol(B.b, Decl(a.ts, 2, 37))
import fooLength = require("./b");
>fooLength : Symbol(fooLength, Decl(index.ts, 7, 24))
fooLength + 1;
>fooLength : Symbol(fooLength, Decl(index.ts, 7, 24))
=== tests/cases/compiler/declarations.d.ts ===
// This test is just like exportDefaultProperty, but with `export =`.
declare namespace foo.bar {
>foo : Symbol(foo, Decl(declarations.d.ts, 0, 0))
>bar : Symbol(bar, Decl(declarations.d.ts, 2, 22))
export type X = number;
>X : Symbol(X, Decl(declarations.d.ts, 2, 27), Decl(declarations.d.ts, 4, 16))
export const X: number;
>X : Symbol(X, Decl(declarations.d.ts, 2, 27), Decl(declarations.d.ts, 4, 16))
}
declare module "foobar" {
export = foo.bar;
>foo.bar : Symbol(foo.bar, Decl(declarations.d.ts, 2, 22))
>foo : Symbol(foo, Decl(declarations.d.ts, 0, 0))
>bar : Symbol(foo.bar, Decl(declarations.d.ts, 2, 22))
}
declare module "foobarx" {
export = foo.bar.X;
>foo.bar.X : Symbol(foo.bar.X, Decl(declarations.d.ts, 2, 27), Decl(declarations.d.ts, 4, 16))
>foo.bar : Symbol(foo.bar, Decl(declarations.d.ts, 2, 22))
>foo : Symbol(foo, Decl(declarations.d.ts, 0, 0))
>bar : Symbol(foo.bar, Decl(declarations.d.ts, 2, 22))
>X : Symbol(foo.bar.X, Decl(declarations.d.ts, 2, 27), Decl(declarations.d.ts, 4, 16))
}
=== tests/cases/compiler/a.ts ===
namespace A {
>A : Symbol(A, Decl(a.ts, 0, 0))
export class B { constructor(b: number) {} }
>B : Symbol(B, Decl(a.ts, 0, 13), Decl(a.ts, 1, 48))
>b : Symbol(b, Decl(a.ts, 1, 33))
export namespace B { export const b: number = 0; }
>B : Symbol(B, Decl(a.ts, 0, 13), Decl(a.ts, 1, 48))
>b : Symbol(b, Decl(a.ts, 2, 37))
}
export = A.B;
>A.B : Symbol(A.B, Decl(a.ts, 0, 13), Decl(a.ts, 1, 48))
>A : Symbol(A, Decl(a.ts, 0, 0))
>B : Symbol(A.B, Decl(a.ts, 0, 13), Decl(a.ts, 1, 48))
=== tests/cases/compiler/b.ts ===
export = "foo".length;
>"foo".length : Symbol(String.length, Decl(lib.d.ts, --, --))
>length : Symbol(String.length, Decl(lib.d.ts, --, --))
@@ -0,0 +1,92 @@
=== tests/cases/compiler/index.ts ===
/// <reference path="declarations.d.ts" />
import { X } from "foobar";
>X : number
import X2 = require("foobarx");
>X2 : number
const x: X = X;
>x : number
>X : number
>X : number
const x2: X2 = X2;
>x2 : number
>X2 : number
>X2 : number
import B = require("./a");
>B : typeof B
const b: B = new B(B.b);
>b : B
>B : B
>new B(B.b) : B
>B : typeof B
>B.b : number
>B : typeof B
>b : number
import fooLength = require("./b");
>fooLength : number
fooLength + 1;
>fooLength + 1 : number
>fooLength : number
>1 : number
=== tests/cases/compiler/declarations.d.ts ===
// This test is just like exportDefaultProperty, but with `export =`.
declare namespace foo.bar {
>foo : typeof foo
>bar : typeof bar
export type X = number;
>X : number
export const X: number;
>X : number
}
declare module "foobar" {
export = foo.bar;
>foo.bar : typeof foo.bar
>foo : typeof foo
>bar : typeof foo.bar
}
declare module "foobarx" {
export = foo.bar.X;
>foo.bar.X : number
>foo.bar : typeof foo.bar
>foo : typeof foo
>bar : typeof foo.bar
>X : number
}
=== tests/cases/compiler/a.ts ===
namespace A {
>A : typeof A
export class B { constructor(b: number) {} }
>B : B
>b : number
export namespace B { export const b: number = 0; }
>B : typeof B
>b : number
>0 : number
}
export = A.B;
>A.B : typeof A.B
>A : typeof A
>B : typeof A.B
=== tests/cases/compiler/b.ts ===
export = "foo".length;
>"foo".length : number
>"foo" : string
>length : number
@@ -0,0 +1,9 @@
//// [exportToString.ts]
const toString = 0;
export { toString };
//// [exportToString.js]
"use strict";
var toString = 0;
exports.toString = toString;
@@ -0,0 +1,7 @@
=== tests/cases/compiler/exportToString.ts ===
const toString = 0;
>toString : Symbol(toString, Decl(exportToString.ts, 0, 5))
export { toString };
>toString : Symbol(toString, Decl(exportToString.ts, 1, 8))
@@ -0,0 +1,8 @@
=== tests/cases/compiler/exportToString.ts ===
const toString = 0;
>toString : number
>0 : number
export { toString };
>toString : number
@@ -0,0 +1,172 @@
//// [instanceofWithStructurallyIdenticalTypes.ts]
// Repro from #7271
class C1 { item: string }
class C2 { item: string[] }
class C3 { item: string }
function foo1(x: C1 | C2 | C3): string {
if (x instanceof C1) {
return x.item;
}
else if (x instanceof C2) {
return x.item[0];
}
else if (x instanceof C3) {
return x.item;
}
return "error";
}
function isC1(c: C1 | C2 | C3): c is C1 { return c instanceof C1 }
function isC2(c: C1 | C2 | C3): c is C2 { return c instanceof C2 }
function isC3(c: C1 | C2 | C3): c is C3 { return c instanceof C3 }
function foo2(x: C1 | C2 | C3): string {
if (isC1(x)) {
return x.item;
}
else if (isC2(x)) {
return x.item[0];
}
else if (isC3(x)) {
return x.item;
}
return "error";
}
// More tests
class A { a: string }
class A1 extends A { }
class A2 { a: string }
class B extends A { b: string }
function goo(x: A) {
if (x instanceof A) {
x; // A
}
else {
x; // never
}
if (x instanceof A1) {
x; // A1
}
else {
x; // A
}
if (x instanceof A2) {
x; // A2
}
else {
x; // A
}
if (x instanceof B) {
x; // B
}
else {
x; // A
}
}
//// [instanceofWithStructurallyIdenticalTypes.js]
// Repro from #7271
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var C1 = (function () {
function C1() {
}
return C1;
}());
var C2 = (function () {
function C2() {
}
return C2;
}());
var C3 = (function () {
function C3() {
}
return C3;
}());
function foo1(x) {
if (x instanceof C1) {
return x.item;
}
else if (x instanceof C2) {
return x.item[0];
}
else if (x instanceof C3) {
return x.item;
}
return "error";
}
function isC1(c) { return c instanceof C1; }
function isC2(c) { return c instanceof C2; }
function isC3(c) { return c instanceof C3; }
function foo2(x) {
if (isC1(x)) {
return x.item;
}
else if (isC2(x)) {
return x.item[0];
}
else if (isC3(x)) {
return x.item;
}
return "error";
}
// More tests
var A = (function () {
function A() {
}
return A;
}());
var A1 = (function (_super) {
__extends(A1, _super);
function A1() {
_super.apply(this, arguments);
}
return A1;
}(A));
var A2 = (function () {
function A2() {
}
return A2;
}());
var B = (function (_super) {
__extends(B, _super);
function B() {
_super.apply(this, arguments);
}
return B;
}(A));
function goo(x) {
if (x instanceof A) {
x; // A
}
else {
x; // never
}
if (x instanceof A1) {
x; // A1
}
else {
x; // A
}
if (x instanceof A2) {
x; // A2
}
else {
x; // A
}
if (x instanceof B) {
x; // B
}
else {
x; // A
}
}
@@ -0,0 +1,192 @@
=== tests/cases/compiler/instanceofWithStructurallyIdenticalTypes.ts ===
// Repro from #7271
class C1 { item: string }
>C1 : Symbol(C1, Decl(instanceofWithStructurallyIdenticalTypes.ts, 0, 0))
>item : Symbol(C1.item, Decl(instanceofWithStructurallyIdenticalTypes.ts, 2, 10))
class C2 { item: string[] }
>C2 : Symbol(C2, Decl(instanceofWithStructurallyIdenticalTypes.ts, 2, 25))
>item : Symbol(C2.item, Decl(instanceofWithStructurallyIdenticalTypes.ts, 3, 10))
class C3 { item: string }
>C3 : Symbol(C3, Decl(instanceofWithStructurallyIdenticalTypes.ts, 3, 27))
>item : Symbol(C3.item, Decl(instanceofWithStructurallyIdenticalTypes.ts, 4, 10))
function foo1(x: C1 | C2 | C3): string {
>foo1 : Symbol(foo1, Decl(instanceofWithStructurallyIdenticalTypes.ts, 4, 25))
>x : Symbol(x, Decl(instanceofWithStructurallyIdenticalTypes.ts, 6, 14))
>C1 : Symbol(C1, Decl(instanceofWithStructurallyIdenticalTypes.ts, 0, 0))
>C2 : Symbol(C2, Decl(instanceofWithStructurallyIdenticalTypes.ts, 2, 25))
>C3 : Symbol(C3, Decl(instanceofWithStructurallyIdenticalTypes.ts, 3, 27))
if (x instanceof C1) {
>x : Symbol(x, Decl(instanceofWithStructurallyIdenticalTypes.ts, 6, 14))
>C1 : Symbol(C1, Decl(instanceofWithStructurallyIdenticalTypes.ts, 0, 0))
return x.item;
>x.item : Symbol(C1.item, Decl(instanceofWithStructurallyIdenticalTypes.ts, 2, 10))
>x : Symbol(x, Decl(instanceofWithStructurallyIdenticalTypes.ts, 6, 14))
>item : Symbol(C1.item, Decl(instanceofWithStructurallyIdenticalTypes.ts, 2, 10))
}
else if (x instanceof C2) {
>x : Symbol(x, Decl(instanceofWithStructurallyIdenticalTypes.ts, 6, 14))
>C2 : Symbol(C2, Decl(instanceofWithStructurallyIdenticalTypes.ts, 2, 25))
return x.item[0];
>x.item : Symbol(C2.item, Decl(instanceofWithStructurallyIdenticalTypes.ts, 3, 10))
>x : Symbol(x, Decl(instanceofWithStructurallyIdenticalTypes.ts, 6, 14))
>item : Symbol(C2.item, Decl(instanceofWithStructurallyIdenticalTypes.ts, 3, 10))
}
else if (x instanceof C3) {
>x : Symbol(x, Decl(instanceofWithStructurallyIdenticalTypes.ts, 6, 14))
>C3 : Symbol(C3, Decl(instanceofWithStructurallyIdenticalTypes.ts, 3, 27))
return x.item;
>x.item : Symbol(C3.item, Decl(instanceofWithStructurallyIdenticalTypes.ts, 4, 10))
>x : Symbol(x, Decl(instanceofWithStructurallyIdenticalTypes.ts, 6, 14))
>item : Symbol(C3.item, Decl(instanceofWithStructurallyIdenticalTypes.ts, 4, 10))
}
return "error";
}
function isC1(c: C1 | C2 | C3): c is C1 { return c instanceof C1 }
>isC1 : Symbol(isC1, Decl(instanceofWithStructurallyIdenticalTypes.ts, 17, 1))
>c : Symbol(c, Decl(instanceofWithStructurallyIdenticalTypes.ts, 19, 14))
>C1 : Symbol(C1, Decl(instanceofWithStructurallyIdenticalTypes.ts, 0, 0))
>C2 : Symbol(C2, Decl(instanceofWithStructurallyIdenticalTypes.ts, 2, 25))
>C3 : Symbol(C3, Decl(instanceofWithStructurallyIdenticalTypes.ts, 3, 27))
>c : Symbol(c, Decl(instanceofWithStructurallyIdenticalTypes.ts, 19, 14))
>C1 : Symbol(C1, Decl(instanceofWithStructurallyIdenticalTypes.ts, 0, 0))
>c : Symbol(c, Decl(instanceofWithStructurallyIdenticalTypes.ts, 19, 14))
>C1 : Symbol(C1, Decl(instanceofWithStructurallyIdenticalTypes.ts, 0, 0))
function isC2(c: C1 | C2 | C3): c is C2 { return c instanceof C2 }
>isC2 : Symbol(isC2, Decl(instanceofWithStructurallyIdenticalTypes.ts, 19, 66))
>c : Symbol(c, Decl(instanceofWithStructurallyIdenticalTypes.ts, 20, 14))
>C1 : Symbol(C1, Decl(instanceofWithStructurallyIdenticalTypes.ts, 0, 0))
>C2 : Symbol(C2, Decl(instanceofWithStructurallyIdenticalTypes.ts, 2, 25))
>C3 : Symbol(C3, Decl(instanceofWithStructurallyIdenticalTypes.ts, 3, 27))
>c : Symbol(c, Decl(instanceofWithStructurallyIdenticalTypes.ts, 20, 14))
>C2 : Symbol(C2, Decl(instanceofWithStructurallyIdenticalTypes.ts, 2, 25))
>c : Symbol(c, Decl(instanceofWithStructurallyIdenticalTypes.ts, 20, 14))
>C2 : Symbol(C2, Decl(instanceofWithStructurallyIdenticalTypes.ts, 2, 25))
function isC3(c: C1 | C2 | C3): c is C3 { return c instanceof C3 }
>isC3 : Symbol(isC3, Decl(instanceofWithStructurallyIdenticalTypes.ts, 20, 66))
>c : Symbol(c, Decl(instanceofWithStructurallyIdenticalTypes.ts, 21, 14))
>C1 : Symbol(C1, Decl(instanceofWithStructurallyIdenticalTypes.ts, 0, 0))
>C2 : Symbol(C2, Decl(instanceofWithStructurallyIdenticalTypes.ts, 2, 25))
>C3 : Symbol(C3, Decl(instanceofWithStructurallyIdenticalTypes.ts, 3, 27))
>c : Symbol(c, Decl(instanceofWithStructurallyIdenticalTypes.ts, 21, 14))
>C3 : Symbol(C3, Decl(instanceofWithStructurallyIdenticalTypes.ts, 3, 27))
>c : Symbol(c, Decl(instanceofWithStructurallyIdenticalTypes.ts, 21, 14))
>C3 : Symbol(C3, Decl(instanceofWithStructurallyIdenticalTypes.ts, 3, 27))
function foo2(x: C1 | C2 | C3): string {
>foo2 : Symbol(foo2, Decl(instanceofWithStructurallyIdenticalTypes.ts, 21, 66))
>x : Symbol(x, Decl(instanceofWithStructurallyIdenticalTypes.ts, 23, 14))
>C1 : Symbol(C1, Decl(instanceofWithStructurallyIdenticalTypes.ts, 0, 0))
>C2 : Symbol(C2, Decl(instanceofWithStructurallyIdenticalTypes.ts, 2, 25))
>C3 : Symbol(C3, Decl(instanceofWithStructurallyIdenticalTypes.ts, 3, 27))
if (isC1(x)) {
>isC1 : Symbol(isC1, Decl(instanceofWithStructurallyIdenticalTypes.ts, 17, 1))
>x : Symbol(x, Decl(instanceofWithStructurallyIdenticalTypes.ts, 23, 14))
return x.item;
>x.item : Symbol(C1.item, Decl(instanceofWithStructurallyIdenticalTypes.ts, 2, 10))
>x : Symbol(x, Decl(instanceofWithStructurallyIdenticalTypes.ts, 23, 14))
>item : Symbol(C1.item, Decl(instanceofWithStructurallyIdenticalTypes.ts, 2, 10))
}
else if (isC2(x)) {
>isC2 : Symbol(isC2, Decl(instanceofWithStructurallyIdenticalTypes.ts, 19, 66))
>x : Symbol(x, Decl(instanceofWithStructurallyIdenticalTypes.ts, 23, 14))
return x.item[0];
>x.item : Symbol(C2.item, Decl(instanceofWithStructurallyIdenticalTypes.ts, 3, 10))
>x : Symbol(x, Decl(instanceofWithStructurallyIdenticalTypes.ts, 23, 14))
>item : Symbol(C2.item, Decl(instanceofWithStructurallyIdenticalTypes.ts, 3, 10))
}
else if (isC3(x)) {
>isC3 : Symbol(isC3, Decl(instanceofWithStructurallyIdenticalTypes.ts, 20, 66))
>x : Symbol(x, Decl(instanceofWithStructurallyIdenticalTypes.ts, 23, 14))
return x.item;
>x.item : Symbol(C3.item, Decl(instanceofWithStructurallyIdenticalTypes.ts, 4, 10))
>x : Symbol(x, Decl(instanceofWithStructurallyIdenticalTypes.ts, 23, 14))
>item : Symbol(C3.item, Decl(instanceofWithStructurallyIdenticalTypes.ts, 4, 10))
}
return "error";
}
// More tests
class A { a: string }
>A : Symbol(A, Decl(instanceofWithStructurallyIdenticalTypes.ts, 34, 1))
>a : Symbol(A.a, Decl(instanceofWithStructurallyIdenticalTypes.ts, 38, 9))
class A1 extends A { }
>A1 : Symbol(A1, Decl(instanceofWithStructurallyIdenticalTypes.ts, 38, 21))
>A : Symbol(A, Decl(instanceofWithStructurallyIdenticalTypes.ts, 34, 1))
class A2 { a: string }
>A2 : Symbol(A2, Decl(instanceofWithStructurallyIdenticalTypes.ts, 39, 22))
>a : Symbol(A2.a, Decl(instanceofWithStructurallyIdenticalTypes.ts, 40, 10))
class B extends A { b: string }
>B : Symbol(B, Decl(instanceofWithStructurallyIdenticalTypes.ts, 40, 22))
>A : Symbol(A, Decl(instanceofWithStructurallyIdenticalTypes.ts, 34, 1))
>b : Symbol(B.b, Decl(instanceofWithStructurallyIdenticalTypes.ts, 41, 19))
function goo(x: A) {
>goo : Symbol(goo, Decl(instanceofWithStructurallyIdenticalTypes.ts, 41, 31))
>x : Symbol(x, Decl(instanceofWithStructurallyIdenticalTypes.ts, 43, 13))
>A : Symbol(A, Decl(instanceofWithStructurallyIdenticalTypes.ts, 34, 1))
if (x instanceof A) {
>x : Symbol(x, Decl(instanceofWithStructurallyIdenticalTypes.ts, 43, 13))
>A : Symbol(A, Decl(instanceofWithStructurallyIdenticalTypes.ts, 34, 1))
x; // A
>x : Symbol(x, Decl(instanceofWithStructurallyIdenticalTypes.ts, 43, 13))
}
else {
x; // never
>x : Symbol(x, Decl(instanceofWithStructurallyIdenticalTypes.ts, 43, 13))
}
if (x instanceof A1) {
>x : Symbol(x, Decl(instanceofWithStructurallyIdenticalTypes.ts, 43, 13))
>A1 : Symbol(A1, Decl(instanceofWithStructurallyIdenticalTypes.ts, 38, 21))
x; // A1
>x : Symbol(x, Decl(instanceofWithStructurallyIdenticalTypes.ts, 43, 13))
}
else {
x; // A
>x : Symbol(x, Decl(instanceofWithStructurallyIdenticalTypes.ts, 43, 13))
}
if (x instanceof A2) {
>x : Symbol(x, Decl(instanceofWithStructurallyIdenticalTypes.ts, 43, 13))
>A2 : Symbol(A2, Decl(instanceofWithStructurallyIdenticalTypes.ts, 39, 22))
x; // A2
>x : Symbol(x, Decl(instanceofWithStructurallyIdenticalTypes.ts, 43, 13))
}
else {
x; // A
>x : Symbol(x, Decl(instanceofWithStructurallyIdenticalTypes.ts, 43, 13))
}
if (x instanceof B) {
>x : Symbol(x, Decl(instanceofWithStructurallyIdenticalTypes.ts, 43, 13))
>B : Symbol(B, Decl(instanceofWithStructurallyIdenticalTypes.ts, 40, 22))
x; // B
>x : Symbol(x, Decl(instanceofWithStructurallyIdenticalTypes.ts, 43, 13))
}
else {
x; // A
>x : Symbol(x, Decl(instanceofWithStructurallyIdenticalTypes.ts, 43, 13))
}
}
@@ -0,0 +1,211 @@
=== tests/cases/compiler/instanceofWithStructurallyIdenticalTypes.ts ===
// Repro from #7271
class C1 { item: string }
>C1 : C1
>item : string
class C2 { item: string[] }
>C2 : C2
>item : string[]
class C3 { item: string }
>C3 : C3
>item : string
function foo1(x: C1 | C2 | C3): string {
>foo1 : (x: C1 | C2 | C3) => string
>x : C1 | C2 | C3
>C1 : C1
>C2 : C2
>C3 : C3
if (x instanceof C1) {
>x instanceof C1 : boolean
>x : C1 | C2 | C3
>C1 : typeof C1
return x.item;
>x.item : string
>x : C1
>item : string
}
else if (x instanceof C2) {
>x instanceof C2 : boolean
>x : C2 | C3
>C2 : typeof C2
return x.item[0];
>x.item[0] : string
>x.item : string[]
>x : C2
>item : string[]
>0 : number
}
else if (x instanceof C3) {
>x instanceof C3 : boolean
>x : C3
>C3 : typeof C3
return x.item;
>x.item : string
>x : C3
>item : string
}
return "error";
>"error" : string
}
function isC1(c: C1 | C2 | C3): c is C1 { return c instanceof C1 }
>isC1 : (c: C1 | C2 | C3) => c is C1
>c : C1 | C2 | C3
>C1 : C1
>C2 : C2
>C3 : C3
>c : any
>C1 : C1
>c instanceof C1 : boolean
>c : C1 | C2 | C3
>C1 : typeof C1
function isC2(c: C1 | C2 | C3): c is C2 { return c instanceof C2 }
>isC2 : (c: C1 | C2 | C3) => c is C2
>c : C1 | C2 | C3
>C1 : C1
>C2 : C2
>C3 : C3
>c : any
>C2 : C2
>c instanceof C2 : boolean
>c : C1 | C2 | C3
>C2 : typeof C2
function isC3(c: C1 | C2 | C3): c is C3 { return c instanceof C3 }
>isC3 : (c: C1 | C2 | C3) => c is C3
>c : C1 | C2 | C3
>C1 : C1
>C2 : C2
>C3 : C3
>c : any
>C3 : C3
>c instanceof C3 : boolean
>c : C1 | C2 | C3
>C3 : typeof C3
function foo2(x: C1 | C2 | C3): string {
>foo2 : (x: C1 | C2 | C3) => string
>x : C1 | C2 | C3
>C1 : C1
>C2 : C2
>C3 : C3
if (isC1(x)) {
>isC1(x) : boolean
>isC1 : (c: C1 | C2 | C3) => c is C1
>x : C1 | C2 | C3
return x.item;
>x.item : string
>x : C1
>item : string
}
else if (isC2(x)) {
>isC2(x) : boolean
>isC2 : (c: C1 | C2 | C3) => c is C2
>x : C2 | C3
return x.item[0];
>x.item[0] : string
>x.item : string[]
>x : C2
>item : string[]
>0 : number
}
else if (isC3(x)) {
>isC3(x) : boolean
>isC3 : (c: C1 | C2 | C3) => c is C3
>x : C3
return x.item;
>x.item : string
>x : C3
>item : string
}
return "error";
>"error" : string
}
// More tests
class A { a: string }
>A : A
>a : string
class A1 extends A { }
>A1 : A1
>A : A
class A2 { a: string }
>A2 : A2
>a : string
class B extends A { b: string }
>B : B
>A : A
>b : string
function goo(x: A) {
>goo : (x: A) => void
>x : A
>A : A
if (x instanceof A) {
>x instanceof A : boolean
>x : A
>A : typeof A
x; // A
>x : A
}
else {
x; // never
>x : never
}
if (x instanceof A1) {
>x instanceof A1 : boolean
>x : A
>A1 : typeof A1
x; // A1
>x : A1
}
else {
x; // A
>x : A
}
if (x instanceof A2) {
>x instanceof A2 : boolean
>x : A
>A2 : typeof A2
x; // A2
>x : A2
}
else {
x; // A
>x : A
}
if (x instanceof B) {
>x instanceof B : boolean
>x : A
>B : typeof B
x; // B
>x : B
}
else {
x; // A
>x : A
}
}
Loaded 100 of 205 files, more files were not shown because too many files have changed in this diff. Show more