Merge branch 'master' into tupleTypes

This commit is contained in:
Anders Hejlsberg
2014-09-05 13:52:45 -07:00
4441 changed files with 183758 additions and 41025 deletions
+3 -2
View File
@@ -1,5 +1,5 @@
node_modules/
built/
built/*
tests/cases/*.js
tests/cases/*/*.js
tests/cases/*/*/*.js
@@ -23,6 +23,7 @@ tests/services/baselines/prototyping/local/*
tests/services/browser/typescriptServices.js
scripts/processDiagnosticMessages.d.ts
scripts/processDiagnosticMessages.js
scripts/importDefinitelyTypedTests.js
src/harness/*.js
rwc-report.html
*.swp
@@ -35,4 +36,4 @@ tests/*.d.ts
*.config
scripts/debug.bat
scripts/run.bat
coverage/
coverage/
+1 -1
View File
@@ -32,7 +32,7 @@ To run all tests, invoke the runtests target using jake:
`jake runtests`
This will all tests; to run only a specific subset of tests, use:
This run will all tests; to run only a specific subset of tests, use:
`jake runtests tests=<regex>`
+50 -11
View File
@@ -43,7 +43,6 @@ var compilerSources = [
var servicesSources = [
"core.ts",
"sys.ts",
"types.ts",
"scanner.ts",
"parser.ts",
@@ -71,6 +70,7 @@ var harnessSources = [
"fourslashRunner.ts",
"projectsRunner.ts",
"unittestrunner.ts",
"loggedIO.ts",
"rwcRunner.ts",
"runner.ts"
].map(function (f) {
@@ -123,6 +123,8 @@ function concatenateFiles(destinationFile, sourceFiles) {
}
var useDebugMode = false;
var host = (process.env.host || process.env.TYPESCRIPT_HOST || "node");
var compilerFilename = "tsc.js";
/* Compiles a file from a list of sources
* @param outFile: the target file name
* @param sources: an array of the names of the source files
@@ -134,10 +136,9 @@ var useDebugMode = false;
function compileFile(outFile, sources, prereqs, prefixes, useBuiltCompiler, noOutFile) {
file(outFile, prereqs, function() {
var dir = useBuiltCompiler ? builtLocalDirectory : LKGDirectory;
var compilerFilename = "tsc.js";
var options = "-removeComments --module commonjs -noImplicitAny "; //" -propagateEnumConstants "
var cmd = (process.env.host || process.env.TYPESCRIPT_HOST || "node") + " " + dir + compilerFilename + " " + options + " ";
var cmd = host + " " + dir + compilerFilename + " " + options + " ";
if (useDebugMode) {
cmd = cmd + " " + path.join(harnessDirectory, "external/es5compat.ts") + " " + path.join(harnessDirectory, "external/json2.ts") + " ";
}
@@ -230,7 +231,7 @@ task("generate-diagnostics", [diagnosticInfoMapTs])
// Local target to build the compiler and services
var tscFile = path.join(builtLocalDirectory, "tsc.js");
var tscFile = path.join(builtLocalDirectory, compilerFilename);
compileFile(tscFile, compilerSources, [builtLocalDirectory, copyright].concat(compilerSources), [copyright], /*useBuiltCompiler:*/ false);
var servicesFile = path.join(builtLocalDirectory, "typescriptServices.js");
@@ -312,9 +313,9 @@ function exec(cmd, completeHandler) {
complete();
});
ex.addListener("error", function(e, status) {
process.stderr.write(status);
process.stderr.write(e);
complete();
process.stderr.write(status);
process.stderr.write(e);
complete();
})
try{
ex.run();
@@ -360,10 +361,15 @@ task("runtests", ["tests", builtLocalDirectory], function() {
if(fs.existsSync(testConfigFile)) {
fs.unlinkSync(testConfigFile);
}
if(tests) {
writeTestConfigFile(tests, testConfigFile);
}
if (tests && tests.toLocaleLowerCase() === "rwc") {
testTimeout = 50000;
}
colors = process.env.colors || process.env.color
colors = colors ? ' --no-colors ' : ''
tests = tests ? ' -g ' + tests : '';
@@ -377,9 +383,9 @@ task("runtests", ["tests", builtLocalDirectory], function() {
desc("Generates code coverage data via instanbul")
task("generate-code-coverage", ["tests", builtLocalDirectory], function () {
var cmd = 'istanbul cover node_modules/mocha/bin/_mocha -- -R min -t ' + testTimeout + ' ' + run;
console.log(cmd);
exec(cmd);
var cmd = 'istanbul cover node_modules/mocha/bin/_mocha -- -R min -t ' + testTimeout + ' ' + run;
console.log(cmd);
exec(cmd);
}, { async: true });
// Browser tests
@@ -464,7 +470,7 @@ compileFile(webhostJsPath, [webhostPath], [tscFile, webhostPath].concat(libraryT
desc("Builds the tsc web host");
task("webhost", [webhostJsPath], function() {
jake.cpR(path.join(builtLocalDirectory, "lib.d.ts"), "tests/webhost/", {silent: true});
jake.cpR(path.join(builtLocalDirectory, "lib.d.ts"), "tests/webhost/", {silent: true});
});
// Perf compiler
@@ -473,3 +479,36 @@ var perftscJsPath = "built/local/perftsc.js";
compileFile(perftscJsPath, [perftscPath], [tscFile, perftscPath, "tests/perfsys.ts"].concat(libraryTargets), [], true);
desc("Builds augmented version of the compiler for perf tests");
task("perftsc", [perftscJsPath]);
// Instrumented compiler
var loggedIOpath = harnessDirectory + 'loggedIO.ts';
var loggedIOJsPath = builtLocalDirectory + 'loggedIO.js';
file(loggedIOJsPath, [builtLocalDirectory, loggedIOpath], function() {
var temp = builtLocalDirectory + 'temp';
jake.mkdirP(temp);
var options = "--outdir " + temp + ' ' + loggedIOpath;
var cmd = host + " " + LKGDirectory + compilerFilename + " " + options + " ";
console.log(cmd + "\n");
var ex = jake.createExec([cmd]);
ex.addListener("cmdEnd", function() {
fs.renameSync(temp + '/harness/loggedIO.js', loggedIOJsPath);
jake.rmRf(temp);
complete();
});
ex.run();
}, {async: true});
var instrumenterPath = harnessDirectory + 'instrumenter.ts';
var instrumenterJsPath = builtLocalDirectory + 'instrumenter.js';
compileFile(instrumenterJsPath, [instrumenterPath], [tscFile, instrumenterPath], [], true);
desc("Builds an instrumented tsc.js");
task('tsc-instrumented', [loggedIOJsPath, instrumenterJsPath, tscFile], function() {
var cmd = host + ' ' + instrumenterJsPath + ' record iocapture ' + builtLocalDirectory + compilerFilename;
console.log(cmd);
var ex = jake.createExec([cmd]);
ex.addListener("cmdEnd", function() {
complete();
});
ex.run();
}, { async: true });
+13 -14
View File
@@ -956,11 +956,24 @@ declare var JSON: JSON;
/////////////////////////////
interface Array<T> {
/**
* Gets or sets the length of the array. This is a number one higher than the highest element defined in an array.
*/
length: number;
/**
* Returns a string representation of an array.
*/
toString(): string;
toLocaleString(): string;
/**
* Appends new elements to an array, and returns the new length of the array.
* @param items New elements of the Array.
*/
push(...items: T[]): number;
/**
* Removes the last element from an array and returns it.
*/
pop(): T;
/**
* Combines two or more arrays.
* @param items Additional items to add to the end of array1.
@@ -976,15 +989,6 @@ interface Array<T> {
* @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma.
*/
join(separator?: string): string;
/**
* Removes the last element from an array and returns it.
*/
pop(): T;
/**
* Appends new elements to an array, and returns the new length of the array.
* @param items New elements of the Array.
*/
push(...items: T[]): number;
/**
* Reverses the elements in an Array.
*/
@@ -1101,11 +1105,6 @@ interface Array<T> {
*/
reduceRight<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U;
/**
* Gets or sets the length of the array. This is a number one higher than the highest element defined in an array.
*/
length: number;
[n: number]: T;
}
declare var Array: {
+13 -14
View File
@@ -956,11 +956,24 @@ declare var JSON: JSON;
/////////////////////////////
interface Array<T> {
/**
* Gets or sets the length of the array. This is a number one higher than the highest element defined in an array.
*/
length: number;
/**
* Returns a string representation of an array.
*/
toString(): string;
toLocaleString(): string;
/**
* Appends new elements to an array, and returns the new length of the array.
* @param items New elements of the Array.
*/
push(...items: T[]): number;
/**
* Removes the last element from an array and returns it.
*/
pop(): T;
/**
* Combines two or more arrays.
* @param items Additional items to add to the end of array1.
@@ -976,15 +989,6 @@ interface Array<T> {
* @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma.
*/
join(separator?: string): string;
/**
* Removes the last element from an array and returns it.
*/
pop(): T;
/**
* Appends new elements to an array, and returns the new length of the array.
* @param items New elements of the Array.
*/
push(...items: T[]): number;
/**
* Reverses the elements in an Array.
*/
@@ -1101,11 +1105,6 @@ interface Array<T> {
*/
reduceRight<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U;
/**
* Gets or sets the length of the array. This is a number one higher than the highest element defined in an array.
*/
length: number;
[n: number]: T;
}
declare var Array: {
-13134
View File
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -1,2 +1,2 @@
#!/usr/bin/env node
require('./tc.js')
require('./tsc.js')
+1524 -689
View File
File diff suppressed because it is too large Load Diff
+2453 -1575
View File
File diff suppressed because it is too large Load Diff
Binary file not shown.
Binary file not shown.
+124
View File
@@ -0,0 +1,124 @@
declare var require: any, process: any;
declare var __dirname: any;
var fs = require("fs");
var path = require("path");
var child_process = require('child_process');
var tscRoot = path.join(__dirname, "..\\");
var tscPath = path.join(tscRoot, "built", "instrumented", "tsc.js");
var rwcTestPath = path.join(tscRoot, "tests", "cases", "rwc", "dt");
var definitelyTypedRoot = process.argv[2];
function fileExtensionIs(path: string, extension: string): boolean {
var pathLen = path.length;
var extLen = extension.length;
return pathLen > extLen && path.substr(pathLen - extLen, extLen).toLocaleLowerCase() === extension.toLocaleLowerCase();
}
function copyFileSync(source, destination) {
var text = fs.readFileSync(source);
fs.writeFileSync(destination, text);
}
function importDefinitelyTypedTest(testCaseName: string, testFiles: string[], responseFile: string ) {
var cmd = "node " + tscPath + " --module commonjs " + testFiles.join(" ");
if (responseFile) cmd += " @" + responseFile;
var testDirectoryName = testCaseName + "_" + Math.floor((Math.random() * 10000) + 1);
var testDirectoryPath = path.join(process.env["temp"], testDirectoryName);
if (fs.existsSync(testDirectoryPath)) {
throw new Error("Could not create test directory");
}
fs.mkdirSync(testDirectoryPath);
child_process.exec(cmd, {
maxBuffer: 1 * 1024 * 1024,
cwd: testDirectoryPath
}, (error, stdout, stderr) => {
//console.log("importing " + testCaseName + " ...");
//console.log(cmd);
if (error) {
console.log("importing " + testCaseName + " ...");
console.log(cmd);
console.log("==> error " + JSON.stringify(error));
console.log("==> stdout " + String(stdout));
console.log("==> stderr " + String(stderr));
console.log("\r\n");
return;
}
// copy generated file to output location
var outputFilePath = path.join(testDirectoryPath, "iocapture0.json");
var testCasePath = path.join(rwcTestPath, "DefinitelyTyped_" + testCaseName + ".json");
copyFileSync(outputFilePath, testCasePath);
//console.log("output generated at: " + outputFilePath);
if (!fs.existsSync(testCasePath)) {
throw new Error("could not find test case at: " + testCasePath);
}
else {
fs.unlinkSync(outputFilePath);
fs.rmdirSync(testDirectoryPath);
//console.log("testcase generated at: " + testCasePath);
//console.log("Done.");
}
//console.log("\r\n");
})
.on('error', function (error) {
console.log("==> error " + JSON.stringify(error));
console.log("\r\n");
});
}
function importDefinitelyTypedTests(definitelyTypedRoot: string): void {
fs.readdir(definitelyTypedRoot, (err, subDirectorys) => {
if (err) throw err;
subDirectorys
.filter(d => ["_infrastructure", "node_modules", ".git"].indexOf(d) >= 0)
.filter(i => fs.statSync(path.join(definitelyTypedRoot, i)).isDirectory())
.forEach(d => {
var directoryPath = path.join(definitelyTypedRoot, d);
fs.readdir(directoryPath, function (err, files) {
if (err) throw err;
var tsFiles = [];
var testFiles = [];
var paramFile;
files
.map(f => path.join(directoryPath, f))
.forEach(f => {
if (fileExtensionIs(f, ".ts")) tsFiles.push(f);
else if (fileExtensionIs(f, ".tscparams")) paramFile = f;
if (fileExtensionIs(f, "-tests.ts")) testFiles.push(f);
});
if (testFiles.length === 0) {
// no test files but multiple d.ts's, e.g. winjs
var regexp = new RegExp(d + "(([-][0-9])|([\.]d[\.]ts))");
if (tsFiles.length > 1 && tsFiles.every(t => fileExtensionIs(t, ".d.ts") && regexp.test(t))) {
tsFiles.forEach(filename => {
importDefinitelyTypedTest(path.basename(filename, ".d.ts"), [filename], paramFile);
});
}
else {
importDefinitelyTypedTest(d, tsFiles, paramFile);
}
}
else {
testFiles.forEach(filename => {
importDefinitelyTypedTest(path.basename(filename, "-tests.ts"), [filename], paramFile);
});
}
});
})
});
}
importDefinitelyTypedTests(definitelyTypedRoot);
+384 -156
View File
@@ -11,6 +11,18 @@ module ts {
var nextNodeId = 1;
var nextMergeId = 1;
export function getDeclarationOfKind(symbol: Symbol, kind: SyntaxKind): Declaration {
var declarations = symbol.declarations;
for (var i = 0; i < declarations.length; i++) {
var declaration = declarations[i];
if (declaration.kind === kind) {
return declaration;
}
}
return undefined;
}
/// fullTypeCheck denotes if this instance of the typechecker will be used to get semantic diagnostics.
/// If fullTypeCheck === true - then typechecker should do every possible check to produce all errors
/// If fullTypeCheck === false - typechecker can shortcut and skip checks that only produce errors.
@@ -25,6 +37,34 @@ module ts {
var emptyArray: any[] = [];
var emptySymbols: SymbolTable = {};
var checker: TypeChecker = {
getProgram: () => program,
getDiagnostics: getDiagnostics,
getGlobalDiagnostics: getGlobalDiagnostics,
getNodeCount: () => sum(program.getSourceFiles(), "nodeCount"),
getIdentifierCount: () => sum(program.getSourceFiles(), "identifierCount"),
getSymbolCount: () => sum(program.getSourceFiles(), "symbolCount"),
getTypeCount: () => typeCount,
checkProgram: checkProgram,
emitFiles: invokeEmitter,
getParentOfSymbol: getParentOfSymbol,
getTypeOfSymbol: getTypeOfSymbol,
getPropertiesOfType: getPropertiesOfType,
getPropertyOfType: getPropertyOfType,
getSignaturesOfType: getSignaturesOfType,
getIndexTypeOfType: getIndexTypeOfType,
getReturnTypeOfSignature: getReturnTypeOfSignature,
getSymbolsInScope: getSymbolsInScope,
getSymbolInfo: getSymbolInfo,
getTypeOfNode: getTypeOfNode,
getApparentType: getApparentType,
typeToString: typeToString,
symbolToString: symbolToString,
getAugmentedPropertiesOfApparentType: getAugmentedPropertiesOfApparentType,
getRootSymbol: getRootSymbol,
getContextualType: getContextualType
};
var undefinedSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "undefined");
var argumentsSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "arguments");
@@ -72,34 +112,6 @@ module ts {
var diagnostics: Diagnostic[] = [];
var diagnosticsModified: boolean = false;
var checker: TypeChecker = {
getProgram: () => program,
getDiagnostics: getDiagnostics,
getGlobalDiagnostics: getGlobalDiagnostics,
getNodeCount: () => sum(program.getSourceFiles(), "nodeCount"),
getIdentifierCount: () => sum(program.getSourceFiles(), "identifierCount"),
getSymbolCount: () => sum(program.getSourceFiles(), "symbolCount"),
getTypeCount: () => typeCount,
checkProgram: checkProgram,
emitFiles: invokeEmitter,
getSymbolOfNode: getSymbolOfNode,
getParentOfSymbol: getParentOfSymbol,
getTypeOfSymbol: getTypeOfSymbol,
getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol,
getPropertiesOfType: getPropertiesOfType,
getPropertyOfType: getPropertyOfType,
getSignaturesOfType: getSignaturesOfType,
getIndexTypeOfType: getIndexTypeOfType,
getReturnTypeOfSignature: getReturnTypeOfSignature,
resolveEntityName: resolveEntityName,
getSymbolsInScope: getSymbolsInScope,
getSymbolInfo: getSymbolInfo,
getTypeOfExpression: getTypeOfExpression,
typeToString: typeToString,
symbolToString: symbolToString,
getAugmentedPropertiesOfApparentType: getAugmentedPropertiesOfApparentType
};
function addDiagnostic(diagnostic: Diagnostic) {
diagnostics.push(diagnostic);
diagnosticsModified = true;
@@ -359,8 +371,7 @@ module ts {
var node = <ImportDeclaration>getDeclarationOfKind(symbol, SyntaxKind.ImportDeclaration);
var target = node.externalModuleName ?
resolveExternalModuleName(node, node.externalModuleName) :
resolveEntityName(node, node.entityName, node.entityName.kind === SyntaxKind.QualifiedName ?
SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace : SymbolFlags.Namespace);
getSymbolOfPartOfRightHandSideOfImport(node.entityName, node);
if (links.target === resolvingSymbol) {
links.target = target || unknownSymbol;
}
@@ -374,6 +385,33 @@ module ts {
return links.target;
}
// This function is only for imports with entity names
function getSymbolOfPartOfRightHandSideOfImport(entityName: EntityName, importDeclaration?: ImportDeclaration): Symbol {
if (!importDeclaration) {
importDeclaration = getAncestor(entityName, SyntaxKind.ImportDeclaration);
Debug.assert(importDeclaration);
}
// There are three things we might try to look for. In the following examples,
// the search term is enclosed in |...|:
//
// import a = |b|; // Namespace
// import a = |b.c|; // Value, type, namespace
// import a = |b.c|.d; // Namespace
if (entityName.kind === SyntaxKind.Identifier && isRightSideOfQualifiedNameOrPropertyAccess(entityName)) {
entityName = entityName.parent;
}
// Check for case 1 and 3 in the above example
if (entityName.kind === SyntaxKind.Identifier || entityName.parent.kind === SyntaxKind.QualifiedName) {
return resolveEntityName(importDeclaration, entityName, SymbolFlags.Namespace);
}
else {
// Case 2 in above example
// entityName.kind could be a QualifiedName or a Missing identifier
Debug.assert(entityName.parent.kind === SyntaxKind.ImportDeclaration);
return resolveEntityName(importDeclaration, entityName, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace);
}
}
function getFullyQualifiedName(symbol: Symbol) {
return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol);
}
@@ -545,18 +583,6 @@ module ts {
return false;
}
function getDeclarationOfKind(symbol: Symbol, kind: SyntaxKind): Declaration {
var declarations = symbol.declarations;
for (var i = 0; i < declarations.length; i++) {
var declaration = declarations[i];
if (declaration.kind === kind) {
return declaration;
}
}
return undefined;
}
function findConstructorDeclaration(node: ClassDeclaration): ConstructorDeclaration {
var members = node.members;
for (var i = 0; i < members.length; i++) {
@@ -780,7 +806,7 @@ module ts {
// But it cant, hence the accessible is going to be undefined, but that doesnt mean m.c is accessible
// It is accessible if the parent m is accessible because then m.c can be accessed through qualification
meaningToLook = getQualifiedLeftMeaning(meaning);
symbol = symbol.parent;
symbol = getParentOfSymbol(symbol);
}
// This could be a symbol that is not exported in the external module
@@ -882,7 +908,7 @@ module ts {
// Get qualified name
if (enclosingDeclaration &&
// Properties/methods/Signatures/Constructors/TypeParameters do not need qualification
!(symbol.flags & SymbolFlags.PropertyOrAccessor & SymbolFlags.Signature & SymbolFlags.Constructor & SymbolFlags.Method & SymbolFlags.TypeParameter)) {
!(symbol.flags & (SymbolFlags.PropertyOrAccessor | SymbolFlags.Signature | SymbolFlags.Constructor | SymbolFlags.Method | SymbolFlags.TypeParameter))) {
var symbolName: string;
while (symbol) {
var isFirstName = !symbolName;
@@ -903,7 +929,7 @@ module ts {
if (accessibleSymbolChain && !needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) {
break;
}
symbol = accessibleSymbolChain ? accessibleSymbolChain[0].parent : symbol.parent;
symbol = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol);
meaning = getQualifiedLeftMeaning(meaning);
}
@@ -1459,7 +1485,7 @@ module ts {
function getTypeOfFuncClassEnumModule(symbol: Symbol): Type {
var links = getSymbolLinks(symbol);
if (!links.type) {
var type = links.type = createObjectType(TypeFlags.Anonymous, symbol);
links.type = createObjectType(TypeFlags.Anonymous, symbol);
}
return links.type;
}
@@ -1805,27 +1831,39 @@ module ts {
function resolveAnonymousTypeMembers(type: ObjectType) {
var symbol = type.symbol;
var members = emptySymbols;
var callSignatures = emptyArray;
var constructSignatures = emptyArray;
if (symbol.flags & SymbolFlags.HasExports) {
members = symbol.exports;
if (symbol.flags & SymbolFlags.TypeLiteral) {
var members = symbol.members;
var callSignatures = getSignaturesOfSymbol(members["__call"]);
var constructSignatures = getSignaturesOfSymbol(members["__new"]);
var stringIndexType = getIndexTypeOfSymbol(symbol, IndexKind.String);
var numberIndexType = getIndexTypeOfSymbol(symbol, IndexKind.Number);
}
if (symbol.flags & (SymbolFlags.Function | SymbolFlags.Method)) {
callSignatures = getSignaturesOfSymbol(symbol);
}
if (symbol.flags & SymbolFlags.Class) {
var classType = getDeclaredTypeOfClass(symbol);
constructSignatures = getSignaturesOfSymbol(symbol.members["__constructor"]);
if (!constructSignatures.length) constructSignatures = getDefaultConstructSignatures(classType);
if (classType.baseTypes.length) {
var members = createSymbolTable(getNamedMembers(members));
addInheritedMembers(members, getPropertiesOfType(getTypeOfSymbol(classType.baseTypes[0].symbol)));
else {
// Combinations of function, class, enum and module
var members = emptySymbols;
var callSignatures: Signature[] = emptyArray;
var constructSignatures: Signature[] = emptyArray;
if (symbol.flags & SymbolFlags.HasExports) {
members = symbol.exports;
}
if (symbol.flags & (SymbolFlags.Function | SymbolFlags.Method)) {
callSignatures = getSignaturesOfSymbol(symbol);
}
if (symbol.flags & SymbolFlags.Class) {
var classType = getDeclaredTypeOfClass(symbol);
constructSignatures = getSignaturesOfSymbol(symbol.members["__constructor"]);
if (!constructSignatures.length) {
constructSignatures = getDefaultConstructSignatures(classType);
}
if (classType.baseTypes.length) {
members = createSymbolTable(getNamedMembers(members));
addInheritedMembers(members, getPropertiesOfType(getTypeOfSymbol(classType.baseTypes[0].symbol)));
}
}
var stringIndexType: Type = undefined;
var numberIndexType: Type = (symbol.flags & SymbolFlags.Enum) ? stringType : undefined;
}
var numberIndexType = (symbol.flags & SymbolFlags.Enum) ? stringType : undefined;
setObjectTypeMembers(type, members, callSignatures, constructSignatures, /* stringIndexType */ undefined, numberIndexType);
setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType);
}
function resolveObjectTypeMembers(type: ObjectType): ResolvedObjectType {
@@ -2246,11 +2284,11 @@ module ts {
}
var type = getDeclaredTypeOfSymbol(symbol);
if (!(type.flags & TypeFlags.ObjectType)) {
error(getTypeDeclaration(symbol), Diagnostics.Global_type_0_must_be_a_class_or_interface_type, name);
error(getTypeDeclaration(symbol), Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbol.name);
return emptyObjectType;
}
if (((<InterfaceType>type).typeParameters ? (<InterfaceType>type).typeParameters.length : 0) !== arity) {
error(getTypeDeclaration(symbol), Diagnostics.Global_type_0_must_have_1_type_parameter_s, name, arity);
error(getTypeDeclaration(symbol), Diagnostics.Global_type_0_must_have_1_type_parameter_s, symbol.name, arity);
return emptyObjectType;
}
return <ObjectType>type;
@@ -2301,13 +2339,8 @@ module ts {
function getTypeFromTypeLiteralNode(node: TypeLiteralNode): Type {
var links = getNodeLinks(node);
if (!links.resolvedType) {
var symbol = node.symbol;
var members = symbol.members;
var callSignatures = getSignaturesOfSymbol(members["__call"]);
var constructSignatures = getSignaturesOfSymbol(members["__new"]);
var stringIndexType = getIndexTypeOfSymbol(symbol, IndexKind.String);
var numberIndexType = getIndexTypeOfSymbol(symbol, IndexKind.Number);
links.resolvedType = createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexType, numberIndexType);
// Deferred resolution of members is handled by resolveObjectTypeMembers
links.resolvedType = createObjectType(TypeFlags.Anonymous, node.symbol);
}
return links.resolvedType;
}
@@ -2351,6 +2384,12 @@ module ts {
return getTypeFromTupleTypeNode(<TupleTypeNode>node);
case SyntaxKind.TypeLiteral:
return getTypeFromTypeLiteralNode(<TypeLiteralNode>node);
// This function assumes that an identifier or qualified name is a type expression
// Callers should first ensure this by calling isTypeNode
case SyntaxKind.Identifier:
case SyntaxKind.QualifiedName:
var symbol = getSymbolInfo(node);
return getDeclaredTypeOfSymbol(symbol);
default:
return unknownType;
}
@@ -3174,6 +3213,7 @@ module ts {
symbol.declarations = p.declarations;
symbol.parent = p.parent;
symbol.type = widenedTypes[index++];
symbol.target = p;
if (p.valueDeclaration) symbol.valueDeclaration = p.valueDeclaration;
members[symbol.name] = symbol;
});
@@ -3566,7 +3606,8 @@ module ts {
return false;
}
function checkSuperExpression(node: Node, isCallExpression: boolean): Type {
function checkSuperExpression(node: Node): Type {
var isCallExpression = node.parent.kind === SyntaxKind.CallExpression && (<CallExpression>node.parent).func === node;
var enclosingClass = <ClassDeclaration>getAncestor(node, SyntaxKind.ClassDeclaration);
var baseClass: Type;
if (enclosingClass && enclosingClass.baseType) {
@@ -3876,6 +3917,7 @@ module ts {
prop.parent = member.parent;
if (member.valueDeclaration) prop.valueDeclaration = member.valueDeclaration;
prop.type = type;
prop.target = member;
member = prop;
}
else {
@@ -4236,7 +4278,7 @@ module ts {
function resolveCallExpression(node: CallExpression): Signature {
if (node.func.kind === SyntaxKind.SuperKeyword) {
var superType = checkSuperExpression(node.func, true);
var superType = checkSuperExpression(node.func);
if (superType !== unknownType) {
return resolveCall(node, getSignaturesOfType(superType, SignatureKind.Construct));
}
@@ -4884,7 +4926,7 @@ module ts {
case SyntaxKind.ThisKeyword:
return checkThisExpression(node);
case SyntaxKind.SuperKeyword:
return checkSuperExpression(node, false);
return checkSuperExpression(node);
case SyntaxKind.NullKeyword:
return nullType;
case SyntaxKind.TrueKeyword:
@@ -5003,6 +5045,7 @@ module ts {
if (fullTypeCheck) {
checkCollisionWithCapturedSuperVariable(node, node.name);
checkCollisionWithCapturedThisVariable(node, node.name);
checkCollistionWithRequireExportsInGeneratedCode(node, node.name);
checkCollisionWithArgumentsInGeneratedCode(node);
if (program.getCompilerOptions().noImplicitAny && !node.type) {
switch (node.kind) {
@@ -5749,6 +5792,24 @@ module ts {
}
}
function checkCollistionWithRequireExportsInGeneratedCode(node: Node, name: Identifier) {
if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) {
return;
}
// Uninstantiated modules shouldnt do this check
if (node.kind === SyntaxKind.ModuleDeclaration && !isInstantiated(node)) {
return;
}
// In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
var parent = node.kind === SyntaxKind.VariableDeclaration ? node.parent.parent : node.parent;
if (parent.kind === SyntaxKind.SourceFile && isExternalModule(<SourceFile>parent)) {
// If the declaration happens to be in external module, report error that require and exports are reserved keywords
error(name, Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_an_external_module, name.text, name.text);
}
}
function checkVariableDeclaration(node: VariableDeclaration) {
checkSourceElement(node.type);
checkExportsOnMergedDeclarations(node);
@@ -5776,6 +5837,7 @@ module ts {
checkCollisionWithCapturedSuperVariable(node, node.name);
checkCollisionWithCapturedThisVariable(node, node.name);
checkCollistionWithRequireExportsInGeneratedCode(node, node.name);
if (!useTypeFromValueDeclaration) {
// TypeScript 1.0 spec (April 2014): 5.1
// Multiple declarations for the same variable name in the same declaration space are permitted,
@@ -6045,6 +6107,7 @@ module ts {
checkTypeNameIsReserved(node.name, Diagnostics.Class_name_cannot_be_0);
checkTypeParameters(node.typeParameters);
checkCollisionWithCapturedThisVariable(node, node.name);
checkCollistionWithRequireExportsInGeneratedCode(node, node.name);
checkExportsOnMergedDeclarations(node);
var symbol = getSymbolOfNode(node);
var type = <InterfaceType>getDeclaredTypeOfSymbol(symbol);
@@ -6260,6 +6323,7 @@ module ts {
}
checkTypeNameIsReserved(node.name, Diagnostics.Enum_name_cannot_be_0);
checkCollisionWithCapturedThisVariable(node, node.name);
checkCollistionWithRequireExportsInGeneratedCode(node, node.name);
checkExportsOnMergedDeclarations(node);
var enumSymbol = getSymbolOfNode(node);
var enumType = getDeclaredTypeOfSymbol(enumSymbol);
@@ -6333,6 +6397,7 @@ module ts {
function checkModuleDeclaration(node: ModuleDeclaration) {
if (fullTypeCheck) {
checkCollisionWithCapturedThisVariable(node, node.name);
checkCollistionWithRequireExportsInGeneratedCode(node, node.name);
checkExportsOnMergedDeclarations(node);
var symbol = getSymbolOfNode(node);
if (symbol.flags & SymbolFlags.ValueModule && symbol.declarations.length > 1 && !isInAmbientContext(node)) {
@@ -6367,6 +6432,7 @@ module ts {
function checkImportDeclaration(node: ImportDeclaration) {
checkCollisionWithCapturedThisVariable(node, node.name);
checkCollistionWithRequireExportsInGeneratedCode(node, node.name);
var symbol = getSymbolOfNode(node);
var target: Symbol;
@@ -6640,32 +6706,21 @@ module ts {
return mapToArray(symbols);
}
// True if the given identifier is the identifier of a declaration node
function isDeclarationIdentifier(identifier: Identifier): boolean {
if (identifier.parent) {
switch (identifier.parent.kind) {
case SyntaxKind.TypeParameter:
case SyntaxKind.Parameter:
case SyntaxKind.VariableDeclaration:
case SyntaxKind.Property:
case SyntaxKind.PropertyAssignment:
case SyntaxKind.EnumMember:
case SyntaxKind.Method:
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionExpression:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.ModuleDeclaration:
case SyntaxKind.ImportDeclaration:
return (<Declaration>identifier.parent).name === identifier;
case SyntaxKind.CatchBlock:
return (<CatchBlock>identifier.parent).variable === identifier;
}
// True if the given identifier is the name of a type declaration node (class, interface, enum, type parameter, etc)
function isTypeDeclarationName(name: Node): boolean {
return name.kind == SyntaxKind.Identifier &&
isTypeDeclaration(name.parent) &&
(<Declaration>name.parent).name === name;
}
function isTypeDeclaration(node: Node): boolean {
switch (node.kind) {
case SyntaxKind.TypeParameter:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.EnumDeclaration:
return true;
}
return false;
}
// True if the given identifier is part of a type reference
@@ -6697,57 +6752,162 @@ module ts {
case SyntaxKind.PostfixOperator:
case SyntaxKind.BinaryExpression:
case SyntaxKind.ConditionalExpression:
case SyntaxKind.OmittedExpression:
return true;
case SyntaxKind.QualifiedName:
while (node.parent && node.parent.kind === SyntaxKind.QualifiedName) node = node.parent;
return node.parent && node.parent.kind === SyntaxKind.TypeQuery;
while (node.parent.kind === SyntaxKind.QualifiedName) node = node.parent;
return node.parent.kind === SyntaxKind.TypeQuery;
case SyntaxKind.Identifier:
if (node.parent.kind === SyntaxKind.TypeQuery) {
return true;
}
// Fall through
case SyntaxKind.NumericLiteral:
case SyntaxKind.StringLiteral:
var parent = node.parent;
if (parent) {
if (isExpression(parent)) return true;
switch (parent.kind) {
case SyntaxKind.VariableDeclaration:
case SyntaxKind.Parameter:
case SyntaxKind.Property:
case SyntaxKind.EnumMember:
return (<VariableDeclaration>parent).initializer === node;
case SyntaxKind.ExpressionStatement:
case SyntaxKind.IfStatement:
case SyntaxKind.DoStatement:
case SyntaxKind.WhileStatement:
case SyntaxKind.ReturnStatement:
case SyntaxKind.WithStatement:
case SyntaxKind.SwitchStatement:
case SyntaxKind.CaseClause:
case SyntaxKind.ThrowStatement:
case SyntaxKind.SwitchStatement:
return (<ExpressionStatement>parent).expression === node;
case SyntaxKind.ForStatement:
return (<ForStatement>parent).initializer === node || (<ForStatement>parent).condition === node ||
(<ForStatement>parent).iterator === node;
case SyntaxKind.ForInStatement:
return (<ForInStatement>parent).variable === node || (<ForInStatement>parent).expression === node;
}
switch (parent.kind) {
case SyntaxKind.VariableDeclaration:
case SyntaxKind.Parameter:
case SyntaxKind.Property:
case SyntaxKind.EnumMember:
case SyntaxKind.PropertyAssignment:
return (<VariableDeclaration>parent).initializer === node;
case SyntaxKind.ExpressionStatement:
case SyntaxKind.IfStatement:
case SyntaxKind.DoStatement:
case SyntaxKind.WhileStatement:
case SyntaxKind.ReturnStatement:
case SyntaxKind.WithStatement:
case SyntaxKind.SwitchStatement:
case SyntaxKind.CaseClause:
case SyntaxKind.ThrowStatement:
case SyntaxKind.SwitchStatement:
return (<ExpressionStatement>parent).expression === node;
case SyntaxKind.ForStatement:
return (<ForStatement>parent).initializer === node ||
(<ForStatement>parent).condition === node ||
(<ForStatement>parent).iterator === node;
case SyntaxKind.ForInStatement:
return (<ForInStatement>parent).variable === node ||
(<ForInStatement>parent).expression === node;
case SyntaxKind.TypeAssertion:
return node === (<TypeAssertion>parent).operand;
default:
if (isExpression(parent)) {
return true;
}
}
}
return false;
}
function isTypeNode(node: Node): boolean {
if (node.kind >= SyntaxKind.FirstTypeNode && node.kind <= SyntaxKind.LastTypeNode) {
return true;
}
switch (node.kind) {
case SyntaxKind.AnyKeyword:
case SyntaxKind.NumberKeyword:
case SyntaxKind.StringKeyword:
case SyntaxKind.BooleanKeyword:
return true;
case SyntaxKind.VoidKeyword:
return node.parent.kind !== SyntaxKind.PrefixOperator;
case SyntaxKind.StringLiteral:
// Specialized signatures can have string literals as their parameters' type names
return node.parent.kind === SyntaxKind.Parameter;
// Identifiers and qualified names may be type nodes, depending on their context. Climb
// above them to find the lowest container
case SyntaxKind.Identifier:
// If the identifier is the RHS of a qualified name, then it's a type iff its parent is.
if (node.parent.kind === SyntaxKind.QualifiedName) {
node = node.parent;
}
// Fall through
case SyntaxKind.QualifiedName:
// At this point, node is either a qualified name or an identifier
var parent = node.parent;
if (parent.kind === SyntaxKind.TypeQuery) {
return false;
}
// Do not recursively call isTypeNode on the parent. In the example:
//
// var a: A.B.C;
//
// Calling isTypeNode would consider the qualified name A.B a type node. Only C or
// A.B.C is a type node.
if (parent.kind >= SyntaxKind.FirstTypeNode && parent.kind <= SyntaxKind.LastTypeNode) {
return true;
}
switch (parent.kind) {
case SyntaxKind.TypeParameter:
return node === (<TypeParameterDeclaration>parent).constraint;
case SyntaxKind.Property:
case SyntaxKind.Parameter:
case SyntaxKind.VariableDeclaration:
return node === (<VariableDeclaration>parent).type;
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionExpression:
case SyntaxKind.ArrowFunction:
case SyntaxKind.Constructor:
case SyntaxKind.Method:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
return node === (<FunctionDeclaration>parent).type;
case SyntaxKind.CallSignature:
case SyntaxKind.ConstructSignature:
case SyntaxKind.IndexSignature:
return node === (<SignatureDeclaration>parent).type;
case SyntaxKind.TypeAssertion:
return node === (<TypeAssertion>parent).type;
case SyntaxKind.CallExpression:
case SyntaxKind.NewExpression:
return (<CallExpression>parent).typeArguments.indexOf(node) >= 0;
}
}
return false;
}
function isInRightSideOfImportOrExportAssignment(node: EntityName) {
while (node.parent.kind === SyntaxKind.QualifiedName) {
node = node.parent;
}
if (node.parent.kind === SyntaxKind.ImportDeclaration) {
return (<ImportDeclaration>node.parent).entityName === node;
}
if (node.parent.kind === SyntaxKind.ExportAssignment) {
return (<ExportAssignment>node.parent).exportName === node;
}
return false;
}
function isRightSideOfQualifiedNameOrPropertyAccess(node: Node) {
return (node.parent.kind === SyntaxKind.QualifiedName || node.parent.kind === SyntaxKind.PropertyAccess) &&
(<QualifiedName>node.parent).right === node;
}
function getSymbolOfIdentifier(identifier: Identifier) {
if (isDeclarationIdentifier(identifier)) {
return getSymbolOfNode(identifier.parent);
function getSymbolOfEntityName(entityName: EntityName): Symbol {
if (isDeclarationOrFunctionExpressionOrCatchVariableName(entityName)) {
return getSymbolOfNode(entityName.parent);
}
var entityName: Node = identifier;
while (isRightSideOfQualifiedNameOrPropertyAccess(entityName))
if (entityName.parent.kind === SyntaxKind.ExportAssignment) {
return resolveEntityName(/*location*/ entityName.parent.parent, entityName,
/*all meanings*/ SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Import);
}
if (isInRightSideOfImportOrExportAssignment(entityName)) {
// Since we already checked for ExportAssignment, this really could only be an Import
return getSymbolOfPartOfRightHandSideOfImport(entityName);
}
if (isRightSideOfQualifiedNameOrPropertyAccess(entityName)) {
entityName = entityName.parent;
}
if (isExpression(entityName)) {
if (entityName.kind === SyntaxKind.Identifier) {
@@ -6775,18 +6935,34 @@ module ts {
meaning |= SymbolFlags.Import;
return resolveEntityName(entityName, entityName, meaning);
}
// Do we want to return undefined here?
return undefined;
}
function getSymbolInfo(node: Node) {
if (isDeclarationOrFunctionExpressionOrCatchVariableName(node)) {
// This is a declaration, call getSymbolOfNode
return getSymbolOfNode(node.parent);
}
if (node.kind === SyntaxKind.Identifier && isInRightSideOfImportOrExportAssignment(node)) {
return node.parent.kind === SyntaxKind.ExportAssignment
? getSymbolOfEntityName(<Identifier>node)
: getSymbolOfPartOfRightHandSideOfImport(node);
}
switch (node.kind) {
case SyntaxKind.Identifier:
return getSymbolOfIdentifier(<Identifier>node);
case SyntaxKind.PropertyAccess:
case SyntaxKind.QualifiedName:
return getSymbolOfEntityName(<Identifier>node);
case SyntaxKind.ThisKeyword:
case SyntaxKind.SuperKeyword:
var type = checkExpression(node);
return type.symbol;
case SyntaxKind.ConstructorKeyword:
// constructor keyword for an overload, should take us to the definition if it exist
var constructorDeclaration = node.parent;
@@ -6796,39 +6972,74 @@ module ts {
return undefined;
case SyntaxKind.StringLiteral:
// Property access
if (node.parent.kind === SyntaxKind.IndexedAccess && (<IndexedAccess>node.parent).index === node) {
// External module name in an import declaration
if (node.parent.kind === SyntaxKind.ImportDeclaration && (<ImportDeclaration>node.parent).externalModuleName === node) {
var importSymbol = getSymbolOfNode(node.parent);
var moduleType = getTypeOfSymbol(importSymbol);
return moduleType ? moduleType.symbol : undefined;
}
// Intentinal fallthrough
case SyntaxKind.NumericLiteral:
// index access
if (node.parent.kind == SyntaxKind.IndexedAccess && (<IndexedAccess>node.parent).index === node) {
var objectType = checkExpression((<IndexedAccess>node.parent).object);
if (objectType === unknownType) return undefined;
var apparentType = getApparentType(objectType);
if (<Type>apparentType === unknownType) return undefined;
return getPropertyOfApparentType(apparentType, (<LiteralExpression>node).text);
}
// External module name in an import declaration
else if (node.parent.kind === SyntaxKind.ImportDeclaration && (<ImportDeclaration>node.parent).externalModuleName === node) {
var importSymbol = getSymbolOfNode(node.parent);
var moduleType = getTypeOfSymbol(importSymbol);
return moduleType ? moduleType.symbol : undefined;
}
// External module name in an ambient declaration
else if (node.parent.kind === SyntaxKind.ModuleDeclaration) {
return getSymbolOfNode(node.parent);
}
break;
}
return undefined;
}
function getTypeOfExpression(node: Node) {
function getTypeOfNode(node: Node): Type {
if (isExpression(node)) {
while (isRightSideOfQualifiedNameOrPropertyAccess(node)) {
node = node.parent;
}
return <Type>getApparentType(checkExpression(node));
return getTypeOfExpression(<Expression>node);
}
if (isTypeNode(node)) {
return getTypeFromTypeNode(<TypeNode>node);
}
if (isTypeDeclaration(node)) {
// In this case, we call getSymbolOfNode instead of getSymbolInfo because it is a declaration
var symbol = getSymbolOfNode(node);
return getDeclaredTypeOfSymbol(symbol);
}
if (isTypeDeclarationName(node)) {
var symbol = getSymbolInfo(node);
return getDeclaredTypeOfSymbol(symbol);
}
if (isDeclaration(node)) {
// In this case, we call getSymbolOfNode instead of getSymbolInfo because it is a declaration
var symbol = getSymbolOfNode(node);
return getTypeOfSymbol(symbol);
}
if (isDeclarationOrFunctionExpressionOrCatchVariableName(node)) {
var symbol = getSymbolInfo(node);
return getTypeOfSymbol(symbol);
}
if (isInRightSideOfImportOrExportAssignment(node)) {
var symbol = getSymbolInfo(node);
var declaredType = getDeclaredTypeOfSymbol(symbol);
return declaredType !== unknownType ? declaredType : getTypeOfSymbol(symbol);
}
return unknownType;
}
function getTypeOfExpression(expr: Expression): Type {
if (isRightSideOfQualifiedNameOrPropertyAccess(expr)) {
expr = expr.parent;
}
return checkExpression(expr);
}
function getAugmentedPropertiesOfApparentType(type: Type): Symbol[]{
var apparentType = getApparentType(type);
@@ -6837,13 +7048,13 @@ module ts {
var propertiesByName: Map<Symbol> = {};
var results: Symbol[] = [];
forEach(getPropertiesOfType(apparentType), (s) => {
forEach(getPropertiesOfType(apparentType), s => {
propertiesByName[s.name] = s;
results.push(s);
});
var resolved = resolveObjectTypeMembers(<ObjectType>type);
forEachValue(resolved.members, (s) => {
forEachValue(resolved.members, s => {
if (symbolIsValue(s) && !propertiesByName[s.name]) {
propertiesByName[s.name] = s;
results.push(s);
@@ -6851,7 +7062,7 @@ module ts {
});
if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) {
forEach(getPropertiesOfType(globalFunctionType), (s) => {
forEach(getPropertiesOfType(globalFunctionType), s => {
if (!propertiesByName[s.name]) {
propertiesByName[s.name] = s;
results.push(s);
@@ -6866,6 +7077,10 @@ module ts {
}
}
function getRootSymbol(symbol: Symbol) {
return (symbol.flags & SymbolFlags.Transient) ? getSymbolLinks(symbol).target : symbol;
}
// Emitter support
function isExternalModuleSymbol(symbol: Symbol): boolean {
@@ -6984,7 +7199,20 @@ module ts {
function isImplementationOfOverload(node: FunctionDeclaration) {
if (node.body) {
var symbol = getSymbolOfNode(node);
return getSignaturesOfSymbol(symbol).length > 1;
var signaturesOfSymbol = getSignaturesOfSymbol(symbol);
// If this function body corresponds to function with multiple signature, it is implementation of overload
// eg: function foo(a: string): string;
// function foo(a: number): number;
// function foo(a: any) { // This is implementation of the overloads
// return a;
// }
return signaturesOfSymbol.length > 1 ||
// If there is single signature for the symbol, it is overload if that signature isnt coming from the node
// eg: function foo(a: string): string;
// function foo(a: any) { // This is implementation of the overloads
// return a;
// }
(signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node);
}
return false;
}
+4 -13
View File
@@ -63,8 +63,8 @@ module ts {
}
export function concatenate<T>(array1: T[], array2: T[]): T[] {
if (!array2.length) return array1;
if (!array1.length) return array2;
if (!array2 || !array2.length) return array1;
if (!array1 || !array1.length) return array2;
return array1.concat(array2);
}
@@ -194,14 +194,11 @@ module ts {
export var localizedDiagnosticMessages: Map<string> = undefined;
function getLocaleSpecificMessage(message: string) {
export function getLocaleSpecificMessage(message: string) {
if (ts.localizedDiagnosticMessages) {
message = localizedDiagnosticMessages[message];
}
/* Check to see that we got an actual value back. */
Debug.assert(message, "Diagnostic message does not exist in locale map.");
return message;
}
@@ -518,12 +515,6 @@ module ts {
return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension;
}
export 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.
// otherwise use toLowerCase as a canonical form.
return sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
}
export interface ObjectAllocator {
getNodeConstructor(kind: SyntaxKind): new () => Node;
getSymbolConstructor(): new (flags: SymbolFlags, name: string) => Symbol;
@@ -573,7 +564,7 @@ module ts {
var currentAssertionLevel = AssertionLevel.None;
export function shouldAssert(level: AssertionLevel): boolean {
return this.currentAssertionLevel >= level;
return currentAssertionLevel >= level;
}
export function assert(expression: any, message?: string, verboseDebugInfo?: () => string): void {
+273 -307
View File
@@ -2,20 +2,11 @@
/// <reference path="types.ts" />
module ts {
export var Diagnostics = {
Unknown_compiler_option_0: { code: 6001, category: DiagnosticCategory.Error, key: "Unknown compiler option '{0}'." },
File_0_not_found: { code: 6002, category: DiagnosticCategory.Error, key: "File '{0}' not found." },
File_0_must_have_extension_ts_or_d_ts: { code: 6003, category: DiagnosticCategory.Error, key: "File '{0}' must have extension '.ts' or '.d.ts'." },
Unrecognized_escape_sequence: { code: 1000, category: DiagnosticCategory.Error, key: "Unrecognized escape sequence." },
Unexpected_character_0: { code: 1001, category: DiagnosticCategory.Error, key: "Unexpected character {0}." },
Missing_close_quote_character: { code: 1002, category: DiagnosticCategory.Error, key: "Missing close quote character." },
Identifier_expected: { code: -9999999, category: DiagnosticCategory.Error, key: "Identifier expected." },
_0_keyword_expected: { code: 1004, category: DiagnosticCategory.Error, key: "'{0}' keyword expected." },
_0_expected: { code: -9999999, category: DiagnosticCategory.Error, key: "'{0}' expected." },
Identifier_expected_0_is_a_keyword: { code: 1006, category: DiagnosticCategory.Error, key: "Identifier expected; '{0}' is a keyword." },
Automatic_semicolon_insertion_not_allowed: { code: 1007, category: DiagnosticCategory.Error, key: "Automatic semicolon insertion not allowed." },
Unterminated_string_literal: { code: 1002, category: DiagnosticCategory.Error, key: "Unterminated string literal." },
Identifier_expected: { code: 1003, category: DiagnosticCategory.Error, key: "Identifier expected." },
_0_expected: { code: 1005, category: DiagnosticCategory.Error, key: "'{0}' expected." },
Trailing_comma_not_allowed: { code: 1009, category: DiagnosticCategory.Error, key: "Trailing comma not allowed." },
Asterisk_Slash_expected: { code: 1010, category: DiagnosticCategory.Error, key: "'*/' expected." },
public_or_private_modifier_must_precede_static: { code: 1011, category: DiagnosticCategory.Error, key: "'public' or 'private' modifier must precede 'static'." },
Unexpected_token: { code: 1012, category: DiagnosticCategory.Error, key: "Unexpected token." },
Catch_clause_parameter_cannot_have_a_type_annotation: { code: 1013, category: DiagnosticCategory.Error, key: "Catch clause parameter cannot have a type annotation." },
A_rest_parameter_must_be_last_in_a_parameter_list: { code: 1014, category: DiagnosticCategory.Error, key: "A rest parameter must be last in a parameter list." },
@@ -28,16 +19,16 @@ module ts {
An_index_signature_must_have_a_type_annotation: { code: 1021, category: DiagnosticCategory.Error, key: "An index signature must have a type annotation." },
An_index_signature_parameter_must_have_a_type_annotation: { code: 1022, category: DiagnosticCategory.Error, key: "An index signature parameter must have a type annotation." },
An_index_signature_parameter_type_must_be_string_or_number: { code: 1023, category: DiagnosticCategory.Error, key: "An index signature parameter type must be 'string' or 'number'." },
extends_clause_already_seen: { code: 1024, category: DiagnosticCategory.Error, key: "'extends' clause already seen." },
extends_clause_must_precede_implements_clause: { code: 1025, category: DiagnosticCategory.Error, key: "'extends' clause must precede 'implements' clause." },
Classes_can_only_extend_a_single_class: { code: 1026, category: DiagnosticCategory.Error, key: "Classes can only extend a single class." },
implements_clause_already_seen: { code: 1027, category: DiagnosticCategory.Error, key: "'implements' clause already seen." },
A_class_or_interface_declaration_can_only_have_one_extends_clause: { code: 1024, category: DiagnosticCategory.Error, key: "A class or interface declaration can only have one 'extends' clause." },
An_extends_clause_must_precede_an_implements_clause: { code: 1025, category: DiagnosticCategory.Error, key: "An 'extends' clause must precede an 'implements' clause." },
A_class_can_only_extend_a_single_class: { code: 1026, category: DiagnosticCategory.Error, key: "A class can only extend a single class." },
A_class_declaration_can_only_have_one_implements_clause: { code: 1027, category: DiagnosticCategory.Error, key: "A class declaration can only have one 'implements' clause." },
Accessibility_modifier_already_seen: { code: 1028, category: DiagnosticCategory.Error, key: "Accessibility modifier already seen." },
_0_modifier_must_precede_1_modifier: { code: 1029, category: DiagnosticCategory.Error, key: "'{0}' modifier must precede '{1}' modifier." },
_0_modifier_already_seen: { code: 1030, category: DiagnosticCategory.Error, key: "'{0}' modifier already seen." },
_0_modifier_cannot_appear_on_a_class_element: { code: 1031, category: DiagnosticCategory.Error, key: "'{0}' modifier cannot appear on a class element." },
Interface_declaration_cannot_have_implements_clause: { code: 1032, category: DiagnosticCategory.Error, key: "Interface declaration cannot have 'implements' clause." },
super_invocation_cannot_have_type_arguments: { code: 1034, category: DiagnosticCategory.Error, key: "'super' invocation cannot have type arguments." },
An_interface_declaration_cannot_have_an_implements_clause: { code: 1032, category: DiagnosticCategory.Error, key: "An interface declaration cannot have an 'implements' clause." },
super_must_be_followed_by_an_argument_list_or_member_access: { code: 1034, category: DiagnosticCategory.Error, key: "'super' must be followed by an argument list or member access." },
Only_ambient_modules_can_use_quoted_names: { code: 1035, category: DiagnosticCategory.Error, key: "Only ambient modules can use quoted names." },
Statements_are_not_allowed_in_ambient_contexts: { code: 1036, category: DiagnosticCategory.Error, key: "Statements are not allowed in ambient contexts." },
A_function_implementation_cannot_be_declared_in_an_ambient_context: { code: 1037, category: DiagnosticCategory.Error, key: "A function implementation cannot be declared in an ambient context." },
@@ -53,23 +44,11 @@ module ts {
A_set_accessor_parameter_cannot_have_an_initializer: { code: 1052, category: DiagnosticCategory.Error, key: "A 'set' accessor parameter cannot have an initializer." },
A_set_accessor_cannot_have_rest_parameter: { code: 1053, category: DiagnosticCategory.Error, key: "A 'set' accessor cannot have rest parameter." },
A_get_accessor_cannot_have_parameters: { code: 1054, category: DiagnosticCategory.Error, key: "A 'get' accessor cannot have parameters." },
Modifiers_cannot_appear_here: { code: 1055, category: DiagnosticCategory.Error, key: "Modifiers cannot appear here." },
Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: { code: 1056, category: DiagnosticCategory.Error, key: "Accessors are only available when targeting ECMAScript 5 and higher." },
Enum_member_must_have_initializer: { code: -9999999, category: DiagnosticCategory.Error, key: "Enum member must have initializer." },
Enum_member_must_have_initializer: { code: 1061, category: DiagnosticCategory.Error, key: "Enum member must have initializer." },
An_export_assignment_cannot_be_used_in_an_internal_module: { code: 1063, category: DiagnosticCategory.Error, key: "An export assignment cannot be used in an internal module." },
Ambient_enum_elements_can_only_have_integer_literal_initializers: { code: 1066, category: DiagnosticCategory.Error, key: "Ambient enum elements can only have integer literal initializers." },
module_class_interface_enum_import_or_statement: { code: 1067, category: DiagnosticCategory.NoPrefix, key: "module, class, interface, enum, import or statement" },
Unexpected_token_A_constructor_method_accessor_or_property_was_expected: { code: 1068, category: DiagnosticCategory.Error, key: "Unexpected token. A constructor, method, accessor, or property was expected." },
statement: { code: 1069, category: DiagnosticCategory.NoPrefix, key: "statement" },
case_or_default_clause: { code: 1070, category: DiagnosticCategory.NoPrefix, key: "case or default clause" },
identifier: { code: 1071, category: DiagnosticCategory.NoPrefix, key: "identifier" },
call_construct_index_property_or_function_signature: { code: 1072, category: DiagnosticCategory.NoPrefix, key: "call, construct, index, property or function signature" },
expression: { code: 1073, category: DiagnosticCategory.NoPrefix, key: "expression" },
type_name: { code: 1074, category: DiagnosticCategory.NoPrefix, key: "type name" },
property_or_accessor: { code: 1075, category: DiagnosticCategory.NoPrefix, key: "property or accessor" },
parameter: { code: 1076, category: DiagnosticCategory.NoPrefix, key: "parameter" },
type: { code: 1077, category: DiagnosticCategory.NoPrefix, key: "type" },
type_parameter: { code: 1078, category: DiagnosticCategory.NoPrefix, key: "type parameter" },
A_declare_modifier_cannot_be_used_with_an_import_declaration: { code: 1079, category: DiagnosticCategory.Error, key: "A 'declare' modifier cannot be used with an import declaration." },
Invalid_reference_directive_syntax: { code: 1084, category: DiagnosticCategory.Error, key: "Invalid 'reference' directive syntax." },
Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher: { code: 1085, category: DiagnosticCategory.Error, key: "Octal literals are not available when targeting ECMAScript 5 and higher." },
@@ -88,13 +67,12 @@ module ts {
Invalid_use_of_0_in_strict_mode: { code: 1100, category: DiagnosticCategory.Error, key: "Invalid use of '{0}' in strict mode." },
with_statements_are_not_allowed_in_strict_mode: { code: 1101, category: DiagnosticCategory.Error, key: "'with' statements are not allowed in strict mode." },
delete_cannot_be_called_on_an_identifier_in_strict_mode: { code: 1102, category: DiagnosticCategory.Error, key: "'delete' cannot be called on an identifier in strict mode." },
Invalid_left_hand_side_in_for_in_statement: { code: 1103, category: DiagnosticCategory.Error, key: "Invalid left-hand side in 'for...in' statement." },
A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: { code: 1104, category: DiagnosticCategory.Error, key: "A 'continue' statement can only be used within an enclosing iteration statement." },
A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: { code: 1105, category: DiagnosticCategory.Error, key: "A 'break' statement can only be used within an enclosing iteration or switch statement." },
Jump_target_cannot_cross_function_boundary: { code: 1107, category: DiagnosticCategory.Error, key: "Jump target cannot cross function boundary." },
A_return_statement_can_only_be_used_within_a_function_body: { code: 1108, category: DiagnosticCategory.Error, key: "A 'return' statement can only be used within a function body." },
Expression_expected: { code: -9999999, category: DiagnosticCategory.Error, key: "Expression expected." },
Type_expected: { code: -9999999, category: DiagnosticCategory.Error, key: "Type expected." },
Expression_expected: { code: 1109, category: DiagnosticCategory.Error, key: "Expression expected." },
Type_expected: { code: 1110, category: DiagnosticCategory.Error, key: "Type expected." },
A_constructor_implementation_cannot_be_declared_in_an_ambient_context: { code: 1111, category: DiagnosticCategory.Error, key: "A constructor implementation cannot be declared in an ambient context." },
A_class_member_cannot_be_declared_optional: { code: 1112, category: DiagnosticCategory.Error, key: "A class member cannot be declared optional." },
A_default_clause_cannot_appear_more_than_once_in_a_switch_statement: { code: 1113, category: DiagnosticCategory.Error, key: "A 'default' clause cannot appear more than once in a 'switch' statement." },
@@ -107,193 +85,260 @@ module ts {
An_export_assignment_cannot_have_modifiers: { code: 1120, category: DiagnosticCategory.Error, key: "An export assignment cannot have modifiers." },
Octal_literals_are_not_allowed_in_strict_mode: { code: 1121, category: DiagnosticCategory.Error, key: "Octal literals are not allowed in strict mode." },
A_tuple_type_element_list_cannot_be_empty: { code: 1122, category: DiagnosticCategory.Error, key: "A tuple type element list cannot be empty." },
Duplicate_identifier_0: { code: 2000, category: DiagnosticCategory.Error, key: "Duplicate identifier '{0}'." },
Extends_clause_of_exported_class_0_has_or_is_using_private_name_1: { code: 2018, category: DiagnosticCategory.Error, key: "Extends clause of exported class '{0}' has or is using private name '{1}'." },
Implements_clause_of_exported_class_0_has_or_is_using_private_name_1: { code: 2019, category: DiagnosticCategory.Error, key: "Implements clause of exported class '{0}' has or is using private name '{1}'." },
Extends_clause_of_exported_interface_0_has_or_is_using_private_name_1: { code: 2020, category: DiagnosticCategory.Error, key: "Extends clause of exported interface '{0}' has or is using private name '{1}'." },
Extends_clause_of_exported_class_0_has_or_is_using_name_1_from_private_module_2: { code: 2021, category: DiagnosticCategory.Error, key: "Extends clause of exported class '{0}' has or is using name '{1}' from private module '{2}'." },
Implements_clause_of_exported_class_0_has_or_is_using_name_1_from_private_module_2: { code: 2022, category: DiagnosticCategory.Error, key: "Implements clause of exported class '{0}' has or is using name '{1}' from private module '{2}'." },
Extends_clause_of_exported_interface_0_has_or_is_using_name_1_from_private_module_2: { code: 2023, category: DiagnosticCategory.Error, key: "Extends clause of exported interface '{0}' has or is using name '{1}' from private module '{2}'." },
Public_static_property_0_of_exported_class_has_or_is_using_private_name_1: { code: 2024, category: DiagnosticCategory.Error, key: "Public static property '{0}' of exported class has or is using private name '{1}'." },
Public_property_0_of_exported_class_has_or_is_using_private_name_1: { code: 2025, category: DiagnosticCategory.Error, key: "Public property '{0}' of exported class has or is using private name '{1}'." },
Property_0_of_exported_interface_has_or_is_using_private_name_1: { code: 2026, category: DiagnosticCategory.Error, key: "Property '{0}' of exported interface has or is using private name '{1}'." },
Exported_variable_0_has_or_is_using_private_name_1: { code: 2027, category: DiagnosticCategory.Error, key: "Exported variable '{0}' has or is using private name '{1}'." },
Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 2028, category: DiagnosticCategory.Error, key: "Public static property '{0}' of exported class has or is using name '{1}' from private module '{2}'." },
Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 2029, category: DiagnosticCategory.Error, key: "Public property '{0}' of exported class has or is using name '{1}' from private module '{2}'." },
Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 2030, category: DiagnosticCategory.Error, key: "Property '{0}' of exported interface has or is using name '{1}' from private module '{2}'." },
Exported_variable_0_has_or_is_using_name_1_from_private_module_2: { code: 2031, category: DiagnosticCategory.Error, key: "Exported variable '{0}' has or is using name '{1}' from private module '{2}'." },
Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1: { code: 2032, category: DiagnosticCategory.Error, key: "Parameter '{0}' of constructor from exported class has or is using private name '{1}'." },
Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1: { code: 2033, category: DiagnosticCategory.Error, key: "Parameter '{0}' of public static property setter from exported class has or is using private name '{1}'." },
Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1: { code: 2034, category: DiagnosticCategory.Error, key: "Parameter '{0}' of public property setter from exported class has or is using private name '{1}'." },
Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 2035, category: DiagnosticCategory.Error, key: "Parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'." },
Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 2036, category: DiagnosticCategory.Error, key: "Parameter '{0}' of call signature from exported interface has or is using private name '{1}'." },
Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: { code: 2037, category: DiagnosticCategory.Error, key: "Parameter '{0}' of public static method from exported class has or is using private name '{1}'." },
Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: { code: 2038, category: DiagnosticCategory.Error, key: "Parameter '{0}' of public method from exported class has or is using private name '{1}'." },
Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: { code: 2039, category: DiagnosticCategory.Error, key: "Parameter '{0}' of method from exported interface has or is using private name '{1}'." },
Parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 2040, category: DiagnosticCategory.Error, key: "Parameter '{0}' of exported function has or is using private name '{1}'." },
Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 2041, category: DiagnosticCategory.Error, key: "Parameter '{0}' of constructor from exported class has or is using name '{1}' from private module '{2}'." },
Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 2042, category: DiagnosticCategory.Error, key: "Parameter '{0}' of public static property setter from exported class has or is using name '{1}' from private module '{2}'." },
Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 2043, category: DiagnosticCategory.Error, key: "Parameter '{0}' of public property setter from exported class has or is using name '{1}' from private module '{2}'." },
Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 2044, category: DiagnosticCategory.Error, key: "Parameter '{0}' of constructor signature from exported interface has or is using name '{1}' from private module '{2}'." },
Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 2045, category: DiagnosticCategory.Error, key: "Parameter '{0}' of call signature from exported interface has or is using name '{1}' from private module '{2}'." },
Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 2046, category: DiagnosticCategory.Error, key: "Parameter '{0}' of public static method from exported class has or is using name '{1}' from private module '{2}'." },
Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 2047, category: DiagnosticCategory.Error, key: "Parameter '{0}' of public method from exported class has or is using name '{1}' from private module '{2}'." },
Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 2048, category: DiagnosticCategory.Error, key: "Parameter '{0}' of method from exported interface has or is using name '{1}' from private module '{2}'." },
Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2: { code: 2049, category: DiagnosticCategory.Error, key: "Parameter '{0}' of exported function has or is using name '{1}' from private module '{2}'." },
Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0: { code: 2050, category: DiagnosticCategory.Error, key: "Return type of public static property getter from exported class has or is using private name '{0}'." },
Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0: { code: 2051, category: DiagnosticCategory.Error, key: "Return type of public property getter from exported class has or is using private name '{0}'." },
Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0: { code: 2052, category: DiagnosticCategory.Error, key: "Return type of constructor signature from exported interface has or is using private name '{0}'." },
Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0: { code: 2053, category: DiagnosticCategory.Error, key: "Return type of call signature from exported interface has or is using private name '{0}'." },
Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0: { code: 2054, category: DiagnosticCategory.Error, key: "Return type of index signature from exported interface has or is using private name '{0}'." },
Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0: { code: 2055, category: DiagnosticCategory.Error, key: "Return type of public static method from exported class has or is using private name '{0}'." },
Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0: { code: 2056, category: DiagnosticCategory.Error, key: "Return type of public method from exported class has or is using private name '{0}'." },
Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0: { code: 2057, category: DiagnosticCategory.Error, key: "Return type of method from exported interface has or is using private name '{0}'." },
Return_type_of_exported_function_has_or_is_using_private_name_0: { code: 2058, category: DiagnosticCategory.Error, key: "Return type of exported function has or is using private name '{0}'." },
Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 2059, category: DiagnosticCategory.Error, key: "Return type of public static property getter from exported class has or is using name '{0}' from private module '{1}'." },
Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 2060, category: DiagnosticCategory.Error, key: "Return type of public property getter from exported class has or is using name '{0}' from private module '{1}'." },
Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 2061, category: DiagnosticCategory.Error, key: "Return type of constructor signature from exported interface has or is using name '{0}' from private module '{1}'." },
Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 2062, category: DiagnosticCategory.Error, key: "Return type of call signature from exported interface has or is using name '{0}' from private module '{1}'." },
Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 2063, category: DiagnosticCategory.Error, key: "Return type of index signature from exported interface has or is using name '{0}' from private module '{1}'." },
Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 2064, category: DiagnosticCategory.Error, key: "Return type of public static method from exported class has or is using name '{0}' from private module '{1}'." },
Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 2065, category: DiagnosticCategory.Error, key: "Return type of public method from exported class has or is using name '{0}' from private module '{1}'." },
Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 2066, category: DiagnosticCategory.Error, key: "Return type of method from exported interface has or is using name '{0}' from private module '{1}'." },
Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1: { code: 2067, category: DiagnosticCategory.Error, key: "Return type of exported function has or is using name '{0}' from private module '{1}'." },
Import_declaration_0_is_using_private_name_1: { code: 2181, category: DiagnosticCategory.Error, key: "Import declaration '{0}' is using private name '{1}'." },
Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 2208, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'." },
Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 2209, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of call signature from exported interface has or is using private name '{1}'." },
Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: { code: 2210, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of public static method from exported class has or is using private name '{1}'." },
Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: { code: 2211, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of public method from exported class has or is using private name '{1}'." },
Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: { code: 2212, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of method from exported interface has or is using private name '{1}'." },
Type_parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 2213, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported function has or is using private name '{1}'." },
Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 2214, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of constructor signature from exported interface has or is using name '{1}' from private module '{2}'." },
Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 2215, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of call signature from exported interface has or is using name '{1}' from private module '{2}'." },
Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 2216, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of public static method from exported class has or is using name '{1}' from private module '{2}'." },
Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 2217, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of public method from exported class has or is using name '{1}' from private module '{2}'." },
Type_parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 2218, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of method from exported interface has or is using name '{1}' from private module '{2}'." },
Type_parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2: { code: 2219, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported function has or is using name '{1}' from private module '{2}'." },
Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 2220, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported class has or is using private name '{1}'." },
Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 2221, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported interface has or is using private name '{1}'." },
Type_parameter_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 2222, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported class has or is using name '{1}' from private module '{2}'." },
Type_parameter_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 2223, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported interface has or is using name '{1}' from private module '{2}'." },
new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: { code: 2068, category: DiagnosticCategory.Error, key: "'new T[]' cannot be used to create an array. Use 'new Array<T>()' instead." },
Multiple_constructor_implementations_are_not_allowed: { code: 2070, category: DiagnosticCategory.Error, key: "Multiple constructor implementations are not allowed." },
A_class_may_only_implement_another_class_or_interface: { code: 2074, category: DiagnosticCategory.Error, key: "A class may only implement another class or interface." },
get_and_set_accessor_must_have_the_same_type: { code: 2096, category: DiagnosticCategory.Error, key: "'get' and 'set' accessor must have the same type." },
Static_members_cannot_reference_class_type_parameters: { code: 2099, category: DiagnosticCategory.Error, key: "Static members cannot reference class type parameters." },
super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: { code: 2102, category: DiagnosticCategory.Error, key: "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class" },
The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2112, category: DiagnosticCategory.Error, key: "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." },
The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2113, category: DiagnosticCategory.Error, key: "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." },
An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: { code: 2114, category: DiagnosticCategory.Error, key: "An arithmetic operand must be of type 'any', 'number' or an enum type." },
The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: { code: 2115, category: DiagnosticCategory.Error, key: "The left-hand side of a 'for...in' statement cannot use a type annotation." },
The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: { code: 2116, category: DiagnosticCategory.Error, key: "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'." },
The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2117, category: DiagnosticCategory.Error, key: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter." },
The_left_hand_side_of_an_in_expression_must_be_of_types_any_string_or_number: { code: 2118, category: DiagnosticCategory.Error, key: "The left-hand side of an 'in' expression must be of types 'any', 'string' or 'number'." },
The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2119, category: DiagnosticCategory.Error, key: "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter" },
A_get_accessor_must_return_a_value_or_consist_of_a_single_throw_statement: { code: 2126, category: DiagnosticCategory.Error, key: "A 'get' accessor must return a value or consist of a single 'throw' statement." },
Getter_and_setter_accessors_do_not_agree_in_visibility: { code: 2127, category: DiagnosticCategory.Error, key: "Getter and setter accessors do not agree in visibility." },
A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_or_consist_of_a_single_throw_statement: { code: 2131, category: DiagnosticCategory.Error, key: "A function whose declared type is neither 'void' nor 'any' must return a value or consist of a single 'throw' statement." },
Untyped_function_calls_may_not_accept_type_arguments: { code: 2158, category: DiagnosticCategory.Error, key: "Untyped function calls may not accept type arguments." },
The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2120, category: DiagnosticCategory.Error, key: "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter." },
The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: { code: 2121, category: DiagnosticCategory.Error, key: "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type." },
Setters_cannot_return_a_value: { code: 2122, category: DiagnosticCategory.Error, key: "Setters cannot return a value." },
Invalid_left_hand_side_of_assignment_expression: { code: 2130, category: DiagnosticCategory.Error, key: "Invalid left-hand side of assignment expression." },
Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: { code: 2134, category: DiagnosticCategory.Error, key: "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'." },
All_symbols_within_a_with_block_will_be_resolved_to_any: { code: 2135, category: DiagnosticCategory.Error, key: "All symbols within a 'with' block will be resolved to 'any'." },
The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer: { code: 2139, category: DiagnosticCategory.Error, key: "The operand of an increment or decrement operator must be a variable, property or indexer." },
Overload_signatures_must_all_be_public_or_private: { code: 2150, category: DiagnosticCategory.Error, key: "Overload signatures must all be public or private." },
Overload_signatures_must_all_be_exported_or_not_exported: { code: 2151, category: DiagnosticCategory.Error, key: "Overload signatures must all be exported or not exported." },
Overload_signatures_must_all_be_ambient_or_non_ambient: { code: 2152, category: DiagnosticCategory.Error, key: "Overload signatures must all be ambient or non-ambient." },
Overload_signatures_must_all_be_optional_or_required: { code: 2153, category: DiagnosticCategory.Error, key: "Overload signatures must all be optional or required." },
this_cannot_be_referenced_in_constructor_arguments: { code: 2155, category: DiagnosticCategory.Error, key: "'this' cannot be referenced in constructor arguments." },
Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: { code: 2161, category: DiagnosticCategory.Error, key: "Value of type '{0}' is not callable. Did you mean to include 'new'?" },
A_signature_with_an_implementation_cannot_use_a_string_literal_type: { code: 2163, category: DiagnosticCategory.Error, key: "A signature with an implementation cannot use a string literal type." },
Interface_0_cannot_simultaneously_extend_types_1_and_2_Colon: { code: 2189, category: DiagnosticCategory.Error, key: "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}':" },
Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: { code: 2190, category: DiagnosticCategory.Error, key: "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it." },
Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: { code: 2192, category: DiagnosticCategory.Error, key: "Individual declarations in merged declaration {0} must be all exported or all local." },
super_cannot_be_referenced_in_constructor_arguments: { code: 2193, category: DiagnosticCategory.Error, key: "'super' cannot be referenced in constructor arguments." },
Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: { code: 2194, category: DiagnosticCategory.Error, key: "Return type of constructor signature must be assignable to the instance type of the class" },
Ambient_external_module_declaration_cannot_specify_relative_module_name: { code: 2196, category: DiagnosticCategory.Error, key: "Ambient external module declaration cannot specify relative module name." },
Import_declaration_in_an_ambient_external_module_declaration_cannot_reference_external_module_through_relative_external_module_name: { code: 2197, category: DiagnosticCategory.Error, key: "Import declaration in an ambient external module declaration cannot reference external module through relative external module name." },
Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: { code: 2200, category: DiagnosticCategory.Error, key: "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference." },
Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: { code: 2205, category: DiagnosticCategory.Error, key: "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference." },
Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: { code: 2206, category: DiagnosticCategory.Error, key: "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference." },
Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: { code: 2207, category: DiagnosticCategory.Error, key: "Expression resolves to '_super' that compiler uses to capture base class reference." },
Duplicate_identifier_i_Compiler_uses_i_to_initialize_rest_parameter: { code: 2224, category: DiagnosticCategory.Error, key: "Duplicate identifier '_i'. Compiler uses '_i' to initialize rest parameter." },
Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: { code: 2225, category: DiagnosticCategory.Error, key: "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters." },
Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list: { code: 2229, category: DiagnosticCategory.Error, key: "Constraint of a type parameter cannot reference any type parameter from the same type parameter list." },
Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2230, category: DiagnosticCategory.Error, key: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." },
Parameter_0_cannot_be_referenced_in_its_initializer: { code: 2231, category: DiagnosticCategory.Error, key: "Parameter '{0}' cannot be referenced in its initializer." },
Duplicate_string_index_signature: { code: 2232, category: DiagnosticCategory.Error, key: "Duplicate string index signature." },
Duplicate_number_index_signature: { code: 2233, category: DiagnosticCategory.Error, key: "Duplicate number index signature." },
All_declarations_of_an_interface_must_have_identical_type_parameters: { code: 2234, category: DiagnosticCategory.Error, key: "All declarations of an interface must have identical type parameters." },
Expression_resolves_to_variable_declaration_i_that_compiler_uses_to_initialize_rest_parameter: { code: 2235, category: DiagnosticCategory.Error, key: "Expression resolves to variable declaration '_i' that compiler uses to initialize rest parameter." },
Function_implementation_name_must_be_0: { code: 2239, category: DiagnosticCategory.Error, key: "Function implementation name must be '{0}'." },
Constructor_implementation_is_missing: { code: 2240, category: DiagnosticCategory.Error, key: "Constructor implementation is missing." },
An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: { code: 2245, category: DiagnosticCategory.Error, key: "An export assignment cannot be used in a module with other exported elements." },
A_parameter_property_is_only_allowed_in_a_constructor_implementation: { code: 2246, category: DiagnosticCategory.Error, key: "A parameter property is only allowed in a constructor implementation." },
Function_overload_must_be_static: { code: 2247, category: DiagnosticCategory.Error, key: "Function overload must be static." },
Function_overload_must_not_be_static: { code: 2248, category: DiagnosticCategory.Error, key: "Function overload must not be static." },
Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 2249, category: DiagnosticCategory.Error, key: "Public static property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named." },
Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 2250, category: DiagnosticCategory.Error, key: "Public property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named." },
Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 2251, category: DiagnosticCategory.Error, key: "Exported variable '{0}' has or is using name '{1}' from external module {2} but cannot be named." },
Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 2252, category: DiagnosticCategory.Error, key: "Parameter '{0}' of constructor from exported class has or is using name '{1}' from external module {2} but cannot be named." },
Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 2253, category: DiagnosticCategory.Error, key: "Parameter '{0}' of public static method from exported class has or is using name '{1}' from external module {2} but cannot be named." },
Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 2254, category: DiagnosticCategory.Error, key: "Parameter '{0}' of public method from exported class has or is using name '{1}' from external module {2} but cannot be named." },
Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 2255, category: DiagnosticCategory.Error, key: "Parameter '{0}' of exported function has or is using name '{1}' from external module {2} but cannot be named." },
Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 2256, category: DiagnosticCategory.Error, key: "Return type of public static property getter from exported class has or is using name '{0}' from external module {1} but cannot be named." },
Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 2257, category: DiagnosticCategory.Error, key: "Return type of public property getter from exported class has or is using name '{0}' from external module {1} but cannot be named." },
Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 2258, category: DiagnosticCategory.Error, key: "Return type of public static method from exported class has or is using name '{0}' from external module {1} but cannot be named." },
Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 2259, category: DiagnosticCategory.Error, key: "Return type of public method from exported class has or is using name '{0}' from external module {1} but cannot be named." },
Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 2260, category: DiagnosticCategory.Error, key: "Return type of exported function has or is using name '{0}' from external module {1} but cannot be named." },
Circular_definition_of_import_alias_0: { code: 3000, category: DiagnosticCategory.Error, key: "Circular definition of import alias '{0}'." },
Cannot_find_name_0: { code: 3001, category: DiagnosticCategory.Error, key: "Cannot find name '{0}'." },
Module_0_has_no_exported_member_1: { code: 3002, category: DiagnosticCategory.Error, key: "Module '{0}' has no exported member '{1}'." },
Cannot_find_external_module_0: { code: 3003, category: DiagnosticCategory.Error, key: "Cannot find external module '{0}'." },
A_module_cannot_have_more_than_one_export_assignment: { code: 3004, category: DiagnosticCategory.Error, key: "A module cannot have more than one export assignment." },
Type_0_recursively_references_itself_as_a_base_type: { code: 3005, category: DiagnosticCategory.Error, key: "Type '{0}' recursively references itself as a base type." },
A_class_may_only_extend_another_class: { code: 3006, category: DiagnosticCategory.Error, key: "A class may only extend another class." },
An_interface_may_only_extend_a_class_or_another_interface: { code: 3007, category: DiagnosticCategory.Error, key: "An interface may only extend a class or another interface." },
Generic_type_0_requires_1_type_argument_s: { code: 3008, category: DiagnosticCategory.Error, key: "Generic type '{0}' requires {1} type argument(s)." },
Type_0_is_not_generic: { code: 3009, category: DiagnosticCategory.Error, key: "Type '{0}' is not generic." },
Cannot_find_global_type_0: { code: 3010, category: DiagnosticCategory.Error, key: "Cannot find global type '{0}'." },
Global_type_0_must_be_a_class_or_interface_type: { code: 3011, category: DiagnosticCategory.Error, key: "Global type '{0}' must be a class or interface type." },
Global_type_0_must_have_1_type_parameter_s: { code: 3012, category: DiagnosticCategory.Error, key: "Global type '{0}' must have {1} type parameter(s)." },
this_cannot_be_referenced_in_a_module_body: { code: 3013, category: DiagnosticCategory.Error, key: "'this' cannot be referenced in a module body." },
this_cannot_be_referenced_in_a_static_property_initializer: { code: 3014, category: DiagnosticCategory.Error, key: "'this' cannot be referenced in a static property initializer." },
this_cannot_be_referenced_in_current_location: { code: -9999999, category: DiagnosticCategory.Error, key: "'this' cannot be referenced in current location." },
super_can_only_be_referenced_in_a_derived_class: { code: 3015, category: DiagnosticCategory.Error, key: "'super' can only be referenced in a derived class." },
Property_0_does_not_exist_on_type_1: { code: 3017, category: DiagnosticCategory.Error, key: "Property '{0}' does not exist on type '{1}'." },
An_index_expression_argument_must_be_of_type_string_number_or_any: { code: 3018, category: DiagnosticCategory.Error, key: "An index expression argument must be of type 'string', 'number', or 'any'." },
Type_0_does_not_satisfy_the_constraint_1_Colon: { code: 3019, category: DiagnosticCategory.Error, key: "Type '{0}' does not satisfy the constraint '{1}':" },
Type_0_does_not_satisfy_the_constraint_1: { code: 3019, category: DiagnosticCategory.Error, key: "Type '{0}' does not satisfy the constraint '{1}'." },
Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 3020, category: DiagnosticCategory.Error, key: "Supplied parameters do not match any signature of call target." },
Cannot_invoke_an_expression_whose_type_lacks_a_call_signature: { code: 3021, category: DiagnosticCategory.Error, key: "Cannot invoke an expression whose type lacks a call signature." },
Only_a_void_function_can_be_called_with_the_new_keyword: { code: 3022, category: DiagnosticCategory.Error, key: "Only a void function can be called with the 'new' keyword." },
Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: { code: 3023, category: DiagnosticCategory.Error, key: "Cannot use 'new' with an expression whose type lacks a call or construct signature." },
Neither_type_0_nor_type_1_is_assignable_to_the_other_Colon: { code: 3024, category: DiagnosticCategory.Error, key: "Neither type '{0}' nor type '{1}' is assignable to the other:" },
Neither_type_0_nor_type_1_is_assignable_to_the_other: { code: 3024, category: DiagnosticCategory.Error, key: "Neither type '{0}' nor type '{1}' is assignable to the other." },
No_best_common_type_exists_among_return_expressions: { code: 3027, category: DiagnosticCategory.Error, key: "No best common type exists among return expressions." },
Operator_0_cannot_be_applied_to_types_1_and_2: { code: 3028, category: DiagnosticCategory.Error, key: "Operator '{0}' cannot be applied to types '{1}' and '{2}'." },
No_best_common_type_exists_between_0_and_1: { code: 3029, category: DiagnosticCategory.Error, key: "No best common type exists between '{0}' and '{1}'." },
No_best_common_type_exists_between_0_1_and_2: { code: 3030, category: DiagnosticCategory.Error, key: "No best common type exists between '{0}', '{1}', and '{2}'." },
A_rest_parameter_must_be_of_an_array_type: { code: 3031, category: DiagnosticCategory.Error, key: "A rest parameter must be of an array type." },
A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: { code: 3032, category: DiagnosticCategory.Error, key: "A parameter initializer is only allowed in a function or constructor implementation." },
Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: { code: 3033, category: DiagnosticCategory.Error, key: "Specialized overload signature is not assignable to any non-specialized signature." },
Duplicate_function_implementation: { code: 3034, category: DiagnosticCategory.Error, key: "Duplicate function implementation." },
Overload_signature_is_not_compatible_with_function_implementation: { code: 3035, category: DiagnosticCategory.Error, key: "Overload signature is not compatible with function implementation." },
Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: { code: 3036, category: DiagnosticCategory.Error, key: "Argument of type '{0}' is not assignable to parameter of type '{1}'." },
Index_signature_is_missing_in_type_0: { code: 4003, category: DiagnosticCategory.Error, key: "Index signature is missing in type '{0}'." },
Index_signatures_are_incompatible_Colon: { code: 4004, category: DiagnosticCategory.Error, key: "Index signatures are incompatible:" },
Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: { code: 4016, category: DiagnosticCategory.NoPrefix, key: "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function." },
Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: { code: 4017, category: DiagnosticCategory.NoPrefix, key: "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function." },
Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: { code: 4018, category: DiagnosticCategory.NoPrefix, key: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor." },
Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: { code: 4019, category: DiagnosticCategory.NoPrefix, key: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property." },
In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: { code: 4024, category: DiagnosticCategory.Error, key: "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element." },
Named_properties_0_of_types_1_and_2_are_not_identical: { code: 4032, category: DiagnosticCategory.NoPrefix, key: "Named properties '{0}' of types '{1}' and '{2}' are not identical." },
Variable_declaration_list_cannot_be_empty: { code: 1123, category: DiagnosticCategory.Error, key: "Variable declaration list cannot be empty." },
Digit_expected: { code: 1124, category: DiagnosticCategory.Error, key: "Digit expected." },
Hexadecimal_digit_expected: { code: 1125, category: DiagnosticCategory.Error, key: "Hexadecimal digit expected." },
Unexpected_end_of_text: { code: 1126, category: DiagnosticCategory.Error, key: "Unexpected end of text." },
Invalid_character: { code: 1127, category: DiagnosticCategory.Error, key: "Invalid character." },
Declaration_or_statement_expected: { code: 1128, category: DiagnosticCategory.Error, key: "Declaration or statement expected." },
Statement_expected: { code: 1129, category: DiagnosticCategory.Error, key: "Statement expected." },
case_or_default_expected: { code: 1130, category: DiagnosticCategory.Error, key: "'case' or 'default' expected." },
Property_or_signature_expected: { code: 1131, category: DiagnosticCategory.Error, key: "Property or signature expected." },
Enum_member_expected: { code: 1132, category: DiagnosticCategory.Error, key: "Enum member expected." },
Type_reference_expected: { code: 1133, category: DiagnosticCategory.Error, key: "Type reference expected." },
Variable_declaration_expected: { code: 1134, category: DiagnosticCategory.Error, key: "Variable declaration expected." },
Argument_expression_expected: { code: 1135, category: DiagnosticCategory.Error, key: "Argument expression expected." },
Property_assignment_expected: { code: 1136, category: DiagnosticCategory.Error, key: "Property assignment expected." },
Expression_or_comma_expected: { code: 1137, category: DiagnosticCategory.Error, key: "Expression or comma expected." },
Parameter_declaration_expected: { code: 1138, category: DiagnosticCategory.Error, key: "Parameter declaration expected." },
Type_parameter_declaration_expected: { code: 1139, category: DiagnosticCategory.Error, key: "Type parameter declaration expected." },
Type_argument_expected: { code: 1140, category: DiagnosticCategory.Error, key: "Type argument expected." },
String_literal_expected: { code: 1141, category: DiagnosticCategory.Error, key: "String literal expected." },
Line_break_not_permitted_here: { code: 1142, category: DiagnosticCategory.Error, key: "Line break not permitted here." },
catch_or_finally_expected: { code: 1143, category: DiagnosticCategory.Error, key: "'catch' or 'finally' expected." },
Block_or_expected: { code: 1144, category: DiagnosticCategory.Error, key: "Block or ';' expected." },
Modifiers_not_permitted_on_index_signature_members: { code: 1145, category: DiagnosticCategory.Error, key: "Modifiers not permitted on index signature members." },
Declaration_expected: { code: 1146, category: DiagnosticCategory.Error, key: "Declaration expected." },
Import_declarations_in_an_internal_module_cannot_reference_an_external_module: { code: 1147, category: DiagnosticCategory.Error, key: "Import declarations in an internal module cannot reference an external module." },
Cannot_compile_external_modules_unless_the_module_flag_is_provided: { code: 1148, category: DiagnosticCategory.Error, key: "Cannot compile external modules unless the '--module' flag is provided." },
Filename_0_differs_from_already_included_filename_1_only_in_casing: { code: 1149, category: DiagnosticCategory.Error, key: "Filename '{0}' differs from already included filename '{1}' only in casing" },
new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: { code: 1150, category: DiagnosticCategory.Error, key: "'new T[]' cannot be used to create an array. Use 'new Array<T>()' instead." },
Duplicate_identifier_0: { code: 2300, category: DiagnosticCategory.Error, key: "Duplicate identifier '{0}'." },
Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: DiagnosticCategory.Error, key: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." },
Static_members_cannot_reference_class_type_parameters: { code: 2302, category: DiagnosticCategory.Error, key: "Static members cannot reference class type parameters." },
Circular_definition_of_import_alias_0: { code: 2303, category: DiagnosticCategory.Error, key: "Circular definition of import alias '{0}'." },
Cannot_find_name_0: { code: 2304, category: DiagnosticCategory.Error, key: "Cannot find name '{0}'." },
Module_0_has_no_exported_member_1: { code: 2305, category: DiagnosticCategory.Error, key: "Module '{0}' has no exported member '{1}'." },
File_0_is_not_an_external_module: { code: 2306, category: DiagnosticCategory.Error, key: "File '{0}' is not an external module." },
Cannot_find_external_module_0: { code: 2307, category: DiagnosticCategory.Error, key: "Cannot find external module '{0}'." },
A_module_cannot_have_more_than_one_export_assignment: { code: 2308, category: DiagnosticCategory.Error, key: "A module cannot have more than one export assignment." },
An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: { code: 2309, category: DiagnosticCategory.Error, key: "An export assignment cannot be used in a module with other exported elements." },
Type_0_recursively_references_itself_as_a_base_type: { code: 2310, category: DiagnosticCategory.Error, key: "Type '{0}' recursively references itself as a base type." },
A_class_may_only_extend_another_class: { code: 2311, category: DiagnosticCategory.Error, key: "A class may only extend another class." },
An_interface_may_only_extend_a_class_or_another_interface: { code: 2312, category: DiagnosticCategory.Error, key: "An interface may only extend a class or another interface." },
Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list: { code: 2313, category: DiagnosticCategory.Error, key: "Constraint of a type parameter cannot reference any type parameter from the same type parameter list." },
Generic_type_0_requires_1_type_argument_s: { code: 2314, category: DiagnosticCategory.Error, key: "Generic type '{0}' requires {1} type argument(s)." },
Type_0_is_not_generic: { code: 2315, category: DiagnosticCategory.Error, key: "Type '{0}' is not generic." },
Global_type_0_must_be_a_class_or_interface_type: { code: 2316, category: DiagnosticCategory.Error, key: "Global type '{0}' must be a class or interface type." },
Global_type_0_must_have_1_type_parameter_s: { code: 2317, category: DiagnosticCategory.Error, key: "Global type '{0}' must have {1} type parameter(s)." },
Cannot_find_global_type_0: { code: 2318, category: DiagnosticCategory.Error, key: "Cannot find global type '{0}'." },
Named_properties_0_of_types_1_and_2_are_not_identical: { code: 2319, category: DiagnosticCategory.Error, key: "Named properties '{0}' of types '{1}' and '{2}' are not identical." },
Interface_0_cannot_simultaneously_extend_types_1_and_2_Colon: { code: 2320, category: DiagnosticCategory.Error, key: "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}':" },
Excessive_stack_depth_comparing_types_0_and_1: { code: 2321, category: DiagnosticCategory.Error, key: "Excessive stack depth comparing types '{0}' and '{1}'." },
Type_0_is_not_assignable_to_type_1_Colon: { code: 2322, category: DiagnosticCategory.Error, key: "Type '{0}' is not assignable to type '{1}':" },
Type_0_is_not_assignable_to_type_1: { code: 2323, category: DiagnosticCategory.Error, key: "Type '{0}' is not assignable to type '{1}'." },
Property_0_is_missing_in_type_1: { code: 2324, category: DiagnosticCategory.Error, key: "Property '{0}' is missing in type '{1}'." },
Private_property_0_cannot_be_reimplemented: { code: 2325, category: DiagnosticCategory.Error, key: "Private property '{0}' cannot be reimplemented." },
Types_of_property_0_are_incompatible_Colon: { code: 2326, category: DiagnosticCategory.Error, key: "Types of property '{0}' are incompatible:" },
Required_property_0_cannot_be_reimplemented_with_optional_property_in_1: { code: 2327, category: DiagnosticCategory.Error, key: "Required property '{0}' cannot be reimplemented with optional property in '{1}'." },
Types_of_parameters_0_and_1_are_incompatible_Colon: { code: 2328, category: DiagnosticCategory.Error, key: "Types of parameters '{0}' and '{1}' are incompatible:" },
Index_signature_is_missing_in_type_0: { code: 2329, category: DiagnosticCategory.Error, key: "Index signature is missing in type '{0}'." },
Index_signatures_are_incompatible_Colon: { code: 2330, category: DiagnosticCategory.Error, key: "Index signatures are incompatible:" },
this_cannot_be_referenced_in_a_module_body: { code: 2331, category: DiagnosticCategory.Error, key: "'this' cannot be referenced in a module body." },
this_cannot_be_referenced_in_current_location: { code: 2332, category: DiagnosticCategory.Error, key: "'this' cannot be referenced in current location." },
this_cannot_be_referenced_in_constructor_arguments: { code: 2333, category: DiagnosticCategory.Error, key: "'this' cannot be referenced in constructor arguments." },
this_cannot_be_referenced_in_a_static_property_initializer: { code: 2334, category: DiagnosticCategory.Error, key: "'this' cannot be referenced in a static property initializer." },
super_can_only_be_referenced_in_a_derived_class: { code: 2335, category: DiagnosticCategory.Error, key: "'super' can only be referenced in a derived class." },
super_cannot_be_referenced_in_constructor_arguments: { code: 2336, category: DiagnosticCategory.Error, key: "'super' cannot be referenced in constructor arguments." },
Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: { code: 2337, category: DiagnosticCategory.Error, key: "Super calls are not permitted outside constructors or in nested functions inside constructors" },
super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: { code: 2338, category: DiagnosticCategory.Error, key: "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class" },
Property_0_does_not_exist_on_type_1: { code: 2339, category: DiagnosticCategory.Error, key: "Property '{0}' does not exist on type '{1}'." },
Only_public_methods_of_the_base_class_are_accessible_via_the_super_keyword: { code: 2340, category: DiagnosticCategory.Error, key: "Only public methods of the base class are accessible via the 'super' keyword" },
Property_0_is_inaccessible: { code: 2341, category: DiagnosticCategory.Error, key: "Property '{0}' is inaccessible." },
An_index_expression_argument_must_be_of_type_string_number_or_any: { code: 2342, category: DiagnosticCategory.Error, key: "An index expression argument must be of type 'string', 'number', or 'any'." },
Type_0_does_not_satisfy_the_constraint_1_Colon: { code: 2343, category: DiagnosticCategory.Error, key: "Type '{0}' does not satisfy the constraint '{1}':" },
Type_0_does_not_satisfy_the_constraint_1: { code: 2344, category: DiagnosticCategory.Error, key: "Type '{0}' does not satisfy the constraint '{1}'." },
Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: { code: 2345, category: DiagnosticCategory.Error, key: "Argument of type '{0}' is not assignable to parameter of type '{1}'." },
Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 2346, category: DiagnosticCategory.Error, key: "Supplied parameters do not match any signature of call target." },
Untyped_function_calls_may_not_accept_type_arguments: { code: 2347, category: DiagnosticCategory.Error, key: "Untyped function calls may not accept type arguments." },
Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: { code: 2348, category: DiagnosticCategory.Error, key: "Value of type '{0}' is not callable. Did you mean to include 'new'?" },
Cannot_invoke_an_expression_whose_type_lacks_a_call_signature: { code: 2349, category: DiagnosticCategory.Error, key: "Cannot invoke an expression whose type lacks a call signature." },
Only_a_void_function_can_be_called_with_the_new_keyword: { code: 2350, category: DiagnosticCategory.Error, key: "Only a void function can be called with the 'new' keyword." },
Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: { code: 2351, category: DiagnosticCategory.Error, key: "Cannot use 'new' with an expression whose type lacks a call or construct signature." },
Neither_type_0_nor_type_1_is_assignable_to_the_other: { code: 2352, category: DiagnosticCategory.Error, key: "Neither type '{0}' nor type '{1}' is assignable to the other." },
Neither_type_0_nor_type_1_is_assignable_to_the_other_Colon: { code: 2353, category: DiagnosticCategory.Error, key: "Neither type '{0}' nor type '{1}' is assignable to the other:" },
No_best_common_type_exists_among_return_expressions: { code: 2354, category: DiagnosticCategory.Error, key: "No best common type exists among return expressions." },
A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_or_consist_of_a_single_throw_statement: { code: 2355, category: DiagnosticCategory.Error, key: "A function whose declared type is neither 'void' nor 'any' must return a value or consist of a single 'throw' statement." },
An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: { code: 2356, category: DiagnosticCategory.Error, key: "An arithmetic operand must be of type 'any', 'number' or an enum type." },
The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer: { code: 2357, category: DiagnosticCategory.Error, key: "The operand of an increment or decrement operator must be a variable, property or indexer." },
The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2358, category: DiagnosticCategory.Error, key: "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter." },
The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: { code: 2359, category: DiagnosticCategory.Error, key: "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type." },
The_left_hand_side_of_an_in_expression_must_be_of_types_any_string_or_number: { code: 2360, category: DiagnosticCategory.Error, key: "The left-hand side of an 'in' expression must be of types 'any', 'string' or 'number'." },
The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2361, category: DiagnosticCategory.Error, key: "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter" },
The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2362, category: DiagnosticCategory.Error, key: "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." },
The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2363, category: DiagnosticCategory.Error, key: "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." },
Invalid_left_hand_side_of_assignment_expression: { code: 2364, category: DiagnosticCategory.Error, key: "Invalid left-hand side of assignment expression." },
Operator_0_cannot_be_applied_to_types_1_and_2: { code: 2365, category: DiagnosticCategory.Error, key: "Operator '{0}' cannot be applied to types '{1}' and '{2}'." },
No_best_common_type_exists_between_0_1_and_2: { code: 2366, category: DiagnosticCategory.Error, key: "No best common type exists between '{0}', '{1}', and '{2}'." },
No_best_common_type_exists_between_0_and_1: { code: 2367, category: DiagnosticCategory.Error, key: "No best common type exists between '{0}' and '{1}'." },
Type_parameter_name_cannot_be_0: { code: 2368, category: DiagnosticCategory.Error, key: "Type parameter name cannot be '{0}'" },
A_parameter_property_is_only_allowed_in_a_constructor_implementation: { code: 2369, category: DiagnosticCategory.Error, key: "A parameter property is only allowed in a constructor implementation." },
A_rest_parameter_must_be_of_an_array_type: { code: 2370, category: DiagnosticCategory.Error, key: "A rest parameter must be of an array type." },
A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: { code: 2371, category: DiagnosticCategory.Error, key: "A parameter initializer is only allowed in a function or constructor implementation." },
Parameter_0_cannot_be_referenced_in_its_initializer: { code: 2372, category: DiagnosticCategory.Error, key: "Parameter '{0}' cannot be referenced in its initializer." },
Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: { code: 2373, category: DiagnosticCategory.Error, key: "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it." },
Duplicate_string_index_signature: { code: 2374, category: DiagnosticCategory.Error, key: "Duplicate string index signature." },
Duplicate_number_index_signature: { code: 2375, category: DiagnosticCategory.Error, key: "Duplicate number index signature." },
A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: { code: 2376, category: DiagnosticCategory.Error, key: "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties." },
Constructors_for_derived_classes_must_contain_a_super_call: { code: 2377, category: DiagnosticCategory.Error, key: "Constructors for derived classes must contain a 'super' call." },
A_get_accessor_must_return_a_value_or_consist_of_a_single_throw_statement: { code: 2378, category: DiagnosticCategory.Error, key: "A 'get' accessor must return a value or consist of a single 'throw' statement." },
Getter_and_setter_accessors_do_not_agree_in_visibility: { code: 2379, category: DiagnosticCategory.Error, key: "Getter and setter accessors do not agree in visibility." },
get_and_set_accessor_must_have_the_same_type: { code: 2380, category: DiagnosticCategory.Error, key: "'get' and 'set' accessor must have the same type." },
A_signature_with_an_implementation_cannot_use_a_string_literal_type: { code: 2381, category: DiagnosticCategory.Error, key: "A signature with an implementation cannot use a string literal type." },
Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: { code: 2382, category: DiagnosticCategory.Error, key: "Specialized overload signature is not assignable to any non-specialized signature." },
Overload_signatures_must_all_be_exported_or_not_exported: { code: 2383, category: DiagnosticCategory.Error, key: "Overload signatures must all be exported or not exported." },
Overload_signatures_must_all_be_ambient_or_non_ambient: { code: 2384, category: DiagnosticCategory.Error, key: "Overload signatures must all be ambient or non-ambient." },
Overload_signatures_must_all_be_public_or_private: { code: 2385, category: DiagnosticCategory.Error, key: "Overload signatures must all be public or private." },
Overload_signatures_must_all_be_optional_or_required: { code: 2386, category: DiagnosticCategory.Error, key: "Overload signatures must all be optional or required." },
Function_overload_must_be_static: { code: 2387, category: DiagnosticCategory.Error, key: "Function overload must be static." },
Function_overload_must_not_be_static: { code: 2388, category: DiagnosticCategory.Error, key: "Function overload must not be static." },
Function_implementation_name_must_be_0: { code: 2389, category: DiagnosticCategory.Error, key: "Function implementation name must be '{0}'." },
Constructor_implementation_is_missing: { code: 2390, category: DiagnosticCategory.Error, key: "Constructor implementation is missing." },
Function_implementation_is_missing_or_not_immediately_following_the_declaration: { code: 2391, category: DiagnosticCategory.Error, key: "Function implementation is missing or not immediately following the declaration." },
Multiple_constructor_implementations_are_not_allowed: { code: 2392, category: DiagnosticCategory.Error, key: "Multiple constructor implementations are not allowed." },
Duplicate_function_implementation: { code: 2393, category: DiagnosticCategory.Error, key: "Duplicate function implementation." },
Overload_signature_is_not_compatible_with_function_implementation: { code: 2394, category: DiagnosticCategory.Error, key: "Overload signature is not compatible with function implementation." },
Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: { code: 2395, category: DiagnosticCategory.Error, key: "Individual declarations in merged declaration {0} must be all exported or all local." },
Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: { code: 2396, category: DiagnosticCategory.Error, key: "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters." },
Duplicate_identifier_i_Compiler_uses_i_to_initialize_rest_parameter: { code: 2397, category: DiagnosticCategory.Error, key: "Duplicate identifier '_i'. Compiler uses '_i' to initialize rest parameter." },
Expression_resolves_to_variable_declaration_i_that_compiler_uses_to_initialize_rest_parameter: { code: 2398, category: DiagnosticCategory.Error, key: "Expression resolves to variable declaration '_i' that compiler uses to initialize rest parameter." },
Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: { code: 2399, category: DiagnosticCategory.Error, key: "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference." },
Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: { code: 2400, category: DiagnosticCategory.Error, key: "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference." },
Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: { code: 2401, category: DiagnosticCategory.Error, key: "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference." },
Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: { code: 2402, category: DiagnosticCategory.Error, key: "Expression resolves to '_super' that compiler uses to capture base class reference." },
Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: { code: 2403, category: DiagnosticCategory.Error, key: "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'." },
The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: { code: 2404, category: DiagnosticCategory.Error, key: "The left-hand side of a 'for...in' statement cannot use a type annotation." },
The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: { code: 2405, category: DiagnosticCategory.Error, key: "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'." },
Invalid_left_hand_side_in_for_in_statement: { code: 2406, category: DiagnosticCategory.Error, key: "Invalid left-hand side in 'for...in' statement." },
The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2407, category: DiagnosticCategory.Error, key: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter." },
Setters_cannot_return_a_value: { code: 2408, category: DiagnosticCategory.Error, key: "Setters cannot return a value." },
Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: { code: 2409, category: DiagnosticCategory.Error, key: "Return type of constructor signature must be assignable to the instance type of the class" },
All_symbols_within_a_with_block_will_be_resolved_to_any: { code: 2410, category: DiagnosticCategory.Error, key: "All symbols within a 'with' block will be resolved to 'any'." },
Property_0_of_type_1_is_not_assignable_to_string_index_type_2: { code: 2411, category: DiagnosticCategory.Error, key: "Property '{0}' of type '{1}' is not assignable to string index type '{2}'." },
Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: { code: 2412, category: DiagnosticCategory.Error, key: "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'." },
Numeric_index_type_0_is_not_assignable_to_string_index_type_1: { code: 2413, category: DiagnosticCategory.Error, key: "Numeric index type '{0}' is not assignable to string index type '{1}'." },
Class_name_cannot_be_0: { code: 2414, category: DiagnosticCategory.Error, key: "Class name cannot be '{0}'" },
Class_0_incorrectly_extends_base_class_1: { code: 2415, category: DiagnosticCategory.Error, key: "Class '{0}' incorrectly extends base class '{1}'." },
Class_0_incorrectly_extends_base_class_1_Colon: { code: 2416, category: DiagnosticCategory.Error, key: "Class '{0}' incorrectly extends base class '{1}':" },
Class_static_side_0_incorrectly_extends_base_class_static_side_1: { code: 2417, category: DiagnosticCategory.Error, key: "Class static side '{0}' incorrectly extends base class static side '{1}'." },
Class_static_side_0_incorrectly_extends_base_class_static_side_1_Colon: { code: 2418, category: DiagnosticCategory.Error, key: "Class static side '{0}' incorrectly extends base class static side '{1}':" },
Type_name_0_in_extends_clause_does_not_reference_constructor_function_for_0: { code: 2419, category: DiagnosticCategory.Error, key: "Type name '{0}' in extends clause does not reference constructor function for '{0}'." },
Class_0_incorrectly_implements_interface_1: { code: 2420, category: DiagnosticCategory.Error, key: "Class '{0}' incorrectly implements interface '{1}'." },
Class_0_incorrectly_implements_interface_1_Colon: { code: 2421, category: DiagnosticCategory.Error, key: "Class '{0}' incorrectly implements interface '{1}':" },
A_class_may_only_implement_another_class_or_interface: { code: 2422, category: DiagnosticCategory.Error, key: "A class may only implement another class or interface." },
Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: { code: 2423, category: DiagnosticCategory.Error, key: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor." },
Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: { code: 2424, category: DiagnosticCategory.Error, key: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property." },
Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: { code: 2425, category: DiagnosticCategory.Error, key: "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function." },
Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: { code: 2426, category: DiagnosticCategory.Error, key: "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function." },
Interface_name_cannot_be_0: { code: 2427, category: DiagnosticCategory.Error, key: "Interface name cannot be '{0}'" },
All_declarations_of_an_interface_must_have_identical_type_parameters: { code: 2428, category: DiagnosticCategory.Error, key: "All declarations of an interface must have identical type parameters." },
Interface_0_incorrectly_extends_interface_1_Colon: { code: 2429, category: DiagnosticCategory.Error, key: "Interface '{0}' incorrectly extends interface '{1}':" },
Interface_0_incorrectly_extends_interface_1: { code: 2430, category: DiagnosticCategory.Error, key: "Interface '{0}' incorrectly extends interface '{1}'." },
Enum_name_cannot_be_0: { code: 2431, category: DiagnosticCategory.Error, key: "Enum name cannot be '{0}'" },
In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: { code: 2432, category: DiagnosticCategory.Error, key: "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element." },
A_module_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged: { code: 2433, category: DiagnosticCategory.Error, key: "A module declaration cannot be in a different file from a class or function with which it is merged" },
A_module_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged: { code: 2434, category: DiagnosticCategory.Error, key: "A module declaration cannot be located prior to a class or function with which it is merged" },
Ambient_external_modules_cannot_be_nested_in_other_modules: { code: 2435, category: DiagnosticCategory.Error, key: "Ambient external modules cannot be nested in other modules." },
Ambient_external_module_declaration_cannot_specify_relative_module_name: { code: 2436, category: DiagnosticCategory.Error, key: "Ambient external module declaration cannot specify relative module name." },
Module_0_is_hidden_by_a_local_declaration_with_the_same_name: { code: 2437, category: DiagnosticCategory.Error, key: "Module '{0}' is hidden by a local declaration with the same name" },
Import_name_cannot_be_0: { code: 2438, category: DiagnosticCategory.Error, key: "Import name cannot be '{0}'" },
Import_declaration_in_an_ambient_external_module_declaration_cannot_reference_external_module_through_relative_external_module_name: { code: 2439, category: DiagnosticCategory.Error, key: "Import declaration in an ambient external module declaration cannot reference external module through relative external module name." },
Import_declaration_conflicts_with_local_declaration_of_0: { code: 2440, category: DiagnosticCategory.Error, key: "Import declaration conflicts with local declaration of '{0}'" },
Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_an_external_module: { code: 2441, category: DiagnosticCategory.Error, key: "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of an external module." },
Import_declaration_0_is_using_private_name_1: { code: 4000, category: DiagnosticCategory.Error, key: "Import declaration '{0}' is using private name '{1}'." },
Type_parameter_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4001, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported class has or is using name '{1}' from private module '{2}'." },
Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported class has or is using private name '{1}'." },
Type_parameter_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4003, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported interface has or is using name '{1}' from private module '{2}'." },
Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported interface has or is using private name '{1}'." },
Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4005, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of constructor signature from exported interface has or is using name '{1}' from private module '{2}'." },
Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4006, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'." },
Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4007, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of call signature from exported interface has or is using name '{1}' from private module '{2}'." },
Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4008, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of call signature from exported interface has or is using private name '{1}'." },
Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4009, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of public static method from exported class has or is using name '{1}' from private module '{2}'." },
Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: { code: 4010, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of public static method from exported class has or is using private name '{1}'." },
Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4011, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of public method from exported class has or is using name '{1}' from private module '{2}'." },
Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: { code: 4012, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of public method from exported class has or is using private name '{1}'." },
Type_parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4013, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of method from exported interface has or is using name '{1}' from private module '{2}'." },
Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: { code: 4014, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of method from exported interface has or is using private name '{1}'." },
Type_parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2: { code: 4015, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported function has or is using name '{1}' from private module '{2}'." },
Type_parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4016, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported function has or is using private name '{1}'." },
Implements_clause_of_exported_class_0_has_or_is_using_name_1_from_private_module_2: { code: 4017, category: DiagnosticCategory.Error, key: "Implements clause of exported class '{0}' has or is using name '{1}' from private module '{2}'." },
Extends_clause_of_exported_class_0_has_or_is_using_name_1_from_private_module_2: { code: 4018, category: DiagnosticCategory.Error, key: "Extends clause of exported class '{0}' has or is using name '{1}' from private module '{2}'." },
Implements_clause_of_exported_class_0_has_or_is_using_private_name_1: { code: 4019, category: DiagnosticCategory.Error, key: "Implements clause of exported class '{0}' has or is using private name '{1}'." },
Extends_clause_of_exported_class_0_has_or_is_using_private_name_1: { code: 4020, category: DiagnosticCategory.Error, key: "Extends clause of exported class '{0}' has or is using private name '{1}'." },
Extends_clause_of_exported_interface_0_has_or_is_using_name_1_from_private_module_2: { code: 4021, category: DiagnosticCategory.Error, key: "Extends clause of exported interface '{0}' has or is using name '{1}' from private module '{2}'." },
Extends_clause_of_exported_interface_0_has_or_is_using_private_name_1: { code: 4022, category: DiagnosticCategory.Error, key: "Extends clause of exported interface '{0}' has or is using private name '{1}'." },
Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4023, category: DiagnosticCategory.Error, key: "Exported variable '{0}' has or is using name '{1}' from external module {2} but cannot be named." },
Exported_variable_0_has_or_is_using_name_1_from_private_module_2: { code: 4024, category: DiagnosticCategory.Error, key: "Exported variable '{0}' has or is using name '{1}' from private module '{2}'." },
Exported_variable_0_has_or_is_using_private_name_1: { code: 4025, category: DiagnosticCategory.Error, key: "Exported variable '{0}' has or is using private name '{1}'." },
Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4026, category: DiagnosticCategory.Error, key: "Public static property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named." },
Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4027, category: DiagnosticCategory.Error, key: "Public static property '{0}' of exported class has or is using name '{1}' from private module '{2}'." },
Public_static_property_0_of_exported_class_has_or_is_using_private_name_1: { code: 4028, category: DiagnosticCategory.Error, key: "Public static property '{0}' of exported class has or is using private name '{1}'." },
Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4029, category: DiagnosticCategory.Error, key: "Public property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named." },
Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4030, category: DiagnosticCategory.Error, key: "Public property '{0}' of exported class has or is using name '{1}' from private module '{2}'." },
Public_property_0_of_exported_class_has_or_is_using_private_name_1: { code: 4031, category: DiagnosticCategory.Error, key: "Public property '{0}' of exported class has or is using private name '{1}'." },
Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4032, category: DiagnosticCategory.Error, key: "Property '{0}' of exported interface has or is using name '{1}' from private module '{2}'." },
Property_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4033, category: DiagnosticCategory.Error, key: "Property '{0}' of exported interface has or is using private name '{1}'." },
Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4034, category: DiagnosticCategory.Error, key: "Parameter '{0}' of public static property setter from exported class has or is using name '{1}' from private module '{2}'." },
Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1: { code: 4035, category: DiagnosticCategory.Error, key: "Parameter '{0}' of public static property setter from exported class has or is using private name '{1}'." },
Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4036, category: DiagnosticCategory.Error, key: "Parameter '{0}' of public property setter from exported class has or is using name '{1}' from private module '{2}'." },
Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1: { code: 4037, category: DiagnosticCategory.Error, key: "Parameter '{0}' of public property setter from exported class has or is using private name '{1}'." },
Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4038, category: DiagnosticCategory.Error, key: "Return type of public static property getter from exported class has or is using name '{0}' from external module {1} but cannot be named." },
Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 4039, category: DiagnosticCategory.Error, key: "Return type of public static property getter from exported class has or is using name '{0}' from private module '{1}'." },
Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0: { code: 4040, category: DiagnosticCategory.Error, key: "Return type of public static property getter from exported class has or is using private name '{0}'." },
Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4041, category: DiagnosticCategory.Error, key: "Return type of public property getter from exported class has or is using name '{0}' from external module {1} but cannot be named." },
Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 4042, category: DiagnosticCategory.Error, key: "Return type of public property getter from exported class has or is using name '{0}' from private module '{1}'." },
Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0: { code: 4043, category: DiagnosticCategory.Error, key: "Return type of public property getter from exported class has or is using private name '{0}'." },
Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 4044, category: DiagnosticCategory.Error, key: "Return type of constructor signature from exported interface has or is using name '{0}' from private module '{1}'." },
Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0: { code: 4045, category: DiagnosticCategory.Error, key: "Return type of constructor signature from exported interface has or is using private name '{0}'." },
Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 4046, category: DiagnosticCategory.Error, key: "Return type of call signature from exported interface has or is using name '{0}' from private module '{1}'." },
Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0: { code: 4047, category: DiagnosticCategory.Error, key: "Return type of call signature from exported interface has or is using private name '{0}'." },
Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 4048, category: DiagnosticCategory.Error, key: "Return type of index signature from exported interface has or is using name '{0}' from private module '{1}'." },
Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0: { code: 4049, category: DiagnosticCategory.Error, key: "Return type of index signature from exported interface has or is using private name '{0}'." },
Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4050, category: DiagnosticCategory.Error, key: "Return type of public static method from exported class has or is using name '{0}' from external module {1} but cannot be named." },
Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 4051, category: DiagnosticCategory.Error, key: "Return type of public static method from exported class has or is using name '{0}' from private module '{1}'." },
Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0: { code: 4052, category: DiagnosticCategory.Error, key: "Return type of public static method from exported class has or is using private name '{0}'." },
Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4053, category: DiagnosticCategory.Error, key: "Return type of public method from exported class has or is using name '{0}' from external module {1} but cannot be named." },
Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 4054, category: DiagnosticCategory.Error, key: "Return type of public method from exported class has or is using name '{0}' from private module '{1}'." },
Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0: { code: 4055, category: DiagnosticCategory.Error, key: "Return type of public method from exported class has or is using private name '{0}'." },
Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 4056, category: DiagnosticCategory.Error, key: "Return type of method from exported interface has or is using name '{0}' from private module '{1}'." },
Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0: { code: 4057, category: DiagnosticCategory.Error, key: "Return type of method from exported interface has or is using private name '{0}'." },
Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4058, category: DiagnosticCategory.Error, key: "Return type of exported function has or is using name '{0}' from external module {1} but cannot be named." },
Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1: { code: 4059, category: DiagnosticCategory.Error, key: "Return type of exported function has or is using name '{0}' from private module '{1}'." },
Return_type_of_exported_function_has_or_is_using_private_name_0: { code: 4060, category: DiagnosticCategory.Error, key: "Return type of exported function has or is using private name '{0}'." },
Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4061, category: DiagnosticCategory.Error, key: "Parameter '{0}' of constructor from exported class has or is using name '{1}' from external module {2} but cannot be named." },
Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4062, category: DiagnosticCategory.Error, key: "Parameter '{0}' of constructor from exported class has or is using name '{1}' from private module '{2}'." },
Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1: { code: 4063, category: DiagnosticCategory.Error, key: "Parameter '{0}' of constructor from exported class has or is using private name '{1}'." },
Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4064, category: DiagnosticCategory.Error, key: "Parameter '{0}' of constructor signature from exported interface has or is using name '{1}' from private module '{2}'." },
Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4065, category: DiagnosticCategory.Error, key: "Parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'." },
Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4066, category: DiagnosticCategory.Error, key: "Parameter '{0}' of call signature from exported interface has or is using name '{1}' from private module '{2}'." },
Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4067, category: DiagnosticCategory.Error, key: "Parameter '{0}' of call signature from exported interface has or is using private name '{1}'." },
Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4068, category: DiagnosticCategory.Error, key: "Parameter '{0}' of public static method from exported class has or is using name '{1}' from external module {2} but cannot be named." },
Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4069, category: DiagnosticCategory.Error, key: "Parameter '{0}' of public static method from exported class has or is using name '{1}' from private module '{2}'." },
Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: { code: 4070, category: DiagnosticCategory.Error, key: "Parameter '{0}' of public static method from exported class has or is using private name '{1}'." },
Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4071, category: DiagnosticCategory.Error, key: "Parameter '{0}' of public method from exported class has or is using name '{1}' from external module {2} but cannot be named." },
Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4072, category: DiagnosticCategory.Error, key: "Parameter '{0}' of public method from exported class has or is using name '{1}' from private module '{2}'." },
Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: { code: 4073, category: DiagnosticCategory.Error, key: "Parameter '{0}' of public method from exported class has or is using private name '{1}'." },
Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4074, category: DiagnosticCategory.Error, key: "Parameter '{0}' of method from exported interface has or is using name '{1}' from private module '{2}'." },
Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: { code: 4075, category: DiagnosticCategory.Error, key: "Parameter '{0}' of method from exported interface has or is using private name '{1}'." },
Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4076, category: DiagnosticCategory.Error, key: "Parameter '{0}' of exported function has or is using name '{1}' from external module {2} but cannot be named." },
Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2: { code: 4077, category: DiagnosticCategory.Error, key: "Parameter '{0}' of exported function has or is using name '{1}' from private module '{2}'." },
Parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4078, category: DiagnosticCategory.Error, key: "Parameter '{0}' of exported function has or is using private name '{1}'." },
The_current_host_does_not_support_the_0_option: { code: 5001, category: DiagnosticCategory.Error, key: "The current host does not support the '{0}' option." },
Cannot_find_the_common_subdirectory_path_for_the_input_files: { code: 5009, category: DiagnosticCategory.Error, key: "Cannot find the common subdirectory path for the input files." },
Cannot_read_file_0_Colon_1: { code: 5012, category: DiagnosticCategory.Error, key: "Cannot read file '{0}': {1}" },
Unsupported_file_encoding: { code: 5013, category: DiagnosticCategory.NoPrefix, key: "Unsupported file encoding." },
Unsupported_file_encoding: { code: 5013, category: DiagnosticCategory.Error, key: "Unsupported file encoding." },
Unknown_compiler_option_0: { code: 5023, category: DiagnosticCategory.Error, key: "Unknown compiler option '{0}'." },
Could_not_write_file_0_Colon_1: { code: 5033, category: DiagnosticCategory.Error, key: "Could not write file '{0}': {1}" },
Option_mapRoot_cannot_be_specified_without_specifying_sourcemap_option: { code: 5038, category: DiagnosticCategory.Error, key: "Option mapRoot cannot be specified without specifying sourcemap option." },
Option_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option: { code: 5039, category: DiagnosticCategory.Error, key: "Option sourceRoot cannot be specified without specifying sourcemap option." },
@@ -304,13 +349,10 @@ module ts {
Watch_input_files: { code: 6005, category: DiagnosticCategory.Message, key: "Watch input files." },
Redirect_output_structure_to_the_directory: { code: 6006, category: DiagnosticCategory.Message, key: "Redirect output structure to the directory." },
Do_not_emit_comments_to_output: { code: 6009, category: DiagnosticCategory.Message, key: "Do not emit comments to output." },
Skip_resolution_and_preprocessing: { code: 6010, category: DiagnosticCategory.Message, key: "Skip resolution and preprocessing." },
Specify_ECMAScript_target_version_Colon_ES3_default_or_ES5: { code: 6015, category: DiagnosticCategory.Message, key: "Specify ECMAScript target version: 'ES3' (default), or 'ES5'" },
Specify_module_code_generation_Colon_commonjs_or_amd: { code: 6016, category: DiagnosticCategory.Message, key: "Specify module code generation: 'commonjs' or 'amd'" },
Print_this_message: { code: 6017, category: DiagnosticCategory.Message, key: "Print this message." },
Print_the_compiler_s_version: { code: 6019, category: DiagnosticCategory.Message, key: "Print the compiler's version." },
Allow_use_of_deprecated_0_keyword_when_referencing_an_external_module: { code: 6021, category: DiagnosticCategory.Message, key: "Allow use of deprecated '{0}' keyword when referencing an external module." },
Specify_locale_for_errors_and_messages_For_example_0_or_1: { code: 6022, category: DiagnosticCategory.Message, key: "Specify locale for errors and messages. For example '{0}' or '{1}'" },
Syntax_Colon_0: { code: 6023, category: DiagnosticCategory.Message, key: "Syntax: {0}" },
options: { code: 6024, category: DiagnosticCategory.Message, key: "options" },
file: { code: 6025, category: DiagnosticCategory.Message, key: "file" },
@@ -318,29 +360,25 @@ module ts {
Options_Colon: { code: 6027, category: DiagnosticCategory.Message, key: "Options:" },
Version_0: { code: 6029, category: DiagnosticCategory.Message, key: "Version {0}" },
Insert_command_line_options_and_files_from_a_file: { code: 6030, category: DiagnosticCategory.Message, key: "Insert command line options and files from a file." },
Use_the_0_flag_to_see_options: { code: 6031, category: DiagnosticCategory.Message, key: "Use the '{0}' flag to see options." },
File_change_detected_Compiling: { code: 6032, category: DiagnosticCategory.Message, key: "File change detected. Compiling..." },
STRING: { code: 6033, category: DiagnosticCategory.Message, key: "STRING" },
KIND: { code: 6034, category: DiagnosticCategory.Message, key: "KIND" },
FILE: { code: 6035, category: DiagnosticCategory.Message, key: "FILE" },
VERSION: { code: 6036, category: DiagnosticCategory.Message, key: "VERSION" },
LOCATION: { code: 6037, category: DiagnosticCategory.Message, key: "LOCATION" },
DIRECTORY: { code: 6038, category: DiagnosticCategory.Message, key: "DIRECTORY" },
NUMBER: { code: 6039, category: DiagnosticCategory.Message, key: "NUMBER" },
Specify_the_codepage_to_use_when_opening_source_files: { code: 6040, category: DiagnosticCategory.Message, key: "Specify the codepage to use when opening source files." },
Additional_locations_Colon: { code: 6041, category: DiagnosticCategory.Message, key: "Additional locations:" },
Compilation_complete_Watching_for_file_changes: { code: 6042, category: DiagnosticCategory.Message, key: "Compilation complete. Watching for file changes." },
Generates_corresponding_map_file: { code: 6043, category: DiagnosticCategory.Message, key: "Generates corresponding '.map' file." },
Compiler_option_0_expects_an_argument: { code: 6044, category: DiagnosticCategory.Error, key: "Compiler option '{0}' expects an argument." },
Unterminated_quoted_string_in_response_file_0: { code: 6045, category: DiagnosticCategory.Error, key: "Unterminated quoted string in response file '{0}'." },
Argument_for_module_option_must_be_commonjs_or_amd: { code: 6045, category: DiagnosticCategory.Error, key: "Argument for '--module' option must be 'commonjs' or 'amd'." },
Argument_for_target_option_must_be_es3_or_es5: { code: 6046, category: DiagnosticCategory.Error, key: "Argument for '--target' option must be 'es3' or 'es5'." },
Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: { code: 6047, category: DiagnosticCategory.Error, key: "Locale must be of the form <language> or <language>-<territory>. For example '{0}' or '{1}'." },
Unsupported_locale_0: { code: 6048, category: DiagnosticCategory.Error, key: "Unsupported locale '{0}'." },
Unable_to_open_file_0: { code: 6049, category: DiagnosticCategory.Error, key: "Unable to open file '{0}'." },
Corrupted_locale_file_0: { code: 6050, category: DiagnosticCategory.Error, key: "Corrupted locale file {0}." },
No_input_files_specified: { code: 6051, category: DiagnosticCategory.Error, key: "No input files specified." },
Warn_on_expressions_and_declarations_with_an_implied_any_type: { code: 7004, category: DiagnosticCategory.Message, key: "Warn on expressions and declarations with an implied 'any' type." },
Argument_for_module_option_must_be_commonjs_or_amd: { code: 6046, category: DiagnosticCategory.Error, key: "Argument for '--module' option must be 'commonjs' or 'amd'." },
Argument_for_target_option_must_be_es3_or_es5: { code: 6047, category: DiagnosticCategory.Error, key: "Argument for '--target' option must be 'es3' or 'es5'." },
Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: { code: 6048, category: DiagnosticCategory.Error, key: "Locale must be of the form <language> or <language>-<territory>. For example '{0}' or '{1}'." },
Unsupported_locale_0: { code: 6049, category: DiagnosticCategory.Error, key: "Unsupported locale '{0}'." },
Unable_to_open_file_0: { code: 6050, category: DiagnosticCategory.Error, key: "Unable to open file '{0}'." },
Corrupted_locale_file_0: { code: 6051, category: DiagnosticCategory.Error, key: "Corrupted locale file {0}." },
Warn_on_expressions_and_declarations_with_an_implied_any_type: { code: 6052, category: DiagnosticCategory.Message, key: "Warn on expressions and declarations with an implied 'any' type." },
File_0_not_found: { code: 6053, category: DiagnosticCategory.Error, key: "File '{0}' not found." },
File_0_must_have_extension_ts_or_d_ts: { code: 6054, category: DiagnosticCategory.Error, key: "File '{0}' must have extension '.ts' or '.d.ts'." },
Variable_0_implicitly_has_an_1_type: { code: 7005, category: DiagnosticCategory.Error, key: "Variable '{0}' implicitly has an '{1}' type." },
Parameter_0_implicitly_has_an_1_type: { code: 7006, category: DiagnosticCategory.Error, key: "Parameter '{0}' implicitly has an '{1}' type." },
Member_0_implicitly_has_an_1_type: { code: 7008, category: DiagnosticCategory.Error, key: "Member '{0}' implicitly has an '{1}' type." },
@@ -348,83 +386,11 @@ module ts {
_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: { code: 7010, category: DiagnosticCategory.Error, key: "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type." },
Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: { code: 7011, category: DiagnosticCategory.Error, key: "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type." },
Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7013, category: DiagnosticCategory.Error, key: "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type." },
Lambda_function_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: { code: 7014, category: DiagnosticCategory.Error, key: "Lambda function, which lacks return-type annotation, implicitly has an '{0}' return type." },
Array_literal_implicitly_has_an_0_type: { code: 7015, category: DiagnosticCategory.Error, key: "Array literal implicitly has an '{0}' type." },
Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation: { code: 7016, category: DiagnosticCategory.Error, key: "Property '{0}' implicitly has type 'any', because its 'set' accessor lacks a type annotation." },
Index_signature_of_object_type_implicitly_has_an_any_type: { code: 7017, category: DiagnosticCategory.Error, key: "Index signature of object type implicitly has an 'any' type." },
Object_literal_s_property_0_implicitly_has_an_1_type: { code: 7018, category: DiagnosticCategory.Error, key: "Object literal's property '{0}' implicitly has an '{1}' type." },
Rest_parameter_0_implicitly_has_an_any_type: { code: 7019, category: DiagnosticCategory.Error, key: "Rest parameter '{0}' implicitly has an 'any[]' type." },
Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7020, category: DiagnosticCategory.Error, key: "Call signature, which lacks return-type annotation, implicitly has an 'any' return type." },
Variable_declaration_list_cannot_be_empty: { code: -9999999, category: DiagnosticCategory.Error, key: "Variable declaration list cannot be empty." },
Digit_expected: { code: -9999999, category: DiagnosticCategory.Error, key: "Digit expected." },
Hexadecimal_digit_expected: { code: -9999999, category: DiagnosticCategory.Error, key: "Hexadecimal digit expected." },
Unexpected_end_of_text: { code: -9999999, category: DiagnosticCategory.Error, key: "Unexpected end of text." },
Unterminated_string_constant: { code: -9999999, category: DiagnosticCategory.Error, key: "Unterminated string constant." },
Invalid_character: { code: -9999999, category: DiagnosticCategory.Error, key: "Invalid character." },
Declaration_or_statement_expected: { code: -9999999, category: DiagnosticCategory.Error, key: "Declaration or statement expected." },
Statement_expected: { code: -9999999, category: DiagnosticCategory.Error, key: "Statement expected." },
case_or_default_expected: { code: -9999999, category: DiagnosticCategory.Error, key: "'case' or 'default' expected." },
Property_or_signature_expected: { code: -9999999, category: DiagnosticCategory.Error, key: "Property or signature expected." },
Enum_member_expected: { code: -9999999, category: DiagnosticCategory.Error, key: "Enum member expected." },
Type_reference_expected: { code: -9999999, category: DiagnosticCategory.Error, key: "Type reference expected." },
Variable_declaration_expected: { code: -9999999, category: DiagnosticCategory.Error, key: "Variable declaration expected." },
Argument_expression_expected: { code: -9999999, category: DiagnosticCategory.Error, key: "Argument expression expected." },
Property_assignment_expected: { code: -9999999, category: DiagnosticCategory.Error, key: "Property assignment expected." },
Expression_or_comma_expected: { code: -9999999, category: DiagnosticCategory.Error, key: "Expression or comma expected." },
Parameter_declaration_expected: { code: -9999999, category: DiagnosticCategory.Error, key: "Parameter declaration expected." },
Type_parameter_declaration_expected: { code: -9999999, category: DiagnosticCategory.Error, key: "Type parameter declaration expected." },
Type_argument_expected: { code: -9999999, category: DiagnosticCategory.Error, key: "Type argument expected." },
String_literal_expected: { code: -9999999, category: DiagnosticCategory.Error, key: "String literal expected." },
not_preceded_by_parameter_list: { code: -9999999, category: DiagnosticCategory.Error, key: "'=>' not preceded by parameter list." },
Invalid_assignment_target: { code: -9999999, category: DiagnosticCategory.Error, key: "Invalid assignment target." },
super_must_be_followed_by_argument_list_or_member_access: { code: -9999999, category: DiagnosticCategory.Error, key: "'super' must be followed by argument list or member access." },
Line_break_not_permitted_here: { code: -9999999, category: DiagnosticCategory.Error, key: "Line break not permitted here." },
catch_or_finally_expected: { code: -9999999, category: DiagnosticCategory.Error, key: "'catch' or 'finally' expected." },
Block_or_expected: { code: -9999999, category: DiagnosticCategory.Error, key: "Block or ';' expected." },
Modifiers_not_permitted_on_index_signature_members: { code: -9999999, category: DiagnosticCategory.Error, key: "Modifiers not permitted on index signature members." },
Class_member_declaration_expected: { code: -9999999, category: DiagnosticCategory.Error, key: "Class member declaration expected." },
Declaration_expected: { code: -9999999, category: DiagnosticCategory.Error, key: "Declaration expected." },
Invalid_reference_comment: { code: -9999999, category: DiagnosticCategory.Error, key: "Invalid reference comment." },
File_0_is_not_an_external_module: { code: -9999999, category: DiagnosticCategory.Error, key: "File '{0}' is not an external module." },
Excessive_stack_depth_comparing_types_0_and_1: { code: -9999999, category: DiagnosticCategory.Error, key: "Excessive stack depth comparing types '{0}' and '{1}'." },
Type_0_is_not_assignable_to_type_1_Colon: { code: -9999999, category: DiagnosticCategory.Error, key: "Type '{0}' is not assignable to type '{1}':" },
Type_0_is_not_assignable_to_type_1: { code: -9999999, category: DiagnosticCategory.Error, key: "Type '{0}' is not assignable to type '{1}'." },
Property_0_is_missing_in_type_1: { code: -9999999, category: DiagnosticCategory.Error, key: "Property '{0}' is missing in type '{1}'." },
Private_property_0_cannot_be_reimplemented: { code: -9999999, category: DiagnosticCategory.Error, key: "Private property '{0}' cannot be reimplemented." },
Required_property_0_cannot_be_reimplemented_with_optional_property_in_1: { code: 2012, category: DiagnosticCategory.Error, key: "Required property '{0}' cannot be reimplemented with optional property in '{1}'." },
Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: { code: -9999999, category: DiagnosticCategory.Error, key: "Super calls are not permitted outside constructors or in nested functions inside constructors" },
Only_public_methods_of_the_base_class_are_accessible_via_the_super_keyword: { code: -9999999, category: DiagnosticCategory.Error, key: "Only public methods of the base class are accessible via the 'super' keyword" },
A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: { code: -9999999, category: DiagnosticCategory.Error, key: "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties." },
Constructors_for_derived_classes_must_contain_a_super_call: { code: -9999999, category: DiagnosticCategory.Error, key: "Constructors for derived classes must contain a 'super' call." },
Import_name_cannot_be_0: { code: -9999999, category: DiagnosticCategory.Error, key: "Import name cannot be '{0}'" },
Type_parameter_name_cannot_be_0: { code: -9999999, category: DiagnosticCategory.Error, key: "Type parameter name cannot be '{0}'" },
Class_name_cannot_be_0: { code: -9999999, category: DiagnosticCategory.Error, key: "Class name cannot be '{0}'" },
Interface_name_cannot_be_0: { code: -9999999, category: DiagnosticCategory.Error, key: "Interface name cannot be '{0}'" },
Enum_name_cannot_be_0: { code: -9999999, category: DiagnosticCategory.Error, key: "Enum name cannot be '{0}'" },
Types_of_property_0_are_incompatible_Colon: { code: -9999999, category: DiagnosticCategory.Error, key: "Types of property '{0}' are incompatible:" },
Types_of_parameters_0_and_1_are_incompatible_Colon: { code: -9999999, category: DiagnosticCategory.Error, key: "Types of parameters '{0}' and '{1}' are incompatible:" },
Unknown_identifier_0: { code: -9999999, category: DiagnosticCategory.Error, key: "Unknown identifier '{0}'." },
Property_0_is_inaccessible: { code: -9999999, category: DiagnosticCategory.Error, key: "Property '{0}' is inaccessible." },
Function_implementation_is_missing_or_not_immediately_following_the_declaration: { code: -9999999, category: DiagnosticCategory.Error, key: "Function implementation is missing or not immediately following the declaration." },
Property_0_of_type_1_is_not_assignable_to_string_index_type_2: { code: -9999999, category: DiagnosticCategory.Error, key: "Property '{0}' of type '{1}' is not assignable to string index type '{2}'." },
Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: { code: -9999999, category: DiagnosticCategory.Error, key: "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'." },
Numeric_index_type_0_is_not_assignable_to_string_index_type_1: { code: -9999999, category: DiagnosticCategory.Error, key: "Numeric index type '{0}' is not assignable to string index type '{1}'." },
Class_0_incorrectly_extends_base_class_1_Colon: { code: -9999999, category: DiagnosticCategory.Error, key: "Class '{0}' incorrectly extends base class '{1}':" },
Class_0_incorrectly_extends_base_class_1: { code: -9999999, category: DiagnosticCategory.Error, key: "Class '{0}' incorrectly extends base class '{1}'." },
Class_static_side_0_incorrectly_extends_base_class_static_side_1_Colon: { code: -9999999, category: DiagnosticCategory.Error, key: "Class static side '{0}' incorrectly extends base class static side '{1}':" },
Class_static_side_0_incorrectly_extends_base_class_static_side_1: { code: -9999999, category: DiagnosticCategory.Error, key: "Class static side '{0}' incorrectly extends base class static side '{1}'." },
Type_name_0_in_extends_clause_does_not_reference_constructor_function_for_0: { code: -9999999, category: DiagnosticCategory.Error, key: "Type name '{0}' in extends clause does not reference constructor function for '{0}'." },
Class_0_incorrectly_implements_interface_1_Colon: { code: -9999999, category: DiagnosticCategory.Error, key: "Class '{0}' incorrectly implements interface '{1}':" },
Class_0_incorrectly_implements_interface_1: { code: -9999999, category: DiagnosticCategory.Error, key: "Class '{0}' incorrectly implements interface '{1}'." },
Interface_0_incorrectly_extends_interface_1_Colon: { code: -9999999, category: DiagnosticCategory.Error, key: "Interface '{0}' incorrectly extends interface '{1}':" },
Interface_0_incorrectly_extends_interface_1: { code: -9999999, category: DiagnosticCategory.Error, key: "Interface '{0}' incorrectly extends interface '{1}'." },
Ambient_external_modules_cannot_be_nested_in_other_modules: { code: -9999999, category: DiagnosticCategory.Error, key: "Ambient external modules cannot be nested in other modules." },
Import_declarations_in_an_internal_module_cannot_reference_an_external_module: { code: -9999999, category: DiagnosticCategory.Error, key: "Import declarations in an internal module cannot reference an external module." },
A_module_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged: { code: -9999999, category: DiagnosticCategory.Error, key: "A module declaration cannot be in a different file from a class or function with which it is merged" },
A_module_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged: { code: -9999999, category: DiagnosticCategory.Error, key: "A module declaration cannot be located prior to a class or function with which it is merged" },
Cannot_compile_external_modules_unless_the_module_flag_is_provided: { code: -9999999, category: DiagnosticCategory.Error, key: "Cannot compile external modules unless the '--module' flag is provided." },
Import_declaration_conflicts_with_local_declaration_of_0: { code: -9999999, category: DiagnosticCategory.Error, key: "Import declaration conflicts with local declaration of '{0}'" },
Module_0_is_hidden_by_a_local_declaration_with_the_same_name: { code: -9999999, category: DiagnosticCategory.Error, key: "Module '{0}' is hidden by a local declaration with the same name" },
Filename_0_differs_from_already_included_filename_1_only_in_casing: { code: -9999999, category: DiagnosticCategory.Error, key: "Filename '{0}' differs from already included filename '{1}' only in casing" },
You_cannot_rename_this_element: { code: 8000, category: DiagnosticCategory.Error, key: "You cannot rename this element." },
};
}
File diff suppressed because it is too large Load Diff
+523 -92
View File
File diff suppressed because it is too large Load Diff
+122 -43
View File
@@ -1,4 +1,3 @@
/// <reference path="sys.ts"/>
/// <reference path="types.ts"/>
/// <reference path="core.ts"/>
/// <reference path="scanner.ts"/>
@@ -9,7 +8,7 @@ module ts {
export function getNodeConstructor(kind: SyntaxKind): new () => Node {
return nodeConstructors[kind] || (nodeConstructors[kind] = objectAllocator.getNodeConstructor(kind));
}
function createRootNode(kind: SyntaxKind, pos: number, end: number, flags: NodeFlags): Node {
var node = new (getNodeConstructor(kind))();
node.pos = pos;
@@ -139,6 +138,34 @@ module ts {
return (<Identifier>(<ExpressionStatement>node).expression).text === "use strict";
}
export function getLeadingCommentsOfNode(node: Node, sourceFileOfNode: SourceFile) {
// If parameter/type parameter, the prev token trailing comments are part of this node too
if (node.kind === SyntaxKind.Parameter || node.kind === SyntaxKind.TypeParameter) {
// eg (/** blah */ a, /** blah */ b);
return concatenate(getTrailingComments(sourceFileOfNode.text, node.pos),
// eg: (
// /** blah */ a,
// /** blah */ b);
getLeadingComments(sourceFileOfNode.text, node.pos));
}
else {
return getLeadingComments(sourceFileOfNode.text, node.pos);
}
}
export function getJsDocComments(node: Declaration, sourceFileOfNode: SourceFile) {
return filter(getLeadingCommentsOfNode(node, sourceFileOfNode), comment => isJsDocComment(comment));
function isJsDocComment(comment: Comment) {
// js doc is if comment is starting with /** but not if it is /**/
return sourceFileOfNode.text.charCodeAt(comment.pos + 1) === CharacterCodes.asterisk &&
sourceFileOfNode.text.charCodeAt(comment.pos + 2) === CharacterCodes.asterisk &&
sourceFileOfNode.text.charCodeAt(comment.pos + 3) !== CharacterCodes.slash;
}
}
export var fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*<reference\s+path\s*=\s*)('|")(.+?)\2.*?\/>/
// Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
// stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise,
// embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns
@@ -337,6 +364,46 @@ module ts {
return false;
}
export function isDeclaration(node: Node): boolean {
switch (node.kind) {
case SyntaxKind.TypeParameter:
case SyntaxKind.Parameter:
case SyntaxKind.VariableDeclaration:
case SyntaxKind.Property:
case SyntaxKind.PropertyAssignment:
case SyntaxKind.EnumMember:
case SyntaxKind.Method:
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.ModuleDeclaration:
case SyntaxKind.ImportDeclaration:
return true;
}
return false;
}
// True if the given identifier, string literal, or number literal is the name of a declaration node
export function isDeclarationOrFunctionExpressionOrCatchVariableName(name: Node): boolean {
if (name.kind !== SyntaxKind.Identifier && name.kind !== SyntaxKind.StringLiteral && name.kind !== SyntaxKind.NumericLiteral) {
return false;
}
var parent = name.parent;
if (isDeclaration(parent) || parent.kind === SyntaxKind.FunctionExpression) {
return (<Declaration>parent).name === name;
}
if (parent.kind === SyntaxKind.CatchBlock) {
return (<CatchBlock>parent).variable === name;
}
return false;
}
enum ParsingContext {
SourceElements, // Elements in source file
ModuleElements, // Elements in module declaration
@@ -421,7 +488,23 @@ module ts {
nodeIsNestedInLabel(label: Identifier, requireIterationStatement: boolean, stopAtFunctionBoundary: boolean): ControlBlockContext;
}
export function createSourceFile(filename: string, sourceText: string, languageVersion: ScriptTarget, version: number = 0, isOpen: boolean = false): SourceFile {
export function isKeyword(token: SyntaxKind): boolean {
return SyntaxKind.FirstKeyword <= token && token <= SyntaxKind.LastKeyword;
}
export function isModifier(token: SyntaxKind): boolean {
switch (token) {
case SyntaxKind.PublicKeyword:
case SyntaxKind.PrivateKeyword:
case SyntaxKind.StaticKeyword:
case SyntaxKind.ExportKeyword:
case SyntaxKind.DeclareKeyword:
return true;
}
return false;
}
export function createSourceFile(filename: string, sourceText: string, languageVersion: ScriptTarget, version: string, isOpen: boolean = false): SourceFile {
var file: SourceFile;
var scanner: Scanner;
var token: SyntaxKind;
@@ -550,6 +633,13 @@ module ts {
return getLineAndCharacterOfPosition(lineStarts, position);
}
function getPositionFromSourceLineAndCharacter(line: number, character: number): number {
if (!lineStarts) {
lineStarts = getLineStarts(sourceText);
}
return getPositionFromLineAndCharacter(lineStarts, line, character);
}
function error(message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): void {
var start = scanner.getTokenPos();
var length = scanner.getTextPos() - start;
@@ -745,6 +835,10 @@ module ts {
return createNode(SyntaxKind.Missing);
}
function internIdentifier(text: string): string {
return hasProperty(identifiers, text) ? identifiers[text] : (identifiers[text] = text);
}
// An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues
// with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for
// each identifier in order to reduce memory consumption.
@@ -753,7 +847,7 @@ module ts {
if (isIdentifier) {
var node = <Identifier>createNode(SyntaxKind.Identifier);
var text = escapeIdentifier(scanner.getTokenValue());
node.text = hasProperty(identifiers, text) ? identifiers[text] : (identifiers[text] = text);
node.text = internIdentifier(text);
nextToken();
return finishNode(node);
}
@@ -775,28 +869,11 @@ module ts {
function parsePropertyName(): Identifier {
if (token === SyntaxKind.StringLiteral || token === SyntaxKind.NumericLiteral) {
return <LiteralExpression>parsePrimaryExpression();
return parseLiteralNode(/*internName:*/ true);
}
return parseIdentifierName();
}
function isKeyword(token: SyntaxKind): boolean {
return SyntaxKind.FirstKeyword <= token && token <= SyntaxKind.LastKeyword;
}
function isModifier(token: SyntaxKind): boolean {
switch (token) {
case SyntaxKind.PublicKeyword:
case SyntaxKind.PrivateKeyword:
case SyntaxKind.StaticKeyword:
case SyntaxKind.ExportKeyword:
case SyntaxKind.DeclareKeyword:
return true;
}
return false;
}
function parseContextualModifier(t: SyntaxKind): boolean {
return token === t && tryParse(() => {
nextToken();
@@ -1058,9 +1135,11 @@ module ts {
return finishNode(node);
}
function parseLiteralNode(): LiteralExpression {
function parseLiteralNode(internName?:boolean): LiteralExpression {
var node = <LiteralExpression>createNode(token);
node.text = scanner.getTokenValue();
var text = scanner.getTokenValue();
node.text = internName ? internIdentifier(text) : text;
var tokenPos = scanner.getTokenPos();
nextToken();
finishNode(node);
@@ -1087,7 +1166,7 @@ module ts {
}
function parseStringLiteral(): LiteralExpression {
if (token === SyntaxKind.StringLiteral) return parseLiteralNode();
if (token === SyntaxKind.StringLiteral) return parseLiteralNode(/*internName:*/ true);
error(Diagnostics.String_literal_expected);
return <LiteralExpression>createMissingNode();
}
@@ -1944,7 +2023,7 @@ module ts {
primaryExpression.kind === SyntaxKind.SuperKeyword && token !== SyntaxKind.OpenParenToken && token !== SyntaxKind.DotToken;
if (illegalUsageOfSuperKeyword) {
error(Diagnostics.super_must_be_followed_by_argument_list_or_member_access);
error(Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access);
}
var expr = parseCallAndAccess(primaryExpression, /* inNewExpression */ false);
@@ -1997,15 +2076,18 @@ module ts {
var indexedAccess = <IndexedAccess>createNode(SyntaxKind.IndexedAccess, expr.pos);
indexedAccess.object = expr;
// It's not uncommon for a user to write: "new Type[]". Check for that common pattern
// and report a better error message.
// It's not uncommon for a user to write: "new Type[]".
// Check for that common pattern and report a better error message.
if (inNewExpression && parseOptional(SyntaxKind.CloseBracketToken)) {
indexedAccess.index = createMissingNode();
grammarErrorAtPos(bracketStart, scanner.getStartPos() - bracketStart, Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead);
}
// Otherwise parse the indexed access normally.
else {
indexedAccess.index = parseExpression();
if (indexedAccess.index.kind === SyntaxKind.StringLiteral || indexedAccess.index.kind === SyntaxKind.NumericLiteral) {
var literal = <LiteralExpression>indexedAccess.index;
literal.text = internIdentifier(literal.text);
}
parseExpected(SyntaxKind.CloseBracketToken);
}
@@ -2393,8 +2475,6 @@ module ts {
function parseBreakOrContinueStatement(kind: SyntaxKind): BreakOrContinueStatement {
var node = <BreakOrContinueStatement>createNode(kind);
var errorCountBeforeStatement = file.syntacticErrors.length;
var keywordStart = scanner.getTokenPos();
var keywordLength = scanner.getTextPos() - keywordStart;
parseExpected(kind === SyntaxKind.BreakStatement ? SyntaxKind.BreakKeyword : SyntaxKind.ContinueKeyword);
if (!canParseSemicolon()) node.label = parseIdentifier();
parseSemicolon();
@@ -3496,12 +3576,11 @@ module ts {
file.hasNoDefaultLib = true;
}
else {
var fullReferenceRegEx = /^(\/\/\/\s*<reference\s+path\s*=\s*)('|")(.+?)\2.*?\/>/;
var matchResult = fullReferenceRegEx.exec(comment);
var matchResult = fullTripleSlashReferencePathRegEx.exec(comment);
if (!matchResult) {
var start = range.pos;
var length = range.end - start;
errorAtPos(start, length, Diagnostics.Invalid_reference_comment);
errorAtPos(start, length, Diagnostics.Invalid_reference_directive_syntax);
}
else {
referencedFiles.push({
@@ -3546,6 +3625,7 @@ module ts {
file.filename = normalizePath(filename);
file.text = sourceText;
file.getLineAndCharacterFromPosition = getLineAndCharacterlFromSourcePosition;
file.getPositionFromLineAndCharacter = getPositionFromSourceLineAndCharacter;
file.syntacticErrors = [];
file.semanticErrors = [];
var referenceComments = processReferenceComments();
@@ -3558,6 +3638,7 @@ module ts {
file.version = version;
file.isOpen = isOpen;
file.languageVersion = languageVersion;
file.identifiers = identifiers;
return file;
}
@@ -3630,23 +3711,22 @@ module ts {
// Get source file from normalized filename
function findSourceFile(filename: string, isDefaultLib: boolean, refFile?: SourceFile, refStart?: number, refLength?: number): SourceFile {
// Look through existing source files to see if we've encountered it.
var canonicalName = host.getCanonicalFileName(filename);
var file = getSourceFile(filename);
if (file) {
if (host.useCaseSensitiveFileNames() && canonicalName !== file.filename) {
if (hasProperty(filesByName, canonicalName)) {
// We've already looked for this file, use cached result
var file = filesByName[canonicalName];
if (file && host.useCaseSensitiveFileNames() && canonicalName !== file.filename) {
errors.push(createFileDiagnostic(refFile, refStart, refLength,
Diagnostics.Filename_0_differs_from_already_included_filename_1_only_in_casing, filename, file.filename));
}
}
}
else {
// If we haven't, read the file.
file = host.getSourceFile(filename, options.target, hostErrorMessage => {
// We haven't looked for this file, do so now and cache result
var file = filesByName[canonicalName] = host.getSourceFile(filename, options.target, hostErrorMessage => {
errors.push(createFileDiagnostic(refFile, refStart, refLength,
Diagnostics.Cannot_read_file_0_Colon_1, filename, hostErrorMessage));
});
if (file) {
filesByName[host.getCanonicalFileName(filename)] = file;
seenNoDefaultLib = seenNoDefaultLib || file.hasNoDefaultLib;
if (!options.noResolve) {
var basePath = getDirectoryPath(filename);
@@ -3664,7 +3744,6 @@ module ts {
});
}
}
return file;
}
+44 -14
View File
@@ -249,7 +249,8 @@ module ts {
var pos = 0;
var lineStart = 0;
while (pos < text.length) {
switch (text.charCodeAt(pos++)) {
var ch = text.charCodeAt(pos++);
switch (ch) {
case CharacterCodes.carriageReturn:
if (text.charCodeAt(pos) === CharacterCodes.lineFeed) {
pos++;
@@ -258,12 +259,23 @@ module ts {
result.push(lineStart);
lineStart = pos;
break;
default:
if (ch > CharacterCodes.maxAsciiCharacter && isLineBreak(ch)) {
result.push(lineStart);
lineStart = pos;
}
break;
}
}
result.push(lineStart);
return result;
}
export function getPositionFromLineAndCharacter(lineStarts: number[], line: number, character: number): number {
Debug.assert(line > 0);
return lineStarts[line - 1] + character - 1;
}
export function getLineAndCharacterOfPosition(lineStarts: number[], position: number) {
var lineNumber = binarySearch(lineStarts, position);
if (lineNumber < 0) {
@@ -286,14 +298,14 @@ module ts {
var hasOwnProperty = Object.prototype.hasOwnProperty;
function isWhiteSpace(ch: number): boolean {
export function isWhiteSpace(ch: number): boolean {
return ch === CharacterCodes.space || ch === CharacterCodes.tab || ch === CharacterCodes.verticalTab || ch === CharacterCodes.formFeed ||
ch === CharacterCodes.nonBreakingSpace || ch === CharacterCodes.ogham || ch >= CharacterCodes.enQuad && ch <= CharacterCodes.zeroWidthSpace ||
ch === CharacterCodes.narrowNoBreakSpace || ch === CharacterCodes.mathematicalSpace || ch === CharacterCodes.ideographicSpace || ch === CharacterCodes.byteOrderMark;
}
function isLineBreak(ch: number): boolean {
return ch === CharacterCodes.lineFeed || ch === CharacterCodes.carriageReturn || ch === CharacterCodes.lineSeparator || ch === CharacterCodes.paragraphSeparator;
export function isLineBreak(ch: number): boolean {
return ch === CharacterCodes.lineFeed || ch === CharacterCodes.carriageReturn || ch === CharacterCodes.lineSeparator || ch === CharacterCodes.paragraphSeparator || ch === CharacterCodes.nextLine;
}
function isDigit(ch: number): boolean {
@@ -359,9 +371,9 @@ module ts {
// between the given position and the next line break are returned. The return value is an array containing a TextRange for each
// comment. Single-line comment ranges include the the beginning '//' characters but not the ending line break. Multi-line comment
// ranges include the beginning '/* and ending '*/' characters. The return value is undefined if no comments were found.
function getCommentRanges(text: string, pos: number, trailing: boolean): TextRange[] {
var result: TextRange[];
var collecting = trailing;
function getCommentRanges(text: string, pos: number, trailing: boolean): Comment[] {
var result: Comment[];
var collecting = trailing || pos === 0;
while (true) {
var ch = text.charCodeAt(pos);
switch (ch) {
@@ -373,6 +385,9 @@ module ts {
return result;
}
collecting = true;
if (result && result.length) {
result[result.length - 1].hasTrailingNewLine = true;
}
continue;
case CharacterCodes.tab:
case CharacterCodes.verticalTab:
@@ -382,12 +397,14 @@ module ts {
continue;
case CharacterCodes.slash:
var nextChar = text.charCodeAt(pos + 1);
var hasTrailingNewLine = false;
if (nextChar === CharacterCodes.slash || nextChar === CharacterCodes.asterisk) {
var startPos = pos;
pos += 2;
if (nextChar === CharacterCodes.slash) {
while (pos < text.length) {
if (isLineBreak(text.charCodeAt(pos))) {
hasTrailingNewLine = true;
break;
}
pos++;
@@ -404,13 +421,16 @@ module ts {
}
if (collecting) {
if (!result) result = [];
result.push({ pos: startPos, end: pos });
result.push({ pos: startPos, end: pos, hasTrailingNewLine: hasTrailingNewLine });
}
continue;
}
break;
default:
if (ch > CharacterCodes.maxAsciiCharacter && (isWhiteSpace(ch) || isLineBreak(ch))) {
if (result && result.length && isLineBreak(ch)) {
result[result.length - 1].hasTrailingNewLine = true;
}
pos++;
continue;
}
@@ -420,14 +440,26 @@ module ts {
}
}
export function getLeadingComments(text: string, pos: number): TextRange[] {
export function getLeadingComments(text: string, pos: number): Comment[] {
return getCommentRanges(text, pos, /*trailing*/ false);
}
export function getTrailingComments(text: string, pos: number): TextRange[] {
export function getTrailingComments(text: string, pos: number): Comment[] {
return getCommentRanges(text, pos, /*trailing*/ true);
}
export function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean {
return ch >= CharacterCodes.A && ch <= CharacterCodes.Z || ch >= CharacterCodes.a && ch <= CharacterCodes.z ||
ch === CharacterCodes.$ || ch === CharacterCodes._ ||
ch > CharacterCodes.maxAsciiCharacter && isUnicodeIdentifierStart(ch, languageVersion);
}
export function isIdentifierPart(ch: number, languageVersion: ScriptTarget): boolean {
return ch >= CharacterCodes.A && ch <= CharacterCodes.Z || ch >= CharacterCodes.a && ch <= CharacterCodes.z ||
ch >= CharacterCodes._0 && ch <= CharacterCodes._9 || ch === CharacterCodes.$ || ch === CharacterCodes._ ||
ch > CharacterCodes.maxAsciiCharacter && isUnicodeIdentifierPart(ch, languageVersion);
}
export function createScanner(languageVersion: ScriptTarget, text?: string, onError?: ErrorCallback, onComment?: CommentCallback): Scanner {
var pos: number; // Current position (end position of text of current token)
var len: number; // Length of text
@@ -589,7 +621,7 @@ module ts {
}
if (isLineBreak(ch)) {
result += text.substring(start, pos);
error(Diagnostics.Unterminated_string_constant);
error(Diagnostics.Unterminated_string_literal);
break;
}
pos++;
@@ -750,9 +782,8 @@ module ts {
if (text.charCodeAt(pos + 1) === CharacterCodes.asterisk) {
pos += 2;
var safeLength = len - 1; // For lookahead.
var commentClosed = false;
while (pos < safeLength) {
while (pos < len) {
var ch = text.charCodeAt(pos);
if (ch === CharacterCodes.asterisk && text.charCodeAt(pos + 1) === CharacterCodes.slash) {
@@ -768,7 +799,6 @@ module ts {
}
if (!commentClosed) {
pos++;
error(Diagnostics.Asterisk_Slash_expected);
}
+19 -7
View File
@@ -38,7 +38,7 @@ module ts {
}
function trySetLanguageAndTerritory(language: string, territory: string, errors: Diagnostic[]): boolean {
var compilerFilePath = sys.getExecutingFilePath();
var compilerFilePath = normalizePath(sys.getExecutingFilePath());
var containingDirectoryPath = getDirectoryPath(compilerFilePath);
var filePath = combinePaths(containingDirectoryPath, language);
@@ -62,7 +62,7 @@ module ts {
return false;
}
try {
localizedDiagnosticMessages = JSON.parse(fileContents);
ts.localizedDiagnosticMessages = JSON.parse(fileContents);
}
catch (e) {
errors.push(createCompilerDiagnostic(Diagnostics.Corrupted_locale_file_0, filePath));
@@ -86,13 +86,18 @@ module ts {
}
function reportDiagnostic(diagnostic: Diagnostic) {
var output = "";
if (diagnostic.file) {
var loc = diagnostic.file.getLineAndCharacterFromPosition(diagnostic.start);
sys.write(diagnostic.file.filename + "(" + loc.line + "," + loc.character + "): " + diagnostic.messageText + sys.newLine);
}
else {
sys.write(diagnostic.messageText + sys.newLine);
output += diagnostic.file.filename + "(" + loc.line + "," + loc.character + "): ";
}
var category = DiagnosticCategory[diagnostic.category].toLowerCase();
output += category + " TS" + diagnostic.code + ": " + diagnostic.messageText + sys.newLine;
sys.write(output);
}
function reportDiagnostics(diagnostics: Diagnostic[]) {
@@ -132,6 +137,12 @@ module ts {
var currentDirectory: string;
var existingDirectories: Map<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.
// otherwise use toLowerCase as a canonical form.
return sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
}
function getSourceFile(filename: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile {
try {
var text = sys.readFile(filename, options.charset);
@@ -142,7 +153,7 @@ module ts {
}
text = "";
}
return text !== undefined ? createSourceFile(filename, text, languageVersion) : undefined;
return text !== undefined ? createSourceFile(filename, text, languageVersion, /*version:*/ "0") : undefined;
}
function writeFile(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void) {
@@ -318,6 +329,7 @@ module ts {
function compile(commandLine: ParsedCommandLine, compilerHost: CompilerHost) {
var parseStart = new Date().getTime();
var program = createProgram(commandLine.filenames, commandLine.options, compilerHost);
var bindStart = new Date().getTime();
var errors = program.getDiagnostics();
if (errors.length) {
+16 -10
View File
@@ -218,7 +218,11 @@ module ts {
FirstKeyword = BreakKeyword,
LastKeyword = StringKeyword,
FirstFutureReservedWord = ImplementsKeyword,
LastFutureReservedWord = YieldKeyword
LastFutureReservedWord = YieldKeyword,
FirstTypeNode = TypeReference,
LastTypeNode = ArrayType,
FirstPunctuation= OpenBraceToken,
LastPunctuation = CaretEqualsToken
}
export enum NodeFlags {
@@ -517,10 +521,15 @@ module ts {
filename: string;
}
export interface Comment extends TextRange {
hasTrailingNewLine?: boolean;
}
export interface SourceFile extends Block {
filename: string;
text: string;
getLineAndCharacterFromPosition(position: number): { line: number; character: number };
getPositionFromLineAndCharacter(line: number, character: number): number;
amdDependencies: string[];
referencedFiles: FileReference[];
syntacticErrors: Diagnostic[];
@@ -531,8 +540,9 @@ module ts {
identifierCount: number;
symbolCount: number;
isOpen: boolean;
version: number;
version: string;
languageVersion: ScriptTarget;
identifiers: Map<string>;
}
export interface Program {
@@ -598,22 +608,22 @@ module ts {
getTypeCount(): number;
checkProgram(): void;
emitFiles(): EmitResult;
getSymbolOfNode(node: Node): Symbol;
getParentOfSymbol(symbol: Symbol): Symbol;
getTypeOfSymbol(symbol: Symbol): Type;
getDeclaredTypeOfSymbol(symbol: Symbol): Type;
getPropertiesOfType(type: Type): Symbol[];
getPropertyOfType(type: Type, propetyName: string): Symbol;
getSignaturesOfType(type: Type, kind: SignatureKind): Signature[];
getIndexTypeOfType(type: Type, kind: IndexKind): Type;
getReturnTypeOfSignature(signature: Signature): Type;
resolveEntityName(location: Node, name: EntityName, meaning: SymbolFlags): Symbol;
getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[];
getSymbolInfo(node: Node): Symbol;
getTypeOfExpression(node: Expression, contextualType?: Type, contextualMapper?: TypeMapper): Type;
getTypeOfNode(node: Node): Type;
getApparentType(type: Type): ApparentType;
typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string;
symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string;
getAugmentedPropertiesOfApparentType(type: Type): Symbol[];
getRootSymbol(symbol: Symbol): Symbol;
getContextualType(node: Node): Type;
}
export interface TextWriter {
@@ -946,7 +956,6 @@ module ts {
Warning,
Error,
Message,
NoPrefix
}
export interface CompilerOptions {
@@ -1009,9 +1018,6 @@ module ts {
carriageReturn = 0x0D, // \r
lineSeparator = 0x2028,
paragraphSeparator = 0x2029,
// REVIEW: do we need to support this? The scanner doesn't, but our IText does. This seems
// like an odd disparity? (Or maybe it's completely fine for them to be different).
nextLine = 0x0085,
// Unicode 3.0 space characters
+78 -57
View File
@@ -39,19 +39,21 @@ class CompilerBaselineRunner extends RunnerBase {
public checkTestCodeOutput(fileName: string) {
describe('compiler tests for ' + fileName, () => {
// strips the fileName from the path.
var justName = fileName.replace(/^.*[\\\/]/, '');
var content = Harness.IO.readFile(fileName);
var testCaseContent = Harness.TestCaseParser.makeUnitsFromTest(content, fileName);
// Mocha holds onto the closure environment of the describe callback even after the test is done.
// Everything declared here should be cleared out in the "after" callback.
var justName: string;
var content: string;
var testCaseContent: { settings: Harness.TestCaseParser.CompilerSetting[]; testUnitData: Harness.TestCaseParser.TestUnitData[]; }
var units = testCaseContent.testUnitData;
var tcSettings = testCaseContent.settings;
var createNewInstance = false;
var units: Harness.TestCaseParser.TestUnitData[];
var tcSettings: Harness.TestCaseParser.CompilerSetting[];
var createNewInstance: boolean;
var lastUnit = units[units.length - 1];
var rootDir = lastUnit.originalFilePath.indexOf('conformance') === -1 ? 'tests/cases/compiler/' : lastUnit.originalFilePath.substring(0, lastUnit.originalFilePath.lastIndexOf('/')) + '/';
var lastUnit: Harness.TestCaseParser.TestUnitData;
var rootDir: string;
var result: Harness.Compiler.CompilerResult;
var checker: ts.TypeChecker;
var options: ts.CompilerOptions;
// equivalent to the files that will be passed on the command line
var toBeCompiled: { unitName: string; content: string }[];
@@ -66,6 +68,14 @@ class CompilerBaselineRunner extends RunnerBase {
var createNewInstance = false;
before(() => {
justName = fileName.replace(/^.*[\\\/]/, ''); // strips the fileName from the path.
content = Harness.IO.readFile(fileName);
testCaseContent = Harness.TestCaseParser.makeUnitsFromTest(content, fileName);
units = testCaseContent.testUnitData;
tcSettings = testCaseContent.settings;
createNewInstance = false;
lastUnit = units[units.length - 1];
rootDir = lastUnit.originalFilePath.indexOf('conformance') === -1 ? 'tests/cases/compiler/' : lastUnit.originalFilePath.substring(0, lastUnit.originalFilePath.lastIndexOf('/')) + '/';
harnessCompiler = Harness.Compiler.getCompiler();
// We need to assemble the list of input files for the compiler and other related files on the 'filesystem' (ie in a multi-file test)
// If the last file in a test uses require or a triple slash reference we'll assume all other files will be brought in via references,
@@ -85,8 +95,10 @@ class CompilerBaselineRunner extends RunnerBase {
});
}
options = harnessCompiler.compileFiles(toBeCompiled, otherFiles, function (compileResult) {
options = harnessCompiler.compileFiles(toBeCompiled, otherFiles, function (compileResult, _checker) {
result = compileResult;
// The checker will be used by typeWriter
checker = _checker;
}, function (settings) {
harnessCompiler.setCompilerSettings(tcSettings);
});
@@ -97,6 +109,7 @@ class CompilerBaselineRunner extends RunnerBase {
a fresh compiler instance for themselves and then create a fresh one for the next test. Would be nice to get dev fixes
eventually to remove this limitation. */
for (var i = 0; i < tcSettings.length; ++i) {
// noImplicitAny is passed to getCompiler, but target is just passed in the settings blob to setCompilerSettings
if (!createNewInstance && (tcSettings[i].flag == "noimplicitany" || tcSettings[i].flag === 'target')) {
harnessCompiler = Harness.Compiler.getCompiler({
useExistingInstance: false,
@@ -118,6 +131,27 @@ class CompilerBaselineRunner extends RunnerBase {
}
});
after(() => {
// Mocha holds onto the closure environment of the describe callback even after the test is done.
// Therefore we have to clean out large objects after the test is done.
justName = undefined;
content = undefined;
testCaseContent = undefined;
units = undefined;
tcSettings = undefined;
lastUnit = undefined;
rootDir = undefined;
result = undefined;
checker = undefined;
options = undefined;
toBeCompiled = undefined;
otherFiles = undefined;
harnessCompiler = undefined;
declToBeCompiled = undefined;
declOtherFiles = undefined;
declResult = undefined;
});
function getByteOrderMarkText(file: Harness.Compiler.GeneratedFile): string {
return file.writeByteOrderMark ? "\u00EF\u00BB\u00BF" : "";
}
@@ -157,19 +191,40 @@ class CompilerBaselineRunner extends RunnerBase {
// if the .d.ts is non-empty, confirm it compiles correctly as well
if (options.declaration && result.errors.length === 0 && result.declFilesCode.length > 0) {
function getDtsFile(file: { unitName: string; content: string }) {
function addDtsFile(file: { unitName: string; content: string }, dtsFiles: { unitName: string; content: string }[]) {
if (Harness.Compiler.isDTS(file.unitName)) {
return file;
} else {
var declFile = ts.forEach(result.declFilesCode,
declFile => declFile.fileName === (file.unitName.substr(0, file.unitName.length - ".ts".length) + ".d.ts")
dtsFiles.push(file);
}
else {
var declFile = findResultCodeFile(file.unitName);
// Look if there is --out file corresponding to this ts file
if (!declFile && options.out) {
declFile = findResultCodeFile(options.out);
if (!declFile || findUnit(declFile.fileName, declToBeCompiled) ||
findUnit(declFile.fileName, declOtherFiles)) {
return;
}
}
if (declFile) {
dtsFiles.push({ unitName: declFile.fileName, content: declFile.code });
return;
}
}
function findResultCodeFile(fileName: string) {
return ts.forEach(result.declFilesCode,
declFile => declFile.fileName === (fileName.substr(0, fileName.length - ".ts".length) + ".d.ts")
? declFile : undefined);
return { unitName: declFile.fileName, content: declFile.code };
}
function findUnit(fileName: string, units: { unitName: string; content: string }[]) {
return ts.forEach(units, unit => unit.unitName === fileName ? unit : undefined);
}
}
ts.forEach(toBeCompiled, file => { declToBeCompiled.push(getDtsFile(file)); });
ts.forEach(otherFiles, file => { declOtherFiles.push(getDtsFile(file)); });
ts.forEach(toBeCompiled, file => addDtsFile(file, declToBeCompiled));
ts.forEach(otherFiles, file => addDtsFile(file, declOtherFiles));
harnessCompiler.compileFiles(declToBeCompiled, declOtherFiles, function (compileResult) {
declResult = compileResult;
}, function (settings) {
@@ -251,33 +306,16 @@ class CompilerBaselineRunner extends RunnerBase {
it('Correct type baselines for ' + fileName, () => {
// NEWTODO: Type baselines
if (/* ! */ false && /* ! */ result.errors.length === 0) {
if (result.errors.length === 0) {
Harness.Baseline.runBaseline('Correct expression types for ' + fileName, justName.replace(/\.ts/, '.types'), () => {
// TODO: Rewrite this part
//var compiler = new TypeScript.TypeScriptCompiler(
// new TypeScript.NullLogger(), TypeScript.ImmutableCompilationSettings.defaultSettings());
//compiler.addFile('lib.d.ts', TypeScript.ScriptSnapshot.fromString(Harness.Compiler.libTextMinimal),
// TypeScript.ByteOrderMark.None, /*version:*/ "0", /*isOpen:*/ true);
//var allFiles = toBeCompiled.concat(otherFiles);
//allFiles.forEach(file => {
// compiler.addFile(file.unitName, TypeScript.ScriptSnapshot.fromString(file.content),
// TypeScript.ByteOrderMark.None, /*version:*/ "0", /*isOpen:*/ true);
//});
var allFiles: any[] = [];
var compiler: any = undefined;
var typeBaselineText = '';
var allFiles = toBeCompiled.concat(otherFiles).filter(file => !!checker.getProgram().getSourceFile(file.unitName));
var typeLines: string[] = [];
var typeMap: { [fileName: string]: { [lineNum: number]: string[]; } } = {};
var walker = new TypeWriterWalker(checker);
allFiles.forEach(file => {
var codeLines = file.content.split('\n');
var walker = new TypeWriterWalker(file.unitName, compiler);
walker.run();
walker.results.forEach(result => {
var formattedLine = result.identifierName + " : " + result.type;
walker.getTypes(file.unitName).forEach(result => {
var formattedLine = result.sourceText.replace(/\r?\n/g, "") + " : " + result.type;
if (!typeMap[file.unitName]) {
typeMap[file.unitName] = {};
}
@@ -290,23 +328,6 @@ class CompilerBaselineRunner extends RunnerBase {
typeMap[file.unitName][result.line] = typeInfo;
});
var typeBaselineText = '';
var typeLines: string[] = [];
var typeMap: { [fileName: string]: { [lineNum: number]: string[]; } } = {};
allFiles.forEach(file => {
var codeLines = file.content.split('\n');
var walker = new TypeWriterWalker(file.unitName, compiler);
walker.run();
walker.results.forEach(result => {
var formattedLine = result.identifierName + " : " + result.type;
if (!typeMap[file.unitName]) {
typeMap[file.unitName] = {};
} else {
typeLines.push('No type information for this code.');
}
});
});
typeLines.push('=== ' + file.unitName + ' ===\r\n');
for (var i = 0; i < codeLines.length; i++) {
var currentCodeLine = codeLines[i];
+144 -119
View File
@@ -204,30 +204,29 @@ module FourSlash {
this.cancellationToken = new TestCancellationToken();
this.languageServiceShimHost = new Harness.LanguageService.TypeScriptLS(this.cancellationToken);
var harnessCompiler = Harness.Compiler.getCompiler();
var inputFiles: { unitName: string; content: string }[] = [];
testData.files.forEach(file => {
var fixedPath = file.fileName.substr(file.fileName.indexOf('tests/'));
harnessCompiler.addInputFile({ unitName: fixedPath, content: file.content });
});
// NEWTODO: disable resolution for now.
// If the last unit contains require( or /// reference then consider it the only input file
// and the rest will be added via resolution. If not, then assume we have multiple files
// with 0 references in any of them. We could be smarter here to allow scenarios like
// 2 files without references and 1 file with a reference but we have 0 tests like that
// at the moment and an exhaustive search of the test files for that content could be quite slow.
var lastFile = testData.files[testData.files.length - 1];
if (/require\(/.test(lastFile.content) || /reference\spath/.test(lastFile.content)) {
inputFiles.push({ unitName: lastFile.fileName, content: lastFile.content });
} else {
//if (/require\(/.test(lastFile.content) || /reference\spath/.test(lastFile.content)) {
// inputFiles.push({ unitName: lastFile.fileName, content: lastFile.content });
//} else {
inputFiles = testData.files.map(file => {
return { unitName: file.fileName, content: file.content };
});
}
//}
// NEWTODO: Re-implement commented-out section
//harnessCompiler.addInputFiles(inputFiles);
//try {
// var resolvedFiles = harnessCompiler.resolve();
@@ -597,6 +596,29 @@ module FourSlash {
}
}
public verifyReferencesAtPositionListContains(fileName: string, start: number, end: number, isWriteAccess?: boolean) {
this.taoInvalidReason = 'verifyReferencesAtPositionListContains NYI';
var references = this.getReferencesAtCaret();
if (!references || references.length === 0) {
throw new Error('verifyReferencesAtPositionListContains failed - found 0 references, expected at least one.');
}
for (var i = 0; i < references.length; i++) {
var reference = references[i];
if (reference && reference.fileName === fileName && reference.textSpan.start() === start && reference.textSpan.end() === end) {
if (typeof isWriteAccess !== "undefined" && reference.isWriteAccess !== isWriteAccess) {
throw new Error('verifyReferencesAtPositionListContains failed - item isWriteAccess value doe not match, actual: ' + reference.isWriteAccess + ', expected: ' + isWriteAccess + '.');
}
return;
}
}
var missingItem = { fileName: fileName, start: start, end: end, isWriteAccess: isWriteAccess };
throw new Error('verifyReferencesAtPositionListContains failed - could not find the item: ' + JSON.stringify(missingItem) + ' in the returned list: (' + JSON.stringify(references) + ')');
}
public verifyReferencesCountIs(count: number, localFilesOnly: boolean = true) {
this.taoInvalidReason = 'verifyReferences NYI';
@@ -606,19 +628,19 @@ module FourSlash {
if (localFilesOnly) {
var localFiles = this.testData.files.map<string>(file => file.fileName);
// Count only the references in local files. Filter the ones in lib and other files.
references.forEach((entry) => {
ts.forEach(references, entry => {
if (localFiles.some((filename) => filename === entry.fileName)) {
++referencesCount;
}
});
}
else {
referencesCount = references.length;
referencesCount = references && references.length || 0;
}
if (referencesCount !== count) {
var condition = localFilesOnly ? "excluding libs" : "including libs";
throw new Error("Expected references count (" + condition + ") to be " + count + ", but is actually " + references.length);
throw new Error("Expected references count (" + condition + ") to be " + count + ", but is actually " + referencesCount);
}
}
@@ -732,22 +754,22 @@ module FourSlash {
this.taoInvalidReason = 'verifyCurrentSignatureHelpIs NYI';
var help = this.getActiveSignatureHelp();
assert.equal(help.signatureInfo, expected);
assert.equal(help.prefix + help.parameters.map(p => p.display).join(help.separator) + help.suffix, expected);
}
public verifyCurrentParameterIsVariable(isVariable: boolean) {
this.taoInvalidReason = 'verifyCurrentParameterIsVariable NYI';
var activeParameter = this.getActiveParameter();
assert.isNotNull(activeParameter.parameter);
assert.equal(isVariable, activeParameter.parameter.isVariable);
var signature = this.getActiveSignatureHelp();
assert.isNotNull(signature);
assert.equal(isVariable, signature.isVariadic);
}
public verifyCurrentParameterHelpName(name: string) {
this.taoInvalidReason = 'verifyCurrentParameterHelpName NYI';
var activeParameter = this.getActiveParameter();
var activeParameterName = activeParameter.parameter ? activeParameter.parameter.name : activeParameter.typeParameter.name;
var activeParameterName = activeParameter.name;
assert.equal(activeParameterName, name);
}
@@ -756,16 +778,14 @@ module FourSlash {
var activeSignature = this.getActiveSignatureHelp();
var activeParameter = this.getActiveParameter();
var activeParameterMinChar = activeParameter.parameter ? activeParameter.parameter.minChar : activeParameter.typeParameter.minChar;
var activeParameterLimChar = activeParameter.parameter ? activeParameter.parameter.limChar : activeParameter.typeParameter.limChar;
assert.equal(activeSignature.signatureInfo.substring(activeParameterMinChar, activeParameterLimChar), parameter);
assert.equal(activeParameter.display, parameter);
}
public verifyCurrentParameterHelpDocComment(docComment: string) {
this.taoInvalidReason = 'verifyCurrentParameterHelpDocComment NYI';
var activeParameter = this.getActiveParameter();
var activeParameterDocComment = activeParameter.parameter ? activeParameter.parameter.docComment : activeParameter.typeParameter.docComment;
var activeParameterDocComment = activeParameter.documentation;
assert.equal(activeParameterDocComment, docComment);
}
@@ -778,13 +798,13 @@ module FourSlash {
public verifyCurrentSignatureHelpTypeParameterCount(expectedCount: number) {
this.taoInvalidReason = 'verifyCurrentSignatureHelpTypeParameterCount NYI';
assert.equal(this.getActiveSignatureHelp().typeParameters.length, expectedCount);
// assert.equal(this.getActiveSignatureHelp().typeParameters.length, expectedCount);
}
public verifyCurrentSignatureHelpDocComment(docComment: string) {
this.taoInvalidReason = 'verifyCurrentSignatureHelpDocComment NYI';
var actualDocComment = this.getActiveSignatureHelp().docComment;
var actualDocComment = this.getActiveSignatureHelp().documentation;
assert.equal(actualDocComment, docComment);
}
@@ -792,15 +812,15 @@ module FourSlash {
this.scenarioActions.push('<InvokeSignatureHelp />');
this.scenarioActions.push('<VerifySignatureHelpOverloadCountEquals Count="' + expected + '" />');
var help = this.languageService.getSignatureAtPosition(this.activeFile.fileName, this.currentCaretPosition);
var actual = help && help.formal ? help.formal.length : 0;
var help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition);
var actual = help && help.items ? help.items.length : 0;
assert.equal(actual, expected);
}
public verifySignatureHelpPresent(shouldBePresent = true) {
this.taoInvalidReason = 'verifySignatureHelpPresent NYI';
var actual = this.languageService.getSignatureAtPosition(this.activeFile.fileName, this.currentCaretPosition);
var actual = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition);
if (shouldBePresent) {
if (!actual) {
throw new Error("Expected signature help to be present, but it wasn't");
@@ -812,45 +832,32 @@ module FourSlash {
}
}
private getFormalParameter() {
var help = this.languageService.getSignatureAtPosition(this.activeFile.fileName, this.currentCaretPosition);
return help.formal;
}
//private getFormalParameter() {
// var help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition);
// return help.formal;
//}
private getActiveSignatureHelp() {
var help = this.languageService.getSignatureAtPosition(this.activeFile.fileName, this.currentCaretPosition);
var activeFormal = help.activeFormal;
var help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition);
// If the signature hasn't been narrowed down yet (e.g. no parameters have yet been entered),
// 'activeFormal' will be -1 (even if there is only 1 signature). Signature help will show the
// first signature in the signature group, so go with that
if (activeFormal === -1) {
activeFormal = 0;
}
var index = help.selectedItemIndex < 0 ? 0 : help.selectedItemIndex;
return help.formal[activeFormal];
return help.items[index];
}
private getActiveParameter(): { parameter: ts.FormalParameterInfo; typeParameter: ts.FormalTypeParameterInfo; } {
private getActiveParameter(): ts.SignatureHelpParameter {
var currentSig = this.getActiveSignatureHelp();
var help = this.languageService.getSignatureAtPosition(this.activeFile.fileName, this.currentCaretPosition);
var help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition);
var item = help.items[help.selectedItemIndex];
var state = this.languageService.getSignatureHelpCurrentArgumentState(this.activeFile.fileName, this.currentCaretPosition, help.applicableSpan.start());
// Same logic as in getActiveSignatureHelp - this value might be -1 until a parameter value actually gets typed
var currentParam = help.actual.currentParameter;
if (currentParam === -1) currentParam = 0;
if (help.actual.currentParameterIsTypeParameter) {
return {
parameter: null,
typeParameter: currentSig.typeParameters[currentParam]
};
}
else {
return {
parameter: currentSig.parameters[currentParam],
typeParameter: null
};
}
var currentParam = state === null ? 0 : state.argumentIndex;
return item.parameters[currentParam];
}
public getBreakpointStatementLocation(pos: number) {
@@ -859,7 +866,7 @@ module FourSlash {
var spanInfo = this.languageService.getBreakpointStatementAtPosition(this.activeFile.fileName, pos);
var resultString = "\n**Pos: " + pos + " SpanInfo: " + JSON.stringify(spanInfo) + "\n** Statement: ";
if (spanInfo !== null) {
resultString = resultString + this.activeFile.content.substr(spanInfo.minChar, spanInfo.limChar - spanInfo.minChar);
resultString = resultString + this.activeFile.content.substr(spanInfo.start(), spanInfo.length());
}
return resultString;
}
@@ -890,7 +897,7 @@ module FourSlash {
}
public printCurrentParameterHelp() {
var help = this.languageService.getSignatureAtPosition(this.activeFile.fileName, this.currentCaretPosition);
var help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition);
Harness.IO.log(JSON.stringify(help));
}
@@ -944,6 +951,18 @@ module FourSlash {
Harness.IO.log(JSON.stringify(completions));
}
public printReferences() {
var references = this.getReferencesAtCaret();
ts.forEach(references, entry => {
Harness.IO.log(JSON.stringify(entry));
});
}
public printContext() {
var fileNames: string[] = JSON.parse(this.languageServiceShimHost.getScriptFileNames());
ts.forEach(fileNames, Harness.IO.log);
}
private editCheckpoint(filename: string) {
// TODO: What's this for? It is being called by deleteChar
// this.languageService.getScriptLexicalStructure(filename);
@@ -1071,7 +1090,7 @@ module FourSlash {
if (ch === '(' || ch === ',') {
/* Signature help*/
this.languageService.getSignatureAtPosition(this.activeFile.fileName, offset);
this.languageService.getSignatureHelpItems(this.activeFile.fileName, offset);
} else if (prevChar === ' ' && /A-Za-z_/.test(ch)) {
/* Completions */
this.languageService.getCompletionsAtPosition(this.activeFile.fileName, offset, false);
@@ -1111,7 +1130,7 @@ module FourSlash {
// Handle formatting
if (this.enableFormatting) {
var edits = this.languageService.getFormattingEditsOnPaste(this.activeFile.fileName, start, offset, this.formatCodeOptions);
var edits = this.languageService.getFormattingEditsForRange(this.activeFile.fileName, start, offset, this.formatCodeOptions);
offset += this.applyEdits(this.activeFile.fileName, edits, true);
this.editCheckpoint(this.activeFile.fileName);
}
@@ -1175,18 +1194,18 @@ module FourSlash {
};
}
private applyEdits(fileName: string, edits: ts.TextEdit[], isFormattingEdit = false): number {
private applyEdits(fileName: string, edits: ts.TextChange[], isFormattingEdit = false): number {
// We get back a set of edits, but langSvc.editScript only accepts one at a time. Use this to keep track
// of the incremental offest from each edit to the next. Assumption is that these edit ranges don't overlap
var runningOffset = 0;
edits = edits.sort((a, b) => a.minChar - b.minChar);
edits = edits.sort((a, b) => a.span.start() - b.span.start());
// Get a snapshot of the content of the file so we can make sure any formatting edits didn't destroy non-whitespace characters
var snapshot = this.languageServiceShimHost.getScriptSnapshot(fileName);
var oldContent = snapshot.getText(0, snapshot.getLength());
for (var j = 0; j < edits.length; j++) {
this.languageServiceShimHost.editScript(fileName, edits[j].minChar + runningOffset, edits[j].limChar + runningOffset, edits[j].text);
this.updateMarkersForEdit(fileName, edits[j].minChar + runningOffset, edits[j].limChar + runningOffset, edits[j].text);
var change = (edits[j].minChar - edits[j].limChar) + edits[j].text.length;
this.languageServiceShimHost.editScript(fileName, edits[j].span.start() + runningOffset, edits[j].span.end() + runningOffset, edits[j].newText);
this.updateMarkersForEdit(fileName, edits[j].span.start() + runningOffset, edits[j].span.end() + runningOffset, edits[j].newText);
var change = (edits[j].span.start() - edits[j].span.end()) + edits[j].newText.length;
runningOffset += change;
// TODO: Consider doing this at least some of the time for higher fidelity. Currently causes a failure (bug 707150)
// this.languageService.getScriptLexicalStructure(fileName);
@@ -1206,7 +1225,7 @@ module FourSlash {
public formatDocument() {
this.scenarioActions.push('<FormatDocument />');
var edits = this.languageService.getFormattingEditsForDocument(this.activeFile.fileName, 0, this.languageServiceShimHost.getScriptSnapshot(this.activeFile.fileName).getLength(), this.formatCodeOptions);
var edits = this.languageService.getFormattingEditsForDocument(this.activeFile.fileName, this.formatCodeOptions);
this.currentCaretPosition += this.applyEdits(this.activeFile.fileName, edits, true);
this.fixCaretPosition();
}
@@ -1263,7 +1282,7 @@ module FourSlash {
var definition = definitions[definitionIndex];
this.openFile(definition.fileName);
this.currentCaretPosition = definition.minChar;
this.currentCaretPosition = definition.textSpan.start();
}
public verifyDefinitionLocationExists(negative: boolean) {
@@ -1369,7 +1388,7 @@ module FourSlash {
'\t Actual: null');
}
var actual = this.languageServiceShimHost.getScriptSnapshot(this.activeFile.fileName).getText(span.minChar, span.limChar);
var actual = this.languageServiceShimHost.getScriptSnapshot(this.activeFile.fileName).getText(span.start(), span.end());
if (actual !== text) {
throw new Error('verifyCurrentNameOrDottedNameSpanText\n' +
'\tExpected: "' + text + '"\n' +
@@ -1381,7 +1400,7 @@ module FourSlash {
var spanInfo = this.languageService.getNameOrDottedNameSpan(this.activeFile.fileName, pos, pos);
var resultString = "\n**Pos: " + pos + " SpanInfo: " + JSON.stringify(spanInfo) + "\n** Statement: ";
if (spanInfo !== null) {
resultString = resultString + this.languageServiceShimHost.getScriptSnapshot(this.activeFile.fileName).getText(spanInfo.minChar, spanInfo.limChar);
resultString = resultString + this.languageServiceShimHost.getScriptSnapshot(this.activeFile.fileName).getText(spanInfo.start(), spanInfo.end());
}
return resultString;
}
@@ -1410,7 +1429,7 @@ module FourSlash {
public verifyOutliningSpans(spans: TextSpan[]) {
this.taoInvalidReason = 'verifyOutliningSpans NYI';
var actual = this.languageService.getOutliningRegions(this.activeFile.fileName);
var actual = this.languageService.getOutliningSpans(this.activeFile.fileName);
if (actual.length !== spans.length) {
throw new Error('verifyOutliningSpans failed - expected total spans to be ' + spans.length + ', but was ' + actual.length);
@@ -1425,6 +1444,25 @@ module FourSlash {
}
}
public verifyTodoComments(descriptors: string[], spans: TextSpan[]) {
var actual = this.languageService.getTodoComments(this.activeFile.fileName,
descriptors.map(d => new ts.TodoCommentDescriptor(d, 0)));
if (actual.length !== spans.length) {
throw new Error('verifyTodoComments failed - expected total spans to be ' + spans.length + ', but was ' + actual.length);
}
for (var i = 0; i < spans.length; i++) {
var expectedSpan = spans[i];
var actualComment = actual[i];
var actualCommentSpan = new TypeScript.TextSpan(actualComment.position, actualComment.message.length);
if (expectedSpan.start !== actualCommentSpan.start() || expectedSpan.end !== actualCommentSpan.end()) {
throw new Error('verifyOutliningSpans failed - span ' + (i + 1) + ' expected: (' + expectedSpan.start + ',' + expectedSpan.end + '), actual: (' + actualCommentSpan.start() + ',' + actualCommentSpan.end() + ')');
}
}
}
public verifyMatchingBracePosition(bracePosition: number, expectedMatchPosition: number) {
this.taoInvalidReason = 'verifyMatchingBracePosition NYI';
@@ -1584,70 +1622,61 @@ module FourSlash {
public verifyGetScriptLexicalStructureListCount(expected: number) {
this.taoInvalidReason = 'verifyNavigationItemsListContains impossible';
var items = this.languageService.getScriptLexicalStructure(this.activeFile.fileName);
var actual = (items && items.length) || 0;
var items = this.languageService.getNavigationBarItems(this.activeFile.fileName);
var actual = this.getNavigationBarItemsCount(items);
if (expected != actual) {
throw new Error('verifyGetScriptLexicalStructureListCount failed - found: ' + actual + ' navigation items, expected: ' + expected + '.');
}
}
private getNavigationBarItemsCount(items: ts.NavigationBarItem[]) {
var result = 0;
if (items) {
for (var i = 0, n = items.length; i < n; i++) {
result++;
result += this.getNavigationBarItemsCount(items[i].childItems);
}
}
return result;
}
public verifGetScriptLexicalStructureListContains(
name: string,
kind: string,
fileName?: string,
parentName?: string,
isAdditionalSpan?: boolean,
markerPosition?: number) {
this.taoInvalidReason = 'verifGetScriptLexicalStructureListContains impossible';
var items = this.languageService.getScriptLexicalStructure(this.activeFile.fileName);
var items = this.languageService.getNavigationBarItems(this.activeFile.fileName);
if (!items || items.length === 0) {
throw new Error('verifyGetScriptLexicalStructureListContains failed - found 0 navigation items, expected at least one.');
}
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (item && item.name === name && item.kind === kind &&
(fileName === undefined || item.fileName === fileName) &&
(parentName === undefined || item.containerName === parentName)) {
if (markerPosition !== undefined || isAdditionalSpan !== undefined) {
if (isAdditionalSpan) {
if (item.additionalSpans &&
item.additionalSpans.some(span => span.minChar <= markerPosition && markerPosition <= span.limChar)) {
// marker is in an additional span for this item.
return;
}
else {
throw new Error(
'verifGetScriptLexicalStructureListContains failed - ' +
'no additional span was found that contained the position: ' + JSON.stringify(markerPosition) +
' in the item: ' + JSON.stringify(item));
}
}
else if (!isAdditionalSpan) {
if (item.minChar <= markerPosition &&
markerPosition <= item.minChar) {
// marker is in span normal item's span
return;
}
else {
throw new Error(
'verifGetScriptLexicalStructureListContains failed - ' +
'marker was positioned: ' + JSON.stringify(markerPosition) +
' which is not in the item: ' + JSON.stringify(item));
}
}
if (this.navigationBarItemsContains(items, name, kind)) {
return;
}
var missingItem = { name: name, kind: kind };
throw new Error('verifyGetScriptLexicalStructureListContains failed - could not find the item: ' + JSON.stringify(missingItem) + ' in the returned list: (' + JSON.stringify(items) + ')');
}
private navigationBarItemsContains(items: ts.NavigationBarItem[], name: string, kind: string) {
if (items) {
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (item && item.text === name && item.kind === kind) {
return true;
}
else {
return;
if (this.navigationBarItemsContains(item.childItems, name, kind)) {
return true;
}
}
}
var missingItem = { name: name, kind: kind, fileName: fileName, parentName: parentName };
throw new Error('verifyGetScriptLexicalStructureListContains failed - could not find the item: ' + JSON.stringify(missingItem) + ' in the returned list: (' + JSON.stringify(items) + ')');
return false;
}
public printNavigationItems(searchValue: string) {
@@ -1663,14 +1692,14 @@ module FourSlash {
}
public printScriptLexicalStructureItems() {
var items = this.languageService.getScriptLexicalStructure(this.activeFile.fileName);
var items = this.languageService.getNavigationBarItems(this.activeFile.fileName);
var length = items && items.length;
Harness.IO.log('NavigationItems list (' + length + ' items)');
for (var i = 0; i < length; i++) {
var item = items[i];
Harness.IO.log('name: ' + item.name + ', kind: ' + item.kind + ', parentName: ' + item.containerName + ', fileName: ' + item.fileName);
Harness.IO.log('name: ' + item.text + ', kind: ' + item.kind);
}
}
@@ -1689,7 +1718,7 @@ module FourSlash {
for (var i = 0; i < occurances.length; i++) {
var occurance = occurances[i];
if (occurance && occurance.fileName === fileName && occurance.minChar === start && occurance.limChar === end) {
if (occurance && occurance.fileName === fileName && occurance.textSpan.start() === start && occurance.textSpan.end() === end) {
if (typeof isWriteAccess !== "undefined" && occurance.isWriteAccess !== isWriteAccess) {
throw new Error('verifyOccurancesAtPositionListContains failed - item isWriteAccess value doe not match, actual: ' + occurance.isWriteAccess + ', expected: ' + isWriteAccess + '.');
}
@@ -1711,10 +1740,6 @@ module FourSlash {
}
}
private getBOF(): number {
return 0;
}
private getEOF(): number {
return this.languageServiceShimHost.getScriptSnapshot(this.activeFile.fileName).getLength();
}
@@ -1895,12 +1920,12 @@ module FourSlash {
var result = '';
var fourslashFilename = 'fourslash.ts';
var tsFn = 'tests/cases/fourslash/' + fourslashFilename;
fourslashSourceFile = fourslashSourceFile || ts.createSourceFile(tsFn, Harness.IO.readFile(tsFn), ts.ScriptTarget.ES5, /*version*/ 0, /*isOpen*/ false);
fourslashSourceFile = fourslashSourceFile || ts.createSourceFile(tsFn, Harness.IO.readFile(tsFn), ts.ScriptTarget.ES5, /*version*/ "0", /*isOpen*/ false);
var files: { [filename: string]: ts.SourceFile; } = {};
files[fourslashFilename] = fourslashSourceFile;
files[fileName] = ts.createSourceFile(fileName, content, ts.ScriptTarget.ES5, /*version*/ 0, /*isOpen*/ false);
files[Harness.Compiler.defaultLibFileName] = Harness.Compiler.defaultLibSourceFile;
files[Harness.Compiler.getCanonicalFileName(fourslashFilename)] = fourslashSourceFile;
files[Harness.Compiler.getCanonicalFileName(fileName)] = ts.createSourceFile(fileName, content, ts.ScriptTarget.ES5, /*version*/ "0", /*isOpen*/ false);
files[Harness.Compiler.getCanonicalFileName(Harness.Compiler.defaultLibFileName)] = Harness.Compiler.defaultLibSourceFile;
var host = Harness.Compiler.createCompilerHost(files, (fn, contents) => result = contents);
var program = ts.createProgram([fourslashFilename, fileName], { out: "fourslashTestOutput.js" }, host);
+61 -24
View File
@@ -532,15 +532,19 @@ module Harness {
}
export var defaultLibFileName = 'lib.d.ts';
export var defaultLibSourceFile = ts.createSourceFile(defaultLibFileName, IO.readFile(libFolder + 'lib.core.d.ts'), /*languageVersion*/ ts.ScriptTarget.ES5);
export var defaultLibSourceFile = ts.createSourceFile(defaultLibFileName, IO.readFile(libFolder + 'lib.core.d.ts'), /*languageVersion*/ ts.ScriptTarget.ES5, /*version:*/ "0");
export function getCanonicalFileName(fileName: string): string {
return sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
}
export function createCompilerHost(filemap: { [filename: string]: ts.SourceFile; }, writeFile: (fn: string, contents: string, writeByteOrderMark:boolean) => void): ts.CompilerHost {
return {
getCurrentDirectory: sys.getCurrentDirectory,
getCancellationToken: (): any => undefined,
getSourceFile: (fn, languageVersion) => {
if (fn in filemap) {
return filemap[fn];
if (Object.prototype.hasOwnProperty.call(filemap, getCanonicalFileName(fn))) {
return filemap[getCanonicalFileName(fn)];
} else {
var lib = defaultLibFileName;
if (fn === defaultLibFileName) {
@@ -552,7 +556,7 @@ module Harness {
},
getDefaultLibFilename: () => defaultLibFileName,
writeFile: writeFile,
getCanonicalFileName: ts.getCanonicalFileName,
getCanonicalFileName: getCanonicalFileName,
useCaseSensitiveFileNames: () => sys.useCaseSensitiveFileNames,
getNewLine: ()=> sys.newLine
};
@@ -563,7 +567,7 @@ module Harness {
private compileOptions: ts.CompilerOptions;
private settings: Harness.TestCaseParser.CompilerSetting[] = [];
private lastErrors: MinimalDiagnostic[];
private lastErrors: HarnessDiagnostic[];
public reset() {
this.inputFiles = [];
@@ -571,10 +575,6 @@ module Harness {
this.lastErrors = [];
}
public emitAllDeclarations() {
// NEWTODO: Do something here?
}
public reportCompilationErrors() {
return this.lastErrors;
}
@@ -604,12 +604,18 @@ module Harness {
result.files.forEach(file => {
ioHost.writeFile(file.fileName, file.code, false);
});
result.declFilesCode.forEach(file => {
ioHost.writeFile(file.fileName, file.code, false);
});
result.sourceMaps.forEach(file => {
ioHost.writeFile(file.fileName, file.code, false);
});
}, () => { }, this.compileOptions);
}
public compileFiles(inputFiles: { unitName: string; content: string }[],
otherFiles: { unitName: string; content?: string }[],
onComplete: (result: CompilerResult) => void,
onComplete: (result: CompilerResult, checker: ts.TypeChecker) => void,
settingsCallback?: (settings: ts.CompilerOptions) => void,
options?: ts.CompilerOptions) {
@@ -695,6 +701,10 @@ module Harness {
sys.newLine = setting.value;
break;
case 'comments':
options.removeComments = setting.value === 'false';
break;
case 'mapsourcefiles':
case 'maproot':
case 'generatedeclarationfiles':
@@ -702,7 +712,6 @@ module Harness {
case 'gatherDiagnostics':
case 'codepage':
case 'createFileLog':
case 'comments':
case 'filename':
case 'propagateenumconstants':
case 'removecomments':
@@ -723,8 +732,10 @@ module Harness {
var filemap: { [name: string]: ts.SourceFile; } = {};
var register = (file: { unitName: string; content: string; }) => {
var filename = Path.switchToForwardSlashes(file.unitName);
filemap[filename] = ts.createSourceFile(filename, file.content, options.target);
if (file.content !== undefined) {
var filename = Path.switchToForwardSlashes(file.unitName);
filemap[getCanonicalFileName(filename)] = ts.createSourceFile(filename, file.content, options.target, /*version:*/ "0");
}
};
inputFiles.forEach(register);
otherFiles.forEach(register);
@@ -745,7 +756,7 @@ module Harness {
emitResult = checker.emitFiles();
}
var errors: MinimalDiagnostic[] = [];
var errors: HarnessDiagnostic[] = [];
program.getDiagnostics().concat(checker.getDiagnostics()).concat(emitResult ? emitResult.errors : []).forEach(err => {
// TODO: new compiler formats errors after this point to add . and newlines so we'll just do it manually for now
errors.push(getMinimalDiagnostic(err));
@@ -755,7 +766,7 @@ module Harness {
var result = new CompilerResult(fileOutputs, errors, []);
// Covert the source Map data into the baseline
result.updateSourceMapRecord(program, emitResult ? emitResult.sourceMaps : undefined);
onComplete(result);
onComplete(result, checker);
// reset what newline means in case the last test changed it
sys.newLine = '\r\n';
@@ -763,19 +774,43 @@ module Harness {
}
}
export function getMinimalDiagnostic(err: ts.Diagnostic): MinimalDiagnostic {
return { filename: err.file && err.file.filename, start: err.start, end: err.start + err.length, line: 0, character: 0, message: err.messageText };
export function getMinimalDiagnostic(err: ts.Diagnostic): HarnessDiagnostic {
var errorLineInfo = err.file ? err.file.getLineAndCharacterFromPosition(err.start) : { line: 0, character: 0 };
return {
filename: err.file && err.file.filename,
start: err.start,
end: err.start + err.length,
line: errorLineInfo.line,
character: errorLineInfo.character,
message: err.messageText,
category: ts.DiagnosticCategory[err.category].toLowerCase(),
code: err.code
};
}
export function minimalDiagnosticsToString(diagnostics: HarnessDiagnostic[]) {
// This is basically copied from tsc.ts's reportError to replicate what tsc does
var errorOutput = "";
ts.forEach(diagnostics, diagnotic => {
if (diagnotic.filename) {
errorOutput += diagnotic.filename + "(" + diagnotic.line + "," + diagnotic.character + "): ";
}
errorOutput += diagnotic.category + " TS" + diagnotic.code + ": " + diagnotic.message + sys.newLine;
});
return errorOutput;
}
export function getErrorBaseline(inputFiles: { unitName: string; content: string }[],
diagnostics: MinimalDiagnostic[]
diagnostics: HarnessDiagnostic[]
) {
var outputLines: string[] = [];
// Count up all the errors we find so we don't miss any
var totalErrorsReported = 0;
function outputErrorText(error: Harness.Compiler.MinimalDiagnostic) {
function outputErrorText(error: Harness.Compiler.HarnessDiagnostic) {
var errLines = RunnerBase.removeFullPaths(error.message)
.split('\n')
.map(s => s.length > 0 && s.charAt(s.length - 1) === '\r' ? s.substr(0, s.length - 1) : s)
@@ -791,7 +826,7 @@ module Harness {
globalErrors.forEach(err => outputErrorText(err));
// 'merge' the lines of each input file with any errors associated with it
inputFiles.forEach(inputFile => {
inputFiles.filter(f => f.content !== undefined).forEach(inputFile => {
// Filter down to the errors in the file
var fileErrors = diagnostics.filter(e => {
var errFn = e.filename;
@@ -895,13 +930,15 @@ module Harness {
//harnessCompiler.compileString(code, unitName, callback);
}
export interface MinimalDiagnostic {
export interface HarnessDiagnostic {
filename: string;
start: number;
end: number;
line: number;
character: number;
message: string;
category: string;
code: number;
}
export interface GeneratedFile {
@@ -929,13 +966,13 @@ module Harness {
/** Contains the code and errors of a compilation and some helper methods to check its status. */
export class CompilerResult {
public files: GeneratedFile[] = [];
public errors: MinimalDiagnostic[] = [];
public errors: HarnessDiagnostic[] = [];
public declFilesCode: GeneratedFile[] = [];
public sourceMaps: GeneratedFile[] = [];
public sourceMapRecord: string;
/** @param fileResults an array of strings for the fileName and an ITextWriter with its code */
constructor(fileResults: GeneratedFile[], errors: MinimalDiagnostic[], sourceMapRecordLines: string[]) {
constructor(fileResults: GeneratedFile[], errors: HarnessDiagnostic[], sourceMapRecordLines: string[]) {
var lines: string[] = [];
fileResults.forEach(emittedFile => {
@@ -1218,7 +1255,7 @@ module Harness {
}
export function isLibraryFile(filePath: string): boolean {
return filePath.indexOf('lib.d.ts') >= 0 || filePath.indexOf('lib.core.d.ts') >= 0;
return (Path.getFileName(filePath) === 'lib.d.ts') || (Path.getFileName(filePath) === 'lib.core.d.ts');
}
if (Error) (<any>Error).stackTraceLimit = 1;
+26 -61
View File
@@ -80,8 +80,9 @@ module Harness.LanguageService {
return JSON.stringify(this.lineMap.lineStarts());
}
public getTextChangeRangeSinceVersion(scriptVersion: number): string {
var range = this.scriptInfo.getTextChangeRangeBetweenVersions(scriptVersion, this.version);
public getChangeRange(oldScript: ts.ScriptSnapshotShim): string {
var oldShim = <ScriptSnapshotShim>oldScript;
var range = this.scriptInfo.getTextChangeRangeBetweenVersions(oldShim.version, this.version);
if (range === null) {
return null;
}
@@ -101,50 +102,14 @@ module Harness.LanguageService {
}
}
class ScriptSnapshotShimAdapter implements TypeScript.IScriptSnapshot {
private lineStartPositions: number[] = null;
constructor(private scriptSnapshotShim: ts.ScriptSnapshotShim) {}
getText(start: number, end: number): string {return this.scriptSnapshotShim.getText(start, end);}
getLength(): number {return this.scriptSnapshotShim.getLength();}
getLineStartPositions(): number[] { return JSON.parse(this.scriptSnapshotShim.getLineStartPositions()); }
getTextChangeRangeSinceVersion(scriptVersion: number): TypeScript.TextChangeRange {
var encoded = this.scriptSnapshotShim.getTextChangeRangeSinceVersion(scriptVersion);
if (encoded == null) {
return null;
}
var decoded: { span: { start: number; length: number; }; newLength: number; } = JSON.parse(encoded);
return new TypeScript.TextChangeRange(
new TypeScript.TextSpan(decoded.span.start, decoded.span.length), decoded.newLength);
}
}
class LanguageServiceShimHostAdapter implements ts.LanguageServiceHost {
constructor(private shimHost: ts.LanguageServiceShimHost) { }
information(): boolean { return this.shimHost.information(); }
debug(): boolean { return this.shimHost.debug(); }
warning(): boolean { return this.shimHost.warning();}
error(): boolean { return this.shimHost.error(); }
fatal(): boolean { return this.shimHost.fatal(); }
log(s: string): void { this.shimHost.log(s); }
getCompilationSettings(): ts.CompilerOptions { return JSON.parse(this.shimHost.getCompilationSettings()); }
getScriptFileNames(): string[] { return JSON.parse(this.shimHost.getScriptFileNames());}
getScriptSnapshot(fileName: string): TypeScript.IScriptSnapshot { return new ScriptSnapshotShimAdapter(this.shimHost.getScriptSnapshot(fileName));}
getScriptVersion(fileName: string): number { return this.shimHost.getScriptVersion(fileName);}
getScriptIsOpen(fileName: string): boolean { return this.shimHost.getScriptIsOpen(fileName); }
getLocalizedDiagnosticMessages(): any { JSON.parse(this.shimHost.getLocalizedDiagnosticMessages());}
getCancellationToken(): ts.CancellationToken { return this.shimHost.getCancellationToken(); }
}
export class NonCachingDocumentRegistry implements ts.DocumentRegistry {
public static Instance: ts.DocumentRegistry = new NonCachingDocumentRegistry();
public acquireDocument(
fileName: string,
compilationSettings: ts.CompilerOptions,
scriptSnapshot: TypeScript.IScriptSnapshot,
version: number,
version: string,
isOpen: boolean): ts.SourceFile {
return ts.createSourceFile(fileName, scriptSnapshot.getText(0, scriptSnapshot.getLength()), compilationSettings.target, version, isOpen);
}
@@ -154,7 +119,7 @@ module Harness.LanguageService {
fileName: string,
compilationSettings: ts.CompilerOptions,
scriptSnapshot: TypeScript.IScriptSnapshot,
version: number,
version: string,
isOpen: boolean,
textChangeRange: TypeScript.TextChangeRange
): ts.SourceFile {
@@ -167,7 +132,6 @@ module Harness.LanguageService {
}
export class TypeScriptLS implements ts.LanguageServiceShimHost {
private ls: ts.LanguageServiceShim = null;
public newLS: ts.LanguageService;
private fileNameToScript: ts.Map<ScriptInfo> = {};
@@ -252,8 +216,8 @@ module Harness.LanguageService {
return new ScriptSnapshotShim(this.getScriptInfo(fileName));
}
public getScriptVersion(fileName: string): number {
return this.getScriptInfo(fileName).version;
public getScriptVersion(fileName: string): string {
return this.getScriptInfo(fileName).version.toString();
}
public getScriptIsOpen(fileName: string): boolean {
@@ -268,12 +232,13 @@ module Harness.LanguageService {
* To access the non-shim (i.e. actual) language service, use the "ls.languageService" property.
*/
public getLanguageService(): ts.LanguageServiceShim {
var ls = new TypeScript.Services.TypeScriptServicesFactory().createLanguageServiceShim(this);
this.ls = ls;
var hostAdapter = new LanguageServiceShimHostAdapter(this);
this.ls = new TypeScript.Services.TypeScriptServicesFactory().createLanguageServiceShim(this);
return this.ls;
}
this.newLS = ts.createLanguageService(hostAdapter, NonCachingDocumentRegistry.Instance);
return ls;
/** Return a new instance of the classifier service shim */
public getClassifier(): ts.ClassifierShim {
return new TypeScript.Services.TypeScriptServicesFactory().createClassifierShim(this);
}
/** Parse file given its source text */
@@ -316,7 +281,7 @@ module Harness.LanguageService {
}
/** Verify that applying edits to sourceFileName result in the content of the file baselineFileName */
public checkEdits(sourceFileName: string, baselineFileName: string, edits: ts.TextEdit[]) {
public checkEdits(sourceFileName: string, baselineFileName: string, edits: ts.TextChange[]) {
var script = Harness.IO.readFile(sourceFileName);
var formattedScript = this.applyEdits(script, edits);
var baseline = Harness.IO.readFile(baselineFileName);
@@ -345,26 +310,26 @@ module Harness.LanguageService {
/** Apply an array of text edits to a string, and return the resulting string. */
public applyEdits(content: string, edits: ts.TextEdit[]): string {
public applyEdits(content: string, edits: ts.TextChange[]): string {
var result = content;
edits = this.normalizeEdits(edits);
for (var i = edits.length - 1; i >= 0; i--) {
var edit = edits[i];
var prefix = result.substring(0, edit.minChar);
var middle = edit.text;
var suffix = result.substring(edit.limChar);
var prefix = result.substring(0, edit.span.start());
var middle = edit.newText;
var suffix = result.substring(edit.span.end());
result = prefix + middle + suffix;
}
return result;
}
/** Normalize an array of edits by removing overlapping entries and sorting entries on the minChar position. */
private normalizeEdits(edits: ts.TextEdit[]): ts.TextEdit[] {
var result: ts.TextEdit[] = [];
private normalizeEdits(edits: ts.TextChange[]): ts.TextChange[] {
var result: ts.TextChange[] = [];
function mapEdits(edits: ts.TextEdit[]): { edit: ts.TextEdit; index: number; }[] {
var result: { edit: ts.TextEdit; index: number; }[] = [];
function mapEdits(edits: ts.TextChange[]): { edit: ts.TextChange; index: number; }[] {
var result: { edit: ts.TextChange; index: number; }[] = [];
for (var i = 0; i < edits.length; i++) {
result.push({ edit: edits[i], index: i });
}
@@ -372,7 +337,7 @@ module Harness.LanguageService {
}
var temp = mapEdits(edits).sort(function (a, b) {
var result = a.edit.minChar - b.edit.limChar;
var result = a.edit.span.start() - b.edit.span.start();
if (result === 0)
result = a.index - b.index;
return result;
@@ -391,7 +356,7 @@ module Harness.LanguageService {
}
var nextEdit = temp[next].edit;
var gap = nextEdit.minChar - currentEdit.limChar;
var gap = nextEdit.span.start() - currentEdit.span.end();
// non-overlapping edits
if (gap >= 0) {
@@ -400,10 +365,10 @@ module Harness.LanguageService {
next++;
continue;
}
// overlapping edits: for now, we only support ignoring an next edit
// entirely contained in the current edit.
if (currentEdit.minChar >= nextEdit.limChar) {
if (currentEdit.span.end() >= nextEdit.span.end()) {
next++;
continue;
}
+53
View File
@@ -0,0 +1,53 @@
declare var require: any, process: any;
var fs: any = require('fs');
var path: any = require('path');
function instrumentForRecording(fn: string, tscPath: string) {
instrument(tscPath, 'sys = Playback.wrapSystem(sys); sys.startRecord("' + fn + '");', 'sys.endRecord();');
}
function instrumentForReplay(logFilename: string, tscPath: string) {
instrument(tscPath, 'sys = Playback.wrapSystem(sys); sys.startReplay("' + logFilename + '");');
}
function instrument(tscPath: string, prepareCode: string, cleanupCode: string = '') {
var bak = tscPath + '.bak';
fs.exists(bak, (backupExists: boolean) => {
var filename = tscPath;
if (backupExists) {
filename = bak;
}
fs.readFile(filename, 'utf-8', (err: any, tscContent: string) => {
if (err) throw err;
fs.writeFile(bak, tscContent, (err: any) => {
if (err) throw err;
fs.readFile(path.resolve(path.dirname(tscPath) + '/loggedIO.js'), 'utf-8', (err: any, loggerContent: string) => {
if (err) throw err;
var invocationLine = 'ts.executeCommandLine(sys.args);';
var index1 = tscContent.indexOf(invocationLine);
var index2 = index1 + invocationLine.length;
var newContent = tscContent.substr(0, index1) + loggerContent + prepareCode + invocationLine + cleanupCode + tscContent.substr(index2) + '\r\n';
fs.writeFile(tscPath, newContent);
});
});
});
});
}
var isJson = (arg: string) => arg.indexOf(".json") > 0;
var record = process.argv.indexOf('record');
var tscPath = process.argv[process.argv.length - 1];
if (record >= 0) {
console.log('Instrumenting ' + tscPath + ' for recording');
instrumentForRecording(process.argv[record + 1], tscPath);
} else if (process.argv.some(isJson)) {
var filename = process.argv.filter(isJson)[0];
instrumentForReplay(filename, tscPath);
}
+45 -13
View File
@@ -1,4 +1,6 @@
/// <reference path="..\..\src\compiler\sys.ts" />
/// <reference path="..\..\src\harness\harness.ts" />
/// <reference path="..\..\src\harness\runnerbase.ts" />
interface FileInformation {
contents: string;
@@ -93,6 +95,7 @@ module Playback {
function createEmptyLog(): IOLog {
return {
timestamp: (new Date()).toString(),
arguments: [],
currentDirectory: '',
filesRead: [],
@@ -119,6 +122,8 @@ module Playback {
};
wrapper.startReplayFromData = log => {
replayLog = log;
// Remove non-found files from the log (shouldn't really need them, but we still record them for diganostic purposes)
replayLog.filesRead = replayLog.filesRead.filter(f => f.result.contents !== undefined);
};
wrapper.endReplay = () => {
@@ -170,28 +175,50 @@ module Playback {
}
function findResultByPath<T>(wrapper: { resolvePath(s: string): string }, logArray: { path: string; result?: T }[], expectedPath: string, defaultValue?: T): T {
var results = logArray.filter(e => pathsAreEquivalent(e.path, expectedPath, wrapper));
if (results.length === 0) {
if (defaultValue === undefined) {
console.log('Resolved path: ' + wrapper.resolvePath(expectedPath));
console.log('Filenames were: ' + logArray.map(x => x.path).join(', '));
throw new Error('No matching result in log array for path: ' + expectedPath);
} else {
return defaultValue;
var normalizedName = Harness.Path.switchToForwardSlashes(expectedPath).toLowerCase();
// Try to find the result through normal filename
for (var i = 0; i < logArray.length; i++) {
if (Harness.Path.switchToForwardSlashes(logArray[i].path).toLowerCase() === normalizedName) {
return logArray[i].result;
}
}
return results[0].result;
// Fallback, try to resolve the target paths as well
if (replayLog.pathsResolved.length > 0) {
var normalizedResolvedName = wrapper.resolvePath(expectedPath).toLowerCase();
for (var i = 0; i < logArray.length; i++) {
if (wrapper.resolvePath(logArray[i].path).toLowerCase() === normalizedResolvedName) {
return logArray[i].result;
}
}
}
// If we got here, we didn't find a match
if (defaultValue === undefined) {
throw new Error('No matching result in log array for path: ' + expectedPath);
} else {
return defaultValue;
}
}
var pathEquivCache: any = {};
function pathsAreEquivalent(left: string, right: string, wrapper: { resolvePath(s: string): string }) {
var key = left + '-~~-' + right;
function areSame(a: string, b: string) {
return Harness.Path.switchToForwardSlashes(a).toLowerCase() === Harness.Path.switchToForwardSlashes(b).toLowerCase();
}
return areSame(left, right) || areSame(wrapper.resolvePath(left), right) || areSame(left, wrapper.resolvePath(right)) || areSame(wrapper.resolvePath(left), wrapper.resolvePath(right));
function check() {
if (Harness.Path.getFileName(left).toLowerCase() === Harness.Path.getFileName(right).toLowerCase()) {
return areSame(left, right) || areSame(wrapper.resolvePath(left), right) || areSame(left, wrapper.resolvePath(right)) || areSame(wrapper.resolvePath(left), wrapper.resolvePath(right));
}
}
if (pathEquivCache.hasOwnProperty(key)) {
return pathEquivCache[key];
} else {
return pathEquivCache[key] = check();
}
}
function noOpReplay(name: string) {
console.log("Swallowed write operation during replay: " + name);
//console.log("Swallowed write operation during replay: " + name);
}
export function wrapSystem(underlying: System): PlaybackSystem {
@@ -257,10 +284,15 @@ module Playback {
wrapper.resolvePath = recordReplay(wrapper.resolvePath, underlying)(
(path) => callAndRecord(underlying.resolvePath(path), recordLog.pathsResolved, { path: path }),
memoize((path) => findResultByFields(replayLog.pathsResolved, { path: path }, replayLog.currentDirectory ? replayLog.currentDirectory + '/' + path : path)));
memoize((path) => findResultByFields(replayLog.pathsResolved, { path: path }, !ts.isRootedDiskPath(ts.normalizeSlashes(path)) && replayLog.currentDirectory ? replayLog.currentDirectory + '/' + path : ts.normalizeSlashes(path))));
wrapper.readFile = recordReplay(wrapper.readFile, underlying)(
(path) => callAndRecord(underlying.readFile(path), recordLog.filesRead, { path: path, codepage: 0 }),
(path) => {
var result = underlying.readFile(path);
var logEntry = { path: path, codepage: 0, result: { contents: result, codepage: 0 } };
recordLog.filesRead.push(logEntry);
return result;
},
memoize((path) => findResultByPath(wrapper, replayLog.filesRead, path).contents));
wrapper.writeFile = recordReplay(wrapper.writeFile, underlying)(
+3 -17
View File
@@ -174,7 +174,7 @@ class ProjectRunner extends RunnerBase {
else {
var text = getSourceFileText(filename);
if (text !== undefined) {
sourceFile = ts.createSourceFile(filename, text, languageVersion);
sourceFile = ts.createSourceFile(filename, text, languageVersion, /*version:*/ "0");
}
}
@@ -187,7 +187,7 @@ class ProjectRunner extends RunnerBase {
getDefaultLibFilename: () => "lib.d.ts",
writeFile: writeFile,
getCurrentDirectory: getCurrentDirectory,
getCanonicalFileName: ts.getCanonicalFileName,
getCanonicalFileName: Harness.Compiler.getCanonicalFileName,
useCaseSensitiveFileNames: () => sys.useCaseSensitiveFileNames,
getNewLine: () => sys.newLine
};
@@ -293,27 +293,13 @@ class ProjectRunner extends RunnerBase {
}
function getErrorsBaseline(compilerResult: CompileProjectFilesResult) {
// This is copied from tc.ts's reportError to replicate what tc does
var errors = "";
for (var i = 0; i < compilerResult.errors.length; i++) {
var error = compilerResult.errors[i];
// TODO(jfreeman): Remove assert
ts.Debug.assert(error.messageText.indexOf("{NL}") < 0);
if (error.file) {
var loc = error.file.getLineAndCharacterFromPosition(error.start);
errors += error.file.filename + "(" + loc.line + "," + loc.character + "): " + error.messageText + sys.newLine;
}
else {
errors += error.messageText + sys.newLine;
}
}
var inputFiles = ts.map(ts.filter(compilerResult.program.getSourceFiles(),
sourceFile => sourceFile.filename !== "lib.d.ts"),
sourceFile => {
return { unitName: sourceFile.filename, content: sourceFile.text };
});
var diagnostics = ts.map(compilerResult.errors, error => Harness.Compiler.getMinimalDiagnostic(error));
var errors = Harness.Compiler.minimalDiagnosticsToString(diagnostics);
errors += sys.newLine + sys.newLine + Harness.Compiler.getErrorBaseline(inputFiles, diagnostics);
return errors;
+5 -8
View File
@@ -68,17 +68,11 @@ if (testConfigFile !== '') {
runners.push(new GeneratedFourslashRunner());
break;
case 'unittests':
runners.push(new UnitTestRunner(UnittestTestType.Compiler));
runners.push(new UnitTestRunner());
break;
case 'rwc':
runners.push(new RWCRunner());
break;
case 'ls':
runners.push(new UnitTestRunner(UnittestTestType.LanguageService));
break;
case 'services':
runners.push(new UnitTestRunner(UnittestTestType.Services));
break;
case 'reverse':
reverse = true;
break;
@@ -96,9 +90,12 @@ if (runners.length === 0) {
runners.push(new ProjectRunner());
}
//// language services
// language services
runners.push(new FourslashRunner());
//runners.push(new GeneratedFourslashRunner());
// unittests
runners.push(new UnitTestRunner());
}
sys.newLine = '\r\n';
+69 -102
View File
@@ -5,27 +5,6 @@
/// <reference path='..\compiler\commandLineParser.ts'/>
module RWC {
class RWCEmitter implements Harness.Compiler.IEmitterIOHost {
public outputs: { [filename: string]: string; } = {};
constructor() { }
writeFile(path: string, contents: string, writeByteOrderMark: boolean) {
if (path in this.outputs) throw new Error('Emitter attempted to write to "' + path + '" twice');
this.outputs[path] = contents;
}
directoryExists(s: string) {
return false;
}
fileExists(s: string) {
return true;
}
resolvePath(s: string) {
return s;
}
}
function runWithIOLog(ioLog: IOLog, fn: () => void) {
var oldSys = sys;
@@ -41,32 +20,26 @@ module RWC {
}
}
function collateOutputs(emitterIOHost: RWCEmitter, fnTest: (s: string) => {}, clean?: (s: string) => string) {
function collateOutputs(outputFiles: Harness.Compiler.GeneratedFile[], clean?: (s: string) => string) {
// Collect, test, and sort the filenames
var files: string[] = [];
for (var fn in emitterIOHost.outputs) {
if (emitterIOHost.outputs.hasOwnProperty(fn) && fnTest(fn)) {
files.push(fn);
}
}
function cleanName(fn: string) {
var lastSlash = Harness.Path.switchToForwardSlashes(fn).lastIndexOf('/');
return fn.substr(lastSlash + 1).toLowerCase();
}
files.sort((a, b) => cleanName(a).localeCompare(cleanName(b)));
outputFiles.sort((a, b) => cleanName(a.fileName).localeCompare(cleanName(b.fileName)));
// Emit them
var result = '';
files.forEach(fn => {
ts.forEach(outputFiles, outputFile => {
// Some extra spacing if this isn't the first file
if (result.length) result = result + '\r\n\r\n';
// Filename header + content
result = result + '/*====== ' + fn + ' ======*/\r\n';
result = result + '/*====== ' + outputFile.fileName + ' ======*/\r\n';
if (clean) {
result = result + clean(emitterIOHost.outputs[fn]);
result = result + clean(outputFile.code);
} else {
result = result + emitterIOHost.outputs[fn];
result = result + outputFile.code;
}
});
return result;
@@ -86,77 +59,54 @@ module RWC {
});
});
var emitterIOHost = new RWCEmitter();
var inputFiles: { unitName: string; content: string; }[] = [];
var otherFiles: { unitName: string; content: string; }[] = [];
var compilerResult: Harness.Compiler.CompilerResult;
it('can compile', () => {
runWithIOLog(ioLog, () => {
harnessCompiler.reset();
var inputList: string[] = opts.filenames;
var noDefaultLib = false;
var libPath = Harness.IO.directoryName(sys.getExecutingFilePath()) + '/lib.d.ts';
if (!opts.options.noResolve) {
var filemap: any = {};
var host: ts.CompilerHost = {
getCurrentDirectory: () => sys.getCurrentDirectory(),
getCancellationToken: (): any => undefined,
getSourceFile: (fileName, languageVersion) => {
var fileContents: string;
try {
fileContents = sys.readFile(fileName);
}
catch (e) {
// Leave fileContents undefined;
}
return ts.createSourceFile(fileName, fileContents, languageVersion);
},
getDefaultLibFilename: () => libPath,
writeFile: (fn, contents) => emitterIOHost.writeFile(fn, contents, false),
getCanonicalFileName: ts.getCanonicalFileName,
useCaseSensitiveFileNames: () => sys.useCaseSensitiveFileNames,
getNewLine: () => sys.newLine
};
var resolvedProgram = ts.createProgram(opts.filenames, opts.options, host);
resolvedProgram.getSourceFiles().forEach(sourceFile => {
noDefaultLib = noDefaultLib || sourceFile.hasNoDefaultLib;
if (inputList.indexOf(sourceFile.filename) === -1) {
inputList.push(sourceFile.filename);
}
});
}
if (!opts.options.noLib && !noDefaultLib) {
inputList.push(libPath);
}
harnessCompiler.reset();
harnessCompiler.setCompilerSettingsFromOptions(opts.options);
// Load the files
inputList.forEach((item: string) => {
var resolvedPath = Harness.Path.switchToForwardSlashes(sys.resolvePath(item));
try {
var content = sys.readFile(resolvedPath);
}
catch (e) {
// Leave content undefined.
}
harnessCompiler.addInputFile({ unitName: resolvedPath, content: content });
ts.forEach(opts.filenames, fileName => {
inputFiles.push(getHarnessCompilerInputUnit(fileName));
});
harnessCompiler.setCompilerOptions();
if (!opts.options.noLib) {
// Find the lib.d.ts file in the input file and add it to the input files list
var libFile = ts.forEach(ioLog.filesRead, fileRead=> Harness.isLibraryFile(fileRead.path) ? fileRead.path : undefined);
if (libFile) {
inputFiles.push(getHarnessCompilerInputUnit(libFile));
}
}
ts.forEach(ioLog.filesRead, fileRead => {
var resolvedPath = Harness.Path.switchToForwardSlashes(sys.resolvePath(fileRead.path));
var inInputList = ts.forEach(inputFiles, inputFile=> inputFile.unitName === resolvedPath);
if (!inInputList) {
// Add the file to other files
otherFiles.push(getHarnessCompilerInputUnit(fileRead.path));
}
});
// do not use lib since we already read it in above
opts.options.noLib = true;
// Emit the results
harnessCompiler.emitAll(emitterIOHost);
harnessCompiler.emitAllDeclarations();
var compilationErrors = harnessCompiler.reportCompilationErrors();
// Create an error baseline
compilationErrors.forEach(err => {
errors += err.filename + ' line ' + err.line + ': ' + err.message + '\r\n';
});
harnessCompiler.compileFiles(inputFiles, otherFiles, compileResult => {
compilerResult = compileResult;
}, /*settingsCallback*/ undefined, opts.options);
});
function getHarnessCompilerInputUnit(fileName: string) {
var resolvedPath = Harness.Path.switchToForwardSlashes(sys.resolvePath(fileName));
try {
var content = sys.readFile(resolvedPath);
}
catch (e) {
// Leave content undefined.
}
return { unitName: resolvedPath, content: content };
}
});
// Baselines
@@ -165,29 +115,46 @@ module RWC {
it('has the expected emitted code', () => {
Harness.Baseline.runBaseline('has the expected emitted code', baseName + '.output.js', () => {
return collateOutputs(emitterIOHost, fn => fn.substr(fn.length - '.js'.length) === '.js', s => SyntacticCleaner.clean(s));
return collateOutputs(compilerResult.files, s => SyntacticCleaner.clean(s));
}, false, baselineOpts);
});
it('has the expected declaration file content', () => {
Harness.Baseline.runBaseline('has the expected declaration file content', baseName + '.d.ts', () => {
var result = collateOutputs(emitterIOHost, fn => fn.substr(fn.length - '.d.ts'.length) === '.d.ts');
return result.length > 0 ? result : null;
if (compilerResult.errors.length || !compilerResult.declFilesCode.length) {
return null;
}
return collateOutputs(compilerResult.declFilesCode);
}, false, baselineOpts);
});
/*
it('has the expected source maps', () => {
Harness.Baseline.runBaseline('has the expected source maps', baseName + '.map', () => {
var result = collateOutputs(emitterIOHost, fn => fn.substr(fn.length - '.map'.length) === '.map');
return result.length > 0 ? result : null;
if (!compilerResult.sourceMaps.length) {
return null;
}
return collateOutputs(compilerResult.sourceMaps);
}, false, baselineOpts);
});
*/
it('has correct source map record', () => {
if (compilerResult.sourceMapRecord) {
Harness.Baseline.runBaseline('has correct source map record', baseName + '.sourcemap.txt', () => {
return compilerResult.sourceMapRecord;
}, false, baselineOpts);
}
});
it('has the expected errors', () => {
Harness.Baseline.runBaseline('has the expected errors', baseName + '.errors.txt', () => {
return errors.length > 0 ? errors : null;
if (compilerResult.errors.length === 0) {
return null;
}
return Harness.Compiler.minimalDiagnosticsToString(compilerResult.errors) +
sys.newLine + sys.newLine +
Harness.Compiler.getErrorBaseline(inputFiles.concat(otherFiles), compilerResult.errors);
}, false, baselineOpts);
});
+82 -164
View File
@@ -1,180 +1,98 @@
/** TODO: Rewrite entirely **/
class TypeWriterWalker {
constructor(public filename: string, public compiler: any) {
}
public run() { }
public results: any[];
interface TypeWriterResult {
line: number;
column: number;
syntaxKind: string;
sourceText: string;
type: string;
}
/*
class TypeWriterWalker extends TypeScript.SyntaxWalker {
private document: TypeScript.Document;
private syntaxTree: TypeScript.SyntaxTree;
private text: TypeScript.ISimpleText;
private currentPosition = 0;
class TypeWriterWalker {
results: TypeWriterResult[];
currentSourceFile: ts.SourceFile;
public results: {
line: number;
column: number;
syntaxKind: string;
identifierName: string;
type: string;
}[] = [];
constructor(public filename: string, public compiler: TypeScript.TypeScriptCompiler) {
super();
this.document = compiler.getDocument(filename);
this.syntaxTree = this.document.syntaxTree();
this.text = this.syntaxTree.text;
constructor(public checker: ts.TypeChecker) {
}
public run() {
TypeScript.visitNodeOrToken(this, this.syntaxTree.sourceUnit());
public getTypes(fileName: string): TypeWriterResult[] {
var sourceFile = this.checker.getProgram().getSourceFile(fileName);
this.currentSourceFile = sourceFile;
this.results = [];
this.visitNode(sourceFile);
return this.results;
}
private isName(token: TypeScript.ISyntaxToken) {
var parent = token.parent;
private visitNode(node: ts.Node): void {
switch (node.kind) {
// Should always log expressions that are not tokens
// Also, always log the "this" keyword
// TODO: Ideally we should log all expressions, but to compare to the
// old typeWriter baselines, suppress tokens
case ts.SyntaxKind.ThisKeyword:
case ts.SyntaxKind.SuperKeyword:
case ts.SyntaxKind.ArrayLiteral:
case ts.SyntaxKind.ObjectLiteral:
case ts.SyntaxKind.PropertyAccess:
case ts.SyntaxKind.IndexedAccess:
case ts.SyntaxKind.CallExpression:
case ts.SyntaxKind.NewExpression:
case ts.SyntaxKind.TypeAssertion:
case ts.SyntaxKind.ParenExpression:
case ts.SyntaxKind.FunctionExpression:
case ts.SyntaxKind.ArrowFunction:
case ts.SyntaxKind.PrefixOperator:
case ts.SyntaxKind.PostfixOperator:
case ts.SyntaxKind.BinaryExpression:
case ts.SyntaxKind.ConditionalExpression:
this.log(node, this.getTypeOfNode(node));
break;
switch (parent.kind()) {
case TypeScript.SyntaxKind.ContinueStatement:
return (<TypeScript.ContinueStatementSyntax>parent).identifier === token;
case TypeScript.SyntaxKind.BreakStatement:
return (<TypeScript.BreakStatementSyntax>parent).identifier === token;
case TypeScript.SyntaxKind.LabeledStatement:
return (<TypeScript.LabeledStatementSyntax>parent).identifier === token;
// Should not change expression status (maybe expressions)
// TODO: Again, ideally should log number and string literals too,
// but to be consistent with the old typeWriter, just log identifiers
case ts.SyntaxKind.Identifier:
var identifier = <ts.Identifier>node;
if (!this.isLabel(identifier)) {
var type = this.getTypeOfNode(identifier);
this.log(node, type);
}
break;
}
ts.forEachChild(node, child => this.visitNode(child));
}
private isLabel(identifier: ts.Identifier): boolean {
var parent = identifier.parent;
switch (parent.kind) {
case ts.SyntaxKind.ContinueStatement:
case ts.SyntaxKind.BreakStatement:
return (<ts.BreakOrContinueStatement>parent).label === identifier;
case ts.SyntaxKind.LabelledStatement:
return (<ts.LabelledStatement>parent).label === identifier;
}
return false;
}
public visitToken(token: TypeScript.ISyntaxToken) {
if (token.kind() === TypeScript.SyntaxKind.IdentifierName) {
if (!this.isName(token)) {
this.log(token);
}
} else if (token.kind() === TypeScript.SyntaxKind.ThisKeyword) {
this.log(token);
}
return super.visitToken(token);
private log(node: ts.Node, type: ts.Type): void {
var actualPos = ts.skipTrivia(this.currentSourceFile.text, node.pos);
var lineAndCharacter = this.currentSourceFile.getLineAndCharacterFromPosition(actualPos);
var sourceText = ts.getSourceTextOfNodeFromSourceText(this.currentSourceFile.text, node);
// If we got an unknown type, we temporarily want to fall back to just pretending the name
// (source text) of the node is the type. This is to align with the old typeWriter to make
// baseline comparisons easier. In the long term, we will want to just call typeToString
this.results.push({
line: lineAndCharacter.line - 1,
column: lineAndCharacter.character,
syntaxKind: ts.SyntaxKind[node.kind],
sourceText: sourceText,
type: this.checker.typeToString(type, node.parent, ts.TypeFormatFlags.None)
});
}
public visitNode(node: TypeScript.ISyntaxNode) {
return super.visitNode(node);
}
private getAstForElement(element: TypeScript.ISyntaxElement) {
if (!TypeScript.isShared(element)) {
return element;
}
}
private getEnclosingScopeSymbol(ast: TypeScript.ISyntaxElement): TypeScript.PullSymbol {
var enclosingScopeAST = TypeScript.DeclarationEmitter.getEnclosingContainer(ast);
if (enclosingScopeAST) {
var typeInfo = this.compiler.pullGetSymbolInformationFromAST(enclosingScopeAST, this.document);
return typeInfo ? typeInfo.symbol : null;
}
return null;
}
private getTypeOfElement(element: TypeScript.ISyntaxElement) {
var ast = this.getAstForElement(element);
if (ast) {
var typeInfo = this.compiler.pullGetSymbolInformationFromAST(ast, this.document);
if (typeInfo.symbol && typeInfo.symbol.type) {
var enclosingScope = this.getEnclosingScopeSymbol(ast);
return typeInfo.symbol.type.toString(enclosingScope);
}
}
return "<unknown>";
}
public visitPrefixUnaryExpression(node: TypeScript.PrefixUnaryExpressionSyntax) {
this.log(node);
return super.visitPrefixUnaryExpression(node);
}
public visitArrayLiteralExpression(node: TypeScript.ArrayLiteralExpressionSyntax) {
this.log(node);
return super.visitArrayLiteralExpression(node);
}
public visitOmittedExpression(node: TypeScript.OmittedExpressionSyntax) {
this.log(node);
return super.visitOmittedExpression(node);
}
public visitParenthesizedExpression(node: TypeScript.ParenthesizedExpressionSyntax) {
this.log(node);
return super.visitParenthesizedExpression(node);
}
public visitSimpleArrowFunctionExpression(node: TypeScript.SimpleArrowFunctionExpressionSyntax) {
this.log(node);
return super.visitSimpleArrowFunctionExpression(node);
}
public visitParenthesizedArrowFunctionExpression(node: TypeScript.ParenthesizedArrowFunctionExpressionSyntax) {
this.log(node);
return super.visitParenthesizedArrowFunctionExpression(node);
}
public visitObjectCreationExpression(node: TypeScript.ObjectCreationExpressionSyntax) {
this.log(node);
return super.visitObjectCreationExpression(node);
}
public visitCastExpression(node: TypeScript.CastExpressionSyntax) {
this.log(node);
return super.visitCastExpression(node);
}
public visitObjectLiteralExpression(node: TypeScript.ObjectLiteralExpressionSyntax) {
this.log(node);
return super.visitObjectLiteralExpression(node);
}
public visitFunctionExpression(node: TypeScript.FunctionExpressionSyntax) {
this.log(node);
return super.visitFunctionExpression(node);
}
public visitTypeOfExpression(node: TypeScript.TypeOfExpressionSyntax) {
this.log(node);
return super.visitTypeOfExpression(node);
}
public visitDeleteExpression(node: TypeScript.DeleteExpressionSyntax) {
this.log(node);
return super.visitDeleteExpression(node);
}
public visitVoidExpression(node: TypeScript.VoidExpressionSyntax) {
this.log(node);
return super.visitVoidExpression(node);
}
public visitMemberAccessExpression(node: TypeScript.MemberAccessExpressionSyntax) {
this.log(node);
return super.visitMemberAccessExpression(node);
}
public visitPostfixUnaryExpression(node: TypeScript.PostfixUnaryExpressionSyntax) {
this.log(node);
return super.visitPostfixUnaryExpression(node);
}
public visitElementAccessExpression(node: TypeScript.ElementAccessExpressionSyntax) {
this.log(node);
return super.visitElementAccessExpression(node);
}
public visitInvocationExpression(node: TypeScript.InvocationExpressionSyntax) {
this.log(node);
return super.visitInvocationExpression(node);
}
public visitBinaryExpression(node: TypeScript.BinaryExpressionSyntax) {
this.log(node);
return super.visitBinaryExpression(node);
}
public visitConditionalExpression(node: TypeScript.ConditionalExpressionSyntax) {
this.log(node);
return super.visitConditionalExpression(node);
}
public log(node: TypeScript.ISyntaxNodeOrToken) {
var _fullStart = TypeScript.fullStart(node);
if (_fullStart >= 0) {
var pos = this.document.lineMap().getLineAndCharacterFromPosition(_fullStart);
this.results.push({ line: pos.line(), column: pos.character(), syntaxKind: TypeScript.SyntaxKind[node.kind()], identifierName: TypeScript.fullText(node, this.text).trim(), type: this.getTypeOfElement(node) });
}
private getTypeOfNode(node: ts.Node): ts.Type {
var type = this.checker.getTypeOfNode(node);
ts.Debug.assert(type, "type doesn't exist");
return type;
}
}
*/
+6 -22
View File
@@ -1,31 +1,13 @@
///<reference path="harness.ts" />
///<reference path="runnerbase.ts" />
enum UnittestTestType {
Compiler,
LanguageService,
Services,
}
class UnitTestRunner extends RunnerBase {
constructor(public testType?: UnittestTestType) {
constructor() {
super();
}
public initializeTests() {
switch (this.testType) {
case UnittestTestType.Compiler:
this.tests = this.enumerateFiles('tests/cases/unittests/compiler');
break;
case UnittestTestType.LanguageService:
this.tests = this.enumerateFiles('tests/cases/unittests/ls');
break;
default:
if (this.tests.length === 0) {
throw new Error('Unsupported test cases: ' + this.testType);
}
break;
}
this.tests = this.enumerateFiles('tests/cases/unittests/services');
var outfile = new Harness.Compiler.WriterAggregator()
var outerr = new Harness.Compiler.WriterAggregator();
@@ -38,7 +20,7 @@ class UnitTestRunner extends RunnerBase {
});
harnessCompiler.addInputFiles(toBeAdded);
harnessCompiler.setCompilerOptions({ noResolve: true });
var stdout = new Harness.Compiler.EmitterIOHost();
var emitDiagnostics = harnessCompiler.emitAll(stdout);
var results = stdout.toArray();
@@ -59,7 +41,9 @@ class UnitTestRunner extends RunnerBase {
before: before,
after: after,
Harness: Harness,
IO: Harness.IO
IO: Harness.IO,
ts: ts,
TypeScript: TypeScript
// FourSlash: FourSlash
};
}
+37 -80
View File
@@ -24,93 +24,50 @@ module TypeScript.Services {
public static getMatchSpans(syntaxTree: TypeScript.SyntaxTree, position: number): TypeScript.TextSpan[] {
var result: TypeScript.TextSpan[] = [];
var currentToken = findToken(syntaxTree.sourceUnit(), position);
var token = findToken(syntaxTree.sourceUnit(), position);
BraceMatcher.getMatchingCloseBrace(currentToken, position, result);
BraceMatcher.getMatchingOpenBrace(currentToken, position, result);
if (start(token) === position) {
var matchKind = BraceMatcher.getMatchingTokenKind(token);
if (matchKind !== null) {
var parentElement = token.parent;
for (var i = 0, n = childCount(parentElement); i < n; i++) {
var current = childAt(parentElement, i);
if (current !== null && fullWidth(current) > 0) {
if (current.kind() === matchKind) {
var range1 = new TypeScript.TextSpan(start(token), width(token));
var range2 = new TypeScript.TextSpan(start(current), width(current));
if (range1.start() < range2.start()) {
result.push(range1, range2);
}
else {
result.push(range2, range1);
}
break;
}
}
}
}
}
return result;
}
private static getMatchingCloseBrace(currentToken: TypeScript.ISyntaxToken, position: number, result: TypeScript.TextSpan[]) {
if (start(currentToken) === position) {
var closingBraceKind = BraceMatcher.getMatchingCloseBraceTokenKind(currentToken);
if (closingBraceKind !== null) {
var parentElement = currentToken.parent;
var currentPosition = fullStart(currentToken.parent);
for (var i = 0, n = childCount(parentElement); i < n; i++) {
var element = childAt(parentElement, i);
if (element !== null && fullWidth(element) > 0) {
if (element.kind() === closingBraceKind) {
var range1 = new TypeScript.TextSpan(position, width(currentToken));
var range2 = new TypeScript.TextSpan(currentPosition + leadingTriviaWidth(element), width(element));
result.push(range1, range2);
break;
}
currentPosition += fullWidth(element);
}
}
}
}
}
private static getMatchingOpenBrace(currentToken: TypeScript.ISyntaxToken, position: number, result: TypeScript.TextSpan[]) {
// Check if the current token to the left is a close brace
if (currentToken.fullStart() === position) {
currentToken = previousToken(currentToken);
private static getMatchingTokenKind(token: TypeScript.ISyntaxToken): TypeScript.SyntaxKind {
switch (token.kind()) {
case TypeScript.SyntaxKind.OpenBraceToken: return TypeScript.SyntaxKind.CloseBraceToken
case TypeScript.SyntaxKind.OpenParenToken: return TypeScript.SyntaxKind.CloseParenToken;
case TypeScript.SyntaxKind.OpenBracketToken: return TypeScript.SyntaxKind.CloseBracketToken;
case TypeScript.SyntaxKind.LessThanToken: return TypeScript.SyntaxKind.GreaterThanToken;
case TypeScript.SyntaxKind.CloseBraceToken: return TypeScript.SyntaxKind.OpenBraceToken
case TypeScript.SyntaxKind.CloseParenToken: return TypeScript.SyntaxKind.OpenParenToken;
case TypeScript.SyntaxKind.CloseBracketToken: return TypeScript.SyntaxKind.OpenBracketToken;
case TypeScript.SyntaxKind.GreaterThanToken: return TypeScript.SyntaxKind.LessThanToken;
}
if (currentToken !== null && start(currentToken) === (position - 1)) {
var openBraceKind = BraceMatcher.getMatchingOpenBraceTokenKind(currentToken);
if (openBraceKind !== null) {
var parentElement = currentToken.parent;
var currentPosition = fullStart(currentToken.parent) + fullWidth(parentElement);
for (var i = childCount(parentElement) - 1 ; i >= 0; i--) {
var element = childAt(parentElement, i);
if (element !== null && fullWidth(element) > 0) {
if (element.kind() === openBraceKind) {
var range1 = new TypeScript.TextSpan(position - 1, width(currentToken));
var range2 = new TypeScript.TextSpan(currentPosition - lastToken(element).trailingTriviaWidth() - width(element), width(element));
result.push(range1, range2);
break;
}
currentPosition -= fullWidth(element);
}
}
}
}
}
private static getMatchingCloseBraceTokenKind(positionedElement: TypeScript.ISyntaxElement): TypeScript.SyntaxKind {
var element = positionedElement !== null && positionedElement;
switch (element.kind()) {
case TypeScript.SyntaxKind.OpenBraceToken:
return TypeScript.SyntaxKind.CloseBraceToken;
case TypeScript.SyntaxKind.OpenParenToken:
return TypeScript.SyntaxKind.CloseParenToken;
case TypeScript.SyntaxKind.OpenBracketToken:
return TypeScript.SyntaxKind.CloseBracketToken;
case TypeScript.SyntaxKind.LessThanToken:
return TypeScript.SyntaxUtilities.isAngleBracket(positionedElement) ? TypeScript.SyntaxKind.GreaterThanToken : null;
}
return null;
}
private static getMatchingOpenBraceTokenKind(positionedElement: TypeScript.ISyntaxElement): TypeScript.SyntaxKind {
var element = positionedElement !== null && positionedElement;
switch (element.kind()) {
case TypeScript.SyntaxKind.CloseBraceToken:
return TypeScript.SyntaxKind.OpenBraceToken
case TypeScript.SyntaxKind.CloseParenToken:
return TypeScript.SyntaxKind.OpenParenToken;
case TypeScript.SyntaxKind.CloseBracketToken:
return TypeScript.SyntaxKind.OpenBracketToken;
case TypeScript.SyntaxKind.GreaterThanToken:
return TypeScript.SyntaxUtilities.isAngleBracket(positionedElement) ? TypeScript.SyntaxKind.LessThanToken : null;
}
return null;
}
}
}
}
+50 -59
View File
@@ -4,16 +4,13 @@
///<reference path='references.ts' />
module TypeScript.Services.Breakpoints {
function createBreakpointSpanInfo(parentElement: TypeScript.ISyntaxElement, ...childElements: TypeScript.ISyntaxElement[]): ts.SpanInfo {
function createBreakpointSpanInfo(parentElement: TypeScript.ISyntaxElement, ...childElements: TypeScript.ISyntaxElement[]): TextSpan {
if (!parentElement) {
return null;
}
if (childElements.length == 0) {
return {
minChar: TypeScript.start(parentElement),
limChar: TypeScript.end(parentElement)
};
return TextSpan.fromBounds(TypeScript.start(parentElement), TypeScript.end(parentElement));
}
var start: number;
@@ -28,24 +25,18 @@ module TypeScript.Services.Breakpoints {
}
}
return {
minChar: start,
limChar: end
};
return TextSpan.fromBounds(start, end);
}
function createBreakpointSpanInfoWithLimChar(startElement: TypeScript.ISyntaxElement, limChar: number): ts.SpanInfo {
return {
minChar: start(startElement),
limChar: limChar
};
function createBreakpointSpanInfoWithLimChar(startElement: TypeScript.ISyntaxElement, limChar: number): TextSpan {
return TextSpan.fromBounds(start(startElement), limChar);
}
class BreakpointResolver {
constructor(private posLine: number, private lineMap: TypeScript.LineMap) {
}
private breakpointSpanOfToken(positionedToken: TypeScript.ISyntaxToken): ts.SpanInfo {
private breakpointSpanOfToken(positionedToken: TypeScript.ISyntaxToken): TextSpan {
switch (positionedToken.kind()) {
case TypeScript.SyntaxKind.OpenBraceToken:
return this.breakpointSpanOfOpenBrace(positionedToken);
@@ -74,7 +65,7 @@ module TypeScript.Services.Breakpoints {
return this.breakpointSpanOfContainingNode(positionedToken);
}
private breakpointSpanOfOpenBrace(openBraceToken: TypeScript.ISyntaxToken): ts.SpanInfo {
private breakpointSpanOfOpenBrace(openBraceToken: TypeScript.ISyntaxToken): TextSpan {
var container = Syntax.containingNode(openBraceToken);
if (container) {
var originalContainer = container;
@@ -168,7 +159,7 @@ module TypeScript.Services.Breakpoints {
return null;
}
private breakpointSpanOfCloseBrace(closeBraceToken: TypeScript.ISyntaxToken): ts.SpanInfo {
private breakpointSpanOfCloseBrace(closeBraceToken: TypeScript.ISyntaxToken): TextSpan {
var container = Syntax.containingNode(closeBraceToken);
if (container) {
var originalContainer = container;
@@ -243,7 +234,7 @@ module TypeScript.Services.Breakpoints {
}
private breakpointSpanOfComma(commaToken: TypeScript.ISyntaxToken): ts.SpanInfo {
private breakpointSpanOfComma(commaToken: TypeScript.ISyntaxToken): TextSpan {
var commaParent = commaToken.parent;
if (isSeparatedList(commaParent)) {
var grandParent = commaParent.parent;
@@ -271,7 +262,7 @@ module TypeScript.Services.Breakpoints {
return this.breakpointSpanOfContainingNode(commaToken);
}
private breakpointSpanOfCloseParen(closeParenToken: TypeScript.ISyntaxToken): ts.SpanInfo {
private breakpointSpanOfCloseParen(closeParenToken: TypeScript.ISyntaxToken): TextSpan {
var closeParenParent = closeParenToken.parent;
if (closeParenParent) {
switch (closeParenParent.kind()) {
@@ -293,7 +284,7 @@ module TypeScript.Services.Breakpoints {
return blockSyntax.statements && blockSyntax.statements.length != 0;
}
private breakpointSpanOfFirstStatementInBlock(blockNode: TypeScript.ISyntaxNode): ts.SpanInfo {
private breakpointSpanOfFirstStatementInBlock(blockNode: TypeScript.ISyntaxNode): TextSpan {
if (!blockNode) {
return null;
}
@@ -316,7 +307,7 @@ module TypeScript.Services.Breakpoints {
}
}
private breakpointSpanOfLastStatementInBlock(blockNode: TypeScript.ISyntaxNode): ts.SpanInfo {
private breakpointSpanOfLastStatementInBlock(blockNode: TypeScript.ISyntaxNode): TextSpan {
if (!blockNode) {
return null;
}
@@ -339,7 +330,7 @@ module TypeScript.Services.Breakpoints {
}
}
private breakpointSpanOfFirstChildOfSyntaxList(positionedList: TypeScript.ISyntaxNodeOrToken[]): ts.SpanInfo {
private breakpointSpanOfFirstChildOfSyntaxList(positionedList: TypeScript.ISyntaxNodeOrToken[]): TextSpan {
if (!positionedList) {
return null;
}
@@ -363,7 +354,7 @@ module TypeScript.Services.Breakpoints {
}
}
private breakpointSpanOfLastChildOfSyntaxList(positionedList: TypeScript.ISyntaxNodeOrToken[]): ts.SpanInfo {
private breakpointSpanOfLastChildOfSyntaxList(positionedList: TypeScript.ISyntaxNodeOrToken[]): TextSpan {
if (!positionedList) {
return null;
}
@@ -385,7 +376,7 @@ module TypeScript.Services.Breakpoints {
}
}
private breakpointSpanOfNode(positionedNode: TypeScript.ISyntaxNode): ts.SpanInfo {
private breakpointSpanOfNode(positionedNode: ISyntaxNode): TextSpan {
var node = positionedNode;
switch (node.kind()) {
// Declarations with elements
@@ -493,7 +484,7 @@ module TypeScript.Services.Breakpoints {
}
return false;
}
private isInitializerOfForStatement(expressionNode: TypeScript.ISyntaxNode): boolean {
if (!expressionNode) {
return false;
@@ -552,12 +543,12 @@ module TypeScript.Services.Breakpoints {
return false;
}
private breakpointOfLeftOfCommaExpression(commaExpressionNode: TypeScript.ISyntaxNode): ts.SpanInfo {
private breakpointOfLeftOfCommaExpression(commaExpressionNode: TypeScript.ISyntaxNode): TextSpan {
var commaExpression = <TypeScript.BinaryExpressionSyntax>commaExpressionNode;
return this.breakpointSpanOf(commaExpression.left);
}
private breakpointOfExpression(expressionNode: TypeScript.ISyntaxNode): ts.SpanInfo {
private breakpointOfExpression(expressionNode: TypeScript.ISyntaxNode): TextSpan {
if (this.isInitializerOfForStatement(expressionNode) ||
this.isConditionOfForStatement(expressionNode) ||
this.isIncrememtorOfForStatement(expressionNode)) {
@@ -582,7 +573,7 @@ module TypeScript.Services.Breakpoints {
return this.breakpointSpanOfContainingNode(expressionNode);
}
private breakpointSpanOfStatement(statementNode: TypeScript.ISyntaxNode): ts.SpanInfo {
private breakpointSpanOfStatement(statementNode: TypeScript.ISyntaxNode): TextSpan {
var statement = statementNode;
if (statement.kind() == TypeScript.SyntaxKind.EmptyStatement) {
return null;
@@ -722,7 +713,7 @@ module TypeScript.Services.Breakpoints {
return positionedNode && !TypeScript.SyntaxUtilities.isAmbientDeclarationSyntax(positionedNode);
}
private breakpointSpanOfDeclarationWithElements(positionedNode: TypeScript.ISyntaxNode): ts.SpanInfo {
private breakpointSpanOfDeclarationWithElements(positionedNode: TypeScript.ISyntaxNode): TextSpan {
if (!this.canHaveBreakpointInDeclaration(positionedNode)) {
return null;
}
@@ -751,7 +742,7 @@ module TypeScript.Services.Breakpoints {
return !!varDeclaratorSyntax.equalsValueClause;
}
private breakpointSpanOfVariableDeclarator(varDeclaratorNode: TypeScript.ISyntaxNode): ts.SpanInfo {
private breakpointSpanOfVariableDeclarator(varDeclaratorNode: TypeScript.ISyntaxNode): TextSpan {
if (!this.canHaveBreakpointInVariableDeclarator(varDeclaratorNode)) {
return null;
}
@@ -799,7 +790,7 @@ module TypeScript.Services.Breakpoints {
return false;
}
private breakpointSpanOfVariableDeclaration(varDeclarationNode: TypeScript.ISyntaxNode): ts.SpanInfo {
private breakpointSpanOfVariableDeclaration(varDeclarationNode: TypeScript.ISyntaxNode): TextSpan {
if (!this.canHaveBreakpointInDeclaration(varDeclarationNode)) {
return null;
}
@@ -830,7 +821,7 @@ module TypeScript.Services.Breakpoints {
return this.canHaveBreakpointInVariableDeclaration(<TypeScript.ISyntaxNode>variableStatement.variableDeclaration);
}
private breakpointSpanOfVariableStatement(varStatementNode: TypeScript.ISyntaxNode): ts.SpanInfo {
private breakpointSpanOfVariableStatement(varStatementNode: TypeScript.ISyntaxNode): TextSpan {
if (!this.canHaveBreakpointInVariableStatement(varStatementNode)) {
return null;
}
@@ -842,7 +833,7 @@ module TypeScript.Services.Breakpoints {
return createBreakpointSpanInfoWithLimChar(varStatementNode, end(childAt(varDeclarators, 0)));
}
private breakpointSpanOfParameter(parameterNode: TypeScript.ISyntaxNode): ts.SpanInfo {
private breakpointSpanOfParameter(parameterNode: TypeScript.ISyntaxNode): TextSpan {
if (parameterNode.parent.kind() === SyntaxKind.SimpleArrowFunctionExpression) {
return this.breakpointSpanOfNode(<ISyntaxNode>parameterNode.parent);
}
@@ -860,7 +851,7 @@ module TypeScript.Services.Breakpoints {
}
}
private breakpointSpanOfMemberVariableDeclaration(memberVarDeclarationNode: TypeScript.ISyntaxNode): ts.SpanInfo {
private breakpointSpanOfMemberVariableDeclaration(memberVarDeclarationNode: TypeScript.ISyntaxNode): TextSpan {
if (TypeScript.SyntaxUtilities.isAmbientDeclarationSyntax(memberVarDeclarationNode)) {
return null;
}
@@ -874,7 +865,7 @@ module TypeScript.Services.Breakpoints {
}
}
private breakpointSpanOfImportDeclaration(importDeclarationNode: TypeScript.ISyntaxNode): ts.SpanInfo {
private breakpointSpanOfImportDeclaration(importDeclarationNode: TypeScript.ISyntaxNode): TextSpan {
if (TypeScript.SyntaxUtilities.isAmbientDeclarationSyntax(importDeclarationNode)) {
return null;
}
@@ -883,7 +874,7 @@ module TypeScript.Services.Breakpoints {
return createBreakpointSpanInfo(importDeclarationNode, importSyntax.modifiers, importSyntax.importKeyword, importSyntax.identifier, importSyntax.equalsToken, importSyntax.moduleReference);
}
private breakpointSpanOfEnumDeclaration(enumDeclarationNode: TypeScript.ISyntaxNode): ts.SpanInfo {
private breakpointSpanOfEnumDeclaration(enumDeclarationNode: TypeScript.ISyntaxNode): TextSpan {
if (!this.canHaveBreakpointInDeclaration(enumDeclarationNode)) {
return null;
}
@@ -891,7 +882,7 @@ module TypeScript.Services.Breakpoints {
return createBreakpointSpanInfo(enumDeclarationNode);
}
private breakpointSpanOfFirstEnumElement(enumDeclarationNode: TypeScript.ISyntaxNode): ts.SpanInfo {
private breakpointSpanOfFirstEnumElement(enumDeclarationNode: TypeScript.ISyntaxNode): TextSpan {
var enumDeclarationSyntax = <TypeScript.EnumDeclarationSyntax>enumDeclarationNode;
var enumElements = enumDeclarationSyntax.enumElements;
if (enumElements && childCount(enumElements)) {
@@ -901,7 +892,7 @@ module TypeScript.Services.Breakpoints {
return null;
}
private breakpointSpanOfEnumElement(enumElementNode: TypeScript.ISyntaxNode): ts.SpanInfo {
private breakpointSpanOfEnumElement(enumElementNode: TypeScript.ISyntaxNode): TextSpan {
if (TypeScript.SyntaxUtilities.isAmbientDeclarationSyntax(enumElementNode)) {
return null;
}
@@ -909,45 +900,45 @@ module TypeScript.Services.Breakpoints {
return createBreakpointSpanInfo(enumElementNode);
}
private breakpointSpanOfIfStatement(ifStatementNode: TypeScript.ISyntaxNode): ts.SpanInfo {
private breakpointSpanOfIfStatement(ifStatementNode: TypeScript.ISyntaxNode): TextSpan {
var ifStatement = <TypeScript.IfStatementSyntax>ifStatementNode;
return createBreakpointSpanInfo(ifStatementNode, ifStatement.ifKeyword, ifStatement.openParenToken, ifStatement.condition, ifStatement.closeParenToken);
}
private breakpointSpanOfElseClause(elseClauseNode: TypeScript.ISyntaxNode): ts.SpanInfo {
private breakpointSpanOfElseClause(elseClauseNode: TypeScript.ISyntaxNode): TextSpan {
var elseClause = <TypeScript.ElseClauseSyntax>elseClauseNode;
return this.breakpointSpanOf(elseClause.statement);
}
private breakpointSpanOfForInStatement(forInStatementNode: TypeScript.ISyntaxNode): ts.SpanInfo {
private breakpointSpanOfForInStatement(forInStatementNode: TypeScript.ISyntaxNode): TextSpan {
var forInStatement = <TypeScript.ForInStatementSyntax>forInStatementNode;
return createBreakpointSpanInfo(forInStatementNode, forInStatement.forKeyword, forInStatement.openParenToken, forInStatement.variableDeclaration,
forInStatement.left, forInStatement.inKeyword, forInStatement.expression, forInStatement.closeParenToken);
}
private breakpointSpanOfForStatement(forStatementNode: TypeScript.ISyntaxNode): ts.SpanInfo {
private breakpointSpanOfForStatement(forStatementNode: TypeScript.ISyntaxNode): TextSpan {
var forStatement = <TypeScript.ForStatementSyntax>forStatementNode;
return this.breakpointSpanOf(forStatement.variableDeclaration
? <TypeScript.ISyntaxElement>forStatement.variableDeclaration
: forStatement.initializer);
}
private breakpointSpanOfWhileStatement(whileStatementNode: TypeScript.ISyntaxNode): ts.SpanInfo {
private breakpointSpanOfWhileStatement(whileStatementNode: TypeScript.ISyntaxNode): TextSpan {
var whileStatement = <TypeScript.WhileStatementSyntax>whileStatementNode;
return createBreakpointSpanInfo(whileStatementNode, whileStatement.whileKeyword, whileStatement.openParenToken, whileStatement.condition, whileStatement.closeParenToken);
}
private breakpointSpanOfDoStatement(doStatementNode: TypeScript.ISyntaxNode): ts.SpanInfo {
private breakpointSpanOfDoStatement(doStatementNode: TypeScript.ISyntaxNode): TextSpan {
var doStatement = <TypeScript.DoStatementSyntax>doStatementNode;
return createBreakpointSpanInfo(doStatementNode, doStatement.whileKeyword, doStatement.openParenToken, doStatement.condition, doStatement.closeParenToken);
}
private breakpointSpanOfSwitchStatement(switchStatementNode: TypeScript.ISyntaxNode): ts.SpanInfo {
private breakpointSpanOfSwitchStatement(switchStatementNode: TypeScript.ISyntaxNode): TextSpan {
var switchStatement = <TypeScript.SwitchStatementSyntax>switchStatementNode;
return createBreakpointSpanInfo(switchStatementNode, switchStatement.switchKeyword, switchStatement.openParenToken, switchStatement.expression, switchStatement.closeParenToken);
}
private breakpointSpanOfFirstStatementOfFirstCaseClause(switchStatementNode: TypeScript.ISyntaxNode): ts.SpanInfo {
private breakpointSpanOfFirstStatementOfFirstCaseClause(switchStatementNode: TypeScript.ISyntaxNode): TextSpan {
var switchStatement = <TypeScript.SwitchStatementSyntax>switchStatementNode;
if (switchStatement.switchClauses && switchStatement.switchClauses.length == 0) {
return null;
@@ -964,7 +955,7 @@ module TypeScript.Services.Breakpoints {
return this.breakpointSpanOfFirstChildOfSyntaxList(statements);
}
private breakpointSpanOfLastStatementOfLastCaseClause(switchStatementNode: TypeScript.ISyntaxNode): ts.SpanInfo {
private breakpointSpanOfLastStatementOfLastCaseClause(switchStatementNode: TypeScript.ISyntaxNode): TextSpan {
var switchStatement = <TypeScript.SwitchStatementSyntax>switchStatementNode;
if (switchStatement.switchClauses && switchStatement.switchClauses.length == 0) {
return null;
@@ -981,37 +972,37 @@ module TypeScript.Services.Breakpoints {
return this.breakpointSpanOfLastChildOfSyntaxList(statements);
}
private breakpointSpanOfCaseSwitchClause(caseClauseNode: TypeScript.ISyntaxNode): ts.SpanInfo {
private breakpointSpanOfCaseSwitchClause(caseClauseNode: TypeScript.ISyntaxNode): TextSpan {
var caseSwitchClause = <TypeScript.CaseSwitchClauseSyntax>caseClauseNode;
return this.breakpointSpanOfFirstChildOfSyntaxList(caseSwitchClause.statements);
}
private breakpointSpanOfDefaultSwitchClause(defaultSwithClauseNode: TypeScript.ISyntaxNode): ts.SpanInfo {
private breakpointSpanOfDefaultSwitchClause(defaultSwithClauseNode: TypeScript.ISyntaxNode): TextSpan {
var defaultSwitchClause = <TypeScript.DefaultSwitchClauseSyntax>defaultSwithClauseNode;
return this.breakpointSpanOfFirstChildOfSyntaxList(defaultSwitchClause.statements);
}
private breakpointSpanOfWithStatement(withStatementNode: TypeScript.ISyntaxNode): ts.SpanInfo {
private breakpointSpanOfWithStatement(withStatementNode: TypeScript.ISyntaxNode): TextSpan {
var withStatement = <TypeScript.WithStatementSyntax>withStatementNode;
return this.breakpointSpanOf(withStatement.statement);
}
private breakpointSpanOfTryStatement(tryStatementNode: TypeScript.ISyntaxNode): ts.SpanInfo {
private breakpointSpanOfTryStatement(tryStatementNode: TypeScript.ISyntaxNode): TextSpan {
var tryStatement = <TypeScript.TryStatementSyntax>tryStatementNode;
return this.breakpointSpanOfFirstStatementInBlock(<TypeScript.ISyntaxNode>tryStatement.block);
}
private breakpointSpanOfCatchClause(catchClauseNode: TypeScript.ISyntaxNode): ts.SpanInfo {
private breakpointSpanOfCatchClause(catchClauseNode: TypeScript.ISyntaxNode): TextSpan {
var catchClause = <TypeScript.CatchClauseSyntax>catchClauseNode;
return createBreakpointSpanInfo(catchClauseNode, catchClause.catchKeyword, catchClause.openParenToken, catchClause.identifier, catchClause.typeAnnotation, catchClause.closeParenToken);
}
private breakpointSpanOfFinallyClause(finallyClauseNode: TypeScript.ISyntaxNode): ts.SpanInfo {
private breakpointSpanOfFinallyClause(finallyClauseNode: TypeScript.ISyntaxNode): TextSpan {
var finallyClause = <TypeScript.FinallyClauseSyntax>finallyClauseNode;
return this.breakpointSpanOfFirstStatementInBlock(<TypeScript.ISyntaxNode>finallyClause.block);
}
private breakpointSpanOfParenthesizedArrowFunctionExpression(arrowFunctionExpression: ParenthesizedArrowFunctionExpressionSyntax): ts.SpanInfo {
private breakpointSpanOfParenthesizedArrowFunctionExpression(arrowFunctionExpression: ParenthesizedArrowFunctionExpressionSyntax): TextSpan {
if (arrowFunctionExpression.block) {
return this.breakpointSpanOfFirstStatementInBlock(arrowFunctionExpression.block);
}
@@ -1020,7 +1011,7 @@ module TypeScript.Services.Breakpoints {
}
}
private breakpointSpanOfSimpleArrowFunctionExpression(arrowFunctionExpression: SimpleArrowFunctionExpressionSyntax): ts.SpanInfo {
private breakpointSpanOfSimpleArrowFunctionExpression(arrowFunctionExpression: SimpleArrowFunctionExpressionSyntax): TextSpan {
if (arrowFunctionExpression.block) {
return this.breakpointSpanOfFirstStatementInBlock(arrowFunctionExpression.block);
}
@@ -1029,7 +1020,7 @@ module TypeScript.Services.Breakpoints {
}
}
private breakpointSpanOfContainingNode(positionedElement: ISyntaxElement): ts.SpanInfo {
private breakpointSpanOfContainingNode(positionedElement: ISyntaxElement): TextSpan {
var current = positionedElement.parent;
while (!isNode(current)) {
current = current.parent;
@@ -1038,7 +1029,7 @@ module TypeScript.Services.Breakpoints {
return this.breakpointSpanOf(current);
}
private breakpointSpanIfStartsOnSameLine(positionedElement: TypeScript.ISyntaxElement): ts.SpanInfo {
private breakpointSpanIfStartsOnSameLine(positionedElement: TypeScript.ISyntaxElement): TextSpan {
if (positionedElement && this.posLine == this.lineMap.getLineNumberFromPosition(start(positionedElement))) {
return this.breakpointSpanOf(positionedElement);
}
@@ -1046,7 +1037,7 @@ module TypeScript.Services.Breakpoints {
return null;
}
public breakpointSpanOf(positionedElement: TypeScript.ISyntaxElement): ts.SpanInfo {
public breakpointSpanOf(positionedElement: TypeScript.ISyntaxElement): TextSpan {
if (!positionedElement) {
return null;
}
@@ -1075,7 +1066,7 @@ module TypeScript.Services.Breakpoints {
}
}
export function getBreakpointLocation(syntaxTree: TypeScript.SyntaxTree, askedPos: number): ts.SpanInfo {
export function getBreakpointLocation(syntaxTree: TypeScript.SyntaxTree, askedPos: number): TextSpan {
// Cannot set breakpoint in dts file
if (TypeScript.isDTSFile(syntaxTree.fileName())) {
return null;
+2 -2
View File
@@ -732,14 +732,14 @@ module TypeScript.ASTHelpers {
return false;
}
export function getNameOfIdenfierOrQualifiedName(name: ISyntaxElement): string {
export function getNameOfIdentifierOrQualifiedName(name: ISyntaxElement): string {
if (name.kind() === SyntaxKind.IdentifierName) {
return (<ISyntaxToken>name).text();
}
else {
Debug.assert(name.kind() == SyntaxKind.QualifiedName);
var dotExpr = <QualifiedNameSyntax>name;
return getNameOfIdenfierOrQualifiedName(dotExpr.left) + "." + getNameOfIdenfierOrQualifiedName(dotExpr.right);
return getNameOfIdentifierOrQualifiedName(dotExpr.left) + "." + getNameOfIdentifierOrQualifiedName(dotExpr.right);
}
}
-131
View File
@@ -1,131 +0,0 @@
///<reference path='..\core\integerUtilities.ts' />
module TypeScript {
export class BloomFilter {
private bitArray: boolean[];
private hashFunctionCount: number;
public static falsePositiveProbability: number = 0.0001;
/*
* From the bloom filter calculator here: http://hur.st/bloomfilter?n=4&p=1.0E-20
*
* 1) n = Number of items in the filter
*
* 2) p = Probability of false positives, (a double between 0 and 1).
*
* 3) m = Number of bits in the filter
*
* 4) k = Number of hash functions
*
* m = ceil((n * log(p)) / log(1.0 / (pow(2.0, log(2.0)))))
*
* k = round(log(2.0) * m / n)
*
*/
constructor(expectedCount: number) {
var m: number = Math.max(1, BloomFilter.computeM(expectedCount));
var k: number = Math.max(1, BloomFilter.computeK(expectedCount));;
// We must have size in even bytes, so that when we deserialize from bytes we get a bit array with the same count.
// The count is used by the hash functions.
var sizeInEvenBytes = (m + 7) & ~7;
this.bitArray = [];
for (var i = 0, len = sizeInEvenBytes; i < len; i++) {
this.bitArray[i] = false;
}
this.hashFunctionCount = k;
}
// m = ceil((n * log(p)) / log(1.0 / (pow(2.0, log(2.0)))))
static computeM(expectedCount: number): number {
var p: number = BloomFilter.falsePositiveProbability;
var n: number = expectedCount;
var numerator = n * Math.log(p);
var denominator = Math.log(1.0 / Math.pow(2.0, Math.log(2.0)));
return Math.ceil(numerator / denominator);
}
// k = round(log(2.0) * m / n)
static computeK(expectedCount: number): number {
var n: number = expectedCount;
var m: number = BloomFilter.computeM(expectedCount);
var temp = Math.log(2.0) * m / n;
return Math.round(temp);
}
/** Modification of the murmurhash2 algorithm. Code is simpler because it operates over
* strings instead of byte arrays. Because each string character is two bytes, it is known
* that the input will be an even number of bytes (though not necessarily a multiple of 4).
*
* This is needed over the normal 'string.GetHashCode()' because we need to be able to generate
* 'k' different well distributed hashes for any given string s. Also, we want to be able to
* generate these hashes without allocating any memory. My ideal solution would be to use an
* MD5 hash. However, there appears to be no way to do MD5 in .Net where you can:
*
* a) feed it individual values instead of a byte[]
*
* b) have the hash computed into a byte[] you provide instead of a newly allocated one
*
* Generating 'k' pieces of garbage on each insert and lookup seems very wasteful. So,
* instead, we use murmur hash since it provides well distributed values, allows for a
* seed, and allocates no memory.
*
* Murmur hash is public domain. Actual code is included below as reference.
*/
private computeHash(key: string, seed: number): number {
return Hash.computeMurmur2StringHashCode(key, seed);
}
public addKeys(keys: ts.Map<any>) {
for (var name in keys) {
if (ts.lookUp(keys, name)) {
this.add(name);
}
}
}
public add(value: string) {
for (var i = 0; i < this.hashFunctionCount; i++) {
var hash = this.computeHash(value, i);
hash = hash % this.bitArray.length;
this.bitArray[Math.abs(hash)] = true;
}
}
public probablyContains(value: string): boolean {
for (var i = 0; i < this.hashFunctionCount; i++) {
var hash = this.computeHash(value, i);
hash = hash % this.bitArray.length;
if (!this.bitArray[Math.abs(hash)]) {
return false;
}
}
return true;
}
public isEquivalent(filter: BloomFilter): boolean {
return BloomFilter.isEquivalent(this.bitArray, filter.bitArray)
&& this.hashFunctionCount === filter.hashFunctionCount;
}
static isEquivalent(array1: boolean[], array2: boolean[]): boolean {
if (array1.length !== array2.length) {
return false;
}
for (var i = 0; i < array1.length; i++) {
if (array1[i] !== array2[i]) {
return false;
}
}
return true;
}
}
}
+4 -4
View File
@@ -763,7 +763,7 @@ module TypeScript {
var start = new Date().getTime();
var accessors = PullHelpers.getGetterAndSetterFunction(funcDecl, this.semanticInfoChain);
TypeScript.declarationEmitGetAccessorFunctionTime += new Date().getTime();
TypeScript.declarationEmitGetAccessorFunctionTime += new Date().getTime() - start;
var comments: Comment[] = [];
if (accessors.getter) {
@@ -787,7 +787,7 @@ module TypeScript {
private emitMemberAccessorDeclaration(funcDecl: ISyntaxElement, modifiers: ISyntaxToken[], name: ISyntaxToken) {
var start = new Date().getTime();
var accessorSymbol = PullHelpers.getAccessorSymbol(funcDecl, this.semanticInfoChain);
TypeScript.declarationEmitGetAccessorFunctionTime += new Date().getTime();
TypeScript.declarationEmitGetAccessorFunctionTime += new Date().getTime() - start;
if (funcDecl.kind() === SyntaxKind.SetAccessor && accessorSymbol.getGetter()) {
// Setter is being used to emit the type info.
@@ -969,7 +969,7 @@ module TypeScript {
this.declFile.WriteLine("require(" + (<ExternalModuleReferenceSyntax>importDeclAST.moduleReference).stringLiteral.text() + ");");
}
else {
this.declFile.WriteLine(ASTHelpers.getNameOfIdenfierOrQualifiedName((<ModuleNameModuleReferenceSyntax>importDeclAST.moduleReference).moduleName) + ";");
this.declFile.WriteLine(ASTHelpers.getNameOfIdentifierOrQualifiedName((<ModuleNameModuleReferenceSyntax>importDeclAST.moduleReference).moduleName) + ";");
}
}
}
@@ -1023,7 +1023,7 @@ module TypeScript {
this.declFile.Write(moduleDecl.stringLiteral.text());
}
else {
this.declFile.Write(ASTHelpers.getNameOfIdenfierOrQualifiedName(moduleDecl.name));
this.declFile.Write(ASTHelpers.getNameOfIdentifierOrQualifiedName(moduleDecl.name));
}
this.declFile.WriteLine(" {");
-20
View File
@@ -17,31 +17,11 @@
module TypeScript {
export interface Logger {
information(): boolean;
debug(): boolean;
warning(): boolean;
error(): boolean;
fatal(): boolean;
log(s: string): void;
}
export class NullLogger implements Logger {
public information(): boolean { return false; }
public debug(): boolean { return false; }
public warning(): boolean { return false; }
public error(): boolean { return false; }
public fatal(): boolean { return false; }
public log(s: string): void {
}
}
export function timeFunction(logger: Logger, funcDescription: string, func: () => any): any {
var start = (new Date()).getTime();
var result = func();
var end = (new Date()).getTime();
if (logger.information()) {
logger.log(funcDescription + " completed in " + (end - start) + " msec");
}
return result;
}
}
-1
View File
@@ -18,7 +18,6 @@
/////<reference path='precompile.ts' />
/////<reference path='referenceResolver.ts' />
/////<reference path='declarationEmitter.ts' />
/////<reference path='bloomFilter.ts' />
/////<reference path='identifierWalker.ts' />
/////<reference path='settings.ts' />
/////<reference path='typecheck\pullFlags.ts' />
+1 -1
View File
@@ -120,7 +120,7 @@ module TypeScript {
// TODO: We need to expose an extensibility point on our hosts to have them tell us what
// they want the newline string to be. That way we can get the correct result regardless
// of which host we use
return sys.newLine ? sys.newLine : "\r\n";
return "\r\n";
}
function getLargestIndex(diagnostic: string): number {
-112
View File
@@ -1,112 +0,0 @@
///<reference path='references.ts' />
module TypeScript {
export class Hash {
// This table uses FNV1a as a string hash
private static FNV_BASE = 2166136261;
private static FNV_PRIME = 16777619;
private static computeFnv1aCharArrayHashCode(text: number[], start: number, len: number): number {
var hashCode = Hash.FNV_BASE;
var end = start + len;
for (var i = start; i < end; i++) {
hashCode = IntegerUtilities.integerMultiplyLow32Bits(hashCode ^ text[i], Hash.FNV_PRIME);
}
return hashCode;
}
public static computeSimple31BitCharArrayHashCode(key: number[], start: number, len: number): number {
// Start with an int.
var hash = 0;
for (var i = 0; i < len; i++) {
var ch = key[start + i];
// Left shift keeps things as a 32bit int. And we're only doing two adds. Chakra and
// V8 recognize this as not needing to go past the 53 bits needed for the float
// mantissa. Or'ing with 0 keeps this 32 bits.
hash = ((((hash << 5) - hash) | 0) + ch) | 0;
}
// Ensure we fit in 31 bits. That way if/when this gets stored, it won't require any heap
// allocation.
return hash & 0x7FFFFFFF;
}
public static computeSimple31BitStringHashCode(key: string): number {
// Start with an int.
var hash = 0;
var start = 0;
var len = key.length;
for (var i = 0; i < len; i++) {
var ch = key.charCodeAt(start + i);
// Left shift keeps things as a 32bit int. And we're only doing two adds. Chakra and
// V8 recognize this as not needing to go past the 53 bits needed for the float
// mantissa. Or'ing with 0 keeps this 32 bits.
hash = ((((hash << 5) - hash) | 0) + ch) | 0;
}
// Ensure we fit in 31 bits. That way if/when this gets stored, it won't require any heap
// allocation.
return hash & 0x7FFFFFFF;
}
public static computeMurmur2StringHashCode(key: string, seed: number): number {
// 'm' and 'r' are mixing constants generated offline.
// They're not really 'magic', they just happen to work well.
var m: number = 0x5bd1e995;
var r: number = 24;
// Initialize the hash to a 'random' value
var numberOfCharsLeft = key.length;
var h = Math.abs(seed ^ numberOfCharsLeft);
// Mix 4 bytes at a time into the hash. NOTE: 4 bytes is two chars, so we iterate
// through the string two chars at a time.
var index = 0;
while (numberOfCharsLeft >= 2) {
var c1 = key.charCodeAt(index);
var c2 = key.charCodeAt(index + 1);
var k = Math.abs(c1 | (c2 << 16));
k = IntegerUtilities.integerMultiplyLow32Bits(k, m);
k ^= k >> r;
k = IntegerUtilities.integerMultiplyLow32Bits(k, m);
h = IntegerUtilities.integerMultiplyLow32Bits(h, m);
h ^= k;
index += 2;
numberOfCharsLeft -= 2;
}
// Handle the last char (or 2 bytes) if they exist. This happens if the original string had
// odd length.
if (numberOfCharsLeft === 1) {
h ^= key.charCodeAt(index);
h = IntegerUtilities.integerMultiplyLow32Bits(h, m);
}
// Do a few final mixes of the hash to ensure the last few bytes are well-incorporated.
h ^= h >> 13;
h = IntegerUtilities.integerMultiplyLow32Bits(h, m);
h ^= h >> 15;
return h;
}
public static combine(value: number, currentHash: number): number {
// Ensure we stay within 31 bits.
return (((currentHash << 5) + currentHash) + value) & 0x7FFFFFFF;
}
}
}
-1
View File
@@ -6,7 +6,6 @@
///<reference path='diagnosticCore.ts' />
///<reference path='diagnosticInfo.ts' />
///<reference path='errors.ts' />
///<reference path='hash.ts' />
///<reference path='integerUtilities.ts' />
///<reference path='lineMap.ts' />
///<reference path='linePosition.ts' />
+18 -23
View File
@@ -19,28 +19,26 @@ module TypeScript.Services.Formatting {
export class FormattingManager {
private options: FormattingOptions;
constructor(private syntaxTree: SyntaxTree, private snapshot: ITextSnapshot, private rulesProvider: RulesProvider, editorOptions: ts.EditorOptions) {
constructor(private syntaxTree: SyntaxTree,
private snapshot: ITextSnapshot,
private rulesProvider: RulesProvider,
editorOptions: ts.EditorOptions) {
//
// TODO: convert to use FormattingOptions instead of EditorOptions
this.options = new FormattingOptions(!editorOptions.ConvertTabsToSpaces, editorOptions.TabSize, editorOptions.IndentSize, editorOptions.NewLineCharacter);
this.options = new FormattingOptions(!editorOptions.ConvertTabsToSpaces, editorOptions.TabSize, editorOptions.IndentSize, editorOptions.NewLineCharacter)
}
public formatSelection(minChar: number, limChar: number): ts.TextEdit[] {
public formatSelection(minChar: number, limChar: number): ts.TextChange[] {
var span = TextSpan.fromBounds(minChar, limChar);
return this.formatSpan(span, FormattingRequestKind.FormatSelection);
}
public formatDocument(minChar: number, limChar: number): ts.TextEdit[] {
var span = TextSpan.fromBounds(minChar, limChar);
public formatDocument(): ts.TextChange[] {
var span = TextSpan.fromBounds(0, this.snapshot.getLength());
return this.formatSpan(span, FormattingRequestKind.FormatDocument);
}
public formatOnPaste(minChar: number, limChar: number): ts.TextEdit[] {
var span = TextSpan.fromBounds(minChar, limChar);
return this.formatSpan(span, FormattingRequestKind.FormatOnPaste);
}
public formatOnSemicolon(caretPosition: number): ts.TextEdit[] {
public formatOnSemicolon(caretPosition: number): ts.TextChange[] {
var sourceUnit = this.syntaxTree.sourceUnit();
var semicolonPositionedToken = findToken(sourceUnit, caretPosition - 1);
@@ -48,7 +46,7 @@ module TypeScript.Services.Formatting {
// Find the outer most parent that this semicolon terminates
var current: ISyntaxElement = semicolonPositionedToken;
while (current.parent !== null &&
end(current.parent) === end(semicolonPositionedToken) &&
end(current.parent) === end(semicolonPositionedToken) &&
current.parent.kind() !== SyntaxKind.List) {
current = current.parent;
}
@@ -63,7 +61,7 @@ module TypeScript.Services.Formatting {
return [];
}
public formatOnClosingCurlyBrace(caretPosition: number): ts.TextEdit[] {
public formatOnClosingCurlyBrace(caretPosition: number): ts.TextChange[] {
var sourceUnit = this.syntaxTree.sourceUnit();
var closeBracePositionedToken = findToken(sourceUnit, caretPosition - 1);
@@ -71,8 +69,8 @@ module TypeScript.Services.Formatting {
// Find the outer most parent that this closing brace terminates
var current: ISyntaxElement = closeBracePositionedToken;
while (current.parent !== null &&
end(current.parent) === end(closeBracePositionedToken) &&
current.parent.kind() !== SyntaxKind.List) {
end(current.parent) === end(closeBracePositionedToken) &&
current.parent.kind() !== SyntaxKind.List) {
current = current.parent;
}
@@ -86,7 +84,7 @@ module TypeScript.Services.Formatting {
return [];
}
public formatOnEnter(caretPosition: number): ts.TextEdit[] {
public formatOnEnter(caretPosition: number): ts.TextChange[] {
var lineNumber = this.snapshot.getLineNumberFromPosition(caretPosition);
if (lineNumber > 0) {
@@ -103,23 +101,20 @@ module TypeScript.Services.Formatting {
return [];
}
private formatSpan(span: TextSpan, formattingRequestKind: FormattingRequestKind): ts.TextEdit[] {
private formatSpan(span: TextSpan, formattingRequestKind: FormattingRequestKind): ts.TextChange[] {
// Always format from the beginning of the line
var startLine = this.snapshot.getLineFromPosition(span.start());
span = TextSpan.fromBounds(startLine.startPosition(), span.end());
var result: ts.TextEdit[] = [];
var result: ts.TextChange[] = [];
var formattingEdits = Formatter.getEdits(span, this.syntaxTree.sourceUnit(), this.options, true, this.snapshot, this.rulesProvider, formattingRequestKind);
//
// TODO: Change the ILanguageService interface to return TextEditInfo (with start, and length) instead of TextEdit (with minChar and limChar)
formattingEdits.forEach((item) => {
result.push({
minChar: item.position,
limChar: item.position + item.length,
text: item.replaceWith
});
var edit = new ts.TextChange(new TextSpan(item.position, item.length), item.replaceWith);
result.push(edit);
});
return result;
+2 -2
View File
@@ -40,8 +40,8 @@ module TypeScript.Services.Formatting {
public ensureUpToDate(options: ts.FormatCodeOptions) {
if (this.options == null || !ts.compareDataObjects(this.options, options)) {
var activeRules: Rule[] = TypeScript.timeFunction(this.logger, "RulesProvider: createActiveRules()", () => { return this.createActiveRules(options); });
var rulesMap: RulesMap = TypeScript.timeFunction(this.logger, "RulesProvider: RulesMap.create()", () => { return RulesMap.create(activeRules); });
var activeRules = this.createActiveRules(options);
var rulesMap = RulesMap.create(activeRules);
this.activeRules = activeRules;
this.rulesMap = rulesMap;
+5
View File
@@ -17,6 +17,7 @@
module TypeScript.Services.Formatting {
export interface ITextSnapshot {
getLength(): number;
getText(span: TextSpan): string;
getLineNumberFromPosition(position: number): number;
getLineFromPosition(position: number): ITextSnapshotLine;
@@ -30,6 +31,10 @@ module TypeScript.Services.Formatting {
this.lines = [];
}
public getLength(): number {
return this.snapshot.length();
}
public getText(span: TextSpan): string {
return this.snapshot.substr(span.start(), span.length());
}
+278 -282
View File
@@ -1,121 +1,22 @@
///<reference path='references.ts' />
module TypeScript.Services {
interface LexicalScope {
items: ts.Map<ts.NavigateToItem>;
itemNames: string[];
childScopes: ts.Map<LexicalScope>;
childScopeNames: string[];
}
export class NavigationBarItemGetter {
private hasGlobalNode = false;
export class GetScriptLexicalStructureWalker extends TypeScript.SyntaxWalker {
private nameStack: string[] = [];
private kindStack: string[] = [];
private getIndent(node: ISyntaxNode): number {
var indent = this.hasGlobalNode ? 1 : 0;
private parentScopes: LexicalScope[] = [];
private currentScope: LexicalScope;
var current = node.parent;
while (current != null) {
if (current.kind() == SyntaxKind.ModuleDeclaration || current.kind() === SyntaxKind.FunctionDeclaration) {
indent++;
}
private createScope(): LexicalScope {
return {
items: TypeScript.createIntrinsicsObject<ts.NavigateToItem>(),
childScopes: TypeScript.createIntrinsicsObject<LexicalScope>(),
childScopeNames: [],
itemNames: []
};
}
private pushNewContainerScope(containerName: string, kind: string): LexicalScope {
Debug.assert(containerName, "No scope name provided");
var key = kind + "+" + containerName;
this.nameStack.push(containerName);
this.kindStack.push(kind);
var parentScope = this.currentScope;
this.parentScopes.push(parentScope);
var scope = ts.lookUp(parentScope.childScopes, key);
if (!scope) {
scope = this.createScope()
parentScope.childScopes[key] = scope;
parentScope.childScopeNames.push(key);
current = current.parent;
}
this.currentScope = scope;
return parentScope;
}
private popScope() {
Debug.assert(this.parentScopes.length > 0, "No parent scopes to return to")
this.currentScope = this.parentScopes.pop();
this.kindStack.pop();
this.nameStack.pop();
}
constructor(private fileName: string) {
super();
this.currentScope = this.createScope();
}
private collectItems(items: ts.NavigateToItem[], scope = this.currentScope) {
scope.itemNames.forEach(item => {
items.push(scope.items[item]);
});
scope.childScopeNames.forEach(childScope => {
this.collectItems(items, scope.childScopes[childScope]);
});
}
static getListsOfAllScriptLexicalStructure(items: ts.NavigateToItem[], fileName: string, unit: TypeScript.SourceUnitSyntax) {
var visitor = new GetScriptLexicalStructureWalker(fileName);
visitNodeOrToken(visitor, unit);
visitor.collectItems(items);
}
private createItem(node: TypeScript.ISyntaxNode, modifiers: ISyntaxToken[], kind: string, name: string): void {
var key = kind + "+" + name;
if (ts.lookUp(this.currentScope.items, key) !== undefined) {
this.addAdditionalSpan(node, key);
return;
}
var item: ts.NavigateToItem = {
name: name,
kind: kind,
matchKind: ts.MatchKind.exact,
fileName: this.fileName,
kindModifiers: this.getKindModifiers(modifiers),
minChar: start(node),
limChar: end(node),
containerName: this.nameStack.join("."),
containerKind: this.kindStack.length === 0 ? "" : TypeScript.ArrayUtilities.last(this.kindStack),
};
this.currentScope.items[key] = item;
this.currentScope.itemNames.push(key);
}
private addAdditionalSpan(
node: TypeScript.ISyntaxNode,
key: string) {
var item = ts.lookUp(this.currentScope.items, key);
Debug.assert(item !== undefined);
var start = TypeScript.start(node);
var span: ts.SpanInfo = {
minChar: start,
limChar: start + width(node)
};
if (item.additionalSpans) {
item.additionalSpans.push(span);
}
else {
item.additionalSpans = [span];
}
return indent;
}
private getKindModifiers(modifiers: TypeScript.ISyntaxToken[]): string {
@@ -128,30 +29,221 @@ module TypeScript.Services {
return result.length > 0 ? result.join(',') : ts.ScriptElementKindModifier.none;
}
public visitModuleDeclaration(node: TypeScript.ModuleDeclarationSyntax): void {
var names = this.getModuleNames(node);
this.visitModuleDeclarationWorker(node, names, 0);
public getItems(node: TypeScript.SourceUnitSyntax): ts.NavigationBarItem[] {
return this.getItemsWorker(() => this.getTopLevelNodes(node), n => this.createTopLevelItem(n));
}
private visitModuleDeclarationWorker(node: TypeScript.ModuleDeclarationSyntax, names: string[], nameIndex: number): void {
if (nameIndex === names.length) {
// We're after all the module names, descend and process all children.
super.visitModuleDeclaration(node);
private getChildNodes(nodes: IModuleElementSyntax[]): ISyntaxNode[] {
var childNodes: ISyntaxNode[] = [];
for (var i = 0, n = nodes.length; i < n; i++) {
var node = <ISyntaxNode>nodes[i];
if (node.kind() === SyntaxKind.FunctionDeclaration) {
childNodes.push(node);
}
else if (node.kind() === SyntaxKind.VariableStatement) {
var variableDeclaration = (<VariableStatementSyntax>node).variableDeclaration;
childNodes.push.apply(childNodes, variableDeclaration.variableDeclarators);
}
}
else {
var name = names[nameIndex];
var kind = ts.ScriptElementKind.moduleElement;
this.createItem(node, node.modifiers, kind, name);
return childNodes;
}
this.pushNewContainerScope(name, kind);
private getTopLevelNodes(node: SourceUnitSyntax): ISyntaxNode[] {
var topLevelNodes: ISyntaxNode[] = [];
topLevelNodes.push(node);
this.visitModuleDeclarationWorker(node, names, nameIndex + 1);
this.addTopLevelNodes(node.moduleElements, topLevelNodes);
this.popScope();
return topLevelNodes;
}
private addTopLevelNodes(nodes: IModuleElementSyntax[], topLevelNodes: ISyntaxNode[]): void {
for (var i = 0, n = nodes.length; i < n; i++) {
var node = nodes[i];
switch (node.kind()) {
case SyntaxKind.ClassDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.InterfaceDeclaration:
topLevelNodes.push(node);
break;
case SyntaxKind.ModuleDeclaration:
var moduleDeclaration = <ModuleDeclarationSyntax>node;
topLevelNodes.push(node);
this.addTopLevelNodes(moduleDeclaration.moduleElements, topLevelNodes);
break;
case SyntaxKind.FunctionDeclaration:
var functionDeclaration = <FunctionDeclarationSyntax>node;
if (this.isTopLevelFunctionDeclaration(functionDeclaration)) {
topLevelNodes.push(node);
this.addTopLevelNodes(functionDeclaration.block.statements, topLevelNodes);
}
break;
}
}
}
public isTopLevelFunctionDeclaration(functionDeclaration: FunctionDeclarationSyntax) {
// A function declaration is 'top level' if it contains any function declarations
// within it.
return functionDeclaration.block && ArrayUtilities.any(functionDeclaration.block.statements, s => s.kind() === SyntaxKind.FunctionDeclaration);
}
private getItemsWorker(getNodes: () => ISyntaxNode[], createItem: (n: ISyntaxNode) => ts.NavigationBarItem): ts.NavigationBarItem[] {
var items: ts.NavigationBarItem[] = [];
var keyToItem = createIntrinsicsObject<ts.NavigationBarItem>();
var nodes = getNodes();
for (var i = 0, n = nodes.length; i < n; i++) {
var child = nodes[i];
var item = createItem(child);
if (item != null) {
if (item.text.length > 0) {
var key = item.text + "-" + item.kind;
var itemWithSameName = keyToItem[key];
if (itemWithSameName) {
// We had an item with the same name. Merge these items together.
this.merge(itemWithSameName, item);
}
else {
keyToItem[key] = item;
items.push(item);
}
}
}
}
return items;
}
private merge(target: ts.NavigationBarItem, source: ts.NavigationBarItem) {
// First, add any spans in the source to the target.
target.spans.push.apply(target.spans, source.spans);
if (source.childItems) {
if (!target.childItems) {
target.childItems = [];
}
// Next, recursively merge or add any children in the source as appropriate.
outer:
for (var i = 0, n = source.childItems.length; i < n; i++) {
var sourceChild = source.childItems[i];
for (var j = 0, m = target.childItems.length; j < m; j++) {
var targetChild = target.childItems[j];
if (targetChild.text === sourceChild.text && targetChild.kind === sourceChild.kind) {
// Found a match. merge them.
this.merge(targetChild, sourceChild);
continue outer;
}
}
// Didn't find a match, just add this child to the list.
target.childItems.push(sourceChild);
}
}
}
private createChildItem(node: ISyntaxNode): ts.NavigationBarItem {
switch (node.kind()) {
case SyntaxKind.Parameter:
var parameter = <ParameterSyntax>node;
if (parameter.modifiers.length === 0) {
return null;
}
return new ts.NavigationBarItem(parameter.identifier.text(), ts.ScriptElementKind.memberVariableElement, this.getKindModifiers(parameter.modifiers), [TextSpan.fromBounds(start(node), end(node))]);
case SyntaxKind.MemberFunctionDeclaration:
var memberFunction = <MemberFunctionDeclarationSyntax>node;
return new ts.NavigationBarItem(memberFunction.propertyName.text(), ts.ScriptElementKind.memberFunctionElement, this.getKindModifiers(memberFunction.modifiers), [TextSpan.fromBounds(start(node), end(node))]);
case SyntaxKind.GetAccessor:
var getAccessor = <GetAccessorSyntax>node;
return new ts.NavigationBarItem(getAccessor.propertyName.text(), ts.ScriptElementKind.memberGetAccessorElement, this.getKindModifiers(getAccessor.modifiers), [TextSpan.fromBounds(start(node), end(node))]);
case SyntaxKind.SetAccessor:
var setAccessor = <SetAccessorSyntax>node;
return new ts.NavigationBarItem(setAccessor.propertyName.text(), ts.ScriptElementKind.memberSetAccessorElement, this.getKindModifiers(setAccessor.modifiers), [TextSpan.fromBounds(start(node), end(node))]);
case SyntaxKind.IndexSignature:
var indexSignature = <IndexSignatureSyntax>node;
return new ts.NavigationBarItem("[]", ts.ScriptElementKind.indexSignatureElement, ts.ScriptElementKindModifier.none, [TextSpan.fromBounds(start(node), end(node))]);
case SyntaxKind.EnumElement:
var enumElement = <EnumElementSyntax>node;
return new ts.NavigationBarItem(enumElement.propertyName.text(), ts.ScriptElementKind.memberVariableElement, ts.ScriptElementKindModifier.none, [TextSpan.fromBounds(start(node), end(node))]);
case SyntaxKind.CallSignature:
var callSignature = <CallSignatureSyntax>node;
return new ts.NavigationBarItem("()", ts.ScriptElementKind.callSignatureElement, ts.ScriptElementKindModifier.none, [TextSpan.fromBounds(start(node), end(node))]);
case SyntaxKind.ConstructSignature:
var constructSignature = <ConstructSignatureSyntax>node;
return new ts.NavigationBarItem("new()", ts.ScriptElementKind.constructSignatureElement, ts.ScriptElementKindModifier.none, [TextSpan.fromBounds(start(node), end(node))]);
case SyntaxKind.MethodSignature:
var methodSignature = <MethodSignatureSyntax>node;
return new ts.NavigationBarItem(methodSignature.propertyName.text(), ts.ScriptElementKind.memberFunctionElement, ts.ScriptElementKindModifier.none, [TextSpan.fromBounds(start(node), end(node))]);
case SyntaxKind.PropertySignature:
var propertySignature = <PropertySignatureSyntax>node;
return new ts.NavigationBarItem(propertySignature.propertyName.text(), ts.ScriptElementKind.memberVariableElement, ts.ScriptElementKindModifier.none, [TextSpan.fromBounds(start(node), end(node))]);
case SyntaxKind.FunctionDeclaration:
var functionDeclaration = <FunctionDeclarationSyntax>node;
if (!this.isTopLevelFunctionDeclaration(functionDeclaration)) {
return new ts.NavigationBarItem(functionDeclaration.identifier.text(), ts.ScriptElementKind.functionElement, this.getKindModifiers(functionDeclaration.modifiers), [TextSpan.fromBounds(start(node), end(node))]);
}
break;
case SyntaxKind.MemberVariableDeclaration:
var memberVariableDeclaration = <MemberVariableDeclarationSyntax>node;
return new ts.NavigationBarItem(memberVariableDeclaration.variableDeclarator.propertyName.text(), ts.ScriptElementKind.memberVariableElement, this.getKindModifiers(memberVariableDeclaration.modifiers), [TextSpan.fromBounds(start(memberVariableDeclaration.variableDeclarator), end(memberVariableDeclaration.variableDeclarator))]);
case SyntaxKind.VariableDeclarator:
var variableDeclarator = <VariableDeclaratorSyntax>node;
return new ts.NavigationBarItem(variableDeclarator.propertyName.text(), ts.ScriptElementKind.variableElement, ts.ScriptElementKindModifier.none, [TextSpan.fromBounds(start(variableDeclarator), end(variableDeclarator))]);
case SyntaxKind.ConstructorDeclaration:
var constructorDeclaration = <ConstructorDeclarationSyntax>node;
return new ts.NavigationBarItem("constructor", ts.ScriptElementKind.constructorImplementationElement, ts.ScriptElementKindModifier.none, [TextSpan.fromBounds(start(node), end(node))]);
}
return null;
}
private createTopLevelItem(node: ISyntaxNode): ts.NavigationBarItem {
switch (node.kind()) {
case SyntaxKind.SourceUnit:
return this.createSourceUnitItem(<SourceUnitSyntax>node);
case SyntaxKind.ClassDeclaration:
return this.createClassItem(<ClassDeclarationSyntax>node);
case SyntaxKind.EnumDeclaration:
return this.createEnumItem(<EnumDeclarationSyntax>node);
case SyntaxKind.InterfaceDeclaration:
return this.createIterfaceItem(<InterfaceDeclarationSyntax>node);
case SyntaxKind.ModuleDeclaration:
return this.createModuleItem(<ModuleDeclarationSyntax>node);
case SyntaxKind.FunctionDeclaration:
return this.createFunctionItem(<FunctionDeclarationSyntax>node);
}
return null;
}
private getModuleNames(node: TypeScript.ModuleDeclarationSyntax): string[] {
var result: string[] = [];
@@ -176,180 +268,84 @@ module TypeScript.Services {
}
}
public visitClassDeclaration(node: TypeScript.ClassDeclarationSyntax): void {
var name = node.identifier.text();
var kind = ts.ScriptElementKind.classElement;
private createModuleItem(node: ModuleDeclarationSyntax): ts.NavigationBarItem {
var moduleNames = this.getModuleNames(node);
this.createItem(node, node.modifiers, kind, name);
var childItems = this.getItemsWorker(() => this.getChildNodes(node.moduleElements), n => this.createChildItem(n));
this.pushNewContainerScope(name, kind);
super.visitClassDeclaration(node);
this.popScope();
return new ts.NavigationBarItem(moduleNames.join("."),
ts.ScriptElementKind.moduleElement,
this.getKindModifiers(node.modifiers),
[TextSpan.fromBounds(start(node), end(node))],
childItems,
this.getIndent(node));
}
public visitInterfaceDeclaration(node: TypeScript.InterfaceDeclarationSyntax): void {
var name = node.identifier.text();
var kind = ts.ScriptElementKind.interfaceElement;
private createFunctionItem(node: FunctionDeclarationSyntax) {
var childItems = this.getItemsWorker(() => node.block.statements, n => this.createChildItem(n));
this.createItem(node, node.modifiers, kind, name);
this.pushNewContainerScope(name, kind);
super.visitInterfaceDeclaration(node);
this.popScope();
return new ts.NavigationBarItem(node.identifier.text(),
ts.ScriptElementKind.functionElement,
this.getKindModifiers(node.modifiers),
[TextSpan.fromBounds(start(node), end(node))],
childItems,
this.getIndent(node));
}
public visitObjectType(node: TypeScript.ObjectTypeSyntax): void {
// Ignore an object type if we aren't inside an interface declaration. We don't want
// to add some random object type's members to the nav bar.
if (node.parent.kind() === SyntaxKind.InterfaceDeclaration) {
super.visitObjectType(node);
}
}
private createSourceUnitItem(node: SourceUnitSyntax): ts.NavigationBarItem {
var childItems = this.getItemsWorker(() => this.getChildNodes(node.moduleElements), n => this.createChildItem(n));
public visitEnumDeclaration(node: TypeScript.EnumDeclarationSyntax): void {
var name = node.identifier.text();
var kind = ts.ScriptElementKind.enumElement;
this.createItem(node, node.modifiers, kind, name);
this.pushNewContainerScope(name, kind);
super.visitEnumDeclaration(node);
this.popScope();
}
public visitConstructorDeclaration(node: TypeScript.ConstructorDeclarationSyntax): void {
this.createItem(node, TypeScript.Syntax.emptyList<ISyntaxToken>(), ts.ScriptElementKind.constructorImplementationElement, "constructor");
// Search the parameter list of class properties
var parameters = node.callSignature.parameterList.parameters;
if (parameters) {
for (var i = 0, n = parameters.length; i < n; i++) {
var parameter = <ParameterSyntax>parameters[i];
Debug.assert(parameter.kind() === SyntaxKind.Parameter);
if (SyntaxUtilities.containsToken(parameter.modifiers, SyntaxKind.PublicKeyword) ||
SyntaxUtilities.containsToken(parameter.modifiers, SyntaxKind.PrivateKeyword)) {
this.createItem(node, parameter.modifiers, ts.ScriptElementKind.memberVariableElement, parameter.identifier.text());
}
}
if (childItems === null || childItems.length === 0) {
return null;
}
// No need to descend into a constructor;
this.hasGlobalNode = true;
return new ts.NavigationBarItem("<global>",
ts.ScriptElementKind.moduleElement,
ts.ScriptElementKindModifier.none,
[TextSpan.fromBounds(start(node), end(node))],
childItems);
}
public visitMemberFunctionDeclaration(node: TypeScript.MemberFunctionDeclarationSyntax): void {
this.createItem(node, node.modifiers, ts.ScriptElementKind.memberFunctionElement, node.propertyName.text());
private createClassItem(node: ClassDeclarationSyntax): ts.NavigationBarItem {
var constructor = <ConstructorDeclarationSyntax>ArrayUtilities.firstOrDefault(
node.classElements, n => n.kind() === SyntaxKind.ConstructorDeclaration);
// No need to descend into a member function;
// Add the constructor parameters in as children of hte class (for property parameters).
var nodes: ISyntaxNode[] = constructor
? (<ISyntaxNode[]>constructor.callSignature.parameterList.parameters).concat(node.classElements)
: node.classElements;
var childItems = this.getItemsWorker(() => nodes, n => this.createChildItem(n));
return new ts.NavigationBarItem(
node.identifier.text(),
ts.ScriptElementKind.classElement,
this.getKindModifiers(node.modifiers),
[TextSpan.fromBounds(start(node), end(node))],
childItems,
this.getIndent(node));
}
public visitGetAccessor(node: TypeScript.GetAccessorSyntax): void {
this.createItem(node, node.modifiers, ts.ScriptElementKind.memberGetAccessorElement, node.propertyName.text());
// No need to descend into a member accessor;
private createEnumItem(node: TypeScript.EnumDeclarationSyntax): ts.NavigationBarItem {
var childItems = this.getItemsWorker(() => node.enumElements, n => this.createChildItem(n));
return new ts.NavigationBarItem(
node.identifier.text(),
ts.ScriptElementKind.enumElement,
this.getKindModifiers(node.modifiers),
[TextSpan.fromBounds(start(node), end(node))],
childItems,
this.getIndent(node));
}
public visitSetAccessor(node: TypeScript.SetAccessorSyntax): void {
this.createItem(node, node.modifiers, ts.ScriptElementKind.memberSetAccessorElement, node.propertyName.text());
// No need to descend into a member accessor;
}
public visitVariableDeclarator(node: TypeScript.VariableDeclaratorSyntax): void {
var modifiers = node.parent.kind() === SyntaxKind.MemberVariableDeclaration
? (<MemberVariableDeclarationSyntax>node.parent).modifiers
: TypeScript.Syntax.emptyList<ISyntaxToken>();
var kind = node.parent.kind() === SyntaxKind.MemberVariableDeclaration
? ts.ScriptElementKind.memberVariableElement
: ts.ScriptElementKind.variableElement;
this.createItem(node, modifiers, kind, node.propertyName.text());
// No need to descend into a variable declarator;
}
public visitIndexSignature(node: TypeScript.IndexSignatureSyntax): void {
this.createItem(node, TypeScript.Syntax.emptyList<ISyntaxToken>(), ts.ScriptElementKind.indexSignatureElement, "[]");
// No need to descend into an index signature;
}
public visitEnumElement(node: TypeScript.EnumElementSyntax): void {
this.createItem(node, TypeScript.Syntax.emptyList<ISyntaxToken>(), ts.ScriptElementKind.memberVariableElement, node.propertyName.text());
// No need to descend into an enum element;
}
public visitCallSignature(node: TypeScript.CallSignatureSyntax): void {
this.createItem(node, TypeScript.Syntax.emptyList<ISyntaxToken>(), ts.ScriptElementKind.callSignatureElement, "()");
// No need to descend into a call signature;
}
public visitConstructSignature(node: TypeScript.ConstructSignatureSyntax): void {
this.createItem(node, TypeScript.Syntax.emptyList<ISyntaxToken>(), ts.ScriptElementKind.constructSignatureElement, "new()");
// No need to descend into a construct signature;
}
public visitMethodSignature(node: TypeScript.MethodSignatureSyntax): void {
this.createItem(node, TypeScript.Syntax.emptyList<ISyntaxToken>(), ts.ScriptElementKind.memberFunctionElement, node.propertyName.text());
// No need to descend into a method signature;
}
public visitPropertySignature(node: TypeScript.PropertySignatureSyntax): void {
this.createItem(node, TypeScript.Syntax.emptyList<ISyntaxToken>(), ts.ScriptElementKind.memberVariableElement, node.propertyName.text());
// No need to descend into a property signature;
}
public visitFunctionDeclaration(node: TypeScript.FunctionDeclarationSyntax): void {
// in the case of:
// declare function
// the parser will synthesize an identifier.
// we shouldn't add an unnamed function declaration
if (width(node.identifier) > 0) {
this.createItem(node, node.modifiers, ts.ScriptElementKind.functionElement, node.identifier.text());
}
// No need to descend into a function declaration;
}
// Common statement types. Don't even bother walking into them as we'll never find anything
// inside that we'd put in the navbar.
public visitBlock(node: TypeScript.BlockSyntax): void {
}
public visitIfStatement(node: TypeScript.IfStatementSyntax): void {
}
public visitExpressionStatement(node: TypeScript.ExpressionStatementSyntax): void {
}
public visitThrowStatement(node: TypeScript.ThrowStatementSyntax): void {
}
public visitReturnStatement(node: TypeScript.ReturnStatementSyntax): void {
}
public visitSwitchStatement(node: TypeScript.SwitchStatementSyntax): void {
}
public visitWithStatement(node: TypeScript.WithStatementSyntax): void {
}
public visitTryStatement(node: TypeScript.TryStatementSyntax): void {
}
public visitLabeledStatement(node: TypeScript.LabeledStatementSyntax): void {
private createIterfaceItem(node: TypeScript.InterfaceDeclarationSyntax): ts.NavigationBarItem {
var childItems = this.getItemsWorker(() => node.body.typeMembers, n => this.createChildItem(n));
return new ts.NavigationBarItem(
node.identifier.text(),
ts.ScriptElementKind.interfaceElement,
this.getKindModifiers(node.modifiers),
[TextSpan.fromBounds(start(node), end(node))],
childItems,
this.getIndent(node));
}
}
}
+1373 -363
View File
File diff suppressed because it is too large Load Diff
+106 -153
View File
@@ -36,7 +36,7 @@ module ts {
// { span: { start: number; length: number }; newLength: number }
//
// Or null value if there was no change.
getTextChangeRangeSinceVersion(scriptVersion: number): string;
getChangeRange(oldSnapshot: ScriptSnapshotShim): string;
}
//
@@ -48,7 +48,7 @@ module ts {
// Returns a JSON encoded value of the type:
// string[]
getScriptFileNames(): string;
getScriptVersion(fileName: string): number;
getScriptVersion(fileName: string): string;
getScriptIsOpen(fileName: string): boolean;
getScriptSnapshot(fileName: string): ScriptSnapshotShim;
getLocalizedDiagnosticMessages(): string;
@@ -86,44 +86,51 @@ module ts {
getTypeAtPosition(fileName: string, position: number): string;
getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): string;
getBreakpointStatementAtPosition(fileName: string, position: number): string;
getSignatureAtPosition(fileName: string, position: number): string;
getSignatureHelpItems(fileName: string, position: number): string;
getSignatureHelpCurrentArgumentState(fileName: string, position: number, applicableSpanStart: number): string;
// Returns a JSON encoded value of the type:
// { fileName: string; minChar: number; limChar: number; kind: string; name: string; containerKind: string; containerName: string }
// { canRename: boolean, localizedErrorMessage: string, displayName: string, fullDisplayName: string, kind: string, kindModifiers: string, triggerSpan: { start; length } }
getRenameInfo(fileName: string, position: number): string;
// Returns a JSON encoded value of the type:
// { fileName: string; textSpan: { start: number; length: number}; kind: string; name: string; containerKind: string; containerName: string }
//
// Or null value if no definition can be found.
getDefinitionAtPosition(fileName: string, position: number): string;
// Returns a JSON encoded value of the type:
// { fileName: string; minChar: number; limChar: number; isWriteAccess: boolean }[]
// { fileName: string; textSpan: { start: number; length: number}; isWriteAccess: boolean }[]
getReferencesAtPosition(fileName: string, position: number): string;
// Returns a JSON encoded value of the type:
// { fileName: string; minChar: number; limChar: number; isWriteAccess: boolean }[]
// { fileName: string; textSpan: { start: number; length: number}; isWriteAccess: boolean }[]
getOccurrencesAtPosition(fileName: string, position: number): string;
// Returns a JSON encoded value of the type:
// { fileName: string; minChar: number; limChar: number; isWriteAccess: boolean }[]
// { fileName: string; textSpan: { start: number; length: number}; isWriteAccess: boolean }[]
getImplementorsAtPosition(fileName: string, position: number): string;
// Returns a JSON encoded value of the type:
// { name: string; kind: string; kindModifiers: string; containerName: string; containerKind: string; matchKind: string; fileName: string; minChar: number; limChar: number; } [] = [];
// { name: string; kind: string; kindModifiers: string; containerName: string; containerKind: string; matchKind: string; fileName: string; textSpan: { start: number; length: number}; } [] = [];
getNavigateToItems(searchValue: string): string;
// Returns a JSON encoded value of the type:
// { name: string; kind: string; kindModifiers: string; containerName: string; containerKind: string; matchKind: string; fileName: string; minChar: number; limChar: number; } [] = [];
getScriptLexicalStructure(fileName: string): string;
// { text: string; kind: string; kindModifiers: string; bolded: boolean; grayed: boolean; indent: number; spans: { start: number; length: number; }[]; childItems: <recursive use of this type>[] } [] = [];
getNavigationBarItems(fileName: string): string;
// Returns a JSON encoded value of the type:
// { name: string; kind: string; kindModifiers: string; containerName: string; containerKind: string; matchKind: string; fileName: string; minChar: number; limChar: number; } [] = [];
getOutliningRegions(fileName: string): string;
// { textSpan: { start: number, length: number }; hintSpan: { start: number, length: number }; bannerText: string; autoCollapse: boolean } [] = [];
getOutliningSpans(fileName: string): string;
getTodoComments(fileName: string, todoCommentDescriptors: string): string;
getBraceMatchingAtPosition(fileName: string, position: number): string;
getIndentationAtPosition(fileName: string, position: number, options: string/*Services.EditorOptions*/): string;
getFormattingEditsForRange(fileName: string, minChar: number, limChar: number, options: string/*Services.FormatCodeOptions*/): string;
getFormattingEditsForDocument(fileName: string, minChar: number, limChar: number, options: string/*Services.FormatCodeOptions*/): string;
getFormattingEditsOnPaste(fileName: string, minChar: number, limChar: number, options: string/*Services.FormatCodeOptions*/): string;
getFormattingEditsForRange(fileName: string, start: number, end: number, options: string/*Services.FormatCodeOptions*/): string;
getFormattingEditsForDocument(fileName: string, options: string/*Services.FormatCodeOptions*/): string;
getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: string/*Services.FormatCodeOptions*/): string;
getEmitOutput(fileName: string): string;
@@ -283,8 +290,9 @@ module ts {
return this.lineStartPositions;
}
public getTextChangeRangeSinceVersion(scriptVersion: number): TypeScript.TextChangeRange {
var encoded = this.scriptSnapshotShim.getTextChangeRangeSinceVersion(scriptVersion);
public getChangeRange(oldSnapshot: TypeScript.IScriptSnapshot): TypeScript.TextChangeRange {
var oldSnapshotShim = <ScriptSnapshotShimAdapter>oldSnapshot;
var encoded = this.scriptSnapshotShim.getChangeRange(oldSnapshotShim.scriptSnapshotShim);
if (encoded == null) {
return null;
}
@@ -295,30 +303,10 @@ module ts {
}
}
class LanguageServiceShimHostAdapter implements LanguageServiceHost {
export class LanguageServiceShimHostAdapter implements LanguageServiceHost {
constructor(private shimHost: LanguageServiceShimHost) {
}
public information(): boolean {
return this.shimHost.information();
}
public debug(): boolean {
return this.shimHost.debug();
}
public warning(): boolean {
return this.shimHost.warning();
}
public error(): boolean {
return this.shimHost.error();
}
public fatal(): boolean {
return this.shimHost.fatal();
}
public log(s: string): void {
this.shimHost.log(s);
}
@@ -349,7 +337,7 @@ module ts {
return new ScriptSnapshotShimAdapter(this.shimHost.getScriptSnapshot(fileName));
}
public getScriptVersion(fileName: string): number {
public getScriptVersion(fileName: string): string {
return this.shimHost.getScriptVersion(fileName);
}
@@ -455,7 +443,6 @@ module ts {
this.forwardJSONCall(
"refresh(" + throwOnError + ")",
() => {
this.languageService.refresh();
return <any>null;
});
}
@@ -468,8 +455,6 @@ module ts {
return <any>null;
});
}
/// SQUIGGLES
///
private static realizeDiagnostic(diagnostic: Diagnostic): { message: string; start: number; length: number; category: string; } {
return {
@@ -494,7 +479,7 @@ module ts {
public getSyntacticDiagnostics(fileName: string): string {
return this.forwardJSONCall(
"getSyntacticDiagnostics(\"" + fileName + "\")",
"getSyntacticDiagnostics('" + fileName + "')",
() => {
var errors = this.languageService.getSyntacticDiagnostics(fileName);
return errors.map(LanguageServiceShimObject.realizeDiagnostic);
@@ -503,7 +488,7 @@ module ts {
public getSemanticDiagnostics(fileName: string): string {
return this.forwardJSONCall(
"getSemanticDiagnostics(\"" + fileName + "\")",
"getSemanticDiagnostics('" + fileName + "')",
() => {
var errors = this.languageService.getSemanticDiagnostics(fileName);
return errors.map(LanguageServiceShimObject.realizeDiagnostic);
@@ -524,7 +509,7 @@ module ts {
/// in the active file.
public getTypeAtPosition(fileName: string, position: number): string {
return this.forwardJSONCall(
"getTypeAtPosition(\"" + fileName + "\", " + position + ")",
"getTypeAtPosition('" + fileName + "', " + position + ")",
() => {
var typeInfo = this.languageService.getTypeAtPosition(fileName, position);
return typeInfo;
@@ -536,7 +521,7 @@ module ts {
// in the active file.
public getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): string {
return this.forwardJSONCall(
"getNameOrDottedNameSpan(\"" + fileName + "\", " + startPos + ", " + endPos + ")",
"getNameOrDottedNameSpan('" + fileName + "', " + startPos + ", " + endPos + ")",
() => {
var spanInfo = this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos);
return spanInfo;
@@ -547,7 +532,7 @@ module ts {
/// Computes span information of statement at the requested position in the active file.
public getBreakpointStatementAtPosition(fileName: string, position: number): string {
return this.forwardJSONCall(
"getBreakpointStatementAtPosition(\"" + fileName + "\", " + position + ")",
"getBreakpointStatementAtPosition('" + fileName + "', " + position + ")",
() => {
var spanInfo = this.languageService.getBreakpointStatementAtPosition(fileName, position);
return spanInfo;
@@ -555,32 +540,49 @@ module ts {
}
/// SIGNATUREHELP
/// Computes a string representation of the signatures at the requested position
/// in the active file.
public getSignatureAtPosition(fileName: string, position: number): string {
public getSignatureHelpItems(fileName: string, position: number): string {
return this.forwardJSONCall(
"getSignatureAtPosition(\"" + fileName + "\", " + position + ")",
"getSignatureHelpItems('" + fileName + "', " + position + ")",
() => {
var signatureInfo = this.languageService.getSignatureAtPosition(fileName, position);
var signatureInfo = this.languageService.getSignatureHelpItems(fileName, position);
return signatureInfo;
});
}
public getSignatureHelpCurrentArgumentState(fileName: string, position: number, applicableSpanStart: number): string {
return this.forwardJSONCall(
"getSignatureHelpCurrentArgumentState('" + fileName + "', " + position + ", " + applicableSpanStart + ")",
() => {
var signatureInfo = this.languageService.getSignatureHelpItems(fileName, position);
return signatureInfo;
});
}
/// GOTO DEFINITION
/// Computes the definition location and file for the symbol
/// at the requested position.
public getDefinitionAtPosition(fileName: string, position: number): string {
return this.forwardJSONCall(
"getDefinitionAtPosition(\"" + fileName + "\", " + position + ")",
"getDefinitionAtPosition('" + fileName + "', " + position + ")",
() => {
return this.languageService.getDefinitionAtPosition(fileName, position);
});
}
public getRenameInfo(fileName: string, position: number): string {
return this.forwardJSONCall(
"getRenameInfo('" + fileName + "', " + position + ")",
() => {
return this.languageService.getRenameInfo(fileName, position);
});
}
/// GET BRACE MATCHING
public getBraceMatchingAtPosition(fileName: string, position: number): string {
return this.forwardJSONCall(
"getBraceMatchingAtPosition(\"" + fileName + "\", " + position + ")",
"getBraceMatchingAtPosition('" + fileName + "', " + position + ")",
() => {
var textRanges = this.languageService.getBraceMatchingAtPosition(fileName, position);
return textRanges;
@@ -590,11 +592,10 @@ module ts {
/// GET SMART INDENT
public getIndentationAtPosition(fileName: string, position: number, options: string /*Services.EditorOptions*/): string {
return this.forwardJSONCall(
"getIndentationAtPosition(\"" + fileName + "\", " + position + ")",
"getIndentationAtPosition('" + fileName + "', " + position + ")",
() => {
var localOptions: EditorOptions = JSON.parse(options);
var columnOffset = this.languageService.getIndentationAtPosition(fileName, position, localOptions);
return { value: columnOffset };
return this.languageService.getIndentationAtPosition(fileName, position, localOptions);
});
}
@@ -604,7 +605,7 @@ module ts {
/// Each reference is a "fileindex min lim" sub-string.
public getReferencesAtPosition(fileName: string, position: number): string {
return this.forwardJSONCall(
"getReferencesAtPosition(\"" + fileName + "\", " + position + ")",
"getReferencesAtPosition('" + fileName + "', " + position + ")",
() => {
return this.languageService.getReferencesAtPosition(fileName, position);
});
@@ -612,7 +613,7 @@ module ts {
public getOccurrencesAtPosition(fileName: string, position: number): string {
return this.forwardJSONCall(
"getOccurrencesAtPosition(\"" + fileName + "\", " + position + ")",
"getOccurrencesAtPosition('" + fileName + "', " + position + ")",
() => {
return this.languageService.getOccurrencesAtPosition(fileName, position);
});
@@ -621,7 +622,7 @@ module ts {
/// GET IMPLEMENTORS
public getImplementorsAtPosition(fileName: string, position: number): string {
return this.forwardJSONCall(
"getImplementorsAtPosition(\"" + fileName + "\", " + position + ")",
"getImplementorsAtPosition('" + fileName + "', " + position + ")",
() => {
return this.languageService.getImplementorsAtPosition(fileName, position);
});
@@ -634,7 +635,7 @@ module ts {
/// list if requested.
public getCompletionsAtPosition(fileName: string, position: number, isMemberCompletion: boolean) {
return this.forwardJSONCall(
"getCompletionsAtPosition(\"" + fileName + "\", " + position + ", " + isMemberCompletion + ")",
"getCompletionsAtPosition('" + fileName + "', " + position + ", " + isMemberCompletion + ")",
() => {
var completion = this.languageService.getCompletionsAtPosition(fileName, position, isMemberCompletion);
return completion;
@@ -644,52 +645,38 @@ module ts {
/// Get a string based representation of a completion list entry details
public getCompletionEntryDetails(fileName: string, position: number, entryName: string) {
return this.forwardJSONCall(
"getCompletionEntryDetails(\"" + fileName + "\", " + position + ", " + entryName + ")",
"getCompletionEntryDetails('" + fileName + "', " + position + ", " + entryName + ")",
() => {
var details = this.languageService.getCompletionEntryDetails(fileName, position, entryName);
return details;
});
}
/// FORMAT SELECTION
public getFormattingEditsForRange(fileName: string, minChar: number, limChar: number, options: string/*Services.FormatCodeOptions*/): string {
public getFormattingEditsForRange(fileName: string, start: number, end: number, options: string/*Services.FormatCodeOptions*/): string {
return this.forwardJSONCall(
"getFormattingEditsForRange(\"" + fileName + "\", " + minChar + ", " + limChar + ")",
"getFormattingEditsForRange('" + fileName + "', " + start + ", " + end + ")",
() => {
var localOptions: FormatCodeOptions = JSON.parse(options);
var edits = this.languageService.getFormattingEditsForRange(fileName, minChar, limChar, localOptions);
var localOptions: ts.FormatCodeOptions = JSON.parse(options);
var edits = this.languageService.getFormattingEditsForRange(fileName, start, end, localOptions);
return edits;
});
}
/// FORMAT DOCUMENT
public getFormattingEditsForDocument(fileName: string, minChar: number, limChar: number, options: string/*Services.FormatCodeOptions*/): string {
public getFormattingEditsForDocument(fileName: string, options: string/*Services.FormatCodeOptions*/): string {
return this.forwardJSONCall(
"getFormattingEditsForDocument(\"" + fileName + "\", " + minChar + ", " + limChar + ")",
"getFormattingEditsForDocument('" + fileName + "')",
() => {
var localOptions: FormatCodeOptions = JSON.parse(options);
var edits = this.languageService.getFormattingEditsForDocument(fileName, minChar, limChar, localOptions);
var localOptions: ts.FormatCodeOptions = JSON.parse(options);
var edits = this.languageService.getFormattingEditsForDocument(fileName, localOptions);
return edits;
});
}
/// FORMAT ON PASTE
public getFormattingEditsOnPaste(fileName: string, minChar: number, limChar: number, options: string/*Services.FormatCodeOptions*/): string {
return this.forwardJSONCall(
"getFormattingEditsOnPaste(\"" + fileName + "\", " + minChar + ", " + limChar + ")",
() => {
var localOptions: FormatCodeOptions = JSON.parse(options);
var edits = this.languageService.getFormattingEditsOnPaste(fileName, minChar, limChar, localOptions);
return edits;
});
}
/// FORMAT
public getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: string/*Services.FormatCodeOptions*/): string {
return this.forwardJSONCall(
"getFormattingEditsAfterKeystroke(\"" + fileName + "\", " + position + ", \"" + key + "\")",
"getFormattingEditsAfterKeystroke('" + fileName + "', " + position + ", '" + key + "')",
() => {
var localOptions: FormatCodeOptions = JSON.parse(options);
var localOptions: ts.FormatCodeOptions = JSON.parse(options);
var edits = this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions);
return edits;
});
@@ -699,91 +686,57 @@ module ts {
/// Return a list of symbols that are interesting to navigate to
public getNavigateToItems(searchValue: string): string {
return this.forwardJSONCall(
"getNavigateToItems(\"" + searchValue + "\")",
"getNavigateToItems('" + searchValue + "')",
() => {
var items = this.languageService.getNavigateToItems(searchValue);
var result = this._navigateToItemsToString(items);
return result;
return items;
});
}
// GET SCRIPT LEXICAL STRUCTURE
//
public getScriptLexicalStructure(fileName: string): string {
public getNavigationBarItems(fileName: string): string {
return this.forwardJSONCall(
"getScriptLexicalStructure(\"" + fileName + "\")",
"getNavigationBarItems('" + fileName + "')",
() => {
var items = this.languageService.getScriptLexicalStructure(fileName);
var result = this._navigateToItemsToString(items);
return result;
var items = this.languageService.getNavigationBarItems(fileName);
return items;
});
}
// GET OUTLINING REGIONS
//
public getOutliningRegions(fileName: string): string {
public getOutliningSpans(fileName: string): string {
return this.forwardJSONCall(
"getOutliningRegions(\"" + fileName + "\")",
"getOutliningSpans('" + fileName + "')",
() => {
var items = this.languageService.getOutliningRegions(fileName);
// return just the part of data that language service v2 can understand
// language service v2 will use the entire OutliningSpan
var spans = map(items, i => i.textSpan);
return spans;
var items = this.languageService.getOutliningSpans(fileName);
return items;
});
}
public getTodoComments(fileName: string, descriptors: string): string {
return this.forwardJSONCall(
"getTodoComments('" + fileName + "')",
() => {
var items = this.languageService.getTodoComments(fileName, JSON.parse(descriptors));
return items;
});
}
/// Emit
public getEmitOutput(fileName: string): string {
return this.forwardJSONCall(
"getEmitOutput(\"" + fileName + "\")",
"getEmitOutput('" + fileName + "')",
() => {
var output = this.languageService.getEmitOutput(fileName);
return output;
});
}
private _navigateToItemsToString(items: NavigateToItem[]): any {
var result: {
name: string;
kind: string;
kindModifiers: string;
containerName: string;
containerKind: string;
matchKind: string;
fileName: string;
minChar: number;
limChar: number;
additionalSpans?: { start: number; end: number; }[];
}[] = [];
for (var i = 0; i < items.length; i++) {
var item = items[i];
result.push({
name: item.name,
kind: item.kind,
kindModifiers: item.kindModifiers,
containerName: item.containerName,
containerKind: item.containerKind,
matchKind: item.matchKind,
fileName: item.fileName,
minChar: item.minChar,
limChar: item.limChar,
additionalSpans: item.additionalSpans ? item.additionalSpans.map(i => { return { start: i.minChar, end: i.limChar }; }) : undefined
});
}
return result;
}
}
class ClassifierShimObject extends ShimBase implements ClassifierShim {
public classifier: Classifier;
constructor(factory: ShimFactory, public host: Logger) {
constructor(factory: ShimFactory, public logger: Logger) {
super(factory);
this.classifier = createClassifier(this.host);
this.classifier = createClassifier(this.logger);
}
/// COLORIZATION
@@ -801,12 +754,12 @@ module ts {
}
class CoreServicesShimObject extends ShimBase implements CoreServicesShim {
constructor(factory: ShimFactory, public host: Logger) {
constructor(factory: ShimFactory, public logger: Logger) {
super(factory);
}
private forwardJSONCall(actionDescription: string, action: () => any): any {
return forwardJSONCall(this.host, actionDescription, action);
return forwardJSONCall(this.logger, actionDescription, action);
}
///
@@ -814,7 +767,7 @@ module ts {
///
public getPreProcessedFileInfo(fileName: string, sourceText: TypeScript.IScriptSnapshot): string {
return this.forwardJSONCall(
"getPreProcessedFileInfo(\"" + fileName + "\")",
"getPreProcessedFileInfo('" + fileName + "')",
() => {
var result = TypeScript.preProcessFile(fileName, sourceText);
return result;
@@ -840,8 +793,8 @@ module ts {
public createLanguageServiceShim(host: LanguageServiceShimHost): LanguageServiceShim {
try {
var hostAdapter = new LanguageServiceShimHostAdapter(host);
var pullLanguageService = createLanguageService(hostAdapter, this.documentRegistry);
return new LanguageServiceShimObject(this, host, pullLanguageService);
var languageService = createLanguageService(hostAdapter, this.documentRegistry);
return new LanguageServiceShimObject(this, host, languageService);
}
catch (err) {
logInternalError(host, err);
@@ -849,22 +802,22 @@ module ts {
}
}
public createClassifierShim(host: Logger): ClassifierShim {
public createClassifierShim(logger: Logger): ClassifierShim {
try {
return new ClassifierShimObject(this, host);
return new ClassifierShimObject(this, logger);
}
catch (err) {
logInternalError(host, err);
logInternalError(logger, err);
throw err;
}
}
public createCoreServicesShim(host: Logger): CoreServicesShim {
public createCoreServicesShim(logger: Logger): CoreServicesShim {
try {
return new CoreServicesShimObject(this, host);
return new CoreServicesShimObject(this, logger);
}
catch (err) {
logInternalError(host, err);
logInternalError(logger, err);
throw err;
}
}
+69 -45
View File
@@ -38,13 +38,15 @@ module TypeScript.Scanner {
// _packedFullStartAndInfo:
//
// 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 000x <-- has leading trivia
// 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 00x0 <-- has trailing trivia
// 0000 0000 0000 0000 0000 0000 0000 0000 00xx xxxx xxxx xxxx xxxx xxxx xxxx xx00 <-- full start
// 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 00x0 <-- has leading comment (implies has leading trivia)
// 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0x00 <-- has trailing trivia
// 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 x000 <-- has trailing comment (implies has trailing trivia)
// 0000 0000 0000 0000 0000 0000 0000 0000 00xx xxxx xxxx xxxx xxxx xxxx xxxx 0000 <-- full start
// ^ ^ ^
// | | |
// Bit 64 Bit 30 Bit 1
//
// This gives us 28 bits for the start of the token. At 256MB That's more than enough for
// This gives us 26 bits for the start of the token. At 64MB That's more than enough for
// any codebase.
//
// _packedFullWidthAndKind:
@@ -58,31 +60,31 @@ module TypeScript.Scanner {
// This gives us 23bit for width (or 8MB of width which should be enough for any codebase).
enum ScannerConstants {
LargeTokenFullStartShift = 2,
LargeTokenFullStartShift = 4,
LargeTokenFullWidthShift = 7,
LargeTokenLeadingTriviaBitMask = 0x01, // 00000001
LargeTokenLeadingCommentBitMask = 0x02, // 00000010
LargeTokenTrailingTriviaBitMask = 0x04, // 00000100
LargeTokenTrailingCommentBitMask = 0x08, // 00001000
LargeTokenTriviaBitMask = 0x0F, // 00001111
FixedWidthTokenFullStartShift = 7,
FixedWidthTokenMaxFullStart = 0x7FFFFF, // 23 ones.
SmallTokenFullWidthShift = 7,
SmallTokenFullStartShift = 12,
SmallTokenMaxFullStart = 0x3FFFF, // 18 ones.
SmallTokenMaxFullWidth = 0x1F, // 5 ones
SmallTokenFullWidthMask = 0x1F, // 00011111
KindMask = 0x7F, // 01111111
IsVariableWidthMask = 0x80, // 10000000
LargeTokenLeadingTriviaBitMask = 0x01, // 00000001
LargeTokenTrailingTriviaBitMask = 0x02, // 00000010
SmallTokenFullWidthMask = 0x1F, // 00011111
FixedWidthTokenMaxFullStart = 0x7FFFFF, // 23 ones.
SmallTokenMaxFullStart = 0x3FFFF, // 18 ones.
SmallTokenMaxFullWidth = 0x1F, // 5 ones
}
// Make sure our math works for packing/unpacking large fullStarts.
Debug.assert(largeTokenUnpackFullStart(largeTokenPackFullStartAndInfo(1 << 28, 1, 1)) === (1 << 28));
Debug.assert(largeTokenUnpackFullStart(largeTokenPackFullStartAndInfo(3 << 27, 0, 1)) === (3 << 27));
Debug.assert(largeTokenUnpackFullStart(largeTokenPackFullStartAndInfo(10 << 25, 1, 0)) === (10 << 25));
Debug.assert(largeTokenUnpackFullStart(largeTokenPackFullStartAndInfo(1 << 26, 3)) === (1 << 26));
Debug.assert(largeTokenUnpackFullStart(largeTokenPackFullStartAndInfo(3 << 25, 1)) === (3 << 25));
Debug.assert(largeTokenUnpackFullStart(largeTokenPackFullStartAndInfo(10 << 23, 2)) === (10 << 23));
function fixedWidthTokenPackData(fullStart: number, kind: SyntaxKind) {
return (fullStart << ScannerConstants.FixedWidthTokenFullStartShift) | kind;
@@ -94,8 +96,8 @@ module TypeScript.Scanner {
function smallTokenPackData(fullStart: number, fullWidth: number, kind: SyntaxKind) {
return (fullStart << ScannerConstants.SmallTokenFullStartShift) |
(fullWidth << ScannerConstants.SmallTokenFullWidthShift) |
kind;
(fullWidth << ScannerConstants.SmallTokenFullWidthShift) |
kind;
}
function smallTokenUnpackFullWidth(packedData: number): SyntaxKind {
@@ -106,8 +108,8 @@ module TypeScript.Scanner {
return packedData >> ScannerConstants.SmallTokenFullStartShift;
}
function largeTokenPackFullStartAndInfo(fullStart: number, hasLeadingTriviaInfo: number, hasTrailingTriviaInfo: number): number {
return (fullStart << ScannerConstants.LargeTokenFullStartShift) | hasLeadingTriviaInfo | hasTrailingTriviaInfo;
function largeTokenPackFullStartAndInfo(fullStart: number, triviaInfo: number): number {
return (fullStart << ScannerConstants.LargeTokenFullStartShift) | triviaInfo;
}
function largeTokenUnpackFullWidth(packedFullWidthAndKind: number) {
@@ -118,12 +120,24 @@ module TypeScript.Scanner {
return packedFullStartAndInfo >> ScannerConstants.LargeTokenFullStartShift;
}
function largeTokenUnpackHasLeadingTriviaInfo(packed: number): number {
return packed & ScannerConstants.LargeTokenLeadingTriviaBitMask;
function largeTokenUnpackHasLeadingTrivia(packed: number): boolean {
return (packed & ScannerConstants.LargeTokenLeadingTriviaBitMask) !== 0;
}
function largeTokenUnpackHasTrailingTriviaInfo(packed: number): number {
return packed & ScannerConstants.LargeTokenTrailingTriviaBitMask;
function largeTokenUnpackHasTrailingTrivia(packed: number): boolean {
return (packed & ScannerConstants.LargeTokenTrailingTriviaBitMask) !== 0;
}
function largeTokenUnpackHasLeadingComment(packed: number): boolean {
return (packed & ScannerConstants.LargeTokenLeadingCommentBitMask) !== 0;
}
function largeTokenUnpackHasTrailingComment(packed: number): boolean {
return (packed & ScannerConstants.LargeTokenTrailingCommentBitMask) !== 0;
}
function largeTokenUnpackTriviaInfo(packed: number): number {
return packed & ScannerConstants.LargeTokenTriviaBitMask;
}
var isKeywordStartCharacter: number[] = ArrayUtilities.createArray<number>(CharacterCodes.maxAsciiCharacter, 0);
@@ -174,7 +188,7 @@ module TypeScript.Scanner {
var triviaScanner = createScannerInternal(ts.ScriptTarget.ES5, SimpleText.fromString(""), () => { });
interface IScannerToken extends ISyntaxToken {
interface IScannerToken extends ISyntaxToken {
}
function fillSizeInfo(token: IScannerToken, text: ISimpleText): void {
@@ -256,6 +270,8 @@ module TypeScript.Scanner {
public fullStart(): number { return fixedWidthTokenUnpackFullStart(this._packedData); }
public hasLeadingTrivia(): boolean { return false; }
public hasTrailingTrivia(): boolean { return false; }
public hasLeadingComment(): boolean { return false; }
public hasTrailingComment(): boolean { return false; }
public clone(): ISyntaxToken { return new FixedWidthTokenWithNoTrivia(this._packedData); }
}
@@ -271,19 +287,18 @@ module TypeScript.Scanner {
public setFullStart(fullStart: number): void {
this._packedFullStartAndInfo = largeTokenPackFullStartAndInfo(fullStart,
largeTokenUnpackHasLeadingTriviaInfo(this._packedFullStartAndInfo),
largeTokenUnpackHasTrailingTriviaInfo(this._packedFullStartAndInfo));
largeTokenUnpackTriviaInfo(this._packedFullStartAndInfo));
}
private syntaxTreeText(text: ISimpleText) {
private syntaxTreeText(text: ISimpleText) {
var result = text || syntaxTree(this).text;
Debug.assert(result);
return result;
}
public isIncrementallyUnusable(): boolean { return tokenIsIncrementallyUnusable(this); }
public isKeywordConvertedToIdentifier(): boolean { return false; }
public hasSkippedToken(): boolean { return false; }
public isIncrementallyUnusable(): boolean { return tokenIsIncrementallyUnusable(this); }
public isKeywordConvertedToIdentifier(): boolean { return false; }
public hasSkippedToken(): boolean { return false; }
public fullText(text?: ISimpleText): string {
return fullText(this, this.syntaxTreeText(text));
@@ -294,8 +309,8 @@ module TypeScript.Scanner {
return cachedText !== undefined ? cachedText : SyntaxFacts.getText(this.kind());
}
public leadingTrivia(text?: ISimpleText): ISyntaxTriviaList { return leadingTrivia(this, this.syntaxTreeText(text)); }
public trailingTrivia(text?: ISimpleText): ISyntaxTriviaList { return trailingTrivia(this, this.syntaxTreeText(text)); }
public leadingTrivia(text?: ISimpleText): ISyntaxTriviaList { return leadingTrivia(this, this.syntaxTreeText(text)); }
public trailingTrivia(text?: ISimpleText): ISyntaxTriviaList { return trailingTrivia(this, this.syntaxTreeText(text)); }
public leadingTriviaWidth(text?: ISimpleText): number {
return leadingTriviaWidth(this, this.syntaxTreeText(text));
@@ -308,8 +323,10 @@ module TypeScript.Scanner {
public kind(): SyntaxKind { return this._packedFullWidthAndKind & ScannerConstants.KindMask; }
public fullWidth(): number { return largeTokenUnpackFullWidth(this._packedFullWidthAndKind); }
public fullStart(): number { return largeTokenUnpackFullStart(this._packedFullStartAndInfo); }
public hasLeadingTrivia(): boolean { return largeTokenUnpackHasLeadingTriviaInfo(this._packedFullStartAndInfo) !== 0; }
public hasTrailingTrivia(): boolean { return largeTokenUnpackHasTrailingTriviaInfo(this._packedFullStartAndInfo) !== 0; }
public hasLeadingTrivia(): boolean { return largeTokenUnpackHasLeadingTrivia(this._packedFullStartAndInfo); }
public hasTrailingTrivia(): boolean { return largeTokenUnpackHasTrailingTrivia(this._packedFullStartAndInfo); }
public hasLeadingComment(): boolean { return largeTokenUnpackHasLeadingComment(this._packedFullStartAndInfo); }
public hasTrailingComment(): boolean { return largeTokenUnpackHasTrailingComment(this._packedFullStartAndInfo); }
public clone(): ISyntaxToken { return new LargeScannerToken(this._packedFullStartAndInfo, this._packedFullWidthAndKind, this.cachedText); }
}
@@ -351,8 +368,8 @@ module TypeScript.Scanner {
}
function reset(_text: ISimpleText, _start: number, _end: number) {
Debug.assert(_start <= _text.length());
Debug.assert(_end <= _text.length());
Debug.assert(_start <= _text.length(), "Token's start was not within the bounds of text: " + _start + " - [0, " + _text.length() + ")");
Debug.assert(_end <= _text.length(), "Token's end was not within the bounds of text: " + _end + " - [0, " + _text.length() + ")");
if (!str || text !== _text) {
text = _text;
@@ -392,7 +409,7 @@ module TypeScript.Scanner {
else {
// inline the packing logic for perf.
var packedFullStartAndTriviaInfo = (fullStart << ScannerConstants.LargeTokenFullStartShift) |
leadingTriviaInfo | (trailingTriviaInfo << 1);
leadingTriviaInfo | (trailingTriviaInfo << 2);
var packedFullWidthAndKind = (fullWidth << ScannerConstants.LargeTokenFullWidthShift) | kind;
var cachedText = isFixedWidth ? undefined : text.substr(start, end - start);
@@ -505,7 +522,8 @@ module TypeScript.Scanner {
case CharacterCodes.verticalTab:
case CharacterCodes.formFeed:
index++;
result = 1;
// we have trivia
result |= 1;
continue;
case CharacterCodes.carriageReturn:
@@ -516,27 +534,31 @@ module TypeScript.Scanner {
case CharacterCodes.lineFeed:
index++;
// we have trivia
result |= 1;
// If we're consuming leading trivia, then we will continue consuming more
// trivia (including newlines) up to the first token we see. If we're
// consuming trailing trivia, then we break after the first newline we see.
if (isTrailing) {
return 1;
return result;
}
result = 1;
continue;
case CharacterCodes.slash:
if ((index + 1) < _end) {
var ch2 = str.charCodeAt(index + 1);
if (ch2 === CharacterCodes.slash) {
result = 1;
// we have a comment, and we have trivia
result |= 3;
skipSingleLineCommentTrivia();
continue;
}
if (ch2 === CharacterCodes.asterisk) {
result = 1;
// we have a comment, and we have trivia
result |= 3;
skipMultiLineCommentTrivia();
continue;
}
@@ -547,7 +569,7 @@ module TypeScript.Scanner {
default:
if (ch > CharacterCodes.maxAsciiCharacter && slowScanTriviaInfo(ch)) {
result = 1;
result |= 1;
continue;
}
@@ -1427,7 +1449,7 @@ module TypeScript.Scanner {
var fullEnd = fullStart + token.fullWidth();
reset(text, fullStart, fullEnd);
var leadingTriviaInfo = scanTriviaInfo(/*isTrailing: */ false);
scanTriviaInfo(/*isTrailing: */ false);
var start = index;
scanSyntaxKind(isContextualToken(token));
@@ -1616,6 +1638,8 @@ module TypeScript.Scanner {
}
function resetToPosition(absolutePosition: number): void {
Debug.assert(absolutePosition <= text.length(), "Trying to set the position outside the bounds of the text!");
_absolutePosition = absolutePosition;
// First, remove any diagnostics that came after this position.
+24 -9
View File
@@ -17,6 +17,8 @@ module TypeScript {
hasLeadingTrivia(): boolean;
hasTrailingTrivia(): boolean;
hasLeadingComment(): boolean;
hasTrailingComment(): boolean;
hasSkippedToken(): boolean;
@@ -264,7 +266,7 @@ module TypeScript.Syntax {
export function realizeToken(token: ISyntaxToken, text: ISimpleText): ISyntaxToken {
return new RealizedToken(token.fullStart(), token.kind(), token.isKeywordConvertedToIdentifier(), token.leadingTrivia(text), token.text(), token.trailingTrivia(text));
}
export function convertKeywordToIdentifier(token: ISyntaxToken): ISyntaxToken {
return new ConvertedKeywordToken(token);
}
@@ -381,11 +383,14 @@ module TypeScript.Syntax {
public fullText(): string { return ""; }
public hasLeadingTrivia() { return false; }
public leadingTriviaWidth() { return 0; }
public hasTrailingTrivia() { return false; }
public hasLeadingComment() { return false; }
public hasTrailingComment() { return false; }
public hasSkippedToken() { return false; }
public leadingTriviaWidth() { return 0; }
public trailingTriviaWidth() { return 0; }
public leadingTrivia(): ISyntaxTriviaList { return Syntax.emptyTriviaList; }
public trailingTrivia(): ISyntaxTriviaList { return Syntax.emptyTriviaList; }
}
@@ -401,11 +406,11 @@ module TypeScript.Syntax {
public _primaryExpressionBrand: any; public _memberExpressionBrand: any; public _leftHandSideExpressionBrand: any; public _postfixExpressionBrand: any; public _unaryExpressionBrand: any; public _expressionBrand: any; public _typeBrand: any;
constructor(fullStart: number,
kind: SyntaxKind,
isKeywordConvertedToIdentifier: boolean,
leadingTrivia: ISyntaxTriviaList,
text: string,
trailingTrivia: ISyntaxTriviaList) {
kind: SyntaxKind,
isKeywordConvertedToIdentifier: boolean,
leadingTrivia: ISyntaxTriviaList,
text: string,
trailingTrivia: ISyntaxTriviaList) {
this._fullStart = fullStart;
this._kind = kind;
this._isKeywordConvertedToIdentifier = isKeywordConvertedToIdentifier;
@@ -438,8 +443,8 @@ module TypeScript.Syntax {
// Realized tokens are created from the parser. They are *never* incrementally reusable.
public isIncrementallyUnusable() { return true; }
public isKeywordConvertedToIdentifier() {
return this._isKeywordConvertedToIdentifier;
public isKeywordConvertedToIdentifier() {
return this._isKeywordConvertedToIdentifier;
}
public fullStart(): number { return this._fullStart; }
@@ -450,6 +455,8 @@ module TypeScript.Syntax {
public hasLeadingTrivia(): boolean { return this._leadingTrivia.count() > 0; }
public hasTrailingTrivia(): boolean { return this._trailingTrivia.count() > 0; }
public hasLeadingComment(): boolean { return this._leadingTrivia.hasComment(); }
public hasTrailingComment(): boolean { return this._trailingTrivia.hasComment(); }
public leadingTriviaWidth(): number { return this._leadingTrivia.fullWidth(); }
public trailingTriviaWidth(): number { return this._trailingTrivia.fullWidth(); }
@@ -504,6 +511,14 @@ module TypeScript.Syntax {
return this.underlyingToken.hasTrailingTrivia();
}
public hasLeadingComment(): boolean {
return this.underlyingToken.hasLeadingComment();
}
public hasTrailingComment(): boolean {
return this.underlyingToken.hasTrailingComment();
}
public hasSkippedToken(): boolean {
return this.underlyingToken.hasSkippedToken();
}
+7 -5
View File
@@ -16,10 +16,12 @@ module TypeScript {
// always determine this (albeit in a more expensive manner).
getLineStartPositions(): number[];
// Returns a text change range representing what text has changed since the specified version.
// If the change cannot be determined (say, because a file was opened/closed), then 'null'
// should be returned.
getTextChangeRangeSinceVersion(scriptVersion: number): TextChangeRange;
// Gets the TextChangeRange that describe how the text changed between this text and
// an older version. This informatoin is used by the incremental parser to determine
// what sections of the script need to be reparsed. 'null' can be returned if the
// change range cannot be determined. However, in that case, incremental parsing will
// not happen and the entire document will be reparsed.
getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange;
}
export module ScriptSnapshot {
@@ -45,7 +47,7 @@ module TypeScript {
return this._lineStartPositions;
}
public getTextChangeRangeSinceVersion(scriptVersion: number): TypeScript.TextChangeRange {
public getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange {
throw Errors.notYetImplemented();
}
}
+4
View File
@@ -27,6 +27,10 @@ module TypeScript {
this._length = length;
}
public toJSON(key: any): any {
return { start: this._start, length: this._length };
}
public start(): number {
return this._start;
}
+40
View File
@@ -0,0 +1,40 @@
=== tests/cases/compiler/2dArrays.ts ===
class Cell {
>Cell : Cell
}
class Ship {
>Ship : Ship
isSunk: boolean;
>isSunk : boolean
}
class Board {
>Board : Board
ships: Ship[];
>ships : Ship[]
>Ship : Ship
cells: Cell[];
>cells : Cell[]
>Cell : Cell
private allShipsSunk() {
>allShipsSunk : () => boolean
return this.ships.every(function (val) { return val.isSunk; });
>this.ships.every(function (val) { return val.isSunk; }) : boolean
>this.ships.every : (callbackfn: (value: Ship, index: number, array: Ship[]) => boolean, thisArg?: any) => boolean
>this.ships : Ship[]
>this : Board
>ships : Ship[]
>every : (callbackfn: (value: Ship, index: number, array: Ship[]) => boolean, thisArg?: any) => boolean
>function (val) { return val.isSunk; } : (val: Ship) => boolean
>val : Ship
>val.isSunk : boolean
>val : Ship
>isSunk : boolean
}
}
@@ -0,0 +1,33 @@
=== tests/cases/conformance/internalModules/DeclarationMerging/module.d.ts ===
declare module Point {
>Point : typeof Point
export var Origin: { x: number; y: number; }
>Origin : { x: number; y: number; }
>x : number
>y : number
}
=== tests/cases/conformance/internalModules/DeclarationMerging/function.d.ts ===
declare function Point(): { x: number; y: number; }
>Point : typeof Point
>x : number
>y : number
=== tests/cases/conformance/internalModules/DeclarationMerging/test.ts ===
var cl: { x: number; y: number; }
>cl : { x: number; y: number; }
>x : number
>y : number
var cl = Point();
>cl : { x: number; y: number; }
>Point() : { x: number; y: number; }
>Point : typeof Point
var cl = Point.Origin;
>cl : { x: number; y: number; }
>Point.Origin : { x: number; y: number; }
>Point : typeof Point
>Origin : { x: number; y: number; }
@@ -28,4 +28,4 @@ var p = new A.Point(0, 0); // unexpected error here, bug 840000
//// [test.js]
var p;
var p = A.Point.Origin;
var p = new A.Point(0, 0);
var p = new A.Point(0, 0); // unexpected error here, bug 840000
@@ -0,0 +1,59 @@
=== tests/cases/conformance/internalModules/DeclarationMerging/module.d.ts ===
declare module A {
>A : typeof A
export module Point {
>Point : typeof Point
export var Origin: {
>Origin : { x: number; y: number; }
x: number;
>x : number
y: number;
>y : number
}
}
}
=== tests/cases/conformance/internalModules/DeclarationMerging/class.d.ts ===
declare module A {
>A : typeof A
export class Point {
>Point : Point
constructor(x: number, y: number);
>x : number
>y : number
x: number;
>x : number
y: number;
>y : number
}
}
=== tests/cases/conformance/internalModules/DeclarationMerging/test.ts ===
var p: { x: number; y: number; }
>p : { x: number; y: number; }
>x : number
>y : number
var p = A.Point.Origin;
>p : { x: number; y: number; }
>A.Point.Origin : { x: number; y: number; }
>A.Point : typeof A.Point
>A : typeof A
>Point : typeof A.Point
>Origin : { x: number; y: number; }
var p = new A.Point(0, 0); // unexpected error here, bug 840000
>p : { x: number; y: number; }
>new A.Point(0, 0) : A.Point
>A.Point : typeof A.Point
>A : typeof A
>Point : typeof A.Point
@@ -37,4 +37,4 @@ var A;
//// [test.js]
var p;
var p = A.Point.Origin;
var p = new A.Point(0, 0);
var p = new A.Point(0, 0); // unexpected error here, bug 840000
@@ -0,0 +1,53 @@
=== tests/cases/conformance/internalModules/DeclarationMerging/module.d.ts ===
declare module A {
>A : typeof A
export module Point {
>Point : typeof Point
export var Origin: {
>Origin : { x: number; y: number; }
x: number;
>x : number
y: number;
>y : number
}
}
}
=== tests/cases/conformance/internalModules/DeclarationMerging/classPoint.ts ===
module A {
>A : typeof A
export class Point {
>Point : Point
constructor(public x: number, public y: number) { }
>x : number
>y : number
}
}
=== tests/cases/conformance/internalModules/DeclarationMerging/test.ts ===
var p: { x: number; y: number; }
>p : { x: number; y: number; }
>x : number
>y : number
var p = A.Point.Origin;
>p : { x: number; y: number; }
>A.Point.Origin : { x: number; y: number; }
>A.Point : typeof A.Point
>A : typeof A
>Point : typeof A.Point
>Origin : { x: number; y: number; }
var p = new A.Point(0, 0); // unexpected error here, bug 840000
>p : { x: number; y: number; }
>new A.Point(0, 0) : A.Point
>A.Point : typeof A.Point
>A : typeof A
>Point : typeof A.Point
@@ -0,0 +1,37 @@
=== tests/cases/conformance/internalModules/DeclarationMerging/module.d.ts ===
declare module Point {
>Point : typeof Point
export var Origin: { x: number; y: number; }
>Origin : { x: number; y: number; }
>x : number
>y : number
}
=== tests/cases/conformance/internalModules/DeclarationMerging/function.ts ===
function Point() {
>Point : typeof Point
return { x: 0, y: 0 };
>{ x: 0, y: 0 } : { x: number; y: number; }
>x : number
>y : number
}
=== tests/cases/conformance/internalModules/DeclarationMerging/test.ts ===
var cl: { x: number; y: number; }
>cl : { x: number; y: number; }
>x : number
>y : number
var cl = Point();
>cl : { x: number; y: number; }
>Point() : { x: number; y: number; }
>Point : typeof Point
var cl = Point.Origin;
>cl : { x: number; y: number; }
>Point.Origin : { x: number; y: number; }
>Point : typeof Point
>Origin : { x: number; y: number; }
@@ -0,0 +1,6 @@
==== tests/cases/conformance/parser/ecmascript5/ErrorRecovery/ArrowFunctions/ArrowFunction1.ts (1 errors) ====
var v = (a: ) => {
~
!!! Type expected.
};
@@ -0,0 +1,8 @@
==== tests/cases/conformance/parser/ecmascript5/ErrorRecovery/ArrowFunctions/ArrowFunction2.ts (2 errors) ====
var v = (a: b,) => {
~
!!! Trailing comma not allowed.
~
!!! Cannot find name 'b'.
};
@@ -0,0 +1,10 @@
==== tests/cases/conformance/parser/ecmascript5/ErrorRecovery/ArrowFunctions/ArrowFunction3.ts (3 errors) ====
var v = (a): => {
~
!!! ',' expected.
~~
!!! ';' expected.
~
!!! Cannot find name 'a'.
};
@@ -0,0 +1,8 @@
//// [ArrowFunction4.ts]
var v = (a, b) => {
};
//// [ArrowFunction4.js]
var v = function (a, b) {
};
@@ -0,0 +1,8 @@
=== tests/cases/conformance/parser/ecmascript5/ErrorRecovery/ArrowFunctions/ArrowFunction4.ts ===
var v = (a, b) => {
>v : (a: any, b: any) => void
>(a, b) => { } : (a: any, b: any) => void
>a : any
>b : any
};
@@ -50,6 +50,7 @@ module clodule4 {
//// [ClassAndModuleThatMergeWithModuleMemberThatUsesClassTypeParameter.js]
// all expected to be errors
var clodule1 = (function () {
function clodule1() {
}
@@ -25,6 +25,7 @@ var clodule = (function () {
})();
var clodule;
(function (clodule) {
// error: duplicate identifier expected
function fn(x, y) {
return x;
}
@@ -25,6 +25,7 @@ var clodule = (function () {
})();
var clodule;
(function (clodule) {
// error: duplicate identifier expected
function fn(x, y) {
return x;
}
@@ -26,6 +26,7 @@ var clodule = (function () {
})();
var clodule;
(function (clodule) {
// error: duplicate identifier expected
function fn(x, y) {
return clodule.sfn('a');
}
@@ -30,7 +30,7 @@ var Point = (function () {
}
Point.Origin = function () {
return { x: 0, y: 0 };
};
}; // unexpected error here bug 840246
return Point;
})();
var Point;
@@ -38,7 +38,7 @@ var Point;
function Origin() {
return null;
}
Point.Origin = Origin;
Point.Origin = Origin; //expected duplicate identifier error
})(Point || (Point = {}));
var A;
(function (A) {
@@ -49,7 +49,7 @@ var A;
}
Point.Origin = function () {
return { x: 0, y: 0 };
};
}; // unexpected error here bug 840246
return Point;
})();
A.Point = Point;
@@ -57,7 +57,7 @@ var A;
function Origin() {
return "";
}
Point.Origin = Origin;
Point.Origin = Origin; //expected duplicate identifier error
})(A.Point || (A.Point = {}));
var Point = A.Point;
})(A || (A = {}));
@@ -37,7 +37,7 @@ var Point;
(function (Point) {
function Origin() {
return "";
}
} // not an error, since not exported
})(Point || (Point = {}));
var A;
(function (A) {
@@ -55,7 +55,7 @@ var A;
(function (Point) {
function Origin() {
return "";
}
} // not an error since not exported
})(A.Point || (A.Point = {}));
var Point = A.Point;
})(A || (A = {}));
@@ -0,0 +1,49 @@
=== tests/cases/conformance/internalModules/DeclarationMerging/ClassAndModuleThatMergeWithStaticFunctionAndNonExportedFunctionThatShareAName.ts ===
class Point {
>Point : Point
constructor(public x: number, public y: number) { }
>x : number
>y : number
static Origin(): Point { return { x: 0, y: 0 }; }
>Origin : () => Point
>Point : Point
>{ x: 0, y: 0 } : { x: number; y: number; }
>x : number
>y : number
}
module Point {
>Point : typeof Point
function Origin() { return ""; }// not an error, since not exported
>Origin : () => string
}
module A {
>A : typeof A
export class Point {
>Point : Point
constructor(public x: number, public y: number) { }
>x : number
>y : number
static Origin(): Point { return { x: 0, y: 0 }; }
>Origin : () => Point
>Point : Point
>{ x: 0, y: 0 } : { x: number; y: number; }
>x : number
>y : number
}
export module Point {
>Point : typeof Point
function Origin() { return ""; }// not an error since not exported
>Origin : () => string
}
}
@@ -33,7 +33,7 @@ var Point = (function () {
})();
var Point;
(function (Point) {
Point.Origin = "";
Point.Origin = ""; //expected duplicate identifier error
})(Point || (Point = {}));
var A;
(function (A) {
@@ -47,7 +47,7 @@ var A;
})();
A.Point = Point;
(function (Point) {
Point.Origin = "";
Point.Origin = ""; //expected duplicate identifier error
})(A.Point || (A.Point = {}));
var Point = A.Point;
})(A || (A = {}));
@@ -33,7 +33,7 @@ var Point = (function () {
})();
var Point;
(function (Point) {
var Origin = "";
var Origin = ""; // not an error, since not exported
})(Point || (Point = {}));
var A;
(function (A) {
@@ -47,7 +47,7 @@ var A;
})();
A.Point = Point;
(function (Point) {
var Origin = "";
var Origin = ""; // not an error since not exported
})(A.Point || (A.Point = {}));
var Point = A.Point;
})(A || (A = {}));
@@ -0,0 +1,49 @@
=== tests/cases/conformance/internalModules/DeclarationMerging/ClassAndModuleThatMergeWithStaticVariableAndNonExportedVarThatShareAName.ts ===
class Point {
>Point : Point
constructor(public x: number, public y: number) { }
>x : number
>y : number
static Origin: Point = { x: 0, y: 0 };
>Origin : Point
>Point : Point
>{ x: 0, y: 0 } : { x: number; y: number; }
>x : number
>y : number
}
module Point {
>Point : typeof Point
var Origin = ""; // not an error, since not exported
>Origin : string
}
module A {
>A : typeof A
export class Point {
>Point : Point
constructor(public x: number, public y: number) { }
>x : number
>y : number
static Origin: Point = { x: 0, y: 0 };
>Origin : Point
>Point : Point
>{ x: 0, y: 0 } : { x: number; y: number; }
>x : number
>y : number
}
export module Point {
>Point : typeof Point
var Origin = ""; // not an error since not exported
>Origin : string
}
}
@@ -0,0 +1,3 @@
=== tests/cases/conformance/internalModules/DeclarationMerging/ClassAndModuleThatMergeWithStringIndexerAndExportedFunctionWithTypeIncompatibleWithIndexer.ts ===
No type information for this code.
@@ -67,8 +67,9 @@ var X;
var Y = X.Y;
})(X || (X = {}));
//// [test.js]
//var cl: { x: number; y: number; }
var cl = new X.Y.Point(1, 1);
var cl = X.Y.Point.Origin;
var cl = X.Y.Point.Origin; // error not expected here same as bug 83996 ?
//// [simple.js]
var A = (function () {
function A() {
@@ -79,6 +80,7 @@ var A;
(function (A) {
A.Instance = new A();
})(A || (A = {}));
// ensure merging works as expected
var a = A.Instance;
var a = new A();
var a;
@@ -0,0 +1,43 @@
=== tests/cases/conformance/internalModules/DeclarationMerging/EnumAndModuleWithSameNameAndCommonRoot.ts ===
enum enumdule {
>enumdule : enumdule
Red, Blue
>Red : enumdule
>Blue : enumdule
}
module enumdule {
>enumdule : typeof enumdule
export class Point {
>Point : Point
constructor(public x: number, public y: number) { }
>x : number
>y : number
}
}
var x: enumdule;
>x : enumdule
>enumdule : enumdule
var x = enumdule.Red;
>x : enumdule
>enumdule.Red : enumdule
>enumdule : typeof enumdule
>Red : enumdule
var y: { x: number; y: number };
>y : { x: number; y: number; }
>x : number
>y : number
var y = new enumdule.Point(0, 0);
>y : { x: number; y: number; }
>new enumdule.Point(0, 0) : enumdule.Point
>enumdule.Point : typeof enumdule.Point
>enumdule : typeof enumdule
>Point : typeof enumdule.Point
@@ -6,6 +6,6 @@
export = B;
~~~~~~~~~~~
!!! An export assignment cannot be used in a module with other exported elements.
!!! Cannot find name 'B'.
~~~~~~~~~~~
!!! Cannot find name 'B'.
!!! An export assignment cannot be used in a module with other exported elements.
@@ -3,9 +3,9 @@
~~~~~~~~~~~
!!! Cannot compile external modules unless the '--module' flag is provided.
~~~~~~~~~~~
!!! An export assignment cannot be used in a module with other exported elements.
~~~~~~~~~~~
!!! Cannot find name 'B'.
~~~~~~~~~~~
!!! An export assignment cannot be used in a module with other exported elements.
export class C {
}
@@ -0,0 +1,38 @@
=== tests/cases/conformance/internalModules/exportDeclarations/ExportClassWhichExtendsInterfaceWithInaccessibleType.ts ===
module A {
>A : typeof A
interface Point {
>Point : Point
x: number;
>x : number
y: number;
>y : number
fromOrigin(p: Point): number;
>fromOrigin : (p: Point) => number
>p : Point
>Point : Point
}
export class Point2d implements Point {
>Point2d : Point2d
>Point : Point
constructor(public x: number, public y: number) { }
>x : number
>y : number
fromOrigin(p: Point) {
>fromOrigin : (p: Point) => number
>p : Point
>Point : Point
return 1;
}
}
}
@@ -0,0 +1,50 @@
=== tests/cases/conformance/internalModules/exportDeclarations/ExportClassWithAccessibleTypesInTypeParameterConstraintsClassHeritageListMemberTypeAnnotations.ts ===
module A {
>A : typeof A
export class Point {
>Point : Point
x: number;
>x : number
y: number;
>y : number
}
export var Origin: Point = { x: 0, y: 0 };
>Origin : Point
>Point : Point
>{ x: 0, y: 0 } : { x: number; y: number; }
>x : number
>y : number
export class Point3d extends Point {
>Point3d : Point3d
>Point : Point
z: number;
>z : number
}
export var Origin3d: Point3d = { x: 0, y: 0, z: 0 };
>Origin3d : Point3d
>Point3d : Point3d
>{ x: 0, y: 0, z: 0 } : { x: number; y: number; z: number; }
>x : number
>y : number
>z : number
export class Line<TPoint extends Point>{
>Line : Line<TPoint>
>TPoint : TPoint
>Point : Point
constructor(public start: TPoint, public end: TPoint) { }
>start : TPoint
>TPoint : TPoint
>end : TPoint
>TPoint : TPoint
}
}
@@ -0,0 +1,28 @@
=== tests/cases/conformance/internalModules/exportDeclarations/ExportClassWithInaccessibleTypeInIndexerTypeAnnotations.ts ===
module A {
>A : typeof A
class Point {
>Point : Point
x: number;
>x : number
y: number;
>y : number
}
export class points {
>points : points
[idx: number]: Point;
>idx : number
>Point : Point
[idx: string]: Point;
>idx : string
>Point : Point
}
}
@@ -0,0 +1,60 @@
=== tests/cases/conformance/internalModules/exportDeclarations/ExportClassWithInaccessibleTypeInTypeParameterConstraint.ts ===
module A {
>A : typeof A
class Point {
>Point : Point
x: number;
>x : number
y: number;
>y : number
}
export var Origin: Point = { x: 0, y: 0 };
>Origin : Point
>Point : Point
>{ x: 0, y: 0 } : { x: number; y: number; }
>x : number
>y : number
export class Point3d extends Point {
>Point3d : Point3d
>Point : Point
z: number;
>z : number
}
export var Origin3d: Point3d = { x: 0, y: 0, z: 0 };
>Origin3d : Point3d
>Point3d : Point3d
>{ x: 0, y: 0, z: 0 } : { x: number; y: number; z: number; }
>x : number
>y : number
>z : number
export class Line<TPoint extends Point>{
>Line : Line<TPoint>
>TPoint : TPoint
>Point : Point
constructor(public start: TPoint, public end: TPoint) { }
>start : TPoint
>TPoint : TPoint
>end : TPoint
>TPoint : TPoint
static fromorigin2d(p: Point): Line<Point>{
>fromorigin2d : (p: Point) => Line<Point>
>p : Point
>Point : Point
>Line : Line<TPoint>
>Point : Point
return null;
}
}
}
@@ -0,0 +1,39 @@
=== tests/cases/conformance/internalModules/exportDeclarations/ExportFunctionWithAccessibleTypesInParameterAndReturnTypeAnnotation.ts ===
module A {
>A : typeof A
export class Point {
>Point : Point
x: number;
>x : number
y: number;
>y : number
}
export class Line {
>Line : Line
constructor(public start: Point, public end: Point) { }
>start : Point
>Point : Point
>end : Point
>Point : Point
}
export function fromOrigin(p: Point): Line {
>fromOrigin : (p: Point) => Line
>p : Point
>Point : Point
>Line : Line
return new Line({ x: 0, y: 0 }, p);
>new Line({ x: 0, y: 0 }, p) : Line
>Line : typeof Line
>{ x: 0, y: 0 } : { x: number; y: number; }
>x : number
>y : number
>p : Point
}
}
@@ -0,0 +1,39 @@
=== tests/cases/conformance/internalModules/exportDeclarations/ExportFunctionWithInaccessibleTypesInParameterTypeAnnotation.ts ===
module A {
>A : typeof A
class Point {
>Point : Point
x: number;
>x : number
y: number;
>y : number
}
export class Line {
>Line : Line
constructor(public start: Point, public end: Point) { }
>start : Point
>Point : Point
>end : Point
>Point : Point
}
export function fromOrigin(p: Point): Line {
>fromOrigin : (p: Point) => Line
>p : Point
>Point : Point
>Line : Line
return new Line({ x: 0, y: 0 }, p);
>new Line({ x: 0, y: 0 }, p) : Line
>Line : typeof Line
>{ x: 0, y: 0 } : { x: number; y: number; }
>x : number
>y : number
>p : Point
}
}
@@ -0,0 +1,39 @@
=== tests/cases/conformance/internalModules/exportDeclarations/ExportFunctionWithInaccessibleTypesInReturnTypeAnnotation.ts ===
module A {
>A : typeof A
export class Point {
>Point : Point
x: number;
>x : number
y: number;
>y : number
}
class Line {
>Line : Line
constructor(public start: Point, public end: Point) { }
>start : Point
>Point : Point
>end : Point
>Point : Point
}
export function fromOrigin(p: Point): Line {
>fromOrigin : (p: Point) => Line
>p : Point
>Point : Point
>Line : Line
return new Line({ x: 0, y: 0 }, p);
>new Line({ x: 0, y: 0 }, p) : Line
>Line : typeof Line
>{ x: 0, y: 0 } : { x: number; y: number; }
>x : number
>y : number
>p : Point
}
}
@@ -0,0 +1,58 @@
=== tests/cases/conformance/internalModules/exportDeclarations/ExportInterfaceWithAccessibleTypesInTypeParameterConstraintsClassHeritageListMemberTypeAnnotations.ts ===
module A {
>A : typeof A
export interface Point {
>Point : Point
x: number;
>x : number
y: number;
>y : number
}
export var Origin: Point = { x: 0, y: 0 };
>Origin : Point
>Point : Point
>{ x: 0, y: 0 } : { x: number; y: number; }
>x : number
>y : number
export interface Point3d extends Point {
>Point3d : Point3d
>Point : Point
z: number;
>z : number
}
export var Origin3d: Point3d = { x: 0, y: 0, z: 0 };
>Origin3d : Point3d
>Point3d : Point3d
>{ x: 0, y: 0, z: 0 } : { x: number; y: number; z: number; }
>x : number
>y : number
>z : number
export interface Line<TPoint extends Point>{
>Line : Line<TPoint>
>TPoint : TPoint
>Point : Point
new (start: TPoint, end: TPoint);
>start : TPoint
>TPoint : TPoint
>end : TPoint
>TPoint : TPoint
start: TPoint;
>start : TPoint
>TPoint : TPoint
end: TPoint;
>end : TPoint
>TPoint : TPoint
}
}
@@ -0,0 +1,28 @@
=== tests/cases/conformance/internalModules/exportDeclarations/ExportInterfaceWithInaccessibleTypeInIndexerTypeAnnotations.ts ===
module A {
>A : unknown
interface Point {
>Point : Point
x: number;
>x : number
y: number;
>y : number
}
export interface points {
>points : points
[idx: number]: Point;
>idx : number
>Point : Point
[idx: string]: Point;
>idx : string
>Point : Point
}
}
@@ -0,0 +1,58 @@
=== tests/cases/conformance/internalModules/exportDeclarations/ExportInterfaceWithInaccessibleTypeInTypeParameterConstraint.ts ===
module A {
>A : typeof A
interface Point {
>Point : Point
x: number;
>x : number
y: number;
>y : number
}
export var Origin: Point = { x: 0, y: 0 };
>Origin : Point
>Point : Point
>{ x: 0, y: 0 } : { x: number; y: number; }
>x : number
>y : number
export interface Point3d extends Point {
>Point3d : Point3d
>Point : Point
z: number;
>z : number
}
export var Origin3d: Point3d = { x: 0, y: 0, z: 0 };
>Origin3d : Point3d
>Point3d : Point3d
>{ x: 0, y: 0, z: 0 } : { x: number; y: number; z: number; }
>x : number
>y : number
>z : number
export interface Line<TPoint extends Point>{
>Line : Line<TPoint>
>TPoint : TPoint
>Point : Point
new (start: TPoint, end: TPoint);
>start : TPoint
>TPoint : TPoint
>end : TPoint
>TPoint : TPoint
start: TPoint;
>start : TPoint
>TPoint : TPoint
end: TPoint;
>end : TPoint
>TPoint : TPoint
}
}
@@ -0,0 +1,48 @@
=== tests/cases/conformance/internalModules/exportDeclarations/ExportModuleWithAccessibleTypesOnItsExportedMembers.ts ===
module A {
>A : typeof A
export class Point {
>Point : Point
constructor(public x: number, public y: number) { }
>x : number
>y : number
}
export module B {
>B : typeof B
export var Origin: Point = new Point(0, 0);
>Origin : Point
>Point : Point
>new Point(0, 0) : Point
>Point : typeof Point
export class Line {
>Line : Line
constructor(start: Point, end: Point) {
>start : Point
>Point : Point
>end : Point
>Point : Point
}
static fromOrigin(p: Point) {
>fromOrigin : (p: Point) => Line
>p : Point
>Point : Point
return new Line({ x: 0, y: 0 }, p);
>new Line({ x: 0, y: 0 }, p) : Line
>Line : typeof Line
>{ x: 0, y: 0 } : { x: number; y: number; }
>x : number
>y : number
>p : Point
}
}
}
}
@@ -0,0 +1,30 @@
=== tests/cases/conformance/internalModules/exportDeclarations/ExportObjectLiteralAndObjectTypeLiteralWithAccessibleTypesInMemberTypeAnnotations.ts ===
module A {
>A : typeof A
class Point {
>Point : Point
constructor(public x: number, public y: number) { }
>x : number
>y : number
}
export var Origin: Point = { x: 0, y: 0 };
>Origin : Point
>Point : Point
>{ x: 0, y: 0 } : { x: number; y: number; }
>x : number
>y : number
export var Unity = { start: new Point(0, 0), end: new Point(1, 0) };
>Unity : { start: Point; end: Point; }
>{ start: new Point(0, 0), end: new Point(1, 0) } : { start: Point; end: Point; }
>start : Point
>new Point(0, 0) : Point
>Point : typeof Point
>end : Point
>new Point(1, 0) : Point
>Point : typeof Point
}
@@ -0,0 +1,22 @@
=== tests/cases/conformance/internalModules/exportDeclarations/ExportVariableOfGenericTypeWithInaccessibleTypeAsTypeArgument.ts ===
module A {
>A : typeof A
class B {
>B : B
id: number;
>id : number
}
export var beez: Array<B>;
>beez : B[]
>Array : T[]
>B : B
export var beez2 = new Array<B>();
>beez2 : B[]
>new Array<B>() : B[]
>Array : { (arrayLength?: number): any[]; <T>(arrayLength: number): T[]; <T>(...items: T[]): T[]; new (arrayLength?: number): any[]; new <T>(arrayLength: number): T[]; new <T>(...items: T[]): T[]; isArray(arg: any): boolean; prototype: any[]; }
>B : B
}
@@ -14,5 +14,6 @@ module A {
//// [ExportVariableWithAccessibleTypeInTypeAnnotation.js]
var A;
(function (A) {
// valid since Point is exported
A.Origin = { x: 0, y: 0 };
})(A || (A = {}));
@@ -0,0 +1,23 @@
=== tests/cases/conformance/internalModules/exportDeclarations/ExportVariableWithAccessibleTypeInTypeAnnotation.ts ===
module A {
>A : typeof A
export interface Point {
>Point : Point
x: number;
>x : number
y: number;
>y : number
}
// valid since Point is exported
export var Origin: Point = { x: 0, y: 0 };
>Origin : Point
>Point : Point
>{ x: 0, y: 0 } : { x: number; y: number; }
>x : number
>y : number
}
@@ -21,6 +21,8 @@ module A {
//// [ExportVariableWithInaccessibleTypeInTypeAnnotation.js]
var A;
(function (A) {
// valid since Point is exported
A.Origin = { x: 0, y: 0 };
// invalid Point3d is not exported
A.Origin3d = { x: 0, y: 0, z: 0 };
})(A || (A = {}));
@@ -0,0 +1,40 @@
=== tests/cases/conformance/internalModules/exportDeclarations/ExportVariableWithInaccessibleTypeInTypeAnnotation.ts ===
module A {
>A : typeof A
export interface Point {
>Point : Point
x: number;
>x : number
y: number;
>y : number
}
// valid since Point is exported
export var Origin: Point = { x: 0, y: 0 };
>Origin : Point
>Point : Point
>{ x: 0, y: 0 } : { x: number; y: number; }
>x : number
>y : number
interface Point3d extends Point {
>Point3d : Point3d
>Point : Point
z: number;
>z : number
}
// invalid Point3d is not exported
export var Origin3d: Point3d = { x: 0, y: 0, z: 0 };
>Origin3d : Point3d
>Point3d : Point3d
>{ x: 0, y: 0, z: 0 } : { x: number; y: number; z: number; }
>x : number
>y : number
>z : number
}
@@ -64,7 +64,7 @@ var fn;
var fn = A.Point;
var cl;
var cl = A.Point();
var cl = A.Point.Origin;
var cl = A.Point.Origin; // not expected to be an error.
//// [simple.js]
var B;
(function (B) {
@@ -78,7 +78,7 @@ var B;
var Point = B.Point;
})(B || (B = {}));
var fn;
var fn = B.Point;
var fn = B.Point; // not expected to be an error. bug 840000: [corelang] Function of fundule not assignalbe as expected
var cl;
var cl = B.Point();
var cl = B.Point.Origin;
@@ -0,0 +1,54 @@
=== tests/cases/conformance/internalModules/DeclarationMerging/function.ts ===
module A {
>A : typeof A
export function Point() {
>Point : () => { x: number; y: number; }
return { x: 0, y: 0 };
>{ x: 0, y: 0 } : { x: number; y: number; }
>x : number
>y : number
}
}
=== tests/cases/conformance/internalModules/DeclarationMerging/module.ts ===
module B {
>B : typeof B
export module Point {
>Point : typeof Point
export var Origin = { x: 0, y: 0 };
>Origin : { x: number; y: number; }
>{ x: 0, y: 0 } : { x: number; y: number; }
>x : number
>y : number
}
}
=== tests/cases/conformance/internalModules/DeclarationMerging/test.ts ===
var fn: () => { x: number; y: number };
>fn : () => { x: number; y: number; }
>x : number
>y : number
var fn = A.Point;
>fn : () => { x: number; y: number; }
>A.Point : () => { x: number; y: number; }
>A : typeof A
>Point : () => { x: number; y: number; }
var cl: { x: number; y: number; }
>cl : { x: number; y: number; }
>x : number
>y : number
var cl = B.Point.Origin;
>cl : { x: number; y: number; }
>B.Point.Origin : { x: number; y: number; }
>B.Point : typeof B.Point
>B : typeof B
>Point : typeof B.Point
>Origin : { x: number; y: number; }
@@ -9,5 +9,5 @@ var x: typeof M; // Error only a namespace
//// [InvalidNonInstantiatedModule.js]
var m = M;
var x;
var m = M; // Error, not instantiated can not be used as var
var x; // Error only a namespace

Some files were not shown because too many files have changed in this diff Show More