Merge branch 'master' into fixTypeResolutionInTypeSerialization

This commit is contained in:
Ron Buckton
2015-08-06 15:45:24 -07:00
694 changed files with 15788 additions and 8909 deletions
+1
View File
@@ -25,6 +25,7 @@ tests/baselines/reference/projectOutput/*
tests/baselines/local/projectOutput/*
tests/services/baselines/prototyping/local/*
tests/services/browser/typescriptServices.js
scripts/configureNightly.js
scripts/processDiagnosticMessages.d.ts
scripts/processDiagnosticMessages.js
scripts/importDefinitelyTypedTests.js
+70
View File
@@ -0,0 +1,70 @@
TypeScript is authored by:
* Adam Freidin
* Ahmad Farid
* Anders Hejlsberg
* Arnav Singh
* Arthur Ozga
* Basarat Ali Syed
* Ben Duffield
* Bill Ticehurst
* Bryan Forbes
* Caitlin Potter
* Chris Bubernak
* Colby Russell
* Colin Snover
* Cyrus Najmabadi
* Dan Quirk
* Daniel Rosenwasser
* David Li
* Dick van den Brink
* Dirk Bäumer
* Frank Wallis
* Gabriel Isenberg
* Gilad Peleg
* Guillaume Salles
* Harald Niesche
* Ingvar Stepanyan
* Ivo Gabe de Wolff
* James Whitney
* Jason Freeman
* Jason Ramsay
* Jed Mao
* Johannes Rieken
* Jonathan Bond-Caron
* Jonathan Park
* Jonathan Turner
* Josh Kalderimis
* Kagami Sascha Rosylight
* Keith Mashinter
* Kenji Imamula
* Lorant Pinter
* Masahiro Wakame
* Max Deepfield
* Micah Zoltu
* Mohamed Hegazy
* Oleg Mihailik
* Oleksandr Chekhovskyi
* Paul van Brenk
* Pedro Maltez
* Philip Bulley
* piloopin
* Ron Buckton
* Ryan Cavanaugh
* Sheetal Nandi
* Shengping Zhong
* Shyyko Serhiy
* Simon Hürlimann
* Solal Pirelli
* Stan Thomas
* Steve Lucco
* Tien Hoanhtien
* Tingan Ho
* togru
* Tomas Grubliauskas
* TruongSinh Tran-Nguyen
* Vladimir Matveev
* Wesley Wigham
* Yui Tanglertsampan
* Zev Spitz
* Zhengbo Li
+52 -13
View File
@@ -17,7 +17,7 @@ var docDirectory = "doc/";
var builtDirectory = "built/";
var builtLocalDirectory = "built/local/";
var LKGDirectory = "bin/";
var LKGDirectory = "lib/";
var copyright = "CopyrightNotice.txt";
var thirdParty = "ThirdPartyNoticeText.txt";
@@ -138,6 +138,7 @@ var harnessSources = harnessCoreSources.concat([
"services/documentRegistry.ts",
"services/preProcessFile.ts",
"services/patternMatcher.ts",
"session.ts",
"versionCache.ts",
"convertToBase64.ts",
"transpile.ts"
@@ -217,7 +218,7 @@ var compilerFilename = "tsc.js";
function compileFile(outFile, sources, prereqs, prefixes, useBuiltCompiler, noOutFile, generateDeclarations, outDir, preserveConstEnums, keepComments, noResolve, stripInternal, callback) {
file(outFile, prereqs, function() {
var dir = useBuiltCompiler ? builtLocalDirectory : LKGDirectory;
var options = "--module commonjs -noImplicitAny";
var options = "--module commonjs --noImplicitAny --noEmitOnError";
// Keep comments when specifically requested
// or when in debug mode.
@@ -313,7 +314,7 @@ var processDiagnosticMessagesTs = path.join(scriptsDirectory, "processDiagnostic
var diagnosticMessagesJson = path.join(compilerDirectory, "diagnosticMessages.json");
var diagnosticInfoMapTs = path.join(compilerDirectory, "diagnosticInformationMap.generated.ts");
file(processDiagnosticMessagesTs)
file(processDiagnosticMessagesTs);
// processDiagnosticMessages script
compileFile(processDiagnosticMessagesJs,
@@ -338,12 +339,50 @@ file(diagnosticInfoMapTs, [processDiagnosticMessagesJs, diagnosticMessagesJson],
complete();
});
ex.run();
}, {async: true})
}, {async: true});
desc("Generates a diagnostic file in TypeScript based on an input JSON file");
task("generate-diagnostics", [diagnosticInfoMapTs])
task("generate-diagnostics", [diagnosticInfoMapTs]);
// Publish nightly
var configureNightlyJs = path.join(scriptsDirectory, "configureNightly.js");
var configureNightlyTs = path.join(scriptsDirectory, "configureNightly.ts");
var packageJson = "package.json";
var programTs = path.join(compilerDirectory, "program.ts");
file(configureNightlyTs);
compileFile(/*outfile*/configureNightlyJs,
/*sources*/ [configureNightlyTs],
/*prereqs*/ [configureNightlyTs],
/*prefixes*/ [],
/*useBuiltCompiler*/ false,
/*noOutFile*/ false,
/*generateDeclarations*/ false,
/*outDir*/ undefined,
/*preserveConstEnums*/ undefined,
/*keepComments*/ false,
/*noResolve*/ false,
/*stripInternal*/ false);
task("setDebugMode", function() {
useDebugMode = true;
});
task("configure-nightly", [configureNightlyJs], function() {
var cmd = "node " + configureNightlyJs + " " + packageJson + " " + programTs;
console.log(cmd);
exec(cmd);
}, { async: true });
desc("Configure, build, test, and publish the nightly release.");
task("publish-nightly", ["configure-nightly", "LKG", "clean", "setDebugMode", "runtests"], function () {
var cmd = "npm publish --tag next";
console.log(cmd);
exec(cmd);
});
// Local target to build the compiler and services
var tscFile = path.join(builtLocalDirectory, compilerFilename);
compileFile(tscFile, compilerSources, [builtLocalDirectory, copyright].concat(compilerSources), [copyright], /*useBuiltCompiler:*/ false);
@@ -440,11 +479,11 @@ file(specMd, [word2mdJs, specWord], function () {
child_process.exec(cmd, function () {
complete();
});
}, {async: true})
}, {async: true});
desc("Generates a Markdown version of the Language Specification");
task("generate-spec", [specMd])
task("generate-spec", [specMd]);
// Makes a new LKG. This target does not build anything, but errors if not all the outputs are present in the built/local directory
@@ -576,7 +615,7 @@ task("runtests", ["tests", builtLocalDirectory], function() {
exec(cmd, deleteTemporaryProjectOutput);
}, {async: true});
desc("Generates code coverage data via instanbul")
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);
@@ -619,7 +658,7 @@ task("runtests-browser", ["tests", "browserify", builtLocalDirectory], function(
function getDiffTool() {
var program = process.env['DIFF']
if (!program) {
fail("Add the 'DIFF' environment variable to the path of the program you want to use.")
fail("Add the 'DIFF' environment variable to the path of the program you want to use.");
}
return program;
}
@@ -628,14 +667,14 @@ function getDiffTool() {
desc("Diffs the compiler baselines using the diff tool specified by the 'DIFF' environment variable");
task('diff', function () {
var cmd = '"' + getDiffTool() + '" ' + refBaseline + ' ' + localBaseline;
console.log(cmd)
console.log(cmd);
exec(cmd);
}, {async: true});
desc("Diffs the RWC baselines using the diff tool specified by the 'DIFF' environment variable");
task('diff-rwc', function () {
var cmd = '"' + getDiffTool() + '" ' + refRwcBaseline + ' ' + localRwcBaseline;
console.log(cmd)
console.log(cmd);
exec(cmd);
}, {async: true});
@@ -736,9 +775,9 @@ task("lint", [], function() {
function failure(f) { return function() { console.log('FAILURE: Please fix linting errors in ' + f + '\n') }};
var lintTargets = compilerSources.concat(harnessCoreSources);
for(var i in lintTargets) {
for (var i in lintTargets) {
var f = lintTargets[i];
var cmd = 'tslint -f ' + f;
var cmd = 'tslint -c tslint.json ' + f;
exec(cmd, success(f), failure(f));
}
}, { async: true });
+15 -1
View File
@@ -8,6 +8,19 @@
[TypeScript](http://www.typescriptlang.org/) is a language for application-scale JavaScript. TypeScript adds optional types, classes, and modules to JavaScript. TypeScript supports tools for large-scale JavaScript applications for any browser, for any host, on any OS. TypeScript compiles to readable, standards-based JavaScript. Try it out at the [playground](http://www.typescriptlang.org/Playground), and stay up to date via [our blog](http://blogs.msdn.com/typescript) and [twitter account](https://twitter.com/typescriptlang).
## Installing
For the latest stable version:
```
npm install -g typescript
```
For our nightly builds:
```
npm install -g typescript@next
```
## Contribute
@@ -63,7 +76,8 @@ jake runtests # Run tests using the built compiler and test infrastructu
# Use host=<hostName> or tests=<testPath>.
jake runtests-browser # Runs the tests using the built run.js file. Syntax is jake runtests. Optional
parameters 'host=', 'tests=[regex], reporter=[list|spec|json|<more>]'.
jake baseline-accept # This replaces the baseline test results with the results obtained from jake runtests.
jake baseline-accept # This replaces the baseline test results with the results obtained from jake runtests.
jake lint # Runs tslint on the TypeScript source.
jake -T # List the above commands.
```
+1 -1
View File
@@ -1,2 +1,2 @@
#!/usr/bin/env node
require('./tsc.js')
require('../lib/tsc.js')
Regular → Executable
+1 -1
View File
@@ -1,2 +1,2 @@
#!/usr/bin/env node
require('./tsserver.js')
require('../lib/tsserver.js')
Binary file not shown.
Binary file not shown.
+1720 -1192
View File
File diff suppressed because it is too large Load Diff
View File
View File
View File
View File
View File
View File
View File
View File
View File
+8 -4
View File
@@ -2,7 +2,7 @@
"name": "typescript",
"author": "Microsoft Corp.",
"homepage": "http://typescriptlang.org/",
"version": "1.5.3",
"version": "1.6.0",
"license": "Apache-2.0",
"description": "TypeScript is a language for application scale JavaScript development",
"keywords": [
@@ -19,8 +19,7 @@
"type": "git",
"url": "https://github.com/Microsoft/TypeScript.git"
},
"preferGlobal": true,
"main": "./bin/typescript.js",
"main": "./lib/typescript.js",
"bin": {
"tsc": "./bin/tsc",
"tsserver": "./bin/tsserver"
@@ -38,6 +37,11 @@
"tslint": "latest"
},
"scripts": {
"test": "jake runtests"
"pretest": "jake tests",
"test": "jake runtests",
"build": "npm run build:compiler && npm run build:tests",
"build:compiler": "jake local",
"build:tests": "jake tests",
"clean": "jake clean"
}
}
+73
View File
@@ -0,0 +1,73 @@
/// <reference path="../src/compiler/sys.ts" />
/**
* A minimal description for a parsed package.json object.
*/
interface PackageJson {
name: string;
version: string;
keywords: string[];
}
function main(): void {
const sys = ts.sys;
if (sys.args.length < 2) {
sys.write("Usage:" + sys.newLine)
sys.write("\tnode configureNightly.js <package.json location> <file containing version>" + sys.newLine);
return;
}
// Acquire the version from the package.json file and modify it appropriately.
const packageJsonFilePath = ts.normalizePath(sys.args[0]);
const packageJsonContents = sys.readFile(packageJsonFilePath);
const packageJsonValue: PackageJson = JSON.parse(packageJsonContents);
const nightlyVersion = getNightlyVersionString(packageJsonValue.version);
// Modify the package.json structure
packageJsonValue.version = nightlyVersion;
// Acquire and modify the source file that exposes the version string.
const tsFilePath = ts.normalizePath(sys.args[1]);
const tsFileContents = sys.readFile(tsFilePath);
const versionAssignmentRegExp = /export\s+const\s+version\s+=\s+".*";/;
const modifiedTsFileContents = tsFileContents.replace(versionAssignmentRegExp, `export const version = "${nightlyVersion}";`);
// Ensure we are actually changing something - the user probably wants to know that the update failed.
if (tsFileContents === modifiedTsFileContents) {
let err = `\n '${tsFilePath}' was not updated while configuring for a nightly publish.\n `;
if (tsFileContents.match(versionAssignmentRegExp)) {
err += `Ensure that you have not already run this script; otherwise, erase your changes using 'git checkout -- "${tsFilePath}"'.`;
}
else {
err += `The file seems to no longer have a string matching '${versionAssignmentRegExp}'.`;
}
throw err + "\n";
}
// Finally write the changes to disk.
sys.writeFile(packageJsonFilePath, JSON.stringify(packageJsonValue, /*replacer:*/ undefined, /*space:*/ 4))
sys.writeFile(tsFilePath, modifiedTsFileContents);
}
function getNightlyVersionString(versionString: string): string {
// If the version string already contains "-nightly",
// then get the base string and update based on that.
const dashNightlyPos = versionString.indexOf("-dev");
if (dashNightlyPos >= 0) {
versionString = versionString.slice(0, dashNightlyPos);
}
// We're going to append a representation of the current time at the end of the current version.
// String.prototype.toISOString() returns a 24-character string formatted as 'YYYY-MM-DDTHH:mm:ss.sssZ',
// but we'd prefer to just remove separators and limit ourselves to YYYYMMDD.
// UTC time will always be implicit here.
const now = new Date();
const timeStr = now.toISOString().replace(/:|T|\.|-/g, "").slice(0, 8);
return `${versionString}-dev.${timeStr}`;
}
main();
+29 -6
View File
@@ -1,8 +1,16 @@
// word2md - Word to Markdown conversion tool
//
// word2md converts a Microsoft Word document to Markdown formatted text. The tool uses the
// Word Automation APIs to start an instance of Word and access the contents of the document
// being converted. The tool must be run using the cscript.exe script host and requires Word
// to be installed on the target machine. The name of the document to convert must be specified
// as a command line argument and the resulting Markdown is written to standard output. The
// tool recognizes the specific Word styles used in the TypeScript Language Specification.
var sys = (function () {
var fileStream = new ActiveXObject("ADODB.Stream");
fileStream.Type = 2;
fileStream.Type = 2 /*text*/;
var binaryStream = new ActiveXObject("ADODB.Stream");
binaryStream.Type = 1;
binaryStream.Type = 1 /*binary*/;
var args = [];
for (var i = 0; i < WScript.Arguments.length; i++) {
args[i] = WScript.Arguments.Item(i);
@@ -17,11 +25,13 @@ var sys = (function () {
fileStream.Open();
binaryStream.Open();
try {
// Write characters in UTF-8 encoding
fileStream.Charset = "utf-8";
fileStream.WriteText(data);
// We don't want the BOM, skip it by setting the starting location to 3 (size of BOM).
fileStream.Position = 3;
fileStream.CopyTo(binaryStream);
binaryStream.SaveToFile(fileName, 2);
binaryStream.SaveToFile(fileName, 2 /*overwrite*/);
}
finally {
binaryStream.Close();
@@ -59,6 +69,17 @@ function convertDocumentToMarkdown(doc) {
setProperties(replace, replaceOptions);
find.execute(findText, false, false, false, false, false, true, 0, true, replaceText, 2);
}
function fixHyperlinks() {
var count = doc.hyperlinks.count;
for (var i = 0; i < count; i++) {
var hyperlink = doc.hyperlinks.item(i + 1);
var address = hyperlink.address;
if (address && address.length > 0) {
var textToDisplay = hyperlink.textToDisplay;
hyperlink.textToDisplay = "[" + textToDisplay + "](" + address + ")";
}
}
}
function write(s) {
result += s;
}
@@ -184,14 +205,15 @@ function convertDocumentToMarkdown(doc) {
findReplace("&lt;", { style: "Code Fragment" }, "<", {});
findReplace("&lt;", { style: "Terminal" }, "<", {});
findReplace("", { font: { subscript: true } }, "<sub>^&</sub>", { font: { subscript: false } });
findReplace("", { style: "Code Fragment" }, "`^&`", { style: -66 });
findReplace("", { style: "Production" }, "*^&*", { style: -66 });
findReplace("", { style: "Terminal" }, "`^&`", { style: -66 });
findReplace("", { style: "Code Fragment" }, "`^&`", { style: -66 /* default font */ });
findReplace("", { style: "Production" }, "*^&*", { style: -66 /* default font */ });
findReplace("", { style: "Terminal" }, "`^&`", { style: -66 /* default font */ });
findReplace("", { font: { bold: true, italic: true } }, "***^&***", { font: { bold: false, italic: false } });
findReplace("", { font: { italic: true } }, "*^&*", { font: { italic: false } });
doc.fields.toggleShowCodes();
findReplace("^19 REF", {}, "[^&](#^&)", {});
doc.fields.toggleShowCodes();
fixHyperlinks();
writeDocument();
result = result.replace(/\x85/g, "\u2026");
result = result.replace(/\x96/g, "\u2013");
@@ -210,3 +232,4 @@ function main(args) {
app.quit();
}
main(sys.args);
//# sourceMappingURL=file:///c:/ts/scripts/word2md.js.map
+24
View File
@@ -100,9 +100,19 @@ module Word {
toggleShowCodes(): void;
}
export interface Hyperlink {
address: string;
textToDisplay: string;
range: Range;
}
export interface Hyperlinks extends Collection<Hyperlink> {
}
export interface Document {
fields: Fields;
paragraphs: Paragraphs;
hyperlinks: Hyperlinks;
builtInDocumentProperties: Collection<any>;
close(saveChanges: boolean): void;
range(): Range;
@@ -195,6 +205,18 @@ function convertDocumentToMarkdown(doc: Word.Document): string {
find.execute(findText, false, false, false, false, false, true, 0, true, replaceText, 2);
}
function fixHyperlinks() {
var count = doc.hyperlinks.count;
for (var i = 0; i < count; i++) {
var hyperlink = doc.hyperlinks.item(i + 1);
var address = hyperlink.address;
if (address && address.length > 0) {
var textToDisplay = hyperlink.textToDisplay;
hyperlink.textToDisplay = "[" + textToDisplay + "](" + address + ")";
}
}
}
function write(s: string) {
result += s;
}
@@ -347,6 +369,8 @@ function convertDocumentToMarkdown(doc: Word.Document): string {
findReplace("^19 REF", {}, "[^&](#^&)", {});
doc.fields.toggleShowCodes();
fixHyperlinks();
writeDocument();
result = result.replace(/\x85/g, "\u2026");
+17 -11
View File
@@ -139,7 +139,7 @@ namespace ts {
function getDeclarationName(node: Declaration): string {
if (node.name) {
if (node.kind === SyntaxKind.ModuleDeclaration && node.name.kind === SyntaxKind.StringLiteral) {
return '"' + (<LiteralExpression>node.name).text + '"';
return `"${(<LiteralExpression>node.name).text}"`;
}
if (node.name.kind === SyntaxKind.ComputedPropertyName) {
let nameExpression = (<ComputedPropertyName>node.name).expression;
@@ -518,15 +518,21 @@ namespace ts {
}
else {
declareSymbolAndAddToSymbolTable(node, SymbolFlags.ValueModule, SymbolFlags.ValueModuleExcludes);
let currentModuleIsConstEnumOnly = state === ModuleInstanceState.ConstEnumOnly;
if (node.symbol.constEnumOnlyModule === undefined) {
// non-merged case - use the current state
node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly;
if (node.symbol.flags & (SymbolFlags.Function | SymbolFlags.Class | SymbolFlags.RegularEnum)) {
// if module was already merged with some function, class or non-const enum
// treat is a non-const-enum-only
node.symbol.constEnumOnlyModule = false;
}
else {
// merged case: module is const enum only if all its pieces are non-instantiated or const enum
node.symbol.constEnumOnlyModule = node.symbol.constEnumOnlyModule && currentModuleIsConstEnumOnly;
let currentModuleIsConstEnumOnly = state === ModuleInstanceState.ConstEnumOnly;
if (node.symbol.constEnumOnlyModule === undefined) {
// non-merged case - use the current state
node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly;
}
else {
// merged case: module is const enum only if all its pieces are non-instantiated or const enum
node.symbol.constEnumOnlyModule = node.symbol.constEnumOnlyModule && currentModuleIsConstEnumOnly;
}
}
}
}
@@ -824,7 +830,7 @@ namespace ts {
// Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the
// string to contain unicode escapes (as per ES5).
return nodeText === '"use strict"' || nodeText === "'use strict'";
return nodeText === "\"use strict\"" || nodeText === "'use strict'";
}
function bindWorker(node: Node) {
@@ -924,7 +930,7 @@ namespace ts {
function bindSourceFileIfExternalModule() {
setExportContextFlag(file);
if (isExternalModule(file)) {
bindAnonymousDeclaration(file, SymbolFlags.ValueModule, '"' + removeFileExtension(file.fileName) + '"');
bindAnonymousDeclaration(file, SymbolFlags.ValueModule, `"${removeFileExtension(file.fileName)}"`);
}
}
@@ -1056,4 +1062,4 @@ namespace ts {
: declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
}
}
}
}
+796 -471
View File
File diff suppressed because it is too large Load Diff
+5 -2
View File
@@ -335,7 +335,7 @@ namespace ts {
* @param fileName The path to the config file
*/
export function readConfigFile(fileName: string): { config?: any; error?: Diagnostic } {
let text = '';
let text = "";
try {
text = sys.readFile(fileName);
}
@@ -422,10 +422,13 @@ namespace ts {
if (json["files"] instanceof Array) {
fileNames = map(<string[]>json["files"], s => combinePaths(basePath, s));
}
else {
errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array"));
}
}
else {
let exclude = json["exclude"] instanceof Array ? map(<string[]>json["exclude"], normalizeSlashes) : undefined;
let sysFiles = host.readDirectory(basePath, ".ts", exclude).concat(host.readDirectory(basePath, ".tsx", exclude));
let sysFiles = host.readDirectory(basePath, ".ts", exclude).concat(host.readDirectory(basePath, ".tsx", exclude));
for (let i = 0; i < sysFiles.length; i++) {
let name = sysFiles[i];
if (fileExtensionIs(name, ".d.ts")) {
+7 -7
View File
@@ -219,10 +219,10 @@ namespace ts {
export function reduceLeft<T, U>(array: T[], f: (a: U, x: T) => U, initial: U): U;
export function reduceLeft<T, U>(array: T[], f: (a: U, x: T) => U, initial?: U): U {
if (array) {
var count = array.length;
const count = array.length;
if (count > 0) {
var pos = 0;
var result = arguments.length <= 2 ? array[pos++] : initial;
let pos = 0;
let result = arguments.length <= 2 ? array[pos++] : initial;
while (pos < count) {
result = f(<U>result, array[pos++]);
}
@@ -236,9 +236,9 @@ namespace ts {
export function reduceRight<T, U>(array: T[], f: (a: U, x: T) => U, initial: U): U;
export function reduceRight<T, U>(array: T[], f: (a: U, x: T) => U, initial?: U): U {
if (array) {
var pos = array.length - 1;
let pos = array.length - 1;
if (pos >= 0) {
var result = arguments.length <= 2 ? array[pos--] : initial;
let result = arguments.length <= 2 ? array[pos--] : initial;
while (pos >= 0) {
result = f(<U>result, array[pos--]);
}
@@ -523,7 +523,7 @@ namespace ts {
if (path.lastIndexOf("file:///", 0) === 0) {
return "file:///".length;
}
let idx = path.indexOf('://');
let idx = path.indexOf("://");
if (idx !== -1) {
return idx + "://".length;
}
@@ -805,4 +805,4 @@ namespace ts {
Debug.assert(false, message);
}
}
}
}
+1 -1
View File
@@ -1371,7 +1371,7 @@ namespace ts {
else {
writeTextOfNode(currentSourceFile, node.name);
}
if (node.initializer || hasQuestionToken(node)) {
if (resolver.isOptionalParameter(node)) {
write("?");
}
decreaseIndent();
@@ -254,6 +254,7 @@ namespace ts {
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." },
Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: { code: 2353, category: DiagnosticCategory.Error, key: "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'." },
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." },
@@ -293,7 +294,7 @@ namespace ts {
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." },
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_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." },
@@ -424,6 +425,8 @@ namespace ts {
JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: { code: 2607, category: DiagnosticCategory.Error, key: "JSX element class does not support attributes because it does not have a '{0}' property" },
The_global_type_JSX_0_may_not_have_more_than_one_property: { code: 2608, category: DiagnosticCategory.Error, key: "The global type 'JSX.{0}' may not have more than one property" },
Cannot_emit_namespaced_JSX_elements_in_React: { code: 2650, category: DiagnosticCategory.Error, key: "Cannot emit namespaced JSX elements in React" },
A_member_initializer_in_a_const_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_const_enums: { code: 2651, category: DiagnosticCategory.Error, key: "A member initializer in a 'const' enum declaration cannot reference members declared after it, including members defined in other 'const' enums." },
Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: { code: 2652, category: DiagnosticCategory.Error, key: "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead." },
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_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_private_name_1: { code: 4004, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported interface has or is using private name '{1}'." },
@@ -508,7 +511,6 @@ namespace ts {
Option_noEmit_cannot_be_specified_with_option_out_or_outDir: { code: 5040, category: DiagnosticCategory.Error, key: "Option 'noEmit' cannot be specified with option 'out' or 'outDir'." },
Option_noEmit_cannot_be_specified_with_option_declaration: { code: 5041, category: DiagnosticCategory.Error, key: "Option 'noEmit' cannot be specified with option 'declaration'." },
Option_project_cannot_be_mixed_with_source_files_on_a_command_line: { code: 5042, category: DiagnosticCategory.Error, key: "Option 'project' cannot be mixed with source files on a command line." },
Option_sourceMap_cannot_be_specified_with_option_isolatedModules: { code: 5043, category: DiagnosticCategory.Error, key: "Option 'sourceMap' cannot be specified with option 'isolatedModules'." },
Option_declaration_cannot_be_specified_with_option_isolatedModules: { code: 5044, category: DiagnosticCategory.Error, key: "Option 'declaration' cannot be specified with option 'isolatedModules'." },
Option_noEmitOnError_cannot_be_specified_with_option_isolatedModules: { code: 5045, category: DiagnosticCategory.Error, key: "Option 'noEmitOnError' cannot be specified with option 'isolatedModules'." },
Option_out_cannot_be_specified_with_option_isolatedModules: { code: 5046, category: DiagnosticCategory.Error, key: "Option 'out' cannot be specified with option 'isolatedModules'." },
@@ -613,5 +615,6 @@ namespace ts {
Expected_corresponding_JSX_closing_tag_for_0: { code: 17002, category: DiagnosticCategory.Error, key: "Expected corresponding JSX closing tag for '{0}'." },
JSX_attribute_expected: { code: 17003, category: DiagnosticCategory.Error, key: "JSX attribute expected." },
Cannot_use_JSX_unless_the_jsx_flag_is_provided: { code: 17004, category: DiagnosticCategory.Error, key: "Cannot use JSX unless the '--jsx' flag is provided." },
A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: { code: 17005, category: DiagnosticCategory.Error, key: "A constructor cannot contain a 'super' call when its class extends 'null'" },
};
}
+18 -6
View File
@@ -1,4 +1,4 @@
{
{
"Unterminated string literal.": {
"category": "Error",
"code": 1002
@@ -1005,6 +1005,10 @@
"category": "Error",
"code": 2352
},
"Object literal may only specify known properties, and '{0}' does not exist in type '{1}'.": {
"category": "Error",
"code": 2353
},
"No best common type exists among return expressions.": {
"category": "Error",
"code": 2354
@@ -1161,7 +1165,7 @@
"category": "Error",
"code": 2394
},
"Individual declarations in merged declaration {0} must be all exported or all local.": {
"Individual declarations in merged declaration '{0}' must be all exported or all local.": {
"category": "Error",
"code": 2395
},
@@ -1685,6 +1689,14 @@
"category": "Error",
"code": 2650
},
"A member initializer in a 'const' enum declaration cannot reference members declared after it, including members defined in other 'const' enums.": {
"category": "Error",
"code": 2651
},
"Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead.": {
"category": "Error",
"code": 2652
},
"Import declaration '{0}' is using private name '{1}'.": {
"category": "Error",
"code": 4000
@@ -2021,10 +2033,6 @@
"category": "Error",
"code": 5042
},
"Option 'sourceMap' cannot be specified with option 'isolatedModules'.": {
"category": "Error",
"code": 5043
},
"Option 'declaration' cannot be specified with option 'isolatedModules'.": {
"category": "Error",
"code": 5044
@@ -2445,5 +2453,9 @@
"Cannot use JSX unless the '--jsx' flag is provided.": {
"category": "Error",
"code": 17004
},
"A constructor cannot contain a 'super' call when its class extends 'null'": {
"category": "Error",
"code": 17005
}
}
+183 -64
View File
@@ -380,7 +380,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
function base64VLQFormatEncode(inValue: number) {
function base64FormatEncode(inValue: number) {
if (inValue < 64) {
return 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.charAt(inValue);
return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(inValue);
}
throw TypeError(inValue + ": not a 64 based value");
}
@@ -895,7 +895,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
// Any template literal or string literal with an extended escape
// (e.g. "\u{0067}") will need to be downleveled as a escaped string literal.
if (languageVersion < ScriptTarget.ES6 && (isTemplateLiteralKind(node.kind) || node.hasExtendedUnicodeEscape)) {
return getQuotedEscapedLiteralText('"', node.text, '"');
return getQuotedEscapedLiteralText("\"", node.text, "\"");
}
// If we don't need to downlevel and we can reach the original source text using
@@ -908,15 +908,15 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
// or an escaped quoted form of the original text if it's string-like.
switch (node.kind) {
case SyntaxKind.StringLiteral:
return getQuotedEscapedLiteralText('"', node.text, '"');
return getQuotedEscapedLiteralText("\"", node.text, "\"");
case SyntaxKind.NoSubstitutionTemplateLiteral:
return getQuotedEscapedLiteralText('`', node.text, '`');
return getQuotedEscapedLiteralText("`", node.text, "`");
case SyntaxKind.TemplateHead:
return getQuotedEscapedLiteralText('`', node.text, '${');
return getQuotedEscapedLiteralText("`", node.text, "${");
case SyntaxKind.TemplateMiddle:
return getQuotedEscapedLiteralText('}', node.text, '${');
return getQuotedEscapedLiteralText("}", node.text, "${");
case SyntaxKind.TemplateTail:
return getQuotedEscapedLiteralText('}', node.text, '`');
return getQuotedEscapedLiteralText("}", node.text, "`");
case SyntaxKind.NumericLiteral:
return node.text;
}
@@ -947,7 +947,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
text = text.replace(/\r\n?/g, "\n");
text = escapeString(text);
write('"' + text + '"');
write(`"${text}"`);
}
function emitDownlevelTaggedTemplateArray(node: TaggedTemplateExpression, literalEmitter: (literal: LiteralExpression) => void) {
@@ -1134,9 +1134,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
/// 'Div' for upper-cased or dotted names
function emitTagName(name: Identifier|QualifiedName) {
if (name.kind === SyntaxKind.Identifier && isIntrinsicJsxName((<Identifier>name).text)) {
write('"');
write("\"");
emit(name);
write('"');
write("\"");
}
else {
emit(name);
@@ -1148,9 +1148,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
/// about keywords, just non-identifier characters
function emitAttributeName(name: Identifier) {
if (/[A-Za-z_]+[\w*]/.test(name.text)) {
write('"');
write("\"");
emit(name);
write('"');
write("\"");
}
else {
emit(name);
@@ -1248,10 +1248,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
// Don't emit empty strings
if (children[i].kind === SyntaxKind.JsxText) {
let text = getTextToEmit(<JsxText>children[i]);
if(text !== undefined) {
write(', "');
if (text !== undefined) {
write(", \"");
write(text);
write('"');
write("\"");
}
}
else {
@@ -1425,6 +1425,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
case SyntaxKind.IfStatement:
case SyntaxKind.JsxSelfClosingElement:
case SyntaxKind.JsxOpeningElement:
case SyntaxKind.JsxSpreadAttribute:
case SyntaxKind.JsxExpression:
case SyntaxKind.NewExpression:
case SyntaxKind.ParenthesizedExpression:
case SyntaxKind.PostfixUnaryExpression:
@@ -1489,7 +1491,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
if (declaration.kind === SyntaxKind.ImportClause) {
// Identifier references default import
write(getGeneratedNameForNode(<ImportDeclaration>declaration.parent));
write(languageVersion === ScriptTarget.ES3 ? '["default"]' : ".default");
write(languageVersion === ScriptTarget.ES3 ? "[\"default\"]" : ".default");
return;
}
else if (declaration.kind === SyntaxKind.ImportSpecifier) {
@@ -2004,12 +2006,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
function tryEmitConstantValue(node: PropertyAccessExpression | ElementAccessExpression): boolean {
if (compilerOptions.isolatedModules) {
// do not inline enum values in separate compilation mode
return false;
}
let constantValue = resolver.getConstantValue(node);
let constantValue = tryGetConstEnumValue(node);
if (constantValue !== undefined) {
write(constantValue.toString());
if (!compilerOptions.removeComments) {
@@ -2020,6 +2017,16 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
return false;
}
function tryGetConstEnumValue(node: Node): number {
if (compilerOptions.isolatedModules) {
return undefined;
}
return node.kind === SyntaxKind.PropertyAccessExpression || node.kind === SyntaxKind.ElementAccessExpression
? resolver.getConstantValue(<PropertyAccessExpression | ElementAccessExpression>node)
: undefined
}
// Returns 'true' if the code was actually indented, false otherwise.
// If the code is not indented, an optional valueToWriteWhenNotIndenting will be
@@ -2052,10 +2059,20 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
let indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken);
// 1 .toString is a valid property access, emit a space after the literal
// Also emit a space if expression is a integer const enum value - it will appear in generated code as numeric literal
let shouldEmitSpace: boolean;
if (!indentedBeforeDot && node.expression.kind === SyntaxKind.NumericLiteral) {
let text = getSourceTextOfNodeFromSourceFile(currentSourceFile, node.expression);
shouldEmitSpace = text.indexOf(tokenToString(SyntaxKind.DotToken)) < 0;
if (!indentedBeforeDot) {
if (node.expression.kind === SyntaxKind.NumericLiteral) {
// check if numeric literal was originally written with a dot
let text = getSourceTextOfNodeFromSourceFile(currentSourceFile, node.expression);
shouldEmitSpace = text.indexOf(tokenToString(SyntaxKind.DotToken)) < 0;
}
else {
// check if constant enum value is integer
let constantValue = tryGetConstEnumValue(node.expression);
// isFinite handles cases when constantValue is undefined
shouldEmitSpace = isFinite(constantValue) && Math.floor(constantValue) === constantValue;
}
}
if (shouldEmitSpace) {
@@ -3012,6 +3029,26 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
return result;
}
function emitEs6ExportDefaultCompat(node: Node) {
if (node.parent.kind === SyntaxKind.SourceFile) {
Debug.assert(!!(node.flags & NodeFlags.Default) || node.kind === SyntaxKind.ExportAssignment);
// only allow export default at a source file level
if (compilerOptions.module === ModuleKind.CommonJS || compilerOptions.module === ModuleKind.AMD || compilerOptions.module === ModuleKind.UMD) {
if (!currentSourceFile.symbol.exports["___esModule"]) {
if (languageVersion === ScriptTarget.ES5) {
// default value of configurable, enumerable, writable are `false`.
write("Object.defineProperty(exports, \"__esModule\", { value: true });");
writeLine();
}
else if (languageVersion === ScriptTarget.ES3) {
write("exports.__esModule = true;");
writeLine();
}
}
}
}
}
function emitExportMemberAssignment(node: FunctionLikeDeclaration | ClassDeclaration) {
if (node.flags & NodeFlags.Export) {
writeLine();
@@ -3034,9 +3071,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
else {
if (node.flags & NodeFlags.Default) {
emitEs6ExportDefaultCompat(node);
if (languageVersion === ScriptTarget.ES3) {
write("exports[\"default\"]");
} else {
}
else {
write("exports.default");
}
}
@@ -3249,7 +3288,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
function emitAssignmentExpression(root: BinaryExpression) {
let target = root.left;
let value = root.right;
if (isAssignmentExpressionStatement) {
if (isEmptyObjectLiteralOrArrayLiteral(target)) {
emit(value);
}
else if (isAssignmentExpressionStatement) {
emitDestructuringAssignment(target, value);
}
else {
@@ -4227,11 +4270,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emitDetachedComments(ctor.body.statements);
}
emitCaptureThisForNodeIfNecessary(node);
let superCall: ExpressionStatement;
if (ctor) {
emitDefaultValueAssignments(ctor);
emitRestParameter(ctor);
if (baseTypeElement) {
var superCall = findInitialSuperCall(ctor);
superCall = findInitialSuperCall(ctor);
if (superCall) {
writeLine();
emit(superCall);
@@ -4839,6 +4883,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
function emitSerializedTypeNode(node: TypeNode) {
if (!node) {
return;
}
switch (node.kind) {
case SyntaxKind.VoidKeyword:
write("void 0");
@@ -4912,7 +4960,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
let temp = createAndRecordTempVariable(TempFlags.Auto);
write("(typeof (");
emitNodeWithoutSourceMap(temp);
write(" = ")
write(" = ");
emitEntityNameAsExpression(typeName, /*useFallback*/ true);
write(") === 'function' && ");
emitNodeWithoutSourceMap(temp);
@@ -4971,7 +5019,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
//
// For the rules on serializing the type of each parameter declaration, see `serializeTypeOfDeclaration`.
if (node) {
var valueDeclaration: FunctionLikeDeclaration;
let valueDeclaration: FunctionLikeDeclaration;
if (node.kind === SyntaxKind.ClassDeclaration) {
valueDeclaration = getFirstConstructorWithBody(<ClassDeclaration>node);
}
@@ -4980,8 +5028,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
if (valueDeclaration) {
var parameters = valueDeclaration.parameters;
var parameterCount = parameters.length;
const parameters = valueDeclaration.parameters;
const parameterCount = parameters.length;
if (parameterCount > 0) {
for (var i = 0; i < parameterCount; i++) {
if (i > 0) {
@@ -4989,7 +5037,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
if (parameters[i].dotDotDotToken) {
var parameterType = parameters[i].type;
let parameterType = parameters[i].type;
if (parameterType.kind === SyntaxKind.ArrayType) {
parameterType = (<ArrayTypeNode>parameterType).elementType;
}
@@ -5013,7 +5061,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
/** Serializes the return type of function. Used by the __metadata decorator for a method. */
function emitSerializedReturnTypeOfNode(node: Node): string | string[] {
if (node && isFunctionLike(node)) {
if (node && isFunctionLike(node) && (<FunctionLikeDeclaration>node).type) {
emitSerializedTypeNode((<FunctionLikeDeclaration>node).type);
return;
}
@@ -5412,17 +5460,43 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
(!isExternalModule(currentSourceFile) && resolver.isTopLevelValueImportEqualsWithEntityName(node))) {
emitLeadingComments(node);
emitStart(node);
if (isES6ExportedDeclaration(node)) {
write("export ");
write("var ");
// variable declaration for import-equals declaration can be hoisted in system modules
// in this case 'var' should be omitted and emit should contain only initialization
let variableDeclarationIsHoisted = shouldHoistVariable(node, /*checkIfSourceFileLevelDecl*/ true);
// is it top level export import v = a.b.c in system module?
// if yes - it needs to be rewritten as exporter('v', v = a.b.c)
let isExported = isSourceFileLevelDeclarationInSystemJsModule(node, /*isExported*/ true);
if (!variableDeclarationIsHoisted) {
Debug.assert(!isExported);
if (isES6ExportedDeclaration(node)) {
write("export ");
write("var ");
}
else if (!(node.flags & NodeFlags.Export)) {
write("var ");
}
}
else if (!(node.flags & NodeFlags.Export)) {
write("var ");
if (isExported) {
write(`${exportFunctionForFile}("`);
emitNodeWithoutSourceMap(node.name);
write(`", `);
}
emitModuleMemberName(node);
write(" = ");
emit(node.moduleReference);
write(";");
if (isExported) {
write(")");
}
write(";");
emitEnd(node);
emitExportImportAssignments(node);
emitTrailingComments(node);
@@ -5543,6 +5617,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write(")");
}
else {
emitEs6ExportDefaultCompat(node);
emitContainingModuleName(node);
if (languageVersion === ScriptTarget.ES3) {
write("[\"default\"] = ");
@@ -5761,6 +5836,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write(`function ${exportStarFunction}(m) {`);
increaseIndent();
writeLine();
write(`var exports = {};`);
writeLine();
write(`for(var n in m) {`);
increaseIndent();
writeLine();
@@ -5768,10 +5845,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
if (localNames) {
write(`&& !${localNames}.hasOwnProperty(n)`);
}
write(`) ${exportFunctionForFile}(n, m[n]);`);
write(`) exports[n] = m[n];`);
decreaseIndent();
writeLine();
write("}");
writeLine();
write(`${exportFunctionForFile}(exports);`);
decreaseIndent();
writeLine();
write("}");
@@ -5943,6 +6022,15 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
return;
}
if (isInternalModuleImportEqualsDeclaration(node)) {
if (!hoistedVars) {
hoistedVars = [];
}
hoistedVars.push(node.name);
return;
}
if (isBindingPattern(node)) {
forEach((<BindingPattern>node).elements, visit);
@@ -6104,16 +6192,23 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
if ((<ExportDeclaration>importNode).exportClause) {
// export {a, b as c} from 'foo'
// emit as:
// exports('a', _foo["a"])
// exports('c', _foo["b"])
// var reexports = {}
// reexports['a'] = _foo["a"];
// reexports['c'] = _foo["b"];
// exports_(reexports);
let reexportsVariableName = makeUniqueName("reexports");
writeLine();
write(`var ${reexportsVariableName} = {};`);
writeLine();
for (let e of (<ExportDeclaration>importNode).exportClause.elements) {
writeLine();
write(`${exportFunctionForFile}("`);
write(`${reexportsVariableName}["`);
emitNodeWithoutSourceMap(e.name);
write(`", ${parameterName}["`);
write(`"] = ${parameterName}["`);
emitNodeWithoutSourceMap(e.propertyName || e.name);
write(`"]);`);
write(`"];`);
writeLine();
}
write(`${exportFunctionForFile}(${reexportsVariableName});`);
}
else {
writeLine();
@@ -6140,14 +6235,17 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
writeLine();
for (let i = startIndex; i < node.statements.length; ++i) {
let statement = node.statements[i];
// - imports/exports are not emitted for system modules
// - external module related imports/exports are not emitted for system modules
// - function declarations are not emitted because they were already hoisted
switch (statement.kind) {
case SyntaxKind.ExportDeclaration:
case SyntaxKind.ImportDeclaration:
case SyntaxKind.ImportEqualsDeclaration:
case SyntaxKind.FunctionDeclaration:
continue;
case SyntaxKind.ImportEqualsDeclaration:
if (!isInternalModuleImportEqualsDeclaration(statement)) {
continue;
}
}
writeLine();
emit(statement);
@@ -6186,6 +6284,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write(`], function(${exportFunctionForFile}) {`);
writeLine();
increaseIndent();
emitEmitHelpers(node);
emitCaptureThisForNodeIfNecessary(node);
emitSystemModuleBody(node, startIndex);
decreaseIndent();
@@ -6257,6 +6356,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
function emitAMDModule(node: SourceFile, startIndex: number) {
emitEmitHelpers(node);
collectExternalModuleInfo(node);
writeLine();
@@ -6278,6 +6378,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
function emitCommonJSModule(node: SourceFile, startIndex: number) {
emitEmitHelpers(node);
collectExternalModuleInfo(node);
emitExportStarHelper();
emitCaptureThisForNodeIfNecessary(node);
@@ -6287,6 +6388,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
function emitUMDModule(node: SourceFile, startIndex: number) {
emitEmitHelpers(node);
collectExternalModuleInfo(node);
// Module is detected first to support Browserify users that load into a browser with an AMD loader
@@ -6316,6 +6418,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
exportSpecifiers = undefined;
exportEquals = undefined;
hasExportStars = false;
emitEmitHelpers(node);
emitCaptureThisForNodeIfNecessary(node);
emitLinesStartingAt(node.statements, startIndex);
emitTempDeclarations(/*newLine*/ true);
@@ -6361,7 +6464,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
if (isLineBreak(c)) {
if (firstNonWhitespace !== -1 && (lastNonWhitespace - firstNonWhitespace + 1 > 0)) {
let part = text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1);
result = (result ? result + '" + \' \' + "' : '') + part;
result = (result ? result + "\" + ' ' + \"" : "") + part;
}
firstNonWhitespace = -1;
}
@@ -6374,7 +6477,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
if (firstNonWhitespace !== -1) {
let part = text.substr(firstNonWhitespace);
result = (result ? result + '" + \' \' + "' : '') + part;
result = (result ? result + "\" + ' ' + \"" : "") + part;
}
return result;
@@ -6399,14 +6502,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
function emitJsxText(node: JsxText) {
switch (compilerOptions.jsx) {
case JsxEmit.React:
write('"');
write("\"");
write(trimReactWhitespace(node));
write('"');
write("\"");
break;
case JsxEmit.Preserve:
default: // Emit JSX-preserve as default when no --jsx flag is specified
write(getTextOfNode(node, true));
writer.writeLiteral(getTextOfNode(node, true));
break;
}
}
@@ -6416,9 +6519,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
switch (compilerOptions.jsx) {
case JsxEmit.Preserve:
default:
write('{');
write("{");
emit(node.expression);
write('}');
write("}");
break;
case JsxEmit.React:
emit(node.expression);
@@ -6454,14 +6557,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
}
function emitSourceFileNode(node: SourceFile) {
// Start new file on new line
writeLine();
emitDetachedComments(node);
// emit prologue directives prior to __extends
let startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false);
function emitEmitHelpers(node: SourceFile): void {
// Only emit helpers if the user did not say otherwise.
if (!compilerOptions.noEmitHelpers) {
// Only Emit __extends function when target ES5.
@@ -6489,6 +6585,16 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
awaiterEmitted = true;
}
}
}
function emitSourceFileNode(node: SourceFile) {
// Start new file on new line
writeLine();
emitShebang();
emitDetachedComments(node);
// emit prologue directives prior to __extends
let startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false);
if (isExternalModule(node) || compilerOptions.isolatedModules) {
if (languageVersion >= ScriptTarget.ES6) {
@@ -6512,6 +6618,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
exportSpecifiers = undefined;
exportEquals = undefined;
hasExportStars = false;
emitEmitHelpers(node);
emitCaptureThisForNodeIfNecessary(node);
emitLinesStartingAt(node.statements, startIndex);
emitTempDeclarations(/*newLine*/ true);
@@ -6773,6 +6880,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
return leadingComments;
}
/**
* Removes all but the pinned or triple slash comments.
* @param ranges The array to be filtered
* @param onlyPinnedOrTripleSlashComments whether the filtering should be performed.
*/
function filterComments(ranges: CommentRange[], onlyPinnedOrTripleSlashComments: boolean): CommentRange[] {
// If we're removing comments, then we want to strip out all but the pinned or
// triple slash comments.
@@ -6900,6 +7012,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
}
}
function emitShebang() {
let shebang = getShebang(currentSourceFile.text);
if (shebang) {
write(shebang);
}
}
function isPinnedOrTripleSlashComment(comment: CommentRange) {
if (currentSourceFile.text.charCodeAt(comment.pos + 1) === CharacterCodes.asterisk) {
+4 -4
View File
@@ -3148,7 +3148,7 @@ namespace ts {
}
function parseAwaitExpression() {
var node = <AwaitExpression>createNode(SyntaxKind.AwaitExpression);
const node = <AwaitExpression>createNode(SyntaxKind.AwaitExpression);
nextToken();
node.expression = parseUnaryExpressionOrHigher();
return finishNode(node);
@@ -3340,7 +3340,7 @@ namespace ts {
case SyntaxKind.LessThanToken:
return parseJsxElementOrSelfClosingElement();
}
Debug.fail('Unknown JSX child kind ' + token);
Debug.fail("Unknown JSX child kind " + token);
}
function parseJsxChildren(openingTagName: EntityName): NodeArray<JsxChild> {
@@ -5140,7 +5140,7 @@ namespace ts {
// the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`)
// If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect.
if (token === SyntaxKind.FromKeyword || (token === SyntaxKind.StringLiteral && !scanner.hasPrecedingLineBreak())) {
parseExpected(SyntaxKind.FromKeyword)
parseExpected(SyntaxKind.FromKeyword);
node.moduleSpecifier = parseModuleSpecifier();
}
}
@@ -6011,7 +6011,7 @@ namespace ts {
return;
function visitNode(node: IncrementalNode) {
let text = '';
let text = "";
if (aggressiveChecks && shouldCheckNode(node)) {
text = oldText.substring(node.pos, node.end);
}
+3 -7
View File
@@ -8,7 +8,7 @@ namespace ts {
/* @internal */ export let ioWriteTime = 0;
/** The version of the TypeScript compiler release */
export const version = "1.5.3";
export const version = "1.6.0";
export function findConfigFile(searchPath: string): string {
let fileName = "tsconfig.json";
@@ -341,7 +341,7 @@ namespace ts {
});
}
function getDeclarationDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {
function getDeclarationDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {
return runWithCancellationToken(() => {
if (!isDeclarationFile(sourceFile)) {
let resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken);
@@ -350,7 +350,7 @@ namespace ts {
return ts.getDeclarationDiagnostics(getEmitHost(writeFile), resolver, sourceFile);
}
});
}
}
function getOptionsDiagnostics(): Diagnostic[] {
let allDiagnostics: Diagnostic[] = [];
@@ -602,10 +602,6 @@ namespace ts {
function verifyCompilerOptions() {
if (options.isolatedModules) {
if (options.sourceMap) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_sourceMap_cannot_be_specified_with_option_isolatedModules));
}
if (options.declaration) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_declaration_cannot_be_specified_with_option_isolatedModules));
}
+45 -2
View File
@@ -401,6 +401,9 @@ namespace ts {
case CharacterCodes.greaterThan:
// Starts of conflict marker trivia
return true;
case CharacterCodes.hash:
// Only if its the beginning can we have #! trivia
return pos === 0;
default:
return ch > CharacterCodes.maxAsciiCharacter;
}
@@ -461,6 +464,13 @@ namespace ts {
}
break;
case CharacterCodes.hash:
if (isShebangTrivia(text, pos)) {
pos = scanShebangTrivia(text, pos);
continue;
}
break;
default:
if (ch > CharacterCodes.maxAsciiCharacter && (isWhiteSpace(ch) || isLineBreak(ch))) {
pos++;
@@ -528,6 +538,20 @@ namespace ts {
return pos;
}
const shebangTriviaRegex = /^#!.*/;
function isShebangTrivia(text: string, pos: number) {
// Shebangs check must only be done at the start of the file
Debug.assert(pos === 0);
return shebangTriviaRegex.test(text);
}
function scanShebangTrivia(text: string, pos: number) {
let shebang = shebangTriviaRegex.exec(text)[0];
pos = pos + shebang.length;
return pos;
}
// Extract comments from the given source text starting at the given position. If trailing is
// false, whitespace is skipped until the first line break and comments between that location
// and the next token are returned.If trailing is true, comments occurring between the given
@@ -617,6 +641,13 @@ namespace ts {
export function getTrailingCommentRanges(text: string, pos: number): CommentRange[] {
return getCommentRanges(text, pos, /*trailing*/ true);
}
/** Optionally, get the shebang */
export function getShebang(text: string): string {
return shebangTriviaRegex.test(text)
? shebangTriviaRegex.exec(text)[0]
: undefined;
}
export function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean {
return ch >= CharacterCodes.A && ch <= CharacterCodes.Z || ch >= CharacterCodes.a && ch <= CharacterCodes.z ||
@@ -629,9 +660,9 @@ namespace ts {
ch >= CharacterCodes._0 && ch <= CharacterCodes._9 || ch === CharacterCodes.$ || ch === CharacterCodes._ ||
ch > CharacterCodes.maxAsciiCharacter && isUnicodeIdentifierPart(ch, languageVersion);
}
/* @internal */
// Creates a scanner over a (possibly unspecified) range of a piece of text.
// Creates a scanner over a (possibly unspecified) range of a piece of text.
export function createScanner(languageVersion: ScriptTarget,
skipTrivia: boolean,
languageVariant = LanguageVariant.Standard,
@@ -1087,6 +1118,18 @@ namespace ts {
return token = SyntaxKind.EndOfFileToken;
}
let ch = text.charCodeAt(pos);
// Special handling for shebang
if (ch === CharacterCodes.hash && pos === 0 && isShebangTrivia(text, pos)) {
pos = scanShebangTrivia(text, pos);
if (skipTrivia) {
continue;
}
else {
return token = SyntaxKind.ShebangTrivia;
}
}
switch (ch) {
case CharacterCodes.lineFeed:
case CharacterCodes.carriageReturn:
+13 -13
View File
@@ -30,8 +30,8 @@ namespace ts {
declare var global: any;
declare var __filename: string;
declare var Buffer: {
new (str: string, encoding ?: string): any;
}
new (str: string, encoding?: string): any;
};
declare class Enumerator {
public atEnd(): boolean;
@@ -188,13 +188,13 @@ namespace ts {
};
}
function getNodeSystem(): System {
var _fs = require("fs");
var _path = require("path");
var _os = require('os');
const _fs = require("fs");
const _path = require("path");
const _os = require("os");
var platform: string = _os.platform();
const platform: string = _os.platform();
// win32\win64 are case insensitive platforms, MacOS (darwin) by default is also case insensitive
var useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin";
const useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin";
function readFile(fileName: string, encoding?: string): string {
if (!_fs.existsSync(fileName)) {
@@ -228,7 +228,7 @@ namespace ts {
function writeFile(fileName: string, data: string, writeByteOrderMark?: boolean): void {
// If a BOM is required, emit one
if (writeByteOrderMark) {
data = '\uFEFF' + data;
data = "\uFEFF" + data;
}
_fs.writeFileSync(fileName, data, "utf8");
@@ -271,10 +271,10 @@ namespace ts {
newLine: _os.EOL,
useCaseSensitiveFileNames: useCaseSensitiveFileNames,
write(s: string): void {
var buffer = new Buffer(s, 'utf8');
var offset: number = 0;
var toWrite: number = buffer.length;
var written = 0;
const buffer = new Buffer(s, "utf8");
let offset: number = 0;
let toWrite: number = buffer.length;
let written = 0;
// 1 is a standard descriptor for stdout
while ((written = _fs.writeSync(1, buffer, offset, toWrite)) < toWrite) {
offset += written;
@@ -297,7 +297,7 @@ namespace ts {
}
callback(fileName);
};
}
},
resolvePath: function (path: string): string {
return _path.resolve(path);
+12 -11
View File
@@ -3,7 +3,7 @@
namespace ts {
export interface SourceFile {
fileWatcher: FileWatcher;
fileWatcher?: FileWatcher;
}
/**
@@ -14,7 +14,7 @@ namespace ts {
let matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase());
if (!matchResult) {
errors.push(createCompilerDiagnostic(Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, 'en', 'ja-jp'));
errors.push(createCompilerDiagnostic(Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp"));
return false;
}
@@ -49,7 +49,7 @@ namespace ts {
}
// TODO: Add codePage support for readFile?
let fileContents = '';
let fileContents = "";
try {
fileContents = sys.readFile(filePath);
}
@@ -245,7 +245,7 @@ namespace ts {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.Compilation_complete_Watching_for_file_changes));
}
function getSourceFile(fileName: string, languageVersion: ScriptTarget, onError ?: (message: string) => void) {
function getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void) {
// Return existing SourceFile object if one is available
if (cachedProgram) {
let sourceFile = cachedProgram.getSourceFile(fileName);
@@ -355,22 +355,23 @@ namespace ts {
return { program, exitStatus };
function compileProgram(): ExitStatus {
// First get any syntactic errors.
let diagnostics = program.getSyntacticDiagnostics();
reportDiagnostics(diagnostics);
let diagnostics: Diagnostic[];
// First get and report any syntactic errors.
diagnostics = program.getSyntacticDiagnostics();
// If we didn't have any syntactic errors, then also try getting the global and
// semantic errors.
if (diagnostics.length === 0) {
let diagnostics = program.getGlobalDiagnostics();
reportDiagnostics(diagnostics);
diagnostics = program.getGlobalDiagnostics();
if (diagnostics.length === 0) {
let diagnostics = program.getSemanticDiagnostics();
reportDiagnostics(diagnostics);
diagnostics = program.getSemanticDiagnostics();
}
}
reportDiagnostics(diagnostics);
// If the user doesn't want us to emit, then we're done at this point.
if (compilerOptions.noEmit) {
return diagnostics.length
+31 -5
View File
@@ -17,6 +17,7 @@ namespace ts {
}
// token > SyntaxKind.Identifer => token is a keyword
// Also, If you add a new SyntaxKind be sure to keep the `Markers` section at the bottom in sync
export const enum SyntaxKind {
Unknown,
EndOfFileToken,
@@ -24,6 +25,8 @@ namespace ts {
MultiLineCommentTrivia,
NewLineTrivia,
WhitespaceTrivia,
// We detect and preserve #! on the first line
ShebangTrivia,
// We detect and provide better error recovery when we encounter a git merge marker. This
// allows us to edit files with git-conflict markers in them in a much more pleasant manner.
ConflictMarkerTrivia,
@@ -1404,6 +1407,7 @@ namespace ts {
getPropertyOfType(type: Type, propertyName: string): Symbol;
getSignaturesOfType(type: Type, kind: SignatureKind): Signature[];
getIndexTypeOfType(type: Type, kind: IndexKind): Type;
getBaseTypes(type: InterfaceType): ObjectType[];
getReturnTypeOfSignature(signature: Signature): Type;
getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[];
@@ -1430,6 +1434,7 @@ namespace ts {
getJsxElementAttributesType(elementNode: JsxOpeningLikeElement): Type;
getJsxIntrinsicTagNames(): Symbol[];
isOptionalParameter(node: ParameterDeclaration): boolean;
// Should not be called directly. Should only be accessed through the Program instance.
/* @internal */ getDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
@@ -1574,6 +1579,7 @@ namespace ts {
getBlockScopedVariableId(node: Identifier): number;
getReferencedValueDeclaration(reference: Identifier): Declaration;
getTypeReferenceSerializationKind(typeName: EntityName): TypeReferenceSerializationKind;
isOptionalParameter(node: ParameterDeclaration): boolean;
}
export const enum SymbolFlags {
@@ -1762,10 +1768,14 @@ namespace ts {
FromSignature = 0x00040000, // Created for signature assignment check
ObjectLiteral = 0x00080000, // Originates in an object literal
/* @internal */
ContainsUndefinedOrNull = 0x00100000, // Type is or contains Undefined or Null type
FreshObjectLiteral = 0x00100000, // Fresh object literal type
/* @internal */
ContainsObjectLiteral = 0x00200000, // Type is or contains object literal type
ESSymbol = 0x00400000, // Type of symbol primitive introduced in ES6
ContainsUndefinedOrNull = 0x00200000, // Type is or contains Undefined or Null type
/* @internal */
ContainsObjectLiteral = 0x00400000, // Type is or contains object literal type
/* @internal */
ContainsAnyFunctionType = 0x00800000, // Type is or contains object literal type
ESSymbol = 0x01000000, // Type of symbol primitive introduced in ES6
/* @internal */
Intrinsic = Any | String | Number | Boolean | ESSymbol | Void | Undefined | Null,
@@ -1774,10 +1784,12 @@ namespace ts {
StringLike = String | StringLiteral,
NumberLike = Number | Enum,
ObjectType = Class | Interface | Reference | Tuple | Anonymous,
UnionOrIntersection = Union | Intersection,
UnionOrIntersection = Union | Intersection,
StructuredType = ObjectType | Union | Intersection,
/* @internal */
RequiresWidening = ContainsUndefinedOrNull | ContainsObjectLiteral
RequiresWidening = ContainsUndefinedOrNull | ContainsObjectLiteral,
/* @internal */
PropagatingFlags = ContainsUndefinedOrNull | ContainsObjectLiteral | ContainsAnyFunctionType
}
// Properties common to all types
@@ -1806,7 +1818,9 @@ namespace ts {
typeParameters: TypeParameter[]; // Type parameters (undefined if non-generic)
outerTypeParameters: TypeParameter[]; // Outer type parameters (undefined if none)
localTypeParameters: TypeParameter[]; // Local type parameters (undefined if none)
/* @internal */
resolvedBaseConstructorType?: Type; // Resolved base constructor type of class
/* @internal */
resolvedBaseTypes: ObjectType[]; // Resolved base types
}
@@ -1858,6 +1872,14 @@ namespace ts {
numberIndexType?: Type; // Numeric index type
}
/* @internal */
// Object literals are initially marked fresh. Freshness disappears following an assignment,
// before a type assertion, or when when an object literal's type is widened. The regular
// version of a fresh type is identical except for the TypeFlags.FreshObjectLiteral flag.
export interface FreshObjectLiteralType extends ResolvedType {
regularType: ResolvedType; // Regular version of fresh type
}
// Just a place to cache element types of iterables and iterators
/* @internal */
export interface IterableOrIteratorType extends ObjectType, UnionType {
@@ -1912,6 +1934,9 @@ namespace ts {
/* @internal */
export interface TypeMapper {
(t: TypeParameter): Type;
context?: InferenceContext; // The inference context this mapper was created from.
// Only inference mappers have this set (in createInferenceMapper).
// The identity mapper and regular instantiation mappers do not need it.
}
/* @internal */
@@ -2208,6 +2233,7 @@ namespace ts {
export interface CompilerHost {
getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile;
getCancellationToken?(): CancellationToken;
getDefaultLibFileName(options: CompilerOptions): string;
writeFile: WriteFileCallback;
getCurrentDirectory(): string;
+15 -6
View File
@@ -568,7 +568,7 @@ namespace ts {
}
}
export function isVariableLike(node: Node): boolean {
export function isVariableLike(node: Node): node is VariableLikeDeclaration {
if (node) {
switch (node.kind) {
case SyntaxKind.BindingElement:
@@ -965,7 +965,7 @@ namespace ts {
return (<ExternalModuleReference>(<ImportEqualsDeclaration>node).moduleReference).expression;
}
export function isInternalModuleImportEqualsDeclaration(node: Node) {
export function isInternalModuleImportEqualsDeclaration(node: Node): node is ImportEqualsDeclaration {
return node.kind === SyntaxKind.ImportEqualsDeclaration && (<ImportEqualsDeclaration>node).moduleReference.kind !== SyntaxKind.ExternalModuleReference;
}
@@ -988,15 +988,13 @@ namespace ts {
if (node) {
switch (node.kind) {
case SyntaxKind.Parameter:
return (<ParameterDeclaration>node).questionToken !== undefined;
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
return (<MethodDeclaration>node).questionToken !== undefined;
case SyntaxKind.ShorthandPropertyAssignment:
case SyntaxKind.PropertyAssignment:
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.PropertySignature:
return (<PropertyDeclaration>node).questionToken !== undefined;
return (<ParameterDeclaration | MethodDeclaration | PropertyDeclaration>node).questionToken !== undefined;
}
}
@@ -1884,7 +1882,7 @@ namespace ts {
function writeTrimmedCurrentLine(pos: number, nextLineStart: number) {
let end = Math.min(comment.end, nextLineStart - 1);
let currentLineText = currentSourceFile.text.substring(pos, end).replace(/^\s+|\s+$/g, '');
let currentLineText = currentSourceFile.text.substring(pos, end).replace(/^\s+|\s+$/g, "");
if (currentLineText) {
// trimmed forward and ending spaces text
writer.write(currentLineText);
@@ -1997,6 +1995,17 @@ namespace ts {
(node.parent.kind === SyntaxKind.PropertyAccessExpression && (<PropertyAccessExpression>node.parent).name === node);
}
export function isEmptyObjectLiteralOrArrayLiteral(expression: Node): boolean {
let kind = expression.kind;
if (kind === SyntaxKind.ObjectLiteralExpression) {
return (<ObjectLiteralExpression>expression).properties.length === 0;
}
if (kind === SyntaxKind.ArrayLiteralExpression) {
return (<ArrayLiteralExpression>expression).elements.length === 0;
}
return false;
}
export function getLocalSymbolForExportDefault(symbol: Symbol) {
return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & NodeFlags.Default) ? symbol.valueDeclaration.localSymbol : undefined;
}
+60 -60
View File
@@ -1,6 +1,6 @@
/// <reference path='harness.ts' />
/// <reference path='runnerbase.ts' />
/// <reference path='typeWriter.ts' />
/// <reference path="harness.ts" />
/// <reference path="runnerbase.ts" />
/// <reference path="typeWriter.ts" />
const enum CompilerTestType {
Conformance,
@@ -9,7 +9,7 @@ const enum CompilerTestType {
}
class CompilerBaselineRunner extends RunnerBase {
private basePath = 'tests/cases';
private basePath = "tests/cases";
private testSuiteName: string;
private errors: boolean;
private emit: boolean;
@@ -25,21 +25,21 @@ class CompilerBaselineRunner extends RunnerBase {
this.decl = true;
this.output = true;
if (testType === CompilerTestType.Conformance) {
this.testSuiteName = 'conformance';
this.testSuiteName = "conformance";
}
else if (testType === CompilerTestType.Regressions) {
this.testSuiteName = 'compiler';
this.testSuiteName = "compiler";
}
else if (testType === CompilerTestType.Test262) {
this.testSuiteName = 'test262';
this.testSuiteName = "test262";
} else {
this.testSuiteName = 'compiler'; // default to this for historical reasons
this.testSuiteName = "compiler"; // default to this for historical reasons
}
this.basePath += '/' + this.testSuiteName;
this.basePath += "/" + this.testSuiteName;
}
public checkTestCodeOutput(fileName: string) {
describe('compiler tests for ' + fileName, () => {
describe("compiler tests for " + 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.
let justName: string;
@@ -64,14 +64,14 @@ class CompilerBaselineRunner extends RunnerBase {
let createNewInstance = false;
before(() => {
justName = fileName.replace(/^.*[\\\/]/, ''); // strips the fileName from the path.
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('/')) + '/';
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,
@@ -106,7 +106,7 @@ class CompilerBaselineRunner extends RunnerBase {
eventually to remove this limitation. */
for (let 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')) {
if (!createNewInstance && (tcSettings[i].flag == "noimplicitany" || tcSettings[i].flag === "target")) {
harnessCompiler = Harness.Compiler.getCompiler();
harnessCompiler.setCompilerSettings(tcSettings);
createNewInstance = true;
@@ -148,9 +148,9 @@ class CompilerBaselineRunner extends RunnerBase {
}
// check errors
it('Correct errors for ' + fileName, () => {
it("Correct errors for " + fileName, () => {
if (this.errors) {
Harness.Baseline.runBaseline('Correct errors for ' + fileName, justName.replace(/\.tsx?$/, '.errors.txt'), (): string => {
Harness.Baseline.runBaseline("Correct errors for " + fileName, justName.replace(/\.tsx?$/, ".errors.txt"), (): string => {
if (result.errors.length === 0) return null;
return getErrorBaseline(toBeCompiled, otherFiles, result);
});
@@ -158,12 +158,12 @@ class CompilerBaselineRunner extends RunnerBase {
});
// Source maps?
it('Correct sourcemap content for ' + fileName, () => {
it("Correct sourcemap content for " + fileName, () => {
if (options.sourceMap || options.inlineSourceMap) {
Harness.Baseline.runBaseline('Correct sourcemap content for ' + fileName, justName.replace(/\.tsx?$/, '.sourcemap.txt'), () => {
Harness.Baseline.runBaseline("Correct sourcemap content for " + fileName, justName.replace(/\.tsx?$/, ".sourcemap.txt"), () => {
let record = result.getSourceMapRecord();
if (options.noEmitOnError && result.errors.length !== 0 && record === undefined) {
// Because of the noEmitOnError option no files are created. We need to return null because baselining isn't required.
// Because of the noEmitOnError option no files are created. We need to return null because baselining isn"t required.
return null;
}
return record;
@@ -171,35 +171,35 @@ class CompilerBaselineRunner extends RunnerBase {
}
});
it('Correct JS output for ' + fileName, () => {
if (!ts.fileExtensionIs(lastUnit.name, '.d.ts') && this.emit) {
it("Correct JS output for " + fileName, () => {
if (!ts.fileExtensionIs(lastUnit.name, ".d.ts") && this.emit) {
if (result.files.length === 0 && result.errors.length === 0) {
throw new Error('Expected at least one js file to be emitted or at least one error to be created.');
throw new Error("Expected at least one js file to be emitted or at least one error to be created.");
}
// check js output
Harness.Baseline.runBaseline('Correct JS output for ' + fileName, justName.replace(/\.tsx?/, '.js'), () => {
let tsCode = '';
Harness.Baseline.runBaseline("Correct JS output for " + fileName, justName.replace(/\.tsx?/, ".js"), () => {
let tsCode = "";
let tsSources = otherFiles.concat(toBeCompiled);
if (tsSources.length > 1) {
tsCode += '//// [' + fileName + '] ////\r\n\r\n';
tsCode += "//// [" + fileName + "] ////\r\n\r\n";
}
for (let i = 0; i < tsSources.length; i++) {
tsCode += '//// [' + Harness.Path.getFileName(tsSources[i].unitName) + ']\r\n';
tsCode += tsSources[i].content + (i < (tsSources.length - 1) ? '\r\n' : '');
tsCode += "//// [" + Harness.Path.getFileName(tsSources[i].unitName) + "]\r\n";
tsCode += tsSources[i].content + (i < (tsSources.length - 1) ? "\r\n" : "");
}
let jsCode = '';
let jsCode = "";
for (let i = 0; i < result.files.length; i++) {
jsCode += '//// [' + Harness.Path.getFileName(result.files[i].fileName) + ']\r\n';
jsCode += "//// [" + Harness.Path.getFileName(result.files[i].fileName) + "]\r\n";
jsCode += getByteOrderMarkText(result.files[i]);
jsCode += result.files[i].code;
}
if (result.declFilesCode.length > 0) {
jsCode += '\r\n\r\n';
jsCode += "\r\n\r\n";
for (let i = 0; i < result.declFilesCode.length; i++) {
jsCode += '//// [' + Harness.Path.getFileName(result.declFilesCode[i].fileName) + ']\r\n';
jsCode += "//// [" + Harness.Path.getFileName(result.declFilesCode[i].fileName) + "]\r\n";
jsCode += getByteOrderMarkText(result.declFilesCode[i]);
jsCode += result.declFilesCode[i].code;
}
@@ -210,13 +210,13 @@ class CompilerBaselineRunner extends RunnerBase {
}, options);
if (declFileCompilationResult && declFileCompilationResult.declResult.errors.length) {
jsCode += '\r\n\r\n//// [DtsFileErrors]\r\n';
jsCode += '\r\n\r\n';
jsCode += "\r\n\r\n//// [DtsFileErrors]\r\n";
jsCode += "\r\n\r\n";
jsCode += getErrorBaseline(declFileCompilationResult.declInputFiles, declFileCompilationResult.declOtherFiles, declFileCompilationResult.declResult);
}
if (jsCode.length > 0) {
return tsCode + '\r\n\r\n' + jsCode;
return tsCode + "\r\n\r\n" + jsCode;
} else {
return null;
}
@@ -224,28 +224,28 @@ class CompilerBaselineRunner extends RunnerBase {
}
});
it('Correct Sourcemap output for ' + fileName, () => {
it("Correct Sourcemap output for " + fileName, () => {
if (options.inlineSourceMap) {
if (result.sourceMaps.length > 0) {
throw new Error('No sourcemap files should be generated if inlineSourceMaps was set.');
throw new Error("No sourcemap files should be generated if inlineSourceMaps was set.");
}
return null;
}
else if (options.sourceMap) {
if (result.sourceMaps.length !== result.files.length) {
throw new Error('Number of sourcemap files should be same as js files.');
throw new Error("Number of sourcemap files should be same as js files.");
}
Harness.Baseline.runBaseline('Correct Sourcemap output for ' + fileName, justName.replace(/\.tsx?/, '.js.map'), () => {
Harness.Baseline.runBaseline("Correct Sourcemap output for " + fileName, justName.replace(/\.tsx?/, ".js.map"), () => {
if (options.noEmitOnError && result.errors.length !== 0 && result.sourceMaps.length === 0) {
// We need to return null here or the runBaseLine will actually create a empty file.
// Baselining isn't required here because there is no output.
return null;
}
let sourceMapCode = '';
let sourceMapCode = "";
for (let i = 0; i < result.sourceMaps.length; i++) {
sourceMapCode += '//// [' + Harness.Path.getFileName(result.sourceMaps[i].fileName) + ']\r\n';
sourceMapCode += "//// [" + Harness.Path.getFileName(result.sourceMaps[i].fileName) + "]\r\n";
sourceMapCode += getByteOrderMarkText(result.sourceMaps[i]);
sourceMapCode += result.sourceMaps[i].code;
}
@@ -255,7 +255,7 @@ class CompilerBaselineRunner extends RunnerBase {
}
});
it('Correct type/symbol baselines for ' + fileName, () => {
it("Correct type/symbol baselines for " + fileName, () => {
if (fileName.indexOf("APISample") >= 0) {
return;
}
@@ -317,15 +317,15 @@ class CompilerBaselineRunner extends RunnerBase {
let fullBaseLine = generateBaseLine(fullResults, isSymbolBaseLine);
let pullBaseLine = generateBaseLine(pullResults, isSymbolBaseLine);
let fullExtension = isSymbolBaseLine ? '.symbols' : '.types';
let pullExtension = isSymbolBaseLine ? '.symbols.pull' : '.types.pull';
let fullExtension = isSymbolBaseLine ? ".symbols" : ".types";
let pullExtension = isSymbolBaseLine ? ".symbols.pull" : ".types.pull";
if (fullBaseLine !== pullBaseLine) {
Harness.Baseline.runBaseline('Correct full information for ' + fileName, justName.replace(/\.tsx?/, fullExtension), () => fullBaseLine);
Harness.Baseline.runBaseline('Correct pull information for ' + fileName, justName.replace(/\.tsx?/, pullExtension), () => pullBaseLine);
Harness.Baseline.runBaseline("Correct full information for " + fileName, justName.replace(/\.tsx?/, fullExtension), () => fullBaseLine);
Harness.Baseline.runBaseline("Correct pull information for " + fileName, justName.replace(/\.tsx?/, pullExtension), () => pullBaseLine);
}
else {
Harness.Baseline.runBaseline('Correct information for ' + fileName, justName.replace(/\.tsx?/, fullExtension), () => fullBaseLine);
Harness.Baseline.runBaseline("Correct information for " + fileName, justName.replace(/\.tsx?/, fullExtension), () => fullBaseLine);
}
}
@@ -334,7 +334,7 @@ class CompilerBaselineRunner extends RunnerBase {
let typeMap: { [fileName: string]: { [lineNum: number]: string[]; } } = {};
allFiles.forEach(file => {
let codeLines = file.content.split('\n');
let codeLines = file.content.split("\n");
typeWriterResults[file.unitName].forEach(result => {
if (isSymbolBaseline && !result.symbol) {
return;
@@ -354,30 +354,30 @@ class CompilerBaselineRunner extends RunnerBase {
typeMap[file.unitName][result.line] = typeInfo;
});
typeLines.push('=== ' + file.unitName + ' ===\r\n');
typeLines.push("=== " + file.unitName + " ===\r\n");
for (let i = 0; i < codeLines.length; i++) {
let currentCodeLine = codeLines[i];
typeLines.push(currentCodeLine + '\r\n');
typeLines.push(currentCodeLine + "\r\n");
if (typeMap[file.unitName]) {
let typeInfo = typeMap[file.unitName][i];
if (typeInfo) {
typeInfo.forEach(ty => {
typeLines.push('>' + ty + '\r\n');
typeLines.push(">" + ty + "\r\n");
});
if (i + 1 < codeLines.length && (codeLines[i + 1].match(/^\s*[{|}]\s*$/) || codeLines[i + 1].trim() === '')) {
if (i + 1 < codeLines.length && (codeLines[i + 1].match(/^\s*[{|}]\s*$/) || codeLines[i + 1].trim() === "")) {
}
else {
typeLines.push('\r\n');
typeLines.push("\r\n");
}
}
}
else {
typeLines.push('No type information for this code.');
typeLines.push("No type information for this code.");
}
}
});
return typeLines.join('');
return typeLines.join("");
}
}
});
@@ -385,7 +385,7 @@ class CompilerBaselineRunner extends RunnerBase {
}
public initializeTests() {
describe(this.testSuiteName + ' tests', () => {
describe(this.testSuiteName + " tests", () => {
describe("Setup compiler for compiler baselines", () => {
let harnessCompiler = Harness.Compiler.getCompiler();
this.parseOptions();
@@ -416,23 +416,23 @@ class CompilerBaselineRunner extends RunnerBase {
this.decl = false;
this.output = false;
let opts = this.options.split(',');
let opts = this.options.split(",");
for (let i = 0; i < opts.length; i++) {
switch (opts[i]) {
case 'error':
case "error":
this.errors = true;
break;
case 'emit':
case "emit":
this.emit = true;
break;
case 'decl':
case "decl":
this.decl = true;
break;
case 'output':
case "output":
this.output = true;
break;
default:
throw new Error('unsupported flag');
throw new Error("unsupported flag");
}
}
}
+306 -237
View File
File diff suppressed because it is too large Load Diff
+37 -37
View File
@@ -1,6 +1,6 @@
///<reference path='fourslash.ts' />
///<reference path='harness.ts'/>
///<reference path='runnerbase.ts' />
///<reference path="fourslash.ts" />
///<reference path="harness.ts"/>
///<reference path="runnerbase.ts" />
const enum FourSlashTestType {
Native,
@@ -16,16 +16,16 @@ class FourSlashRunner extends RunnerBase {
super();
switch (testType) {
case FourSlashTestType.Native:
this.basePath = 'tests/cases/fourslash';
this.testSuiteName = 'fourslash';
this.basePath = "tests/cases/fourslash";
this.testSuiteName = "fourslash";
break;
case FourSlashTestType.Shims:
this.basePath = 'tests/cases/fourslash/shims';
this.testSuiteName = 'fourslash-shims';
this.basePath = "tests/cases/fourslash/shims";
this.testSuiteName = "fourslash-shims";
break;
case FourSlashTestType.Server:
this.basePath = 'tests/cases/fourslash/server';
this.testSuiteName = 'fourslash-server';
this.basePath = "tests/cases/fourslash/server";
this.testSuiteName = "fourslash-server";
break;
}
}
@@ -35,25 +35,25 @@ class FourSlashRunner extends RunnerBase {
this.tests = this.enumerateFiles(this.basePath, /\.ts/i, { recursive: false });
}
describe(this.testSuiteName + ' tests', () => {
describe(this.testSuiteName + " tests", () => {
this.tests.forEach((fn: string) => {
describe(fn, () => {
fn = ts.normalizeSlashes(fn);
let justName = fn.replace(/^.*[\\\/]/, '');
let justName = fn.replace(/^.*[\\\/]/, "");
// Convert to relative path
let testIndex = fn.indexOf('tests/');
let testIndex = fn.indexOf("tests/");
if (testIndex >= 0) fn = fn.substr(testIndex);
if (justName && !justName.match(/fourslash\.ts$/i) && !justName.match(/\.d\.ts$/i)) {
it(this.testSuiteName + ' test ' + justName + ' runs correctly', () => {
it(this.testSuiteName + " test " + justName + " runs correctly", () => {
FourSlash.runFourSlashTest(this.basePath, this.testType, fn);
});
}
});
});
describe('Generate Tao XML', () => {
describe("Generate Tao XML", () => {
let invalidReasons: any = {};
FourSlash.xmlData.forEach(xml => {
if (xml.invalidReason !== null) {
@@ -69,37 +69,37 @@ class FourSlashRunner extends RunnerBase {
invalidReport.sort((lhs, rhs) => lhs.count > rhs.count ? -1 : lhs.count === rhs.count ? 0 : 1);
let lines: string[] = [];
lines.push('<!-- Blocked Test Report');
lines.push("<!-- Blocked Test Report");
invalidReport.forEach((reasonAndCount) => {
lines.push(reasonAndCount.count + ' tests blocked by ' + reasonAndCount.reason);
lines.push(reasonAndCount.count + " tests blocked by " + reasonAndCount.reason);
});
lines.push('-->');
lines.push('<TaoTest xmlns="http://microsoft.com/schemas/VSLanguages/TAO">');
lines.push(' <InitTest>');
lines.push(' <StartTarget />');
lines.push(' </InitTest>');
lines.push(' <ScenarioList>');
lines.push("-->");
lines.push("<TaoTest xmlns=\"http://microsoft.com/schemas/VSLanguages/TAO\">");
lines.push(" <InitTest>");
lines.push(" <StartTarget />");
lines.push(" </InitTest>");
lines.push(" <ScenarioList>");
FourSlash.xmlData.forEach(xml => {
if (xml.invalidReason !== null) {
lines.push('<!-- Skipped ' + xml.originalName + ', reason: ' + xml.invalidReason + ' -->');
lines.push("<!-- Skipped " + xml.originalName + ", reason: " + xml.invalidReason + " -->");
} else {
lines.push(' <Scenario Name="' + xml.originalName + '">');
lines.push(" <Scenario Name=\"" + xml.originalName + "\">");
xml.actions.forEach(action => {
lines.push(' ' + action);
lines.push(" " + action);
});
lines.push(' </Scenario>');
lines.push(" </Scenario>");
}
});
lines.push(' </ScenarioList>');
lines.push(' <CleanupScenario>');
lines.push(' <CloseAllDocuments />');
lines.push(' <CleanupCreatedFiles />');
lines.push(' </CleanupScenario>');
lines.push(' <CleanupTest>');
lines.push(' <CloseTarget />');
lines.push(' </CleanupTest>');
lines.push('</TaoTest>');
Harness.IO.writeFile('built/local/fourslash.xml', lines.join('\r\n'));
lines.push(" </ScenarioList>");
lines.push(" <CleanupScenario>");
lines.push(" <CloseAllDocuments />");
lines.push(" <CleanupCreatedFiles />");
lines.push(" </CleanupScenario>");
lines.push(" <CleanupTest>");
lines.push(" <CloseTarget />");
lines.push(" </CleanupTest>");
lines.push("</TaoTest>");
Harness.IO.writeFile("built/local/fourslash.xml", lines.join("\r\n"));
});
});
}
@@ -108,6 +108,6 @@ class FourSlashRunner extends RunnerBase {
class GeneratedFourslashRunner extends FourSlashRunner {
constructor(testType: FourSlashTestType) {
super(testType);
this.basePath += '/generated/';
this.basePath += "/generated/";
}
}
+159 -155
View File
@@ -14,23 +14,27 @@
// limitations under the License.
//
/// <reference path='..\services\services.ts' />
/// <reference path='..\services\shims.ts' />
/// <reference path='..\server\session.ts' />
/// <reference path='..\server\client.ts' />
/// <reference path='..\server\node.d.ts' />
/// <reference path='external\mocha.d.ts'/>
/// <reference path='external\chai.d.ts'/>
/// <reference path='sourceMapRecorder.ts'/>
/// <reference path='runnerbase.ts'/>
/// <reference path="..\services\services.ts" />
/// <reference path="..\services\shims.ts" />
/// <reference path="..\server\session.ts" />
/// <reference path="..\server\client.ts" />
/// <reference path="..\server\node.d.ts" />
/// <reference path="external\mocha.d.ts"/>
/// <reference path="external\chai.d.ts"/>
/// <reference path="sourceMapRecorder.ts"/>
/// <reference path="runnerbase.ts"/>
var Buffer: BufferConstructor = require('buffer').Buffer;
// Block scoped definitions work poorly for global variables, temporarily enable var
/* tslint:disable:no-var-keyword */
var Buffer: BufferConstructor = require("buffer").Buffer;
// this will work in the browser via browserify
var _chai: typeof chai = require('chai');
var _chai: typeof chai = require("chai");
var assert: typeof _chai.assert = _chai.assert;
var expect: typeof _chai.expect = _chai.expect;
declare var __dirname: string; // Node-specific
var global = <any>Function("return this").call(null);
/* tslint:enable:no-var-keyword */
module Utils {
// Setup some globals based on the current environment
@@ -62,7 +66,7 @@ module Utils {
eval(fileContents);
break;
case ExecutionEnvironment.Node:
let vm = require('vm');
let vm = require("vm");
if (nodeContext) {
vm.runInNewContext(fileContents, nodeContext, fileName);
} else {
@@ -70,7 +74,7 @@ module Utils {
}
break;
default:
throw new Error('Unknown context');
throw new Error("Unknown context");
}
}
@@ -79,9 +83,9 @@ module Utils {
// Split up the input file by line
// Note: IE JS engine incorrectly handles consecutive delimiters here when using RegExp split, so
// we have to use string-based splitting instead and try to figure out the delimiting chars
let lines = content.split('\r\n');
let lines = content.split("\r\n");
if (lines.length === 1) {
lines = content.split('\n');
lines = content.split("\n");
if (lines.length === 1) {
lines = content.split("\r");
@@ -92,7 +96,7 @@ module Utils {
/** Reads a file under /tests */
export function readTestFile(path: string) {
if (path.indexOf('tests') < 0) {
if (path.indexOf("tests") < 0) {
path = "tests/" + path;
}
@@ -387,7 +391,7 @@ module Utils {
module Harness.Path {
export function getFileName(fullPath: string) {
return fullPath.replace(/^.*[\\\/]/, '');
return fullPath.replace(/^.*[\\\/]/, "");
}
export function filePath(fullPath: string) {
@@ -411,6 +415,7 @@ module Harness {
log(text: string): void;
getMemoryUsage?(): number;
}
export var IO: IO;
module IOImpl {
declare class Enumerator {
@@ -483,8 +488,8 @@ module Harness {
declare let require: any;
let fs: any, pathModule: any;
if (require) {
fs = require('fs');
pathModule = require('path');
fs = require("fs");
pathModule = require("path");
} else {
fs = pathModule = {};
}
@@ -492,7 +497,7 @@ module Harness {
export let readFile: typeof IO.readFile = ts.sys.readFile;
export let writeFile: typeof IO.writeFile = ts.sys.writeFile;
export let fileExists: typeof IO.fileExists = fs.existsSync;
export let log: typeof IO.log = console.log;
export let log: typeof IO.log = s => console.log(s);
export function createDirectory(path: string) {
if (!directoryExists(path)) {
@@ -558,8 +563,8 @@ module Harness {
let serverRoot = "http://localhost:8888/";
// Unused?
let newLine = '\r\n';
let currentDirectory = () => '';
let newLine = "\r\n";
let currentDirectory = () => "";
let supportsCodePage = () => false;
module Http {
@@ -605,9 +610,9 @@ module Harness {
export function writeToServerSync(url: string, action: string, contents?: string): XHRResponse {
let xhr = new XMLHttpRequest();
try {
let actionMsg = '?action=' + action;
xhr.open('POST', url + actionMsg, false);
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
let actionMsg = "?action=" + action;
xhr.open("POST", url + actionMsg, false);
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.send(contents);
}
catch (e) {
@@ -623,7 +628,7 @@ module Harness {
}
export function deleteFile(path: string) {
Http.writeToServerSync(serverRoot + path, 'DELETE', null);
Http.writeToServerSync(serverRoot + path, "DELETE", null);
}
export function directoryExists(path: string): boolean {
@@ -636,15 +641,15 @@ module Harness {
if (dirPath.match(/localhost:\d+$/) || dirPath.match(/localhost:\d+\/$/)) {
dirPath = null;
// path + fileName
} else if (dirPath.indexOf('.') === -1) {
dirPath = dirPath.substring(0, dirPath.lastIndexOf('/'));
} else if (dirPath.indexOf(".") === -1) {
dirPath = dirPath.substring(0, dirPath.lastIndexOf("/"));
// path
} else {
// strip any trailing slash
if (dirPath.match(/.*\/$/)) {
dirPath = dirPath.substring(0, dirPath.length - 2);
}
dirPath = dirPath.substring(0, dirPath.lastIndexOf('/'));
dirPath = dirPath.substring(0, dirPath.lastIndexOf("/"));
}
return dirPath;
@@ -659,7 +664,7 @@ module Harness {
export function _listFilesImpl(path: string, spec?: RegExp, options?: any) {
let response = Http.getFileFromServerSync(serverRoot + path);
if (response.status === 200) {
let results = response.responseText.split(',');
let results = response.responseText.split(",");
if (spec) {
return results.filter(file => spec.test(file));
} else {
@@ -667,12 +672,12 @@ module Harness {
}
}
else {
return [''];
return [""];
}
};
export let listFiles = Utils.memoize(_listFilesImpl);
export let log = console.log;
export let log = (s: string) => console.log(s);
export function readFile(file: string) {
let response = Http.getFileFromServerSync(serverRoot + file);
@@ -684,12 +689,11 @@ module Harness {
}
export function writeFile(path: string, contents: string) {
Http.writeToServerSync(serverRoot + path, 'WRITE', contents);
Http.writeToServerSync(serverRoot + path, "WRITE", contents);
}
}
}
export var IO: IO;
switch (Utils.getExecutionEnvironment()) {
case Utils.ExecutionEnvironment.CScript:
IO = IOImpl.CScript;
@@ -721,7 +725,7 @@ module Harness {
tcServicesFileName = "built/local/typescriptServices.js";
break;
default:
throw new Error('Unknown context');
throw new Error("Unknown context");
}
export let tcServicesFile = IO.readFile(tcServicesFileName);
@@ -744,12 +748,12 @@ module Harness {
public Write(str: string) {
// out of memory usage concerns avoid using + or += if we're going to do any manipulation of this string later
this.currentLine = [(this.currentLine || ''), str].join('');
this.currentLine = [(this.currentLine || ""), str].join("");
}
public WriteLine(str: string) {
// out of memory usage concerns avoid using + or += if we're going to do any manipulation of this string later
this.lines.push([(this.currentLine || ''), str].join(''));
this.lines.push([(this.currentLine || ""), str].join(""));
this.currentLine = undefined;
}
@@ -798,7 +802,7 @@ module Harness {
if (this.fileCollection.hasOwnProperty(p)) {
let current = <Harness.Compiler.WriterAggregator>this.fileCollection[p];
if (current.lines.length > 0) {
if (p.indexOf('.d.ts') !== -1) { current.lines.unshift(['////[', Path.getFileName(p), ']'].join('')); }
if (p.indexOf(".d.ts") !== -1) { current.lines.unshift(["////[", Path.getFileName(p), "]"].join("")); }
result.push({ fileName: p, file: this.fileCollection[p] });
}
}
@@ -827,12 +831,12 @@ module Harness {
const carriageReturnLineFeed = "\r\n";
const lineFeed = "\n";
export let defaultLibFileName = 'lib.d.ts';
export let defaultLibSourceFile = createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + 'lib.core.d.ts'), /*languageVersion*/ ts.ScriptTarget.Latest);
export let defaultES6LibSourceFile = createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + 'lib.core.es6.d.ts'), /*languageVersion*/ ts.ScriptTarget.Latest);
export let defaultLibFileName = "lib.d.ts";
export let defaultLibSourceFile = createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + "lib.core.d.ts"), /*languageVersion*/ ts.ScriptTarget.Latest);
export let defaultES6LibSourceFile = createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + "lib.core.es6.d.ts"), /*languageVersion*/ ts.ScriptTarget.Latest);
// Cache these between executions so we don't have to re-parse them for every test
export let fourslashFileName = 'fourslash.ts';
export let fourslashFileName = "fourslash.ts";
export let fourslashSourceFile: ts.SourceFile;
export function getCanonicalFileName(fileName: string): string {
@@ -882,7 +886,7 @@ module Harness {
return Object.prototype.hasOwnProperty.call(filemap, getCanonicalFileName(canonicalAbsolutePath)) ? filemap[canonicalAbsolutePath] : undefined;
}
else if (fn === fourslashFileName) {
let tsFn = 'tests/cases/fourslash/' + fourslashFileName;
let tsFn = "tests/cases/fourslash/" + fourslashFileName;
fourslashSourceFile = fourslashSourceFile || createSourceFileAndAssertInvariants(tsFn, Harness.IO.readFile(tsFn), scriptTarget);
return fourslashSourceFile;
}
@@ -973,7 +977,7 @@ module Harness {
settingsCallback(null);
}
let newLine = '\r\n';
let newLine = "\r\n";
options.skipDefaultLibCheck = true;
// Files from built\local that are requested by test "@includeBuiltFiles" to be in the context.
@@ -1010,19 +1014,19 @@ module Harness {
// "fileName", "comments", "declaration", "module", "nolib", "sourcemap", "target", "out", "outdir", "noimplicitany", "noresolve"
case "module":
case "modulegentarget":
if (typeof setting.value === 'string') {
if (setting.value.toLowerCase() === 'amd') {
if (typeof setting.value === "string") {
if (setting.value.toLowerCase() === "amd") {
options.module = ts.ModuleKind.AMD;
} else if (setting.value.toLowerCase() === 'umd') {
} else if (setting.value.toLowerCase() === "umd") {
options.module = ts.ModuleKind.UMD;
} else if (setting.value.toLowerCase() === 'commonjs') {
} else if (setting.value.toLowerCase() === "commonjs") {
options.module = ts.ModuleKind.CommonJS;
} else if (setting.value.toLowerCase() === 'system') {
} else if (setting.value.toLowerCase() === "system") {
options.module = ts.ModuleKind.System;
} else if (setting.value.toLowerCase() === 'unspecified') {
} else if (setting.value.toLowerCase() === "unspecified") {
options.module = ts.ModuleKind.None;
} else {
throw new Error('Unknown module type ' + setting.value);
throw new Error("Unknown module type " + setting.value);
}
} else {
options.module = <any>setting.value;
@@ -1030,152 +1034,152 @@ module Harness {
break;
case "target":
case 'codegentarget':
if (typeof setting.value === 'string') {
if (setting.value.toLowerCase() === 'es3') {
case "codegentarget":
if (typeof setting.value === "string") {
if (setting.value.toLowerCase() === "es3") {
options.target = ts.ScriptTarget.ES3;
} else if (setting.value.toLowerCase() === 'es5') {
} else if (setting.value.toLowerCase() === "es5") {
options.target = ts.ScriptTarget.ES5;
} else if (setting.value.toLowerCase() === 'es6') {
} else if (setting.value.toLowerCase() === "es6") {
options.target = ts.ScriptTarget.ES6;
} else {
throw new Error('Unknown compile target ' + setting.value);
throw new Error("Unknown compile target " + setting.value);
}
} else {
options.target = <any>setting.value;
}
break;
case 'experimentaldecorators':
options.experimentalDecorators = setting.value === 'true';
case "experimentaldecorators":
options.experimentalDecorators = setting.value === "true";
break;
case 'emitdecoratormetadata':
options.emitDecoratorMetadata = setting.value === 'true';
case "emitdecoratormetadata":
options.emitDecoratorMetadata = setting.value === "true";
break;
case 'experimentalasyncfunctions':
options.experimentalAsyncFunctions = setting.value === 'true';
case "experimentalasyncfunctions":
options.experimentalAsyncFunctions = setting.value === "true";
break;
case 'noemithelpers':
options.noEmitHelpers = setting.value === 'true';
case "noemithelpers":
options.noEmitHelpers = setting.value === "true";
break;
case 'noemitonerror':
options.noEmitOnError = setting.value === 'true';
case "noemitonerror":
options.noEmitOnError = setting.value === "true";
break;
case 'noresolve':
options.noResolve = setting.value === 'true';
case "noresolve":
options.noResolve = setting.value === "true";
break;
case 'noimplicitany':
options.noImplicitAny = setting.value === 'true';
case "noimplicitany":
options.noImplicitAny = setting.value === "true";
break;
case 'nolib':
options.noLib = setting.value === 'true';
case "nolib":
options.noLib = setting.value === "true";
break;
case 'out':
case 'outfileoption':
case "out":
case "outfileoption":
options.out = setting.value;
break;
case 'outdiroption':
case 'outdir':
case "outdiroption":
case "outdir":
options.outDir = setting.value;
break;
case 'skipdefaultlibcheck':
case "skipdefaultlibcheck":
options.skipDefaultLibCheck = setting.value === "true";
break;
case 'sourceroot':
case "sourceroot":
options.sourceRoot = setting.value;
break;
case 'maproot':
case "maproot":
options.mapRoot = setting.value;
break;
case 'sourcemap':
options.sourceMap = setting.value === 'true';
case "sourcemap":
options.sourceMap = setting.value === "true";
break;
case 'declaration':
options.declaration = setting.value === 'true';
case "declaration":
options.declaration = setting.value === "true";
break;
case 'newline':
if (setting.value.toLowerCase() === 'crlf') {
case "newline":
if (setting.value.toLowerCase() === "crlf") {
options.newLine = ts.NewLineKind.CarriageReturnLineFeed;
}
else if (setting.value.toLowerCase() === 'lf') {
else if (setting.value.toLowerCase() === "lf") {
options.newLine = ts.NewLineKind.LineFeed;
}
else {
throw new Error('Unknown option for newLine: ' + setting.value);
throw new Error("Unknown option for newLine: " + setting.value);
}
break;
case 'comments':
options.removeComments = setting.value === 'false';
case "comments":
options.removeComments = setting.value === "false";
break;
case 'stripinternal':
options.stripInternal = setting.value === 'true';
case "stripinternal":
options.stripInternal = setting.value === "true";
case 'usecasesensitivefilenames':
useCaseSensitiveFileNames = setting.value === 'true';
case "usecasesensitivefilenames":
useCaseSensitiveFileNames = setting.value === "true";
break;
case 'filename':
case "filename":
// Not supported yet
break;
case 'emitbom':
options.emitBOM = setting.value === 'true';
case "emitbom":
options.emitBOM = setting.value === "true";
break;
case 'errortruncation':
options.noErrorTruncation = setting.value === 'false';
case "errortruncation":
options.noErrorTruncation = setting.value === "false";
break;
case 'preserveconstenums':
options.preserveConstEnums = setting.value === 'true';
case "preserveconstenums":
options.preserveConstEnums = setting.value === "true";
break;
case 'isolatedmodules':
options.isolatedModules = setting.value === 'true';
case "isolatedmodules":
options.isolatedModules = setting.value === "true";
break;
case 'suppressimplicitanyindexerrors':
options.suppressImplicitAnyIndexErrors = setting.value === 'true';
case "suppressimplicitanyindexerrors":
options.suppressImplicitAnyIndexErrors = setting.value === "true";
break;
case 'includebuiltfile':
case "includebuiltfile":
let builtFileName = libFolder + setting.value;
includeBuiltFiles.push({ unitName: builtFileName, content: normalizeLineEndings(IO.readFile(builtFileName), newLine) });
break;
case 'inlinesourcemap':
options.inlineSourceMap = setting.value === 'true';
case "inlinesourcemap":
options.inlineSourceMap = setting.value === "true";
break;
case 'inlinesources':
options.inlineSources = setting.value === 'true';
case "inlinesources":
options.inlineSources = setting.value === "true";
break;
case 'jsx':
options.jsx = setting.value.toLowerCase() === 'react' ? ts.JsxEmit.React :
setting.value.toLowerCase() === 'preserve' ? ts.JsxEmit.Preserve :
case "jsx":
options.jsx = setting.value.toLowerCase() === "react" ? ts.JsxEmit.React :
setting.value.toLowerCase() === "preserve" ? ts.JsxEmit.Preserve :
ts.JsxEmit.None;
break;
default:
throw new Error('Unsupported compiler setting ' + setting.flag);
throw new Error("Unsupported compiler setting " + setting.flag);
}
}
}
@@ -1188,7 +1192,7 @@ module Harness {
// Current directory is needed for rwcRunner to be able to use currentDirectory defined in json file
currentDirectory?: string) {
if (options.declaration && result.errors.length === 0 && result.declFilesCode.length !== result.files.length) {
throw new Error('There were no errors and declFiles generated did not match number of js files generated');
throw new Error("There were no errors and declFiles generated did not match number of js files generated");
}
let declInputFiles: { unitName: string; content: string }[] = [];
@@ -1249,8 +1253,8 @@ module Harness {
}
function normalizeLineEndings(text: string, lineEnding: string): string {
let normalized = text.replace(/\r\n?/g, '\n');
if (lineEnding !== '\n') {
let normalized = text.replace(/\r\n?/g, "\n");
if (lineEnding !== "\n") {
normalized = normalized.replace(/\n/g, lineEnding);
}
return normalized;
@@ -1281,10 +1285,10 @@ module Harness {
let message = ts.flattenDiagnosticMessageText(error.messageText, ts.sys.newLine);
let errLines = RunnerBase.removeFullPaths(message)
.split('\n')
.map(s => s.length > 0 && s.charAt(s.length - 1) === '\r' ? s.substr(0, s.length - 1) : s)
.split("\n")
.map(s => s.length > 0 && s.charAt(s.length - 1) === "\r" ? s.substr(0, s.length - 1) : s)
.filter(s => s.length > 0)
.map(s => '!!! ' + ts.DiagnosticCategory[error.category].toLowerCase() + " TS" + error.code + ": " + s);
.map(s => "!!! " + ts.DiagnosticCategory[error.category].toLowerCase() + " TS" + error.code + ": " + s);
errLines.forEach(e => outputLines.push(e));
totalErrorsReported++;
@@ -1304,7 +1308,7 @@ module Harness {
// Header
outputLines.push('==== ' + inputFile.unitName + ' (' + fileErrors.length + ' errors) ====');
outputLines.push("==== " + inputFile.unitName + " (" + fileErrors.length + " errors) ====");
// Make sure we emit something for every error
let markedErrorCount = 0;
@@ -1313,13 +1317,13 @@ module Harness {
// we have to string-based splitting instead and try to figure out the delimiting chars
let lineStarts = ts.computeLineStarts(inputFile.content);
let lines = inputFile.content.split('\n');
let lines = inputFile.content.split("\n");
if (lines.length === 1) {
lines = lines[0].split("\r");
}
lines.forEach((line, lineIndex) => {
if (line.length > 0 && line.charAt(line.length - 1) === '\r') {
if (line.length > 0 && line.charAt(line.length - 1) === "\r") {
line = line.substr(0, line.length - 1);
}
@@ -1332,7 +1336,7 @@ module Harness {
nextLineStart = lineStarts[lineIndex + 1];
}
// Emit this line from the original file
outputLines.push(' ' + line);
outputLines.push(" " + line);
fileErrors.forEach(err => {
// Does any error start or continue on to this line? Emit squiggles
let end = ts.textSpanEnd(err);
@@ -1344,7 +1348,7 @@ module Harness {
// Calculate the start of the squiggle
let squiggleStart = Math.max(0, relativeOffset);
// TODO/REVIEW: this doesn't work quite right in the browser if a multi file test has files whose names are just the right length relative to one another
outputLines.push(' ' + line.substr(0, squiggleStart).replace(/[^\s]/g, ' ') + new Array(Math.min(length, line.length - squiggleStart) + 1).join('~'));
outputLines.push(" " + line.substr(0, squiggleStart).replace(/[^\s]/g, " ") + new Array(Math.min(length, line.length - squiggleStart) + 1).join("~"));
// If the error ended here, or we're at the end of the file, emit its message
if ((lineIndex === lines.length - 1) || nextLineStart > end) {
@@ -1359,7 +1363,7 @@ module Harness {
});
// Verify we didn't miss any errors in this file
assert.equal(markedErrorCount, fileErrors.length, 'count of errors in ' + inputFile.unitName);
assert.equal(markedErrorCount, fileErrors.length, "count of errors in " + inputFile.unitName);
});
let numLibraryDiagnostics = ts.countWhere(diagnostics, diagnostic => {
@@ -1372,10 +1376,10 @@ module Harness {
});
// Verify we didn't miss any errors in total
assert.equal(totalErrorsReported + numLibraryDiagnostics + numTest262HarnessDiagnostics, diagnostics.length, 'total number of errors');
assert.equal(totalErrorsReported + numLibraryDiagnostics + numTest262HarnessDiagnostics, diagnostics.length, "total number of errors");
return minimalDiagnosticsToString(diagnostics) +
ts.sys.newLine + ts.sys.newLine + outputLines.join('\r\n');
ts.sys.newLine + ts.sys.newLine + outputLines.join("\r\n");
}
export function collateOutputs(outputFiles: Harness.Compiler.GeneratedFile[]): string {
@@ -1383,15 +1387,15 @@ module Harness {
outputFiles.sort((a, b) => cleanName(a.fileName).localeCompare(cleanName(b.fileName)));
// Emit them
let result = '';
let result = "";
for (let outputFile of outputFiles) {
// Some extra spacing if this isn't the first file
if (result.length) {
result += '\r\n\r\n';
result += "\r\n\r\n";
}
// FileName header + content
result += '/*====== ' + outputFile.fileName + ' ======*/\r\n';
result += "/*====== " + outputFile.fileName + " ======*/\r\n";
result += outputFile.code;
}
@@ -1399,7 +1403,7 @@ module Harness {
return result;
function cleanName(fn: string) {
let lastSlash = ts.normalizeSlashes(fn).lastIndexOf('/');
let lastSlash = ts.normalizeSlashes(fn).lastIndexOf("/");
return fn.substr(lastSlash + 1).toLowerCase();
}
}
@@ -1417,7 +1421,7 @@ module Harness {
// This does not need to exist strictly speaking, but many tests will need to be updated if it's removed
export function compileString(code: string, unitName: string, callback: (result: CompilerResult) => void) {
// NEWTODO: Re-implement 'compileString'
throw new Error('compileString NYI');
throw new Error("compileString NYI");
}
export interface GeneratedFile {
@@ -1431,26 +1435,26 @@ module Harness {
}
export function isTS(fileName: string) {
return stringEndsWith(fileName, '.ts');
return stringEndsWith(fileName, ".ts");
}
export function isTSX(fileName: string) {
return stringEndsWith(fileName, '.tsx');
return stringEndsWith(fileName, ".tsx");
}
export function isDTS(fileName: string) {
return stringEndsWith(fileName, '.d.ts');
return stringEndsWith(fileName, ".d.ts");
}
export function isJS(fileName: string) {
return stringEndsWith(fileName, '.js');
return stringEndsWith(fileName, ".js");
}
export function isJSX(fileName: string) {
return stringEndsWith(fileName, '.jsx');
return stringEndsWith(fileName, ".jsx");
}
export function isJSMap(fileName: string) {
return stringEndsWith(fileName, '.js.map');
return stringEndsWith(fileName, ".js.map") || stringEndsWith(fileName, ".jsx.map");
}
/** Contains the code and errors of a compilation and some helper methods to check its status. */
@@ -1477,7 +1481,7 @@ module Harness {
this.sourceMaps.push(emittedFile);
}
else {
throw new Error('Unrecognized file extension for file ' + emittedFile.fileName);
throw new Error("Unrecognized file extension for file " + emittedFile.fileName);
}
});
@@ -1586,10 +1590,10 @@ module Harness {
// Subfile content line
// Append to the current subfile content, inserting a newline needed
if (currentFileContent === null) {
currentFileContent = '';
currentFileContent = "";
} else {
// End-of-line
currentFileContent = currentFileContent + '\n';
currentFileContent = currentFileContent + "\n";
}
currentFileContent = currentFileContent + line;
}
@@ -1600,7 +1604,7 @@ module Harness {
// EOF, push whatever remains
let newTestFile2 = {
content: currentFileContent || '',
content: currentFileContent || "",
name: currentFileName,
fileOptions: currentFileOptions,
originalFilePath: fileName,
@@ -1622,27 +1626,27 @@ module Harness {
export function localPath(fileName: string, baselineFolder?: string, subfolder?: string) {
if (baselineFolder === undefined) {
return baselinePath(fileName, 'local', 'tests/baselines', subfolder);
return baselinePath(fileName, "local", "tests/baselines", subfolder);
}
else {
return baselinePath(fileName, 'local', baselineFolder, subfolder);
return baselinePath(fileName, "local", baselineFolder, subfolder);
}
}
function referencePath(fileName: string, baselineFolder?: string, subfolder?: string) {
if (baselineFolder === undefined) {
return baselinePath(fileName, 'reference', 'tests/baselines', subfolder);
return baselinePath(fileName, "reference", "tests/baselines", subfolder);
}
else {
return baselinePath(fileName, 'reference', baselineFolder, subfolder);
return baselinePath(fileName, "reference", baselineFolder, subfolder);
}
}
function baselinePath(fileName: string, type: string, baselineFolder: string, subfolder?: string) {
if (subfolder !== undefined) {
return Harness.userSpecifiedRoot + baselineFolder + '/' + subfolder + '/' + type + '/' + fileName;
return Harness.userSpecifiedRoot + baselineFolder + "/" + subfolder + "/" + type + "/" + fileName;
} else {
return Harness.userSpecifiedRoot + baselineFolder + '/' + type + '/' + fileName;
return Harness.userSpecifiedRoot + baselineFolder + "/" + type + "/" + fileName;
}
}
@@ -1676,7 +1680,7 @@ module Harness {
let actual = generateContent();
if (actual === undefined) {
throw new Error('The generated content was "undefined". Return "null" if no baselining is required."');
throw new Error("The generated content was \"undefined\". Return \"null\" if no baselining is required.\"");
}
// Store the content in the 'local' folder so we
@@ -1699,10 +1703,10 @@ module Harness {
let refFileName = referencePath(relativeFileName, opts && opts.Baselinefolder, opts && opts.Subfolder);
if (actual === null) {
actual = '<no content>';
actual = "<no content>";
}
let expected = '<no content>';
let expected = "<no content>";
if (IO.fileExists(refFileName)) {
expected = IO.readFile(refFileName);
}
@@ -1711,10 +1715,10 @@ module Harness {
}
function writeComparison(expected: string, actual: string, relativeFileName: string, actualFileName: string, descriptionForDescribe: string) {
let encoded_actual = (new Buffer(actual)).toString('utf8');
let encoded_actual = (new Buffer(actual)).toString("utf8");
if (expected != encoded_actual) {
// Overwrite & issue error
let errMsg = 'The baseline file ' + relativeFileName + ' has changed';
let errMsg = "The baseline file " + relativeFileName + " has changed";
throw new Error(errMsg);
}
}
@@ -1743,7 +1747,7 @@ module Harness {
}
export function isLibraryFile(filePath: string): boolean {
return (Path.getFileName(filePath) === 'lib.d.ts') || (Path.getFileName(filePath) === 'lib.core.d.ts');
return (Path.getFileName(filePath) === "lib.d.ts") || (Path.getFileName(filePath) === "lib.core.d.ts");
}
export function isBuiltFile(filePath: string): boolean {
+5 -5
View File
@@ -1,7 +1,7 @@
/// <reference path='..\services\services.ts' />
/// <reference path='..\services\shims.ts' />
/// <reference path='..\server\client.ts' />
/// <reference path='harness.ts' />
/// <reference path="..\services\services.ts" />
/// <reference path="..\services\shims.ts" />
/// <reference path="..\server\client.ts" />
/// <reference path="harness.ts" />
module Harness.LanguageService {
export class ScriptInfo {
@@ -242,7 +242,7 @@ module Harness.LanguageService {
throw new Error("NYI");
}
getClassificationsForLine(text: string, lexState: ts.EndOfLineState, classifyKeywordsInGenerics?: boolean): ts.ClassificationResult {
let result = this.shim.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics).split('\n');
let result = this.shim.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics).split("\n");
let entries: ts.ClassificationInfo[] = [];
let i = 0;
let position = 0;
+12 -11
View File
@@ -12,6 +12,7 @@ interface FindFileResult {
}
interface IOLog {
timestamp: string;
arguments: string[];
executingPath: string;
currentDirectory: string;
@@ -72,7 +73,7 @@ interface PlaybackControl {
module Playback {
let recordLog: IOLog = undefined;
let replayLog: IOLog = undefined;
let recordLogFileNameBase = '';
let recordLogFileNameBase = "";
interface Memoized<T> {
(s: string): T;
@@ -98,7 +99,7 @@ module Playback {
return {
timestamp: (new Date()).toString(),
arguments: [],
currentDirectory: '',
currentDirectory: "",
filesRead: [],
filesWritten: [],
filesDeleted: [],
@@ -109,7 +110,7 @@ module Playback {
dirExists: [],
dirsCreated: [],
pathsResolved: [],
executingPath: ''
executingPath: ""
};
}
@@ -169,7 +170,7 @@ module Playback {
if (defaultValue !== undefined) {
return defaultValue;
} else {
throw new Error('No matching result in log array for: ' + JSON.stringify(expectedFields));
throw new Error("No matching result in log array for: " + JSON.stringify(expectedFields));
}
}
return results[0].result;
@@ -194,7 +195,7 @@ module Playback {
}
// 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);
throw new Error("No matching result in log array for path: " + expectedPath);
} else {
return defaultValue;
}
@@ -202,7 +203,7 @@ module Playback {
let pathEquivCache: any = {};
function pathsAreEquivalent(left: string, right: string, wrapper: { resolvePath(s: string): string }) {
let key = left + '-~~-' + right;
let key = left + "-~~-" + right;
function areSame(a: string, b: string) {
return ts.normalizeSlashes(a).toLowerCase() === ts.normalizeSlashes(b).toLowerCase();
}
@@ -232,14 +233,14 @@ module Playback {
wrapper.endRecord = () => {
if (recordLog !== undefined) {
let i = 0;
let fn = () => recordLogFileNameBase + i + '.json';
let fn = () => recordLogFileNameBase + i + ".json";
while (underlying.fileExists(fn())) i++;
underlying.writeFile(fn(), JSON.stringify(recordLog));
recordLog = undefined;
}
};
Object.defineProperty(wrapper, 'args', {
Object.defineProperty(wrapper, "args", {
get() {
if (replayLog !== undefined) {
return replayLog.arguments;
@@ -275,7 +276,7 @@ module Playback {
wrapper.getCurrentDirectory = () => {
if (replayLog !== undefined) {
return replayLog.currentDirectory || '';
return replayLog.currentDirectory || "";
} else if (recordLog !== undefined) {
return recordLog.currentDirectory = underlying.getCurrentDirectory();
} else {
@@ -285,7 +286,7 @@ module Playback {
wrapper.resolvePath = recordReplay(wrapper.resolvePath, underlying)(
(path) => callAndRecord(underlying.resolvePath(path), recordLog.pathsResolved, { path: path }),
memoize((path) => findResultByFields(replayLog.pathsResolved, { path: path }, !ts.isRootedDiskPath(ts.normalizeSlashes(path)) && replayLog.currentDirectory ? replayLog.currentDirectory + '/' + path : ts.normalizeSlashes(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) => {
@@ -298,7 +299,7 @@ module Playback {
wrapper.writeFile = recordReplay(wrapper.writeFile, underlying)(
(path, contents) => callAndRecord(underlying.writeFile(path, contents), recordLog.filesWritten, { path: path, contents: contents, bom: false }),
(path, contents) => noOpReplay('writeFile'));
(path, contents) => noOpReplay("writeFile"));
wrapper.exit = (exitCode) => {
if (recordLog !== undefined) {
+13 -13
View File
@@ -74,7 +74,7 @@ class ProjectRunner extends RunnerBase {
catch (e) {
assert(false, "Testcase: " + testCaseFileName + " does not contain valid json format: " + e.message);
}
let testCaseJustName = testCaseFileName.replace(/^.*[\\\/]/, '').replace(/\.json/, "");
let testCaseJustName = testCaseFileName.replace(/^.*[\\\/]/, "").replace(/\.json/, "");
function moduleNameToString(moduleKind: ts.ModuleKind) {
return moduleKind === ts.ModuleKind.AMD
@@ -331,9 +331,9 @@ class ProjectRunner extends RunnerBase {
return Harness.Compiler.getErrorBaseline(inputFiles, compilerResult.errors);
}
let name = 'Compiling project for ' + testCase.scenario + ': testcase ' + testCaseFileName;
let name = "Compiling project for " + testCase.scenario + ": testcase " + testCaseFileName;
describe('Projects tests', () => {
describe("Projects tests", () => {
describe(name, () => {
function verifyCompilerResults(moduleKind: ts.ModuleKind) {
let compilerResult: BatchCompileProjectTestCaseResult;
@@ -367,27 +367,27 @@ class ProjectRunner extends RunnerBase {
compilerResult = batchCompilerProjectTestCase(moduleKind);
});
it('Resolution information of (' + moduleNameToString(moduleKind) + '): ' + testCaseFileName, () => {
Harness.Baseline.runBaseline('Resolution information of (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + '.json', () => {
it("Resolution information of (" + moduleNameToString(moduleKind) + "): " + testCaseFileName, () => {
Harness.Baseline.runBaseline("Resolution information of (" + moduleNameToString(compilerResult.moduleKind) + "): " + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + ".json", () => {
return JSON.stringify(getCompilerResolutionInfo(), undefined, " ");
});
});
it('Errors for (' + moduleNameToString(moduleKind) + '): ' + testCaseFileName, () => {
it("Errors for (" + moduleNameToString(moduleKind) + "): " + testCaseFileName, () => {
if (compilerResult.errors.length) {
Harness.Baseline.runBaseline('Errors for (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + '.errors.txt', () => {
Harness.Baseline.runBaseline("Errors for (" + moduleNameToString(compilerResult.moduleKind) + "): " + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + ".errors.txt", () => {
return getErrorsBaseline(compilerResult);
});
}
});
it('Baseline of emitted result (' + moduleNameToString(moduleKind) + '): ' + testCaseFileName, () => {
it("Baseline of emitted result (" + moduleNameToString(moduleKind) + "): " + testCaseFileName, () => {
if (testCase.baselineCheck) {
ts.forEach(compilerResult.outputFiles, outputFile => {
Harness.Baseline.runBaseline('Baseline of emitted result (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + outputFile.fileName, () => {
Harness.Baseline.runBaseline("Baseline of emitted result (" + moduleNameToString(compilerResult.moduleKind) + "): " + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + outputFile.fileName, () => {
try {
return ts.sys.readFile(getProjectOutputFolder(outputFile.fileName, compilerResult.moduleKind));
}
@@ -400,9 +400,9 @@ class ProjectRunner extends RunnerBase {
});
it('SourceMapRecord for (' + moduleNameToString(moduleKind) + '): ' + testCaseFileName, () => {
it("SourceMapRecord for (" + moduleNameToString(moduleKind) + "): " + testCaseFileName, () => {
if (compilerResult.sourceMapData) {
Harness.Baseline.runBaseline('SourceMapRecord for (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + '.sourcemap.txt', () => {
Harness.Baseline.runBaseline("SourceMapRecord for (" + moduleNameToString(compilerResult.moduleKind) + "): " + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + ".sourcemap.txt", () => {
return Harness.SourceMapRecoder.getSourceMapRecord(compilerResult.sourceMapData, compilerResult.program,
ts.filter(compilerResult.outputFiles, outputFile => Harness.Compiler.isJS(outputFile.emittedFileName)));
});
@@ -411,11 +411,11 @@ class ProjectRunner extends RunnerBase {
// Verify that all the generated .d.ts files compile
it('Errors in generated Dts files for (' + moduleNameToString(moduleKind) + '): ' + testCaseFileName, () => {
it("Errors in generated Dts files for (" + moduleNameToString(moduleKind) + "): " + testCaseFileName, () => {
if (!compilerResult.errors.length && testCase.declaration) {
let dTsCompileResult = compileCompileDTsFiles(compilerResult);
if (dTsCompileResult.errors.length) {
Harness.Baseline.runBaseline('Errors in generated Dts files for (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + '.dts.errors.txt', () => {
Harness.Baseline.runBaseline("Errors in generated Dts files for (" + moduleNameToString(compilerResult.moduleKind) + "): " + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + ".dts.errors.txt", () => {
return getErrorsBaseline(dTsCompileResult);
});
}
+20 -20
View File
@@ -13,12 +13,12 @@
// limitations under the License.
//
/// <reference path='test262Runner.ts' />
/// <reference path='compilerRunner.ts' />
/// <reference path='fourslashRunner.ts' />
/// <reference path='projectsRunner.ts' />
/// <reference path='rwcRunner.ts' />
/// <reference path='harness.ts' />
/// <reference path="test262Runner.ts" />
/// <reference path="compilerRunner.ts" />
/// <reference path="fourslashRunner.ts" />
/// <reference path="projectsRunner.ts" />
/// <reference path="rwcRunner.ts" />
/// <reference path="harness.ts" />
let runners: RunnerBase[] = [];
let iterations: number = 1;
@@ -32,13 +32,13 @@ function runTests(runners: RunnerBase[]) {
}
// users can define tests to run in mytest.config that will override cmd line args, otherwise use cmd line args (test.config), otherwise no options
let mytestconfig = 'mytest.config';
let testconfig = 'test.config';
let mytestconfig = "mytest.config";
let testconfig = "test.config";
let testConfigFile =
Harness.IO.fileExists(mytestconfig) ? Harness.IO.readFile(mytestconfig) :
(Harness.IO.fileExists(testconfig) ? Harness.IO.readFile(testconfig) : '');
(Harness.IO.fileExists(testconfig) ? Harness.IO.readFile(testconfig) : "");
if (testConfigFile !== '') {
if (testConfigFile !== "") {
let testConfig = JSON.parse(testConfigFile);
if (testConfig.light) {
Harness.lightMode = true;
@@ -51,33 +51,33 @@ if (testConfigFile !== '') {
}
switch (option) {
case 'compiler':
case "compiler":
runners.push(new CompilerBaselineRunner(CompilerTestType.Conformance));
runners.push(new CompilerBaselineRunner(CompilerTestType.Regressions));
runners.push(new ProjectRunner());
break;
case 'conformance':
case "conformance":
runners.push(new CompilerBaselineRunner(CompilerTestType.Conformance));
break;
case 'project':
case "project":
runners.push(new ProjectRunner());
break;
case 'fourslash':
case "fourslash":
runners.push(new FourSlashRunner(FourSlashTestType.Native));
break;
case 'fourslash-shims':
case "fourslash-shims":
runners.push(new FourSlashRunner(FourSlashTestType.Shims));
break;
case 'fourslash-server':
case "fourslash-server":
runners.push(new FourSlashRunner(FourSlashTestType.Server));
break;
case 'fourslash-generated':
case "fourslash-generated":
runners.push(new GeneratedFourslashRunner(FourSlashTestType.Native));
break;
case 'rwc':
case "rwc":
runners.push(new RWCRunner());
break;
case 'test262':
case "test262":
runners.push(new Test262BaselineRunner());
break;
}
@@ -102,6 +102,6 @@ if (runners.length === 0) {
// runners.push(new GeneratedFourslashRunner());
}
ts.sys.newLine = '\r\n';
ts.sys.newLine = "\r\n";
runTests(runners);
+3 -5
View File
@@ -1,6 +1,6 @@
/// <reference path="harness.ts" />
class RunnerBase {
abstract class RunnerBase {
constructor() { }
// contains the tests to run
@@ -18,9 +18,7 @@ class RunnerBase {
/** Setup the runner's tests so that they are ready to be executed by the harness
* The first test should be a describe/it block that sets up the harness's compiler instance appropriately
*/
public initializeTests(): void {
throw new Error('method not implemented');
}
public abstract initializeTests(): void;
/** Replaces instances of full paths with fileNames only */
static removeFullPaths(path: string) {
@@ -35,7 +33,7 @@ class RunnerBase {
// when running in the browser the 'full path' is the host name, shows up in error baselines
let localHost = /http:\/localhost:\d+/g;
fixedPath = fixedPath.replace(localHost, '');
fixedPath = fixedPath.replace(localHost, "");
return fixedPath;
}
}
+23 -22
View File
@@ -1,7 +1,7 @@
/// <reference path='harness.ts'/>
/// <reference path='runnerbase.ts' />
/// <reference path='loggedIO.ts' />
/// <reference path='..\compiler\commandLineParser.ts'/>
/// <reference path="harness.ts"/>
/// <reference path="runnerbase.ts" />
/// <reference path="loggedIO.ts" />
/// <reference path="..\compiler\commandLineParser.ts"/>
module RWC {
function runWithIOLog(ioLog: IOLog, fn: () => void) {
@@ -26,8 +26,8 @@ module RWC {
let compilerResult: Harness.Compiler.CompilerResult;
let compilerOptions: ts.CompilerOptions;
let baselineOpts: Harness.Baseline.BaselineOptions = {
Subfolder: 'rwc',
Baselinefolder: 'internal/baselines'
Subfolder: "rwc",
Baselinefolder: "internal/baselines"
};
let baseName = /(.*)\/(.*).json/.exec(ts.normalizeSlashes(jsonPath))[2];
let currentDirectory: string;
@@ -49,7 +49,7 @@ module RWC {
useCustomLibraryFile = undefined;
});
it('can compile', () => {
it("can compile", () => {
let harnessCompiler = Harness.Compiler.getCompiler();
let opts: ts.ParsedCommandLine;
@@ -74,10 +74,11 @@ module RWC {
});
// Add files to compilation
let isInInputList = (resolvedPath: string) => (inputFile: { unitName: string; content: string; }) => inputFile.unitName === resolvedPath;
for (let fileRead of ioLog.filesRead) {
// Check if the file is already added into the set of input files.
var resolvedPath = ts.normalizeSlashes(ts.sys.resolvePath(fileRead.path));
let inInputList = ts.forEach(inputFiles, inputFile => inputFile.unitName === resolvedPath);
const resolvedPath = ts.normalizeSlashes(ts.sys.resolvePath(fileRead.path));
let inInputList = ts.forEach(inputFiles, isInInputList(resolvedPath));
if (!Harness.isLibraryFile(fileRead.path)) {
if (inInputList) {
@@ -123,21 +124,21 @@ module RWC {
content = ts.sys.readFile(unitName);
}
catch (e) {
// Leave content undefined.
content = ts.sys.readFile(fileName);
}
return { unitName, content };
}
});
it('has the expected emitted code', () => {
Harness.Baseline.runBaseline('has the expected emitted code', baseName + '.output.js', () => {
it("has the expected emitted code", () => {
Harness.Baseline.runBaseline("has the expected emitted code", baseName + ".output.js", () => {
return Harness.Compiler.collateOutputs(compilerResult.files);
}, false, baselineOpts);
});
it('has the expected declaration file content', () => {
Harness.Baseline.runBaseline('has the expected declaration file content', baseName + '.d.ts', () => {
it("has the expected declaration file content", () => {
Harness.Baseline.runBaseline("has the expected declaration file content", baseName + ".d.ts", () => {
if (!compilerResult.declFilesCode.length) {
return null;
}
@@ -146,8 +147,8 @@ module RWC {
}, false, baselineOpts);
});
it('has the expected source maps', () => {
Harness.Baseline.runBaseline('has the expected source maps', baseName + '.map', () => {
it("has the expected source maps", () => {
Harness.Baseline.runBaseline("has the expected source maps", baseName + ".map", () => {
if (!compilerResult.sourceMaps.length) {
return null;
}
@@ -156,16 +157,16 @@ module RWC {
}, false, baselineOpts);
});
/*it('has correct source map record', () => {
/*it("has correct source map record", () => {
if (compilerOptions.sourceMap) {
Harness.Baseline.runBaseline('has correct source map record', baseName + '.sourcemap.txt', () => {
Harness.Baseline.runBaseline("has correct source map record", baseName + ".sourcemap.txt", () => {
return compilerResult.getSourceMapRecord();
}, false, baselineOpts);
}
});*/
it('has the expected errors', () => {
Harness.Baseline.runBaseline('has the expected errors', baseName + '.errors.txt', () => {
it("has the expected errors", () => {
Harness.Baseline.runBaseline("has the expected errors", baseName + ".errors.txt", () => {
if (compilerResult.errors.length === 0) {
return null;
}
@@ -176,9 +177,9 @@ module RWC {
// Ideally, a generated declaration file will have no errors. But we allow generated
// declaration file errors as part of the baseline.
it('has the expected errors in generated declaration files', () => {
it("has the expected errors in generated declaration files", () => {
if (compilerOptions.declaration && !compilerResult.errors.length) {
Harness.Baseline.runBaseline('has the expected errors in generated declaration files', baseName + '.dts.errors.txt', () => {
Harness.Baseline.runBaseline("has the expected errors in generated declaration files", baseName + ".dts.errors.txt", () => {
let declFileCompilationResult = Harness.Compiler.getCompiler().compileDeclarationFiles(inputFiles, otherFiles, compilerResult,
/*settingscallback*/ undefined, compilerOptions, currentDirectory);
if (declFileCompilationResult.declResult.errors.length === 0) {
+6 -6
View File
@@ -13,7 +13,7 @@
// limitations under the License.
//
///<reference path='harness.ts'/>
///<reference path="harness.ts"/>
module Harness.SourceMapRecoder {
@@ -50,11 +50,11 @@ module Harness.SourceMapRecoder {
return true;
}
if (sourceMapMappings.charAt(decodingIndex) == ',') {
if (sourceMapMappings.charAt(decodingIndex) == ",") {
return true;
}
if (sourceMapMappings.charAt(decodingIndex) == ';') {
if (sourceMapMappings.charAt(decodingIndex) == ";") {
return true;
}
@@ -117,7 +117,7 @@ module Harness.SourceMapRecoder {
}
while (decodingIndex < sourceMapMappings.length) {
if (sourceMapMappings.charAt(decodingIndex) == ';') {
if (sourceMapMappings.charAt(decodingIndex) == ";") {
// New line
decodeOfEncodedMapping.emittedLine++;
decodeOfEncodedMapping.emittedColumn = 1;
@@ -125,7 +125,7 @@ module Harness.SourceMapRecoder {
continue;
}
if (sourceMapMappings.charAt(decodingIndex) == ',') {
if (sourceMapMappings.charAt(decodingIndex) == ",") {
// Next entry is on same line - no action needed
decodingIndex++;
continue;
@@ -459,6 +459,6 @@ module Harness.SourceMapRecoder {
SourceMapSpanWriter.close(); // If the last spans werent emitted, emit them
}
sourceMapRecoder.Close();
return sourceMapRecoder.lines.join('\r\n');
return sourceMapRecoder.lines.join("\r\n");
}
}
+15 -15
View File
@@ -1,9 +1,9 @@
/// <reference path='harness.ts' />
/// <reference path='runnerbase.ts' />
/// <reference path="harness.ts" />
/// <reference path="runnerbase.ts" />
class Test262BaselineRunner extends RunnerBase {
private static basePath = 'internal/cases/test262';
private static helpersFilePath = 'tests/cases/test262-harness/helpers.d.ts';
private static basePath = "internal/cases/test262";
private static helpersFilePath = "tests/cases/test262-harness/helpers.d.ts";
private static helperFile = {
unitName: Test262BaselineRunner.helpersFilePath,
content: Harness.IO.readFile(Test262BaselineRunner.helpersFilePath)
@@ -15,8 +15,8 @@ class Test262BaselineRunner extends RunnerBase {
module: ts.ModuleKind.CommonJS
};
private static baselineOptions: Harness.Baseline.BaselineOptions = {
Subfolder: 'test262',
Baselinefolder: 'internal/baselines'
Subfolder: "test262",
Baselinefolder: "internal/baselines"
};
private static getTestFilePath(filename: string): string {
@@ -24,7 +24,7 @@ class Test262BaselineRunner extends RunnerBase {
}
private runTest(filePath: string) {
describe('test262 test for ' + filePath, () => {
describe("test262 test for " + filePath, () => {
// 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.
let testState: {
@@ -36,7 +36,7 @@ class Test262BaselineRunner extends RunnerBase {
before(() => {
let content = Harness.IO.readFile(filePath);
let testFilename = ts.removeFileExtension(filePath).replace(/\//g, '_') + ".test";
let testFilename = ts.removeFileExtension(filePath).replace(/\//g, "_") + ".test";
let testCaseContent = Harness.TestCaseParser.makeUnitsFromTest(content, testFilename);
let inputFiles = testCaseContent.testUnitData.map(unit => {
@@ -61,15 +61,15 @@ class Test262BaselineRunner extends RunnerBase {
testState = undefined;
});
it('has the expected emitted code', () => {
Harness.Baseline.runBaseline('has the expected emitted code', testState.filename + '.output.js', () => {
it("has the expected emitted code", () => {
Harness.Baseline.runBaseline("has the expected emitted code", testState.filename + ".output.js", () => {
let files = testState.compilerResult.files.filter(f => f.fileName !== Test262BaselineRunner.helpersFilePath);
return Harness.Compiler.collateOutputs(files);
}, false, Test262BaselineRunner.baselineOptions);
});
it('has the expected errors', () => {
Harness.Baseline.runBaseline('has the expected errors', testState.filename + '.errors.txt', () => {
it("has the expected errors", () => {
Harness.Baseline.runBaseline("has the expected errors", testState.filename + ".errors.txt", () => {
let errors = testState.compilerResult.errors;
if (errors.length === 0) {
return null;
@@ -79,13 +79,13 @@ class Test262BaselineRunner extends RunnerBase {
}, false, Test262BaselineRunner.baselineOptions);
});
it('satisfies inletiants', () => {
it("satisfies inletiants", () => {
let sourceFile = testState.program.getSourceFile(Test262BaselineRunner.getTestFilePath(testState.filename));
Utils.assertInvariants(sourceFile, /*parent:*/ undefined);
});
it('has the expected AST', () => {
Harness.Baseline.runBaseline('has the expected AST', testState.filename + '.AST.txt', () => {
it("has the expected AST", () => {
Harness.Baseline.runBaseline("has the expected AST", testState.filename + ".AST.txt", () => {
let sourceFile = testState.program.getSourceFile(Test262BaselineRunner.getTestFilePath(testState.filename));
return Utils.sourceFileToJSON(sourceFile);
}, false, Test262BaselineRunner.baselineOptions);
+3 -3
View File
@@ -971,14 +971,14 @@ interface JSON {
* @param replacer A function that transforms the results.
* @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
*/
stringify(value: any, replacer: (key: string, value: any) => any, space: any): string;
stringify(value: any, replacer: (key: string, value: any) => any, space: string | number): string;
/**
* Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
* @param value A JavaScript value, usually an object or array, to be converted.
* @param replacer Array that transforms the results.
* @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
*/
stringify(value: any, replacer: any[], space: any): string;
stringify(value: any, replacer: any[], space: string | number): string;
}
/**
* An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.
@@ -1181,4 +1181,4 @@ interface PromiseLike<T> {
*/
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>): PromiseLike<TResult>;
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => void): PromiseLike<TResult>;
}
}
+1 -1
View File
@@ -377,7 +377,7 @@ interface String {
* @param searchString search string
* @param position If position is undefined, 0 is assumed, so as to search all of the String.
*/
contains(searchString: string, position?: number): boolean;
includes(searchString: string, position?: number): boolean;
/**
* Returns true if the sequence of elements of searchString converted to a String is the
+28 -5
View File
@@ -202,9 +202,7 @@ namespace ts.server {
return {
isMemberCompletion: false,
isNewIdentifierLocation: false,
entries: response.body,
fileName: fileName,
position: position
entries: response.body
};
}
@@ -529,8 +527,33 @@ namespace ts.server {
});
}
getDocumentHighlights(fileName: string, position: number): DocumentHighlights[] {
throw new Error("Not Implemented Yet.");
getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[] {
let { line, offset } = this.positionToOneBasedLineOffset(fileName, position);
let args: protocol.DocumentHighlightsRequestArgs = { file: fileName, line, offset, filesToSearch };
let request = this.processRequest<protocol.DocumentHighlightsRequest>(CommandNames.DocumentHighlights, args);
let response = this.processResponse<protocol.DocumentHighlightsResponse>(request);
let self = this;
return response.body.map(convertToDocumentHighlights);
function convertToDocumentHighlights(item: ts.server.protocol.DocumentHighlightsItem): ts.DocumentHighlights {
let { file, highlightSpans } = item;
return {
fileName: file,
highlightSpans: highlightSpans.map(convertHighlightSpan)
};
function convertHighlightSpan(span: ts.server.protocol.HighlightSpan): ts.HighlightSpan {
let start = self.lineOffsetToPosition(file, span.start);
let end = self.lineOffsetToPosition(file, span.end);
return {
textSpan: ts.createTextSpanFromBounds(start, end),
kind: span.kind
};
}
}
}
getOutliningSpans(fileName: string): OutliningSpan[] {
+2 -4
View File
@@ -803,9 +803,6 @@ namespace ts.server {
} else {
this.log("no config file");
}
if (configFileName) {
configFileName = getAbsolutePath(configFileName, searchPath);
}
if (configFileName && (!this.configProjectIsActive(configFileName))) {
var configResult = this.openConfigFile(configFileName, fileName);
if (!configResult.success) {
@@ -910,7 +907,8 @@ namespace ts.server {
configFilename = ts.normalizePath(configFilename);
// file references will be relative to dirPath (or absolute)
var dirPath = ts.getDirectoryPath(configFilename);
var rawConfig: { config?: ProjectOptions; error?: Diagnostic; } = ts.readConfigFile(configFilename);
var contents = this.host.readFile(configFilename)
var rawConfig: { config?: ProjectOptions; error?: Diagnostic; } = ts.parseConfigFileText(configFilename, contents);
if (rawConfig.error) {
return rawConfig.error;
}
+40
View File
@@ -156,6 +156,17 @@ declare namespace ts.server.protocol {
arguments: FileLocationRequestArgs;
}
/**
* Arguments in document highlight request; include: filesToSearch, file,
* line, offset.
*/
export interface DocumentHighlightsRequestArgs extends FileLocationRequestArgs {
/**
* List of files to search for document highlights.
*/
filesToSearch: string[];
}
/**
* Go to definition request; value of command field is
* "definition". Return response giving the file locations that
@@ -238,6 +249,35 @@ declare namespace ts.server.protocol {
body?: OccurrencesResponseItem[];
}
/**
* Get document highlights request; value of command field is
* "documentHighlights". Return response giving spans that are relevant
* in the file at a given line and column.
*/
export interface DocumentHighlightsRequest extends FileLocationRequest {
arguments: DocumentHighlightsRequestArgs
}
export interface HighlightSpan extends TextSpan {
kind: string
}
export interface DocumentHighlightsItem {
/**
* File containing highlight spans.
*/
file: string,
/**
* Spans to highlight in file.
*/
highlightSpans: HighlightSpan[];
}
export interface DocumentHighlightsResponse extends Response {
body?: DocumentHighlightsItem[];
}
/**
* Find references request; value of command field is
* "references". Return response giving the file locations that
+86 -45
View File
@@ -89,6 +89,7 @@ namespace ts.server {
export const NavBar = "navbar";
export const Navto = "navto";
export const Occurrences = "occurrences";
export const DocumentHighlights = "documentHighlights";
export const Open = "open";
export const Quickinfo = "quickinfo";
export const References = "references";
@@ -109,13 +110,13 @@ namespace ts.server {
}
export class Session {
projectService: ProjectService;
pendingOperation = false;
fileHash: ts.Map<number> = {};
nextFileId = 1;
errorTimer: any; /*NodeJS.Timer | number*/
immediateId: any;
changeSeq = 0;
protected projectService: ProjectService;
private pendingOperation = false;
private fileHash: ts.Map<number> = {};
private nextFileId = 1;
private errorTimer: any; /*NodeJS.Timer | number*/
private immediateId: any;
private changeSeq = 0;
constructor(
private host: ServerHost,
@@ -129,7 +130,7 @@ namespace ts.server {
});
}
handleEvent(eventName: string, project: Project, fileName: string) {
private handleEvent(eventName: string, project: Project, fileName: string) {
if (eventName == "context") {
this.projectService.log("got context event, updating diagnostics for" + fileName, "Info");
this.updateErrorCheck([{ fileName, project }], this.changeSeq,
@@ -137,7 +138,7 @@ namespace ts.server {
}
}
logError(err: Error, cmd: string) {
public logError(err: Error, cmd: string) {
var typedErr = <StackTraceError>err;
var msg = "Exception on executing command " + cmd;
if (typedErr.message) {
@@ -149,11 +150,11 @@ namespace ts.server {
this.projectService.log(msg);
}
sendLineToClient(line: string) {
private sendLineToClient(line: string) {
this.host.write(line + this.host.newLine);
}
send(msg: protocol.Message) {
public send(msg: protocol.Message) {
var json = JSON.stringify(msg);
if (this.logger.isVerbose()) {
this.logger.info(msg.type + ": " + json);
@@ -162,7 +163,7 @@ namespace ts.server {
'\r\n\r\n' + json);
}
event(info: any, eventName: string) {
public event(info: any, eventName: string) {
var ev: protocol.Event = {
seq: 0,
type: "event",
@@ -172,7 +173,7 @@ namespace ts.server {
this.send(ev);
}
response(info: any, cmdName: string, reqSeq = 0, errorMsg?: string) {
private response(info: any, cmdName: string, reqSeq = 0, errorMsg?: string) {
var res: protocol.Response = {
seq: 0,
type: "response",
@@ -189,11 +190,11 @@ namespace ts.server {
this.send(res);
}
output(body: any, commandName: string, requestSequence = 0, errorMessage?: string) {
public output(body: any, commandName: string, requestSequence = 0, errorMessage?: string) {
this.response(body, commandName, requestSequence, errorMessage);
}
semanticCheck(file: string, project: Project) {
private semanticCheck(file: string, project: Project) {
try {
var diags = project.compilerService.languageService.getSemanticDiagnostics(file);
@@ -207,7 +208,7 @@ namespace ts.server {
}
}
syntacticCheck(file: string, project: Project) {
private syntacticCheck(file: string, project: Project) {
try {
var diags = project.compilerService.languageService.getSyntacticDiagnostics(file);
if (diags) {
@@ -220,12 +221,12 @@ namespace ts.server {
}
}
errorCheck(file: string, project: Project) {
private errorCheck(file: string, project: Project) {
this.syntacticCheck(file, project);
this.semanticCheck(file, project);
}
updateProjectStructure(seq: number, matchSeq: (seq: number) => boolean, ms = 1500) {
private updateProjectStructure(seq: number, matchSeq: (seq: number) => boolean, ms = 1500) {
setTimeout(() => {
if (matchSeq(seq)) {
this.projectService.updateProjectStructure();
@@ -233,7 +234,7 @@ namespace ts.server {
}, ms);
}
updateErrorCheck(checkList: PendingErrorCheck[], seq: number,
private updateErrorCheck(checkList: PendingErrorCheck[], seq: number,
matchSeq: (seq: number) => boolean, ms = 1500, followMs = 200) {
if (followMs > ms) {
followMs = ms;
@@ -269,7 +270,7 @@ namespace ts.server {
}
}
getDefinition(line: number, offset: number, fileName: string): protocol.FileSpan[] {
private getDefinition(line: number, offset: number, fileName: string): protocol.FileSpan[] {
var file = ts.normalizePath(fileName);
var project = this.projectService.getProjectForFile(file);
if (!project) {
@@ -291,7 +292,7 @@ namespace ts.server {
}));
}
getTypeDefinition(line: number, offset: number, fileName: string): protocol.FileSpan[] {
private getTypeDefinition(line: number, offset: number, fileName: string): protocol.FileSpan[] {
var file = ts.normalizePath(fileName);
var project = this.projectService.getProjectForFile(file);
if (!project) {
@@ -313,7 +314,7 @@ namespace ts.server {
}));
}
getOccurrences(line: number, offset: number, fileName: string): protocol.OccurrencesResponseItem[]{
private getOccurrences(line: number, offset: number, fileName: string): protocol.OccurrencesResponseItem[] {
fileName = ts.normalizePath(fileName);
let project = this.projectService.getProjectForFile(fileName);
@@ -343,7 +344,43 @@ namespace ts.server {
});
}
getProjectInfo(fileName: string, needFileNameList: boolean): protocol.ProjectInfo {
private getDocumentHighlights(line: number, offset: number, fileName: string, filesToSearch: string[]): protocol.DocumentHighlightsItem[] {
fileName = ts.normalizePath(fileName);
let project = this.projectService.getProjectForFile(fileName);
if (!project) {
throw Errors.NoProject;
}
let { compilerService } = project;
let position = compilerService.host.lineOffsetToPosition(fileName, line, offset);
let documentHighlights = compilerService.languageService.getDocumentHighlights(fileName, position, filesToSearch);
if (!documentHighlights) {
return undefined;
}
return documentHighlights.map(convertToDocumentHighlightsItem);
function convertToDocumentHighlightsItem(documentHighlights: ts.DocumentHighlights): ts.server.protocol.DocumentHighlightsItem {
let { fileName, highlightSpans } = documentHighlights;
return {
file: fileName,
highlightSpans: highlightSpans.map(convertHighlightSpan)
};
function convertHighlightSpan(highlightSpan: ts.HighlightSpan): ts.server.protocol.HighlightSpan {
let { textSpan, kind } = highlightSpan;
let start = compilerService.host.positionToLineOffset(fileName, textSpan.start);
let end = compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(textSpan));
return { start, end, kind };
}
}
}
private getProjectInfo(fileName: string, needFileNameList: boolean): protocol.ProjectInfo {
fileName = ts.normalizePath(fileName)
let project = this.projectService.getProjectForFile(fileName)
@@ -358,7 +395,7 @@ namespace ts.server {
return projectInfo;
}
getRenameLocations(line: number, offset: number, fileName: string,findInComments: boolean, findInStrings: boolean): protocol.RenameResponseBody {
private getRenameLocations(line: number, offset: number, fileName: string,findInComments: boolean, findInStrings: boolean): protocol.RenameResponseBody {
var file = ts.normalizePath(fileName);
var project = this.projectService.getProjectForFile(file);
if (!project) {
@@ -426,7 +463,7 @@ namespace ts.server {
return { info: renameInfo, locs: bakedRenameLocs };
}
getReferences(line: number, offset: number, fileName: string): protocol.ReferencesResponseBody {
private getReferences(line: number, offset: number, fileName: string): protocol.ReferencesResponseBody {
// TODO: get all projects for this file; report refs for all projects deleting duplicates
// can avoid duplicates by eliminating same ref file from subsequent projects
var file = ts.normalizePath(fileName);
@@ -473,12 +510,12 @@ namespace ts.server {
};
}
openClientFile(fileName: string) {
private openClientFile(fileName: string) {
var file = ts.normalizePath(fileName);
this.projectService.openClientFile(file);
}
getQuickInfo(line: number, offset: number, fileName: string): protocol.QuickInfoResponseBody {
private getQuickInfo(line: number, offset: number, fileName: string): protocol.QuickInfoResponseBody {
var file = ts.normalizePath(fileName);
var project = this.projectService.getProjectForFile(file);
if (!project) {
@@ -504,7 +541,7 @@ namespace ts.server {
};
}
getFormattingEditsForRange(line: number, offset: number, endLine: number, endOffset: number, fileName: string): protocol.CodeEdit[] {
private getFormattingEditsForRange(line: number, offset: number, endLine: number, endOffset: number, fileName: string): protocol.CodeEdit[] {
var file = ts.normalizePath(fileName);
var project = this.projectService.getProjectForFile(file);
if (!project) {
@@ -531,7 +568,7 @@ namespace ts.server {
});
}
getFormattingEditsAfterKeystroke(line: number, offset: number, key: string, fileName: string): protocol.CodeEdit[] {
private getFormattingEditsAfterKeystroke(line: number, offset: number, key: string, fileName: string): protocol.CodeEdit[] {
var file = ts.normalizePath(fileName);
var project = this.projectService.getProjectForFile(file);
@@ -607,7 +644,7 @@ namespace ts.server {
});
}
getCompletions(line: number, offset: number, prefix: string, fileName: string): protocol.CompletionEntry[] {
private getCompletions(line: number, offset: number, prefix: string, fileName: string): protocol.CompletionEntry[] {
if (!prefix) {
prefix = "";
}
@@ -633,7 +670,7 @@ namespace ts.server {
}, []).sort((a, b) => a.name.localeCompare(b.name));
}
getCompletionEntryDetails(line: number, offset: number,
private getCompletionEntryDetails(line: number, offset: number,
entryNames: string[], fileName: string): protocol.CompletionEntryDetails[] {
var file = ts.normalizePath(fileName);
var project = this.projectService.getProjectForFile(file);
@@ -653,7 +690,7 @@ namespace ts.server {
}, []);
}
getSignatureHelpItems(line: number, offset: number, fileName: string): protocol.SignatureHelpItems {
private getSignatureHelpItems(line: number, offset: number, fileName: string): protocol.SignatureHelpItems {
var file = ts.normalizePath(fileName);
var project = this.projectService.getProjectForFile(file);
if (!project) {
@@ -682,7 +719,7 @@ namespace ts.server {
return result;
}
getDiagnostics(delay: number, fileNames: string[]) {
private getDiagnostics(delay: number, fileNames: string[]) {
var checkList = fileNames.reduce((accum: PendingErrorCheck[], fileName: string) => {
fileName = ts.normalizePath(fileName);
var project = this.projectService.getProjectForFile(fileName);
@@ -697,7 +734,7 @@ namespace ts.server {
}
}
change(line: number, offset: number, endLine: number, endOffset: number, insertString: string, fileName: string) {
private change(line: number, offset: number, endLine: number, endOffset: number, insertString: string, fileName: string) {
var file = ts.normalizePath(fileName);
var project = this.projectService.getProjectForFile(file);
if (project) {
@@ -712,7 +749,7 @@ namespace ts.server {
}
}
reload(fileName: string, tempFileName: string, reqSeq = 0) {
private reload(fileName: string, tempFileName: string, reqSeq = 0) {
var file = ts.normalizePath(fileName);
var tmpfile = ts.normalizePath(tempFileName);
var project = this.projectService.getProjectForFile(file);
@@ -725,7 +762,7 @@ namespace ts.server {
}
}
saveToTmp(fileName: string, tempFileName: string) {
private saveToTmp(fileName: string, tempFileName: string) {
var file = ts.normalizePath(fileName);
var tmpfile = ts.normalizePath(tempFileName);
@@ -735,12 +772,12 @@ namespace ts.server {
}
}
closeClientFile(fileName: string) {
private closeClientFile(fileName: string) {
var file = ts.normalizePath(fileName);
this.projectService.closeClientFile(file);
}
decorateNavigationBarItem(project: Project, fileName: string, items: ts.NavigationBarItem[]): protocol.NavigationBarItem[] {
private decorateNavigationBarItem(project: Project, fileName: string, items: ts.NavigationBarItem[]): protocol.NavigationBarItem[] {
if (!items) {
return undefined;
}
@@ -759,7 +796,7 @@ namespace ts.server {
}));
}
getNavigationBarItems(fileName: string): protocol.NavigationBarItem[] {
private getNavigationBarItems(fileName: string): protocol.NavigationBarItem[] {
var file = ts.normalizePath(fileName);
var project = this.projectService.getProjectForFile(file);
if (!project) {
@@ -775,7 +812,7 @@ namespace ts.server {
return this.decorateNavigationBarItem(project, fileName, items);
}
getNavigateToItems(searchValue: string, fileName: string, maxResultCount?: number): protocol.NavtoItem[] {
private getNavigateToItems(searchValue: string, fileName: string, maxResultCount?: number): protocol.NavtoItem[] {
var file = ts.normalizePath(fileName);
var project = this.projectService.getProjectForFile(file);
if (!project) {
@@ -814,7 +851,7 @@ namespace ts.server {
});
}
getBraceMatching(line: number, offset: number, fileName: string): protocol.TextSpan[] {
private getBraceMatching(line: number, offset: number, fileName: string): protocol.TextSpan[] {
var file = ts.normalizePath(fileName);
var project = this.projectService.getProjectForFile(file);
@@ -836,7 +873,7 @@ namespace ts.server {
}));
}
exit() {
public exit() {
}
private handlers : Map<(request: protocol.Request) => {response?: any, responseRequired?: boolean}> = {
@@ -937,19 +974,23 @@ namespace ts.server {
var { line, offset, file: fileName } = <protocol.FileLocationRequestArgs>request.arguments;
return {response: this.getOccurrences(line, offset, fileName), responseRequired: true};
},
[CommandNames.DocumentHighlights]: (request: protocol.Request) => {
var { line, offset, file: fileName, filesToSearch } = <protocol.DocumentHighlightsRequestArgs>request.arguments;
return {response: this.getDocumentHighlights(line, offset, fileName, filesToSearch), responseRequired: true};
},
[CommandNames.ProjectInfo]: (request: protocol.Request) => {
var { file, needFileNameList } = <protocol.ProjectInfoRequestArgs>request.arguments;
return {response: this.getProjectInfo(file, needFileNameList), responseRequired: true};
},
};
addProtocolHandler(command: string, handler: (request: protocol.Request) => {response?: any, responseRequired: boolean}) {
public addProtocolHandler(command: string, handler: (request: protocol.Request) => {response?: any, responseRequired: boolean}) {
if (this.handlers[command]) {
throw new Error(`Protocol handler already exists for command "${command}"`);
}
this.handlers[command] = handler;
}
executeCommand(request: protocol.Request) : {response?: any, responseRequired?: boolean} {
public executeCommand(request: protocol.Request) : {response?: any, responseRequired?: boolean} {
var handler = this.handlers[request.command];
if (handler) {
return handler(request);
@@ -960,7 +1001,7 @@ namespace ts.server {
}
}
onMessage(message: string) {
public onMessage(message: string) {
if (this.logger.isVerbose()) {
this.logger.info("request: " + message);
var start = this.hrtime();
+1
View File
@@ -418,6 +418,7 @@ namespace ts.formatting {
case SyntaxKind.DefaultClause:
case SyntaxKind.CaseClause:
case SyntaxKind.ParenthesizedExpression:
case SyntaxKind.PropertyAccessExpression:
case SyntaxKind.CallExpression:
case SyntaxKind.NewExpression:
case SyntaxKind.VariableStatement:
+102 -37
View File
@@ -48,6 +48,7 @@ namespace ts {
getConstructSignatures(): Signature[];
getStringIndexType(): Type;
getNumberIndexType(): Type;
getBaseTypes(): ObjectType[]
}
export interface Signature {
@@ -260,26 +261,25 @@ namespace ts {
}
public getFirstToken(sourceFile?: SourceFile): Node {
let children = this.getChildren();
for (let child of children) {
if (child.kind < SyntaxKind.FirstNode) {
return child;
}
return child.getFirstToken(sourceFile);
let children = this.getChildren(sourceFile);
if (!children.length) {
return undefined;
}
let child = children[0];
return child.kind < SyntaxKind.FirstNode ? child : child.getFirstToken(sourceFile);
}
public getLastToken(sourceFile?: SourceFile): Node {
let children = this.getChildren(sourceFile);
for (let i = children.length - 1; i >= 0; i--) {
let child = children[i];
if (child.kind < SyntaxKind.FirstNode) {
return child;
}
return child.getLastToken(sourceFile);
let child = lastOrUndefined(children);
if (!child) {
return undefined;
}
return child.kind < SyntaxKind.FirstNode ? child : child.getLastToken(sourceFile);
}
}
@@ -682,6 +682,11 @@ namespace ts {
getNumberIndexType(): Type {
return this.checker.getIndexTypeOfType(this, IndexKind.Number);
}
getBaseTypes(): ObjectType[] {
return this.flags & (TypeFlags.Class | TypeFlags.Interface)
? this.checker.getBaseTypes(<TypeObject & InterfaceType>this)
: undefined;
}
}
class SignatureObject implements Signature {
@@ -1105,6 +1110,7 @@ namespace ts {
}
export interface HighlightSpan {
fileName?: string;
textSpan: TextSpan;
kind: string;
}
@@ -1411,7 +1417,9 @@ namespace ts {
* @param fileName The name of the file to be released
* @param compilationSettings The compilation settings used to acquire the file
*/
releaseDocument(fileName: string, compilationSettings: CompilerOptions): void
releaseDocument(fileName: string, compilationSettings: CompilerOptions): void;
reportStats(): string;
}
// TODO: move these to enums
@@ -1751,18 +1759,31 @@ namespace ts {
sourceFile.version = version;
sourceFile.scriptSnapshot = scriptSnapshot;
}
export interface TranspileOptions {
compilerOptions?: CompilerOptions;
fileName?: string;
reportDiagnostics?: boolean;
moduleName?: string;
}
export interface TranspileOutput {
outputText: string;
diagnostics?: Diagnostic[];
sourceMapText?: string;
}
/*
* This function will compile source text from 'input' argument using specified compiler options.
* If not options are provided - it will use a set of default compiler options.
* Extra compiler options that will unconditionally be used bu this function are:
* Extra compiler options that will unconditionally be used by this function are:
* - isolatedModules = true
* - allowNonTsExtensions = true
* - noLib = true
* - noResolve = true
*/
export function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string {
let options = compilerOptions ? clone(compilerOptions) : getDefaultCompilerOptions();
*/
export function transpileModule(input: string, transpileOptions?: TranspileOptions): TranspileOutput {
let options = transpileOptions.compilerOptions ? clone(transpileOptions.compilerOptions) : getDefaultCompilerOptions();
options.isolatedModules = true;
@@ -1778,23 +1799,30 @@ namespace ts {
options.noResolve = true;
// Parse
let inputFileName = fileName || "module.ts";
let inputFileName = transpileOptions.fileName || "module.ts";
let sourceFile = createSourceFile(inputFileName, input, options.target);
if (moduleName) {
sourceFile.moduleName = moduleName;
if (transpileOptions.moduleName) {
sourceFile.moduleName = transpileOptions.moduleName;
}
let newLine = getNewLineCharacter(options);
// Output
let outputText: string;
let sourceMapText: string;
// Create a compilerHost object to allow the compiler to read and write files
let compilerHost: CompilerHost = {
getSourceFile: (fileName, target) => fileName === inputFileName ? sourceFile : undefined,
writeFile: (name, text, writeByteOrderMark) => {
Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: " + name);
outputText = text;
if (fileExtensionIs(name, ".map")) {
Debug.assert(sourceMapText === undefined, `Unexpected multiple source map outputs for the file '${name}'`);
sourceMapText = text;
}
else {
Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: " + name);
outputText = text;
}
},
getDefaultLibFileName: () => "lib.d.ts",
useCaseSensitiveFileNames: () => false,
@@ -1804,16 +1832,29 @@ namespace ts {
};
let program = createProgram([inputFileName], options, compilerHost);
addRange(/*to*/ diagnostics, /*from*/ program.getSyntacticDiagnostics(sourceFile));
addRange(/*to*/ diagnostics, /*from*/ program.getOptionsDiagnostics());
let diagnostics: Diagnostic[];
if (transpileOptions.reportDiagnostics) {
diagnostics = [];
addRange(/*to*/ diagnostics, /*from*/ program.getSyntacticDiagnostics(sourceFile));
addRange(/*to*/ diagnostics, /*from*/ program.getOptionsDiagnostics());
}
// Emit
program.emit();
Debug.assert(outputText !== undefined, "Output generation failed");
return outputText;
return { outputText, diagnostics, sourceMapText };
}
/*
* This is a shortcut function for transpileModule - it accepts transpileOptions as parameters and returns only outputText part of the result.
*/
export function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string {
let output = transpileModule(input, { compilerOptions, fileName, reportDiagnostics: !!diagnostics, moduleName });
// addRange correctly handles cases when wither 'from' or 'to' argument is missing
addRange(diagnostics, output.diagnostics);
return output.outputText;
}
export function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean): SourceFile {
@@ -3234,8 +3275,19 @@ namespace ts {
// We are *only* completing on properties from the type being destructured.
isNewIdentifierLocation = false;
typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer);
existingMembers = (<BindingPattern>objectLikeContainer).elements;
let rootDeclaration = getRootDeclaration(objectLikeContainer.parent);
if (isVariableLike(rootDeclaration)) {
// We don't want to complete using the type acquired by the shape
// of the binding pattern; we are only interested in types acquired
// through type declaration or inference.
if (rootDeclaration.initializer || rootDeclaration.type) {
typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer);
existingMembers = (<BindingPattern>objectLikeContainer).elements;
}
}
else {
Debug.fail("Root declaration is not variable-like.")
}
}
else {
Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind);
@@ -3340,23 +3392,36 @@ namespace ts {
case SyntaxKind.LessThanSlashToken:
case SyntaxKind.SlashToken:
case SyntaxKind.Identifier:
if(parent && (parent.kind === SyntaxKind.JsxSelfClosingElement || parent.kind === SyntaxKind.JsxOpeningElement)) {
case SyntaxKind.JsxAttribute:
case SyntaxKind.JsxSpreadAttribute:
if (parent && (parent.kind === SyntaxKind.JsxSelfClosingElement || parent.kind === SyntaxKind.JsxOpeningElement)) {
return <JsxOpeningLikeElement>parent;
}
break;
// The context token is the closing } or " of an attribute, which means
// its parent is a JsxExpression, whose parent is a JsxAttribute,
// whose parent is a JsxOpeningLikeElement
case SyntaxKind.StringLiteral:
if (parent && ((parent.kind === SyntaxKind.JsxAttribute) || (parent.kind === SyntaxKind.JsxSpreadAttribute))) {
return <JsxOpeningLikeElement>parent.parent;
}
break;
case SyntaxKind.CloseBraceToken:
// The context token is the closing } of an attribute, which means
// its parent is a JsxExpression, whose parent is a JsxAttribute,
// whose parent is a JsxOpeningLikeElement
if(parent &&
if (parent &&
parent.kind === SyntaxKind.JsxExpression &&
parent.parent &&
parent.parent.kind === SyntaxKind.JsxAttribute) {
(parent.parent.kind === SyntaxKind.JsxAttribute)) {
return <JsxOpeningLikeElement>parent.parent.parent;
}
if (parent && parent.kind === SyntaxKind.JsxSpreadAttribute) {
return <JsxOpeningLikeElement>parent.parent;
}
break;
}
}
+2 -2
View File
@@ -454,11 +454,11 @@ namespace ts {
}
}
export function realizeDiagnostics(diagnostics: Diagnostic[], newLine: string): { message: string; start: number; length: number; category: string; } []{
export function realizeDiagnostics(diagnostics: Diagnostic[], newLine: string): { message: string; start: number; length: number; category: string; code: number; } []{
return diagnostics.map(d => realizeDiagnostic(d, newLine));
}
function realizeDiagnostic(diagnostic: Diagnostic, newLine: string): { message: string; start: number; length: number; category: string; } {
function realizeDiagnostic(diagnostic: Diagnostic, newLine: string): { message: string; start: number; length: number; category: string; code: number; } {
return {
message: flattenDiagnosticMessageText(diagnostic.messageText, newLine),
start: diagnostic.start,
+1 -3
View File
@@ -611,13 +611,11 @@ namespace ts.SignatureHelp {
let displayParts = mapToDisplayParts(writer =>
typeChecker.getSymbolDisplayBuilder().buildParameterDisplay(parameter, writer, invocation));
let isOptional = hasQuestionToken(parameter.valueDeclaration);
return {
name: parameter.name,
documentation: parameter.getDocumentationComment(),
displayParts,
isOptional
isOptional: typeChecker.isOptionalParameter(<ParameterDeclaration>parameter.valueDeclaration)
};
}
+11 -11
View File
@@ -75,28 +75,28 @@ function delint(sourceFile) {
delintNode(sourceFile);
function delintNode(node) {
switch (node.kind) {
case 196 /* ForStatement */:
case 197 /* ForInStatement */:
case 195 /* WhileStatement */:
case 194 /* DoStatement */:
if (node.statement.kind !== 189 /* Block */) {
case 197 /* ForStatement */:
case 198 /* ForInStatement */:
case 196 /* WhileStatement */:
case 195 /* DoStatement */:
if (node.statement.kind !== 190 /* Block */) {
report(node, "A looping statement's contents should be wrapped in a block body.");
}
break;
case 193 /* IfStatement */:
case 194 /* IfStatement */:
var ifStatement = node;
if (ifStatement.thenStatement.kind !== 189 /* Block */) {
if (ifStatement.thenStatement.kind !== 190 /* Block */) {
report(ifStatement.thenStatement, "An if statement's contents should be wrapped in a block body.");
}
if (ifStatement.elseStatement &&
ifStatement.elseStatement.kind !== 189 /* Block */ &&
ifStatement.elseStatement.kind !== 193 /* IfStatement */) {
ifStatement.elseStatement.kind !== 190 /* Block */ &&
ifStatement.elseStatement.kind !== 194 /* IfStatement */) {
report(ifStatement.elseStatement, "An else statement's contents should be wrapped in a block body.");
}
break;
case 178 /* BinaryExpression */:
case 179 /* BinaryExpression */:
var op = node.operatorToken.kind;
if (op === 29 /* EqualsEqualsToken */ || op == 30 /* ExclamationEqualsToken */) {
if (op === 30 /* EqualsEqualsToken */ || op == 31 /* ExclamationEqualsToken */) {
report(node, "Use '===' and '!=='.");
}
break;
@@ -1,4 +1,4 @@
tests/cases/conformance/statements/for-ofStatements/ES5For-of30.ts(3,6): error TS2461: Type 'string | number' is not an array type.
tests/cases/conformance/statements/for-ofStatements/ES5For-of30.ts(3,6): error TS2461: Type 'number | string' is not an array type.
tests/cases/conformance/statements/for-ofStatements/ES5For-of30.ts(3,7): error TS2322: Type 'number' is not assignable to type 'string'.
tests/cases/conformance/statements/for-ofStatements/ES5For-of30.ts(3,14): error TS2322: Type 'string' is not assignable to type 'number'.
@@ -8,7 +8,7 @@ tests/cases/conformance/statements/for-ofStatements/ES5For-of30.ts(3,14): error
var tuple: [number, string] = [2, "3"];
for ([a = 1, b = ""] of tuple) {
~~~~~~~~~~~~~~~
!!! error TS2461: Type 'string | number' is not an array type.
!!! error TS2461: Type 'number | string' is not an array type.
~
!!! error TS2322: Type 'number' is not assignable to type 'string'.
~
@@ -1,4 +1,4 @@
tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck11.ts(3,6): error TS2322: Type 'string | number' is not assignable to type 'string'.
tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck11.ts(3,6): error TS2322: Type 'number | string' is not assignable to type 'string'.
Type 'number' is not assignable to type 'string'.
@@ -7,5 +7,5 @@ tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck11.ts(3,6)
var v: string;
for (v of union) { }
~
!!! error TS2322: Type 'string | number' is not assignable to type 'string'.
!!! error TS2322: Type 'number | string' is not assignable to type 'string'.
!!! error TS2322: Type 'number' is not assignable to type 'string'.
@@ -3,6 +3,6 @@ var union: string | number[];
>union : string | number[]
for (var v of union) { }
>v : string | number
>v : number | string
>union : string | number[]
@@ -1,8 +1,8 @@
tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck9.ts(2,15): error TS2461: Type 'number | symbol | string[]' is not an array type.
tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck9.ts(2,15): error TS2461: Type 'string[] | number | symbol' is not an array type.
==== tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck9.ts (1 errors) ====
var union: string | string[] | number | symbol;
for (let v of union) { }
~~~~~
!!! error TS2461: Type 'number | symbol | string[]' is not an array type.
!!! error TS2461: Type 'string[] | number | symbol' is not an array type.
@@ -6,14 +6,14 @@ enum Color { R, G, B }
>B : Color
function f1(x: Color | string) {
>f1 : (x: string | Color) => void
>x : string | Color
>f1 : (x: Color | string) => void
>x : Color | string
>Color : Color
if (typeof x === "number") {
>typeof x === "number" : boolean
>typeof x : string
>x : string | Color
>x : Color | string
>"number" : string
var y = x;
@@ -35,14 +35,14 @@ function f1(x: Color | string) {
}
function f2(x: Color | string | string[]) {
>f2 : (x: string | Color | string[]) => void
>x : string | Color | string[]
>f2 : (x: Color | string | string[]) => void
>x : Color | string | string[]
>Color : Color
if (typeof x === "object") {
>typeof x === "object" : boolean
>typeof x : string
>x : string | Color | string[]
>x : Color | string | string[]
>"object" : string
var y = x;
@@ -55,7 +55,7 @@ function f2(x: Color | string | string[]) {
if (typeof x === "number") {
>typeof x === "number" : boolean
>typeof x : string
>x : string | Color | string[]
>x : Color | string | string[]
>"number" : string
var z = x;
@@ -77,7 +77,7 @@ function f2(x: Color | string | string[]) {
if (typeof x === "string") {
>typeof x === "string" : boolean
>typeof x : string
>x : string | Color | string[]
>x : Color | string | string[]
>"string" : string
var a = x;
@@ -34,7 +34,7 @@ var d2: IHasVisualizationModel = i || moduleA;
var d2: IHasVisualizationModel = moduleA || i;
>d2 : IHasVisualizationModel
>IHasVisualizationModel : IHasVisualizationModel
>moduleA || i : IHasVisualizationModel
>moduleA || i : typeof moduleA
>moduleA : typeof moduleA
>i : IHasVisualizationModel
@@ -0,0 +1,22 @@
tests/cases/compiler/aliasesInSystemModule1.ts(2,24): error TS2307: Cannot find module 'foo'.
==== tests/cases/compiler/aliasesInSystemModule1.ts (1 errors) ====
import alias = require('foo');
~~~~~
!!! error TS2307: Cannot find module 'foo'.
import cls = alias.Class;
export import cls2 = alias.Class;
let x = new alias.Class();
let y = new cls();
let z = new cls2();
module M {
export import cls = alias.Class;
let x = new alias.Class();
let y = new cls();
let z = new cls2();
}
@@ -0,0 +1,42 @@
//// [aliasesInSystemModule1.ts]
import alias = require('foo');
import cls = alias.Class;
export import cls2 = alias.Class;
let x = new alias.Class();
let y = new cls();
let z = new cls2();
module M {
export import cls = alias.Class;
let x = new alias.Class();
let y = new cls();
let z = new cls2();
}
//// [aliasesInSystemModule1.js]
System.register(['foo'], function(exports_1) {
var alias;
var cls, cls2, x, y, z, M;
return {
setters:[
function (_alias) {
alias = _alias;
}],
execute: function() {
cls = alias.Class;
exports_1("cls2", cls2 = alias.Class);
x = new alias.Class();
y = new cls();
z = new cls2();
(function (M) {
M.cls = alias.Class;
var x = new alias.Class();
var y = new M.cls();
var z = new cls2();
})(M || (M = {}));
}
}
});
@@ -0,0 +1,21 @@
tests/cases/compiler/aliasesInSystemModule2.ts(2,21): error TS2307: Cannot find module 'foo'.
==== tests/cases/compiler/aliasesInSystemModule2.ts (1 errors) ====
import {alias} from "foo";
~~~~~
!!! error TS2307: Cannot find module 'foo'.
import cls = alias.Class;
export import cls2 = alias.Class;
let x = new alias.Class();
let y = new cls();
let z = new cls2();
module M {
export import cls = alias.Class;
let x = new alias.Class();
let y = new cls();
let z = new cls2();
}
@@ -0,0 +1,41 @@
//// [aliasesInSystemModule2.ts]
import {alias} from "foo";
import cls = alias.Class;
export import cls2 = alias.Class;
let x = new alias.Class();
let y = new cls();
let z = new cls2();
module M {
export import cls = alias.Class;
let x = new alias.Class();
let y = new cls();
let z = new cls2();
}
//// [aliasesInSystemModule2.js]
System.register(["foo"], function(exports_1) {
var foo_1;
var cls, cls2, x, y, z, M;
return {
setters:[
function (_foo_1) {
foo_1 = _foo_1;
}],
execute: function() {
cls = foo_1.alias.Class;
exports_1("cls2", cls2 = foo_1.alias.Class);
x = new foo_1.alias.Class();
y = new cls();
z = new cls2();
(function (M) {
M.cls = foo_1.alias.Class;
var x = new foo_1.alias.Class();
var y = new M.cls();
var z = new cls2();
})(M || (M = {}));
}
}
});
@@ -1,6 +1,7 @@
tests/cases/conformance/types/typeRelationships/apparentType/apparentTypeSupertype.ts(9,7): error TS2415: Class 'Derived<U>' incorrectly extends base class 'Base'.
Types of property 'x' are incompatible.
Type 'U' is not assignable to type 'string'.
Type 'String' is not assignable to type 'string'.
==== tests/cases/conformance/types/typeRelationships/apparentType/apparentTypeSupertype.ts (1 errors) ====
@@ -17,5 +18,6 @@ tests/cases/conformance/types/typeRelationships/apparentType/apparentTypeSuperty
!!! error TS2415: Class 'Derived<U>' incorrectly extends base class 'Base'.
!!! error TS2415: Types of property 'x' are incompatible.
!!! error TS2415: Type 'U' is not assignable to type 'string'.
!!! error TS2415: Type 'String' is not assignable to type 'string'.
x: U;
}
@@ -1,6 +1,7 @@
tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(13,12): error TS2493: Tuple type '[string, number]' with length '2' cannot be assigned to tuple with length '3'.
tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(14,12): error TS2460: Type 'StrNum' has no property '2'.
tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(15,5): error TS2461: Type '{ 0: string; 1: number; }' is not an array type.
tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(15,12): error TS2460: Type '{ 0: string; 1: number; }' has no property '2'.
tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(16,5): error TS2322: Type '[string, number]' is not assignable to type '[number, number, number]'.
Types of property '0' are incompatible.
Type 'string' is not assignable to type 'number'.
@@ -46,7 +47,7 @@ tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(30,5): error
Type 'string' is not assignable to type 'number'.
==== tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts (18 errors) ====
==== tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts (19 errors) ====
interface StrNum extends Array<string|number> {
0: string;
1: number;
@@ -68,6 +69,8 @@ tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(30,5): error
var [g, h, i] = z;
~~~~~~~~~
!!! error TS2461: Type '{ 0: string; 1: number; }' is not an array type.
~
!!! error TS2460: Type '{ 0: string; 1: number; }' has no property '2'.
var j1: [number, number, number] = x;
~~
!!! error TS2322: Type '[string, number]' is not assignable to type '[number, number, number]'.
@@ -294,8 +294,8 @@ module EmptyTypes {
// Order matters here so test all the variants
var a1 = [{ x: 0, y: 'a' }, { x: 'a', y: 'a' }, { x: anyObj, y: 'a' }];
>a1 : { x: any; y: string; }[]
>[{ x: 0, y: 'a' }, { x: 'a', y: 'a' }, { x: anyObj, y: 'a' }] : { x: any; y: string; }[]
>a1 : ({ x: number; y: string; } | { x: string; y: string; } | { x: any; y: string; })[]
>[{ x: 0, y: 'a' }, { x: 'a', y: 'a' }, { x: anyObj, y: 'a' }] : ({ x: number; y: string; } | { x: string; y: string; } | { x: any; y: string; })[]
>{ x: 0, y: 'a' } : { x: number; y: string; }
>x : number
>0 : number
@@ -313,8 +313,8 @@ module EmptyTypes {
>'a' : string
var a2 = [{ x: anyObj, y: 'a' }, { x: 0, y: 'a' }, { x: 'a', y: 'a' }];
>a2 : { x: any; y: string; }[]
>[{ x: anyObj, y: 'a' }, { x: 0, y: 'a' }, { x: 'a', y: 'a' }] : { x: any; y: string; }[]
>a2 : ({ x: any; y: string; } | { x: number; y: string; } | { x: string; y: string; })[]
>[{ x: anyObj, y: 'a' }, { x: 0, y: 'a' }, { x: 'a', y: 'a' }] : ({ x: any; y: string; } | { x: number; y: string; } | { x: string; y: string; })[]
>{ x: anyObj, y: 'a' } : { x: any; y: string; }
>x : any
>anyObj : any
@@ -332,8 +332,8 @@ module EmptyTypes {
>'a' : string
var a3 = [{ x: 0, y: 'a' }, { x: anyObj, y: 'a' }, { x: 'a', y: 'a' }];
>a3 : { x: any; y: string; }[]
>[{ x: 0, y: 'a' }, { x: anyObj, y: 'a' }, { x: 'a', y: 'a' }] : { x: any; y: string; }[]
>a3 : ({ x: number; y: string; } | { x: any; y: string; } | { x: string; y: string; })[]
>[{ x: 0, y: 'a' }, { x: anyObj, y: 'a' }, { x: 'a', y: 'a' }] : ({ x: number; y: string; } | { x: any; y: string; } | { x: string; y: string; })[]
>{ x: 0, y: 'a' } : { x: number; y: string; }
>x : number
>0 : number
@@ -366,22 +366,22 @@ module EmptyTypes {
>base2 : typeof base2
var b1 = [baseObj, base2Obj, ifaceObj];
>b1 : iface[]
>[baseObj, base2Obj, ifaceObj] : iface[]
>b1 : base[]
>[baseObj, base2Obj, ifaceObj] : base[]
>baseObj : base
>base2Obj : base2
>ifaceObj : iface
var b2 = [base2Obj, baseObj, ifaceObj];
>b2 : iface[]
>[base2Obj, baseObj, ifaceObj] : iface[]
>b2 : base2[]
>[base2Obj, baseObj, ifaceObj] : base2[]
>base2Obj : base2
>baseObj : base
>ifaceObj : iface
var b3 = [baseObj, ifaceObj, base2Obj];
>b3 : iface[]
>[baseObj, ifaceObj, base2Obj] : iface[]
>b3 : base[]
>[baseObj, ifaceObj, base2Obj] : base[]
>baseObj : base
>ifaceObj : iface
>base2Obj : base2
@@ -639,7 +639,7 @@ module NonEmptyTypes {
>x : number
>y : base
>base : base
>[{ x: 7, y: new derived() }, { x: 5, y: new base() }] : { x: number; y: base; }[]
>[{ x: 7, y: new derived() }, { x: 5, y: new base() }] : ({ x: number; y: derived; } | { x: number; y: base; })[]
>{ x: 7, y: new derived() } : { x: number; y: derived; }
>x : number
>7 : number
@@ -658,7 +658,7 @@ module NonEmptyTypes {
>x : boolean
>y : base
>base : base
>[{ x: true, y: new derived() }, { x: false, y: new base() }] : { x: boolean; y: base; }[]
>[{ x: true, y: new derived() }, { x: false, y: new base() }] : ({ x: boolean; y: derived; } | { x: boolean; y: base; })[]
>{ x: true, y: new derived() } : { x: boolean; y: derived; }
>x : boolean
>true : boolean
@@ -697,8 +697,8 @@ module NonEmptyTypes {
// Order matters here so test all the variants
var a1 = [{ x: 0, y: 'a' }, { x: 'a', y: 'a' }, { x: anyObj, y: 'a' }];
>a1 : { x: any; y: string; }[]
>[{ x: 0, y: 'a' }, { x: 'a', y: 'a' }, { x: anyObj, y: 'a' }] : { x: any; y: string; }[]
>a1 : ({ x: number; y: string; } | { x: string; y: string; } | { x: any; y: string; })[]
>[{ x: 0, y: 'a' }, { x: 'a', y: 'a' }, { x: anyObj, y: 'a' }] : ({ x: number; y: string; } | { x: string; y: string; } | { x: any; y: string; })[]
>{ x: 0, y: 'a' } : { x: number; y: string; }
>x : number
>0 : number
@@ -716,8 +716,8 @@ module NonEmptyTypes {
>'a' : string
var a2 = [{ x: anyObj, y: 'a' }, { x: 0, y: 'a' }, { x: 'a', y: 'a' }];
>a2 : { x: any; y: string; }[]
>[{ x: anyObj, y: 'a' }, { x: 0, y: 'a' }, { x: 'a', y: 'a' }] : { x: any; y: string; }[]
>a2 : ({ x: any; y: string; } | { x: number; y: string; } | { x: string; y: string; })[]
>[{ x: anyObj, y: 'a' }, { x: 0, y: 'a' }, { x: 'a', y: 'a' }] : ({ x: any; y: string; } | { x: number; y: string; } | { x: string; y: string; })[]
>{ x: anyObj, y: 'a' } : { x: any; y: string; }
>x : any
>anyObj : any
@@ -735,8 +735,8 @@ module NonEmptyTypes {
>'a' : string
var a3 = [{ x: 0, y: 'a' }, { x: anyObj, y: 'a' }, { x: 'a', y: 'a' }];
>a3 : { x: any; y: string; }[]
>[{ x: 0, y: 'a' }, { x: anyObj, y: 'a' }, { x: 'a', y: 'a' }] : { x: any; y: string; }[]
>a3 : ({ x: number; y: string; } | { x: any; y: string; } | { x: string; y: string; })[]
>[{ x: 0, y: 'a' }, { x: anyObj, y: 'a' }, { x: 'a', y: 'a' }] : ({ x: number; y: string; } | { x: any; y: string; } | { x: string; y: string; })[]
>{ x: 0, y: 'a' } : { x: number; y: string; }
>x : number
>0 : number
@@ -769,29 +769,29 @@ module NonEmptyTypes {
>base2 : typeof base2
var b1 = [baseObj, base2Obj, ifaceObj];
>b1 : iface[]
>[baseObj, base2Obj, ifaceObj] : iface[]
>b1 : (base | base2 | iface)[]
>[baseObj, base2Obj, ifaceObj] : (base | base2 | iface)[]
>baseObj : base
>base2Obj : base2
>ifaceObj : iface
var b2 = [base2Obj, baseObj, ifaceObj];
>b2 : iface[]
>[base2Obj, baseObj, ifaceObj] : iface[]
>b2 : (base2 | base | iface)[]
>[base2Obj, baseObj, ifaceObj] : (base2 | base | iface)[]
>base2Obj : base2
>baseObj : base
>ifaceObj : iface
var b3 = [baseObj, ifaceObj, base2Obj];
>b3 : iface[]
>[baseObj, ifaceObj, base2Obj] : iface[]
>b3 : (base | iface | base2)[]
>[baseObj, ifaceObj, base2Obj] : (base | iface | base2)[]
>baseObj : base
>ifaceObj : iface
>base2Obj : base2
var b4 = [ifaceObj, baseObj, base2Obj];
>b4 : iface[]
>[ifaceObj, baseObj, base2Obj] : iface[]
>b4 : (iface | base | base2)[]
>[ifaceObj, baseObj, base2Obj] : (iface | base | base2)[]
>ifaceObj : iface
>baseObj : base
>base2Obj : base2
@@ -1,6 +1,6 @@
tests/cases/compiler/arrayCast.ts(3,1): error TS2352: Neither type '{ foo: string; }[]' nor type '{ id: number; }[]' is assignable to the other.
Type '{ foo: string; }' is not assignable to type '{ id: number; }'.
Property 'id' is missing in type '{ foo: string; }'.
Object literal may only specify known properties, and 'foo' does not exist in type '{ id: number; }'.
==== tests/cases/compiler/arrayCast.ts (1 errors) ====
@@ -10,7 +10,7 @@ tests/cases/compiler/arrayCast.ts(3,1): error TS2352: Neither type '{ foo: strin
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
!!! error TS2352: Neither type '{ foo: string; }[]' nor type '{ id: number; }[]' is assignable to the other.
!!! error TS2352: Type '{ foo: string; }' is not assignable to type '{ id: number; }'.
!!! error TS2352: Property 'id' is missing in type '{ foo: string; }'.
!!! error TS2352: Object literal may only specify known properties, and 'foo' does not exist in type '{ id: number; }'.
// Should succeed, as the {} element causes the type of the array to be {}[]
<{ id: number; }[]>[{ foo: "s" }, {}];
@@ -1,7 +1,7 @@
tests/cases/conformance/expressions/contextualTyping/arrayLiteralExpressionContextualTyping.ts(8,5): error TS2322: Type '[number, number, number, string]' is not assignable to type '[number, number, number]'.
Types of property 'pop' are incompatible.
Type '() => string | number' is not assignable to type '() => number'.
Type 'string | number' is not assignable to type 'number'.
Type '() => number | string' is not assignable to type '() => number'.
Type 'number | string' is not assignable to type 'number'.
Type 'string' is not assignable to type 'number'.
tests/cases/conformance/expressions/contextualTyping/arrayLiteralExpressionContextualTyping.ts(14,5): error TS2322: Type 'number[]' is not assignable to type '[number, number, number]'.
Property '0' is missing in type 'number[]'.
@@ -19,8 +19,8 @@ tests/cases/conformance/expressions/contextualTyping/arrayLiteralExpressionConte
~~~~
!!! error TS2322: Type '[number, number, number, string]' is not assignable to type '[number, number, number]'.
!!! error TS2322: Types of property 'pop' are incompatible.
!!! error TS2322: Type '() => string | number' is not assignable to type '() => number'.
!!! error TS2322: Type 'string | number' is not assignable to type 'number'.
!!! error TS2322: Type '() => number | string' is not assignable to type '() => number'.
!!! error TS2322: Type 'number | string' is not assignable to type 'number'.
!!! error TS2322: Type 'string' is not assignable to type 'number'.
// In a contextually typed array literal expression containing one or more spread elements,
@@ -0,0 +1,72 @@
tests/cases/compiler/arrayLiteralTypeInference.ts(13,5): error TS2322: Type '({ id: number; trueness: boolean; } | { id: number; name: string; })[]' is not assignable to type 'Action[]'.
Type '{ id: number; trueness: boolean; } | { id: number; name: string; }' is not assignable to type 'Action'.
Type '{ id: number; trueness: boolean; }' is not assignable to type 'Action'.
Object literal may only specify known properties, and 'trueness' does not exist in type 'Action'.
tests/cases/compiler/arrayLiteralTypeInference.ts(29,5): error TS2322: Type '({ id: number; trueness: boolean; } | { id: number; name: string; })[]' is not assignable to type '{ id: number; }[]'.
Type '{ id: number; trueness: boolean; } | { id: number; name: string; }' is not assignable to type '{ id: number; }'.
Type '{ id: number; trueness: boolean; }' is not assignable to type '{ id: number; }'.
Object literal may only specify known properties, and 'trueness' does not exist in type '{ id: number; }'.
==== tests/cases/compiler/arrayLiteralTypeInference.ts (2 errors) ====
class Action {
id: number;
}
class ActionA extends Action {
value: string;
}
class ActionB extends Action {
trueNess: boolean;
}
var x1: Action[] = [
~~
!!! error TS2322: Type '({ id: number; trueness: boolean; } | { id: number; name: string; })[]' is not assignable to type 'Action[]'.
!!! error TS2322: Type '{ id: number; trueness: boolean; } | { id: number; name: string; }' is not assignable to type 'Action'.
!!! error TS2322: Type '{ id: number; trueness: boolean; }' is not assignable to type 'Action'.
!!! error TS2322: Object literal may only specify known properties, and 'trueness' does not exist in type 'Action'.
{ id: 2, trueness: false },
{ id: 3, name: "three" }
]
var x2: Action[] = [
new ActionA(),
new ActionB()
]
var x3: Action[] = [
new Action(),
new ActionA(),
new ActionB()
]
var z1: { id: number }[] =
~~
!!! error TS2322: Type '({ id: number; trueness: boolean; } | { id: number; name: string; })[]' is not assignable to type '{ id: number; }[]'.
!!! error TS2322: Type '{ id: number; trueness: boolean; } | { id: number; name: string; }' is not assignable to type '{ id: number; }'.
!!! error TS2322: Type '{ id: number; trueness: boolean; }' is not assignable to type '{ id: number; }'.
!!! error TS2322: Object literal may only specify known properties, and 'trueness' does not exist in type '{ id: number; }'.
[
{ id: 2, trueness: false },
{ id: 3, name: "three" }
]
var z2: { id: number }[] =
[
new ActionA(),
new ActionB()
]
var z3: { id: number }[] =
[
new Action(),
new ActionA(),
new ActionB()
]
@@ -1,113 +0,0 @@
=== tests/cases/compiler/arrayLiteralTypeInference.ts ===
class Action {
>Action : Symbol(Action, Decl(arrayLiteralTypeInference.ts, 0, 0))
id: number;
>id : Symbol(id, Decl(arrayLiteralTypeInference.ts, 0, 14))
}
class ActionA extends Action {
>ActionA : Symbol(ActionA, Decl(arrayLiteralTypeInference.ts, 2, 1))
>Action : Symbol(Action, Decl(arrayLiteralTypeInference.ts, 0, 0))
value: string;
>value : Symbol(value, Decl(arrayLiteralTypeInference.ts, 4, 30))
}
class ActionB extends Action {
>ActionB : Symbol(ActionB, Decl(arrayLiteralTypeInference.ts, 6, 1))
>Action : Symbol(Action, Decl(arrayLiteralTypeInference.ts, 0, 0))
trueNess: boolean;
>trueNess : Symbol(trueNess, Decl(arrayLiteralTypeInference.ts, 8, 30))
}
var x1: Action[] = [
>x1 : Symbol(x1, Decl(arrayLiteralTypeInference.ts, 12, 3))
>Action : Symbol(Action, Decl(arrayLiteralTypeInference.ts, 0, 0))
{ id: 2, trueness: false },
>id : Symbol(id, Decl(arrayLiteralTypeInference.ts, 13, 5))
>trueness : Symbol(trueness, Decl(arrayLiteralTypeInference.ts, 13, 12))
{ id: 3, name: "three" }
>id : Symbol(id, Decl(arrayLiteralTypeInference.ts, 14, 5))
>name : Symbol(name, Decl(arrayLiteralTypeInference.ts, 14, 12))
]
var x2: Action[] = [
>x2 : Symbol(x2, Decl(arrayLiteralTypeInference.ts, 17, 3))
>Action : Symbol(Action, Decl(arrayLiteralTypeInference.ts, 0, 0))
new ActionA(),
>ActionA : Symbol(ActionA, Decl(arrayLiteralTypeInference.ts, 2, 1))
new ActionB()
>ActionB : Symbol(ActionB, Decl(arrayLiteralTypeInference.ts, 6, 1))
]
var x3: Action[] = [
>x3 : Symbol(x3, Decl(arrayLiteralTypeInference.ts, 22, 3))
>Action : Symbol(Action, Decl(arrayLiteralTypeInference.ts, 0, 0))
new Action(),
>Action : Symbol(Action, Decl(arrayLiteralTypeInference.ts, 0, 0))
new ActionA(),
>ActionA : Symbol(ActionA, Decl(arrayLiteralTypeInference.ts, 2, 1))
new ActionB()
>ActionB : Symbol(ActionB, Decl(arrayLiteralTypeInference.ts, 6, 1))
]
var z1: { id: number }[] =
>z1 : Symbol(z1, Decl(arrayLiteralTypeInference.ts, 28, 3))
>id : Symbol(id, Decl(arrayLiteralTypeInference.ts, 28, 9))
[
{ id: 2, trueness: false },
>id : Symbol(id, Decl(arrayLiteralTypeInference.ts, 30, 9))
>trueness : Symbol(trueness, Decl(arrayLiteralTypeInference.ts, 30, 16))
{ id: 3, name: "three" }
>id : Symbol(id, Decl(arrayLiteralTypeInference.ts, 31, 9))
>name : Symbol(name, Decl(arrayLiteralTypeInference.ts, 31, 16))
]
var z2: { id: number }[] =
>z2 : Symbol(z2, Decl(arrayLiteralTypeInference.ts, 34, 3))
>id : Symbol(id, Decl(arrayLiteralTypeInference.ts, 34, 9))
[
new ActionA(),
>ActionA : Symbol(ActionA, Decl(arrayLiteralTypeInference.ts, 2, 1))
new ActionB()
>ActionB : Symbol(ActionB, Decl(arrayLiteralTypeInference.ts, 6, 1))
]
var z3: { id: number }[] =
>z3 : Symbol(z3, Decl(arrayLiteralTypeInference.ts, 40, 3))
>id : Symbol(id, Decl(arrayLiteralTypeInference.ts, 40, 9))
[
new Action(),
>Action : Symbol(Action, Decl(arrayLiteralTypeInference.ts, 0, 0))
new ActionA(),
>ActionA : Symbol(ActionA, Decl(arrayLiteralTypeInference.ts, 2, 1))
new ActionB()
>ActionB : Symbol(ActionB, Decl(arrayLiteralTypeInference.ts, 6, 1))
]
@@ -1,144 +0,0 @@
=== tests/cases/compiler/arrayLiteralTypeInference.ts ===
class Action {
>Action : Action
id: number;
>id : number
}
class ActionA extends Action {
>ActionA : ActionA
>Action : Action
value: string;
>value : string
}
class ActionB extends Action {
>ActionB : ActionB
>Action : Action
trueNess: boolean;
>trueNess : boolean
}
var x1: Action[] = [
>x1 : Action[]
>Action : Action
>[ { id: 2, trueness: false }, { id: 3, name: "three" }] : ({ id: number; trueness: boolean; } | { id: number; name: string; })[]
{ id: 2, trueness: false },
>{ id: 2, trueness: false } : { id: number; trueness: boolean; }
>id : number
>2 : number
>trueness : boolean
>false : boolean
{ id: 3, name: "three" }
>{ id: 3, name: "three" } : { id: number; name: string; }
>id : number
>3 : number
>name : string
>"three" : string
]
var x2: Action[] = [
>x2 : Action[]
>Action : Action
>[ new ActionA(), new ActionB()] : (ActionA | ActionB)[]
new ActionA(),
>new ActionA() : ActionA
>ActionA : typeof ActionA
new ActionB()
>new ActionB() : ActionB
>ActionB : typeof ActionB
]
var x3: Action[] = [
>x3 : Action[]
>Action : Action
>[ new Action(), new ActionA(), new ActionB()] : Action[]
new Action(),
>new Action() : Action
>Action : typeof Action
new ActionA(),
>new ActionA() : ActionA
>ActionA : typeof ActionA
new ActionB()
>new ActionB() : ActionB
>ActionB : typeof ActionB
]
var z1: { id: number }[] =
>z1 : { id: number; }[]
>id : number
[
>[ { id: 2, trueness: false }, { id: 3, name: "three" } ] : ({ id: number; trueness: boolean; } | { id: number; name: string; })[]
{ id: 2, trueness: false },
>{ id: 2, trueness: false } : { id: number; trueness: boolean; }
>id : number
>2 : number
>trueness : boolean
>false : boolean
{ id: 3, name: "three" }
>{ id: 3, name: "three" } : { id: number; name: string; }
>id : number
>3 : number
>name : string
>"three" : string
]
var z2: { id: number }[] =
>z2 : { id: number; }[]
>id : number
[
>[ new ActionA(), new ActionB() ] : (ActionA | ActionB)[]
new ActionA(),
>new ActionA() : ActionA
>ActionA : typeof ActionA
new ActionB()
>new ActionB() : ActionB
>ActionB : typeof ActionB
]
var z3: { id: number }[] =
>z3 : { id: number; }[]
>id : number
[
>[ new Action(), new ActionA(), new ActionB() ] : Action[]
new Action(),
>new Action() : Action
>Action : typeof Action
new ActionA(),
>new ActionA() : ActionA
>ActionA : typeof ActionA
new ActionB()
>new ActionB() : ActionB
>ActionB : typeof ActionB
]
@@ -23,8 +23,8 @@ var as = [a, b]; // { x: number; y?: number };[]
>b : { x: number; z?: number; }
var bs = [b, a]; // { x: number; z?: number };[]
>bs : ({ x: number; y?: number; } | { x: number; z?: number; })[]
>[b, a] : ({ x: number; y?: number; } | { x: number; z?: number; })[]
>bs : ({ x: number; z?: number; } | { x: number; y?: number; })[]
>[b, a] : ({ x: number; z?: number; } | { x: number; y?: number; })[]
>b : { x: number; z?: number; }
>a : { x: number; y?: number; }
@@ -36,8 +36,8 @@ var cs = [a, b, c]; // { x: number; y?: number };[]
>c : { x: number; a?: number; }
var ds = [(x: Object) => 1, (x: string) => 2]; // { (x:Object) => number }[]
>ds : ((x: Object) => number)[]
>[(x: Object) => 1, (x: string) => 2] : ((x: Object) => number)[]
>ds : (((x: Object) => number) | ((x: string) => number))[]
>[(x: Object) => 1, (x: string) => 2] : (((x: Object) => number) | ((x: string) => number))[]
>(x: Object) => 1 : (x: Object) => number
>x : Object
>Object : Object
@@ -47,8 +47,8 @@ var ds = [(x: Object) => 1, (x: string) => 2]; // { (x:Object) => number }[]
>2 : number
var es = [(x: string) => 2, (x: Object) => 1]; // { (x:string) => number }[]
>es : ((x: string) => number)[]
>[(x: string) => 2, (x: Object) => 1] : ((x: string) => number)[]
>es : (((x: string) => number) | ((x: Object) => number))[]
>[(x: string) => 2, (x: Object) => 1] : (((x: string) => number) | ((x: Object) => number))[]
>(x: string) => 2 : (x: string) => number
>x : string
>2 : number
@@ -0,0 +1,50 @@
tests/cases/conformance/expressions/arrayLiterals/arrayLiterals.ts(24,5): error TS2322: Type '({ a: string; b: number; c: string; } | { a: string; b: number; c: number; })[]' is not assignable to type '{ [n: number]: { a: string; b: number; }; }'.
Index signatures are incompatible.
Type '{ a: string; b: number; c: string; } | { a: string; b: number; c: number; }' is not assignable to type '{ a: string; b: number; }'.
Type '{ a: string; b: number; c: string; }' is not assignable to type '{ a: string; b: number; }'.
Object literal may only specify known properties, and 'c' does not exist in type '{ a: string; b: number; }'.
==== tests/cases/conformance/expressions/arrayLiterals/arrayLiterals.ts (1 errors) ====
// Empty array literal with no contextual type has type Undefined[]
var arr1= [[], [1], ['']];
var arr2 = [[null], [1], ['']];
// Array literal with elements of only EveryType E has type E[]
var stringArrArr = [[''], [""]];
var stringArr = ['', ""];
var numberArr = [0, 0.0, 0x00, 1e1];
var boolArr = [false, true, false, true];
class C { private p; }
var classArr = [new C(), new C()];
var classTypeArray = [C, C, C];
var classTypeArray: Array<typeof C>; // Should OK, not be a parse error
// Contextual type C with numeric index signature makes array literal of EveryType E of type BCT(E,C)[]
var context1: { [n: number]: { a: string; b: number; }; } = [{ a: '', b: 0, c: '' }, { a: "", b: 3, c: 0 }];
~~~~~~~~
!!! error TS2322: Type '({ a: string; b: number; c: string; } | { a: string; b: number; c: number; })[]' is not assignable to type '{ [n: number]: { a: string; b: number; }; }'.
!!! error TS2322: Index signatures are incompatible.
!!! error TS2322: Type '{ a: string; b: number; c: string; } | { a: string; b: number; c: number; }' is not assignable to type '{ a: string; b: number; }'.
!!! error TS2322: Type '{ a: string; b: number; c: string; }' is not assignable to type '{ a: string; b: number; }'.
!!! error TS2322: Object literal may only specify known properties, and 'c' does not exist in type '{ a: string; b: number; }'.
var context2 = [{ a: '', b: 0, c: '' }, { a: "", b: 3, c: 0 }];
// Contextual type C with numeric index signature of type Base makes array literal of Derived have type Base[]
class Base { private p; }
class Derived1 extends Base { private m };
class Derived2 extends Base { private n };
var context3: Base[] = [new Derived1(), new Derived2()];
// Contextual type C with numeric index signature of type Base makes array literal of Derived1 and Derived2 have type Base[]
var context4: Base[] = [new Derived1(), new Derived1()];
@@ -1,94 +0,0 @@
=== tests/cases/conformance/expressions/arrayLiterals/arrayLiterals.ts ===
// Empty array literal with no contextual type has type Undefined[]
var arr1= [[], [1], ['']];
>arr1 : Symbol(arr1, Decl(arrayLiterals.ts, 2, 3))
var arr2 = [[null], [1], ['']];
>arr2 : Symbol(arr2, Decl(arrayLiterals.ts, 4, 3))
// Array literal with elements of only EveryType E has type E[]
var stringArrArr = [[''], [""]];
>stringArrArr : Symbol(stringArrArr, Decl(arrayLiterals.ts, 8, 3))
var stringArr = ['', ""];
>stringArr : Symbol(stringArr, Decl(arrayLiterals.ts, 10, 3))
var numberArr = [0, 0.0, 0x00, 1e1];
>numberArr : Symbol(numberArr, Decl(arrayLiterals.ts, 12, 3))
var boolArr = [false, true, false, true];
>boolArr : Symbol(boolArr, Decl(arrayLiterals.ts, 14, 3))
class C { private p; }
>C : Symbol(C, Decl(arrayLiterals.ts, 14, 41))
>p : Symbol(p, Decl(arrayLiterals.ts, 16, 9))
var classArr = [new C(), new C()];
>classArr : Symbol(classArr, Decl(arrayLiterals.ts, 17, 3))
>C : Symbol(C, Decl(arrayLiterals.ts, 14, 41))
>C : Symbol(C, Decl(arrayLiterals.ts, 14, 41))
var classTypeArray = [C, C, C];
>classTypeArray : Symbol(classTypeArray, Decl(arrayLiterals.ts, 19, 3), Decl(arrayLiterals.ts, 20, 3))
>C : Symbol(C, Decl(arrayLiterals.ts, 14, 41))
>C : Symbol(C, Decl(arrayLiterals.ts, 14, 41))
>C : Symbol(C, Decl(arrayLiterals.ts, 14, 41))
var classTypeArray: Array<typeof C>; // Should OK, not be a parse error
>classTypeArray : Symbol(classTypeArray, Decl(arrayLiterals.ts, 19, 3), Decl(arrayLiterals.ts, 20, 3))
>Array : Symbol(Array, Decl(lib.d.ts, 1000, 23), Decl(lib.d.ts, 1171, 11))
>C : Symbol(C, Decl(arrayLiterals.ts, 14, 41))
// Contextual type C with numeric index signature makes array literal of EveryType E of type BCT(E,C)[]
var context1: { [n: number]: { a: string; b: number; }; } = [{ a: '', b: 0, c: '' }, { a: "", b: 3, c: 0 }];
>context1 : Symbol(context1, Decl(arrayLiterals.ts, 23, 3))
>n : Symbol(n, Decl(arrayLiterals.ts, 23, 17))
>a : Symbol(a, Decl(arrayLiterals.ts, 23, 30))
>b : Symbol(b, Decl(arrayLiterals.ts, 23, 41))
>a : Symbol(a, Decl(arrayLiterals.ts, 23, 62))
>b : Symbol(b, Decl(arrayLiterals.ts, 23, 69))
>c : Symbol(c, Decl(arrayLiterals.ts, 23, 75))
>a : Symbol(a, Decl(arrayLiterals.ts, 23, 86))
>b : Symbol(b, Decl(arrayLiterals.ts, 23, 93))
>c : Symbol(c, Decl(arrayLiterals.ts, 23, 99))
var context2 = [{ a: '', b: 0, c: '' }, { a: "", b: 3, c: 0 }];
>context2 : Symbol(context2, Decl(arrayLiterals.ts, 24, 3))
>a : Symbol(a, Decl(arrayLiterals.ts, 24, 17))
>b : Symbol(b, Decl(arrayLiterals.ts, 24, 24))
>c : Symbol(c, Decl(arrayLiterals.ts, 24, 30))
>a : Symbol(a, Decl(arrayLiterals.ts, 24, 41))
>b : Symbol(b, Decl(arrayLiterals.ts, 24, 48))
>c : Symbol(c, Decl(arrayLiterals.ts, 24, 54))
// Contextual type C with numeric index signature of type Base makes array literal of Derived have type Base[]
class Base { private p; }
>Base : Symbol(Base, Decl(arrayLiterals.ts, 24, 63))
>p : Symbol(p, Decl(arrayLiterals.ts, 27, 12))
class Derived1 extends Base { private m };
>Derived1 : Symbol(Derived1, Decl(arrayLiterals.ts, 27, 25))
>Base : Symbol(Base, Decl(arrayLiterals.ts, 24, 63))
>m : Symbol(m, Decl(arrayLiterals.ts, 28, 29))
class Derived2 extends Base { private n };
>Derived2 : Symbol(Derived2, Decl(arrayLiterals.ts, 28, 42))
>Base : Symbol(Base, Decl(arrayLiterals.ts, 24, 63))
>n : Symbol(n, Decl(arrayLiterals.ts, 29, 29))
var context3: Base[] = [new Derived1(), new Derived2()];
>context3 : Symbol(context3, Decl(arrayLiterals.ts, 30, 3))
>Base : Symbol(Base, Decl(arrayLiterals.ts, 24, 63))
>Derived1 : Symbol(Derived1, Decl(arrayLiterals.ts, 27, 25))
>Derived2 : Symbol(Derived2, Decl(arrayLiterals.ts, 28, 42))
// Contextual type C with numeric index signature of type Base makes array literal of Derived1 and Derived2 have type Base[]
var context4: Base[] = [new Derived1(), new Derived1()];
>context4 : Symbol(context4, Decl(arrayLiterals.ts, 33, 3))
>Base : Symbol(Base, Decl(arrayLiterals.ts, 24, 63))
>Derived1 : Symbol(Derived1, Decl(arrayLiterals.ts, 27, 25))
>Derived1 : Symbol(Derived1, Decl(arrayLiterals.ts, 27, 25))
@@ -1,153 +0,0 @@
=== tests/cases/conformance/expressions/arrayLiterals/arrayLiterals.ts ===
// Empty array literal with no contextual type has type Undefined[]
var arr1= [[], [1], ['']];
>arr1 : (number[] | string[])[]
>[[], [1], ['']] : (number[] | string[])[]
>[] : undefined[]
>[1] : number[]
>1 : number
>[''] : string[]
>'' : string
var arr2 = [[null], [1], ['']];
>arr2 : (number[] | string[])[]
>[[null], [1], ['']] : (number[] | string[])[]
>[null] : null[]
>null : null
>[1] : number[]
>1 : number
>[''] : string[]
>'' : string
// Array literal with elements of only EveryType E has type E[]
var stringArrArr = [[''], [""]];
>stringArrArr : string[][]
>[[''], [""]] : string[][]
>[''] : string[]
>'' : string
>[""] : string[]
>"" : string
var stringArr = ['', ""];
>stringArr : string[]
>['', ""] : string[]
>'' : string
>"" : string
var numberArr = [0, 0.0, 0x00, 1e1];
>numberArr : number[]
>[0, 0.0, 0x00, 1e1] : number[]
>0 : number
>0.0 : number
>0x00 : number
>1e1 : number
var boolArr = [false, true, false, true];
>boolArr : boolean[]
>[false, true, false, true] : boolean[]
>false : boolean
>true : boolean
>false : boolean
>true : boolean
class C { private p; }
>C : C
>p : any
var classArr = [new C(), new C()];
>classArr : C[]
>[new C(), new C()] : C[]
>new C() : C
>C : typeof C
>new C() : C
>C : typeof C
var classTypeArray = [C, C, C];
>classTypeArray : typeof C[]
>[C, C, C] : typeof C[]
>C : typeof C
>C : typeof C
>C : typeof C
var classTypeArray: Array<typeof C>; // Should OK, not be a parse error
>classTypeArray : typeof C[]
>Array : T[]
>C : typeof C
// Contextual type C with numeric index signature makes array literal of EveryType E of type BCT(E,C)[]
var context1: { [n: number]: { a: string; b: number; }; } = [{ a: '', b: 0, c: '' }, { a: "", b: 3, c: 0 }];
>context1 : { [n: number]: { a: string; b: number; }; }
>n : number
>a : string
>b : number
>[{ a: '', b: 0, c: '' }, { a: "", b: 3, c: 0 }] : ({ a: string; b: number; c: string; } | { a: string; b: number; c: number; })[]
>{ a: '', b: 0, c: '' } : { a: string; b: number; c: string; }
>a : string
>'' : string
>b : number
>0 : number
>c : string
>'' : string
>{ a: "", b: 3, c: 0 } : { a: string; b: number; c: number; }
>a : string
>"" : string
>b : number
>3 : number
>c : number
>0 : number
var context2 = [{ a: '', b: 0, c: '' }, { a: "", b: 3, c: 0 }];
>context2 : ({ a: string; b: number; c: string; } | { a: string; b: number; c: number; })[]
>[{ a: '', b: 0, c: '' }, { a: "", b: 3, c: 0 }] : ({ a: string; b: number; c: string; } | { a: string; b: number; c: number; })[]
>{ a: '', b: 0, c: '' } : { a: string; b: number; c: string; }
>a : string
>'' : string
>b : number
>0 : number
>c : string
>'' : string
>{ a: "", b: 3, c: 0 } : { a: string; b: number; c: number; }
>a : string
>"" : string
>b : number
>3 : number
>c : number
>0 : number
// Contextual type C with numeric index signature of type Base makes array literal of Derived have type Base[]
class Base { private p; }
>Base : Base
>p : any
class Derived1 extends Base { private m };
>Derived1 : Derived1
>Base : Base
>m : any
class Derived2 extends Base { private n };
>Derived2 : Derived2
>Base : Base
>n : any
var context3: Base[] = [new Derived1(), new Derived2()];
>context3 : Base[]
>Base : Base
>[new Derived1(), new Derived2()] : (Derived1 | Derived2)[]
>new Derived1() : Derived1
>Derived1 : typeof Derived1
>new Derived2() : Derived2
>Derived2 : typeof Derived2
// Contextual type C with numeric index signature of type Base makes array literal of Derived1 and Derived2 have type Base[]
var context4: Base[] = [new Derived1(), new Derived1()];
>context4 : Base[]
>Base : Base
>[new Derived1(), new Derived1()] : Derived1[]
>new Derived1() : Derived1
>Derived1 : typeof Derived1
>new Derived1() : Derived1
>Derived1 : typeof Derived1
@@ -24,8 +24,8 @@ var a1 = ["hello", "world"]
>"world" : string
var a2 = [, , , ...a0, "hello"];
>a2 : (string | number)[]
>[, , , ...a0, "hello"] : (string | number)[]
>a2 : (number | string)[]
>[, , , ...a0, "hello"] : (number | string)[]
> : undefined
> : undefined
> : undefined
@@ -151,8 +151,8 @@ interface myArray2 extends Array<Number|String> { }
>String : String
var d0 = [1, true, ...temp,]; // has type (string|number|boolean)[]
>d0 : (string | number | boolean)[]
>[1, true, ...temp,] : (string | number | boolean)[]
>d0 : (number | boolean | string)[]
>[1, true, ...temp,] : (number | boolean | string)[]
>1 : number
>true : boolean
>...temp : string
@@ -214,8 +214,8 @@ var d8: number[][] = [[...temp1]]
>temp1 : number[]
var d9 = [[...temp1], ...["hello"]];
>d9 : (string | number[])[]
>[[...temp1], ...["hello"]] : (string | number[])[]
>d9 : (number[] | string)[]
>[[...temp1], ...["hello"]] : (number[] | string)[]
>[...temp1] : number[]
>...temp1 : number
>temp1 : number[]
@@ -24,8 +24,8 @@ var a1 = ["hello", "world"]
>"world" : string
var a2 = [, , , ...a0, "hello"];
>a2 : (string | number)[]
>[, , , ...a0, "hello"] : (string | number)[]
>a2 : (number | string)[]
>[, , , ...a0, "hello"] : (number | string)[]
> : undefined
> : undefined
> : undefined
@@ -140,8 +140,8 @@ interface myArray2 extends Array<Number|String> { }
>String : String
var d0 = [1, true, ...temp, ]; // has type (string|number|boolean)[]
>d0 : (string | number | boolean)[]
>[1, true, ...temp, ] : (string | number | boolean)[]
>d0 : (number | boolean | string)[]
>[1, true, ...temp, ] : (number | boolean | string)[]
>1 : number
>true : boolean
>...temp : string
@@ -176,10 +176,10 @@ var d4: myArray2 = [...temp, ...temp1];
>temp1 : number[]
var d5 = [...a2];
>d5 : (string | number)[]
>[...a2] : (string | number)[]
>...a2 : string | number
>a2 : (string | number)[]
>d5 : (number | string)[]
>[...a2] : (number | string)[]
>...a2 : number | string
>a2 : (number | string)[]
var d6 = [...a3];
>d6 : number[]
@@ -201,8 +201,8 @@ var d8: number[][] = [[...temp1]]
>temp1 : number[]
var d9 = [[...temp1], ...["hello"]];
>d9 : (string | number[])[]
>[[...temp1], ...["hello"]] : (string | number[])[]
>d9 : (number[] | string)[]
>[[...temp1], ...["hello"]] : (number[] | string)[]
>[...temp1] : number[]
>...temp1 : number
>temp1 : number[]
@@ -5,18 +5,18 @@ tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(11,5): error
Type 'string' is not assignable to type 'boolean'.
tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(17,5): error TS2322: Type '[number, number, string, boolean]' is not assignable to type '[number, number]'.
Types of property 'pop' are incompatible.
Type '() => string | number | boolean' is not assignable to type '() => number'.
Type 'string | number | boolean' is not assignable to type 'number'.
Type '() => number | string | boolean' is not assignable to type '() => number'.
Type 'number | string | boolean' is not assignable to type 'number'.
Type 'string' is not assignable to type 'number'.
tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(32,5): error TS2322: Type '(number[] | string[])[]' is not assignable to type 'tup'.
Property '0' is missing in type '(number[] | string[])[]'.
tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(33,5): error TS2322: Type 'number[]' is not assignable to type '[number, number, number]'.
Property '0' is missing in type 'number[]'.
tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(34,5): error TS2322: Type '(string | number)[]' is not assignable to type 'myArray'.
tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(34,5): error TS2322: Type '(number | string)[]' is not assignable to type 'myArray'.
Types of property 'push' are incompatible.
Type '(...items: (string | number)[]) => number' is not assignable to type '(...items: Number[]) => number'.
Type '(...items: (number | string)[]) => number' is not assignable to type '(...items: Number[]) => number'.
Types of parameters 'items' and 'items' are incompatible.
Type 'string | number' is not assignable to type 'Number'.
Type 'number | string' is not assignable to type 'Number'.
Type 'string' is not assignable to type 'Number'.
Property 'toFixed' is missing in type 'String'.
@@ -49,8 +49,8 @@ tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(34,5): error
~~~~~~~~
!!! error TS2322: Type '[number, number, string, boolean]' is not assignable to type '[number, number]'.
!!! error TS2322: Types of property 'pop' are incompatible.
!!! error TS2322: Type '() => string | number | boolean' is not assignable to type '() => number'.
!!! error TS2322: Type 'string | number | boolean' is not assignable to type 'number'.
!!! error TS2322: Type '() => number | string | boolean' is not assignable to type '() => number'.
!!! error TS2322: Type 'number | string | boolean' is not assignable to type 'number'.
!!! error TS2322: Type 'string' is not assignable to type 'number'.
// The resulting type an array literal expression is determined as follows:
@@ -76,11 +76,11 @@ tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(34,5): error
!!! error TS2322: Property '0' is missing in type 'number[]'.
var c2: myArray = [...temp1, ...temp]; // Error cannot assign (number|string)[] to number[]
~~
!!! error TS2322: Type '(string | number)[]' is not assignable to type 'myArray'.
!!! error TS2322: Type '(number | string)[]' is not assignable to type 'myArray'.
!!! error TS2322: Types of property 'push' are incompatible.
!!! error TS2322: Type '(...items: (string | number)[]) => number' is not assignable to type '(...items: Number[]) => number'.
!!! error TS2322: Type '(...items: (number | string)[]) => number' is not assignable to type '(...items: Number[]) => number'.
!!! error TS2322: Types of parameters 'items' and 'items' are incompatible.
!!! error TS2322: Type 'string | number' is not assignable to type 'Number'.
!!! error TS2322: Type 'number | string' is not assignable to type 'Number'.
!!! error TS2322: Type 'string' is not assignable to type 'Number'.
!!! error TS2322: Property 'toFixed' is missing in type 'String'.
@@ -77,8 +77,8 @@ var myDerivedList: DerivedList<number>;
>DerivedList : DerivedList<U>
var as = [list, myDerivedList]; // List<number>[]
>as : List<number>[]
>[list, myDerivedList] : List<number>[]
>as : (List<number> | DerivedList<number>)[]
>[list, myDerivedList] : (List<number> | DerivedList<number>)[]
>list : List<number>
>myDerivedList : DerivedList<number>
@@ -0,0 +1,35 @@
tests/cases/conformance/types/specifyingTypes/typeLiterals/arrayOfFunctionTypes3.ts(17,13): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
tests/cases/conformance/types/specifyingTypes/typeLiterals/arrayOfFunctionTypes3.ts(26,10): error TS2349: Cannot invoke an expression whose type lacks a call signature.
==== tests/cases/conformance/types/specifyingTypes/typeLiterals/arrayOfFunctionTypes3.ts (2 errors) ====
// valid uses of arrays of function types
var x = [() => 1, () => { }];
var r2 = x[0]();
class C {
foo: string;
}
var y = [C, C];
var r3 = new y[0]();
var a: { (x: number): number; (x: string): string; };
var b: { (x: number): number; (x: string): string; };
var c: { (x: number): number; (x: any): any; };
var z = [a, b, c];
var r4 = z[0];
var r5 = r4(''); // any not string
~~
!!! error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
var r5b = r4(1);
var a2: { <T>(x: T): number; (x: string): string;};
var b2: { <T>(x: T): number; (x: string): string; };
var c2: { (x: number): number; <T>(x: T): any; };
var z2 = [a2, b2, c2];
var r6 = z2[0];
var r7 = r6(''); // any not string
~~~~~~
!!! error TS2349: Cannot invoke an expression whose type lacks a call signature.
@@ -1,93 +0,0 @@
=== tests/cases/conformance/types/specifyingTypes/typeLiterals/arrayOfFunctionTypes3.ts ===
// valid uses of arrays of function types
var x = [() => 1, () => { }];
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 2, 3))
var r2 = x[0]();
>r2 : Symbol(r2, Decl(arrayOfFunctionTypes3.ts, 3, 3))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 2, 3))
class C {
>C : Symbol(C, Decl(arrayOfFunctionTypes3.ts, 3, 16))
foo: string;
>foo : Symbol(foo, Decl(arrayOfFunctionTypes3.ts, 5, 9))
}
var y = [C, C];
>y : Symbol(y, Decl(arrayOfFunctionTypes3.ts, 8, 3))
>C : Symbol(C, Decl(arrayOfFunctionTypes3.ts, 3, 16))
>C : Symbol(C, Decl(arrayOfFunctionTypes3.ts, 3, 16))
var r3 = new y[0]();
>r3 : Symbol(r3, Decl(arrayOfFunctionTypes3.ts, 9, 3))
>y : Symbol(y, Decl(arrayOfFunctionTypes3.ts, 8, 3))
var a: { (x: number): number; (x: string): string; };
>a : Symbol(a, Decl(arrayOfFunctionTypes3.ts, 11, 3))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 11, 10))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 11, 31))
var b: { (x: number): number; (x: string): string; };
>b : Symbol(b, Decl(arrayOfFunctionTypes3.ts, 12, 3))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 12, 10))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 12, 31))
var c: { (x: number): number; (x: any): any; };
>c : Symbol(c, Decl(arrayOfFunctionTypes3.ts, 13, 3))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 13, 10))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 13, 31))
var z = [a, b, c];
>z : Symbol(z, Decl(arrayOfFunctionTypes3.ts, 14, 3))
>a : Symbol(a, Decl(arrayOfFunctionTypes3.ts, 11, 3))
>b : Symbol(b, Decl(arrayOfFunctionTypes3.ts, 12, 3))
>c : Symbol(c, Decl(arrayOfFunctionTypes3.ts, 13, 3))
var r4 = z[0];
>r4 : Symbol(r4, Decl(arrayOfFunctionTypes3.ts, 15, 3))
>z : Symbol(z, Decl(arrayOfFunctionTypes3.ts, 14, 3))
var r5 = r4(''); // any not string
>r5 : Symbol(r5, Decl(arrayOfFunctionTypes3.ts, 16, 3))
>r4 : Symbol(r4, Decl(arrayOfFunctionTypes3.ts, 15, 3))
var r5b = r4(1);
>r5b : Symbol(r5b, Decl(arrayOfFunctionTypes3.ts, 17, 3))
>r4 : Symbol(r4, Decl(arrayOfFunctionTypes3.ts, 15, 3))
var a2: { <T>(x: T): number; (x: string): string;};
>a2 : Symbol(a2, Decl(arrayOfFunctionTypes3.ts, 19, 3))
>T : Symbol(T, Decl(arrayOfFunctionTypes3.ts, 19, 11))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 19, 14))
>T : Symbol(T, Decl(arrayOfFunctionTypes3.ts, 19, 11))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 19, 30))
var b2: { <T>(x: T): number; (x: string): string; };
>b2 : Symbol(b2, Decl(arrayOfFunctionTypes3.ts, 20, 3))
>T : Symbol(T, Decl(arrayOfFunctionTypes3.ts, 20, 11))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 20, 14))
>T : Symbol(T, Decl(arrayOfFunctionTypes3.ts, 20, 11))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 20, 30))
var c2: { (x: number): number; <T>(x: T): any; };
>c2 : Symbol(c2, Decl(arrayOfFunctionTypes3.ts, 21, 3))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 21, 11))
>T : Symbol(T, Decl(arrayOfFunctionTypes3.ts, 21, 32))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 21, 35))
>T : Symbol(T, Decl(arrayOfFunctionTypes3.ts, 21, 32))
var z2 = [a2, b2, c2];
>z2 : Symbol(z2, Decl(arrayOfFunctionTypes3.ts, 23, 3))
>a2 : Symbol(a2, Decl(arrayOfFunctionTypes3.ts, 19, 3))
>b2 : Symbol(b2, Decl(arrayOfFunctionTypes3.ts, 20, 3))
>c2 : Symbol(c2, Decl(arrayOfFunctionTypes3.ts, 21, 3))
var r6 = z2[0];
>r6 : Symbol(r6, Decl(arrayOfFunctionTypes3.ts, 24, 3))
>z2 : Symbol(z2, Decl(arrayOfFunctionTypes3.ts, 23, 3))
var r7 = r6(''); // any not string
>r7 : Symbol(r7, Decl(arrayOfFunctionTypes3.ts, 25, 3))
>r6 : Symbol(r6, Decl(arrayOfFunctionTypes3.ts, 24, 3))
@@ -1,116 +0,0 @@
=== tests/cases/conformance/types/specifyingTypes/typeLiterals/arrayOfFunctionTypes3.ts ===
// valid uses of arrays of function types
var x = [() => 1, () => { }];
>x : (() => void)[]
>[() => 1, () => { }] : (() => void)[]
>() => 1 : () => number
>1 : number
>() => { } : () => void
var r2 = x[0]();
>r2 : void
>x[0]() : void
>x[0] : () => void
>x : (() => void)[]
>0 : number
class C {
>C : C
foo: string;
>foo : string
}
var y = [C, C];
>y : typeof C[]
>[C, C] : typeof C[]
>C : typeof C
>C : typeof C
var r3 = new y[0]();
>r3 : C
>new y[0]() : C
>y[0] : typeof C
>y : typeof C[]
>0 : number
var a: { (x: number): number; (x: string): string; };
>a : { (x: number): number; (x: string): string; }
>x : number
>x : string
var b: { (x: number): number; (x: string): string; };
>b : { (x: number): number; (x: string): string; }
>x : number
>x : string
var c: { (x: number): number; (x: any): any; };
>c : { (x: number): number; (x: any): any; }
>x : number
>x : any
var z = [a, b, c];
>z : { (x: number): number; (x: any): any; }[]
>[a, b, c] : { (x: number): number; (x: any): any; }[]
>a : { (x: number): number; (x: string): string; }
>b : { (x: number): number; (x: string): string; }
>c : { (x: number): number; (x: any): any; }
var r4 = z[0];
>r4 : { (x: number): number; (x: any): any; }
>z[0] : { (x: number): number; (x: any): any; }
>z : { (x: number): number; (x: any): any; }[]
>0 : number
var r5 = r4(''); // any not string
>r5 : any
>r4('') : any
>r4 : { (x: number): number; (x: any): any; }
>'' : string
var r5b = r4(1);
>r5b : number
>r4(1) : number
>r4 : { (x: number): number; (x: any): any; }
>1 : number
var a2: { <T>(x: T): number; (x: string): string;};
>a2 : { <T>(x: T): number; (x: string): string; }
>T : T
>x : T
>T : T
>x : string
var b2: { <T>(x: T): number; (x: string): string; };
>b2 : { <T>(x: T): number; (x: string): string; }
>T : T
>x : T
>T : T
>x : string
var c2: { (x: number): number; <T>(x: T): any; };
>c2 : { (x: number): number; <T>(x: T): any; }
>x : number
>T : T
>x : T
>T : T
var z2 = [a2, b2, c2];
>z2 : { (x: number): number; <T>(x: T): any; }[]
>[a2, b2, c2] : { (x: number): number; <T>(x: T): any; }[]
>a2 : { <T>(x: T): number; (x: string): string; }
>b2 : { <T>(x: T): number; (x: string): string; }
>c2 : { (x: number): number; <T>(x: T): any; }
var r6 = z2[0];
>r6 : { (x: number): number; <T>(x: T): any; }
>z2[0] : { (x: number): number; <T>(x: T): any; }
>z2 : { (x: number): number; <T>(x: T): any; }[]
>0 : number
var r7 = r6(''); // any not string
>r7 : any
>r6('') : any
>r6 : { (x: number): number; <T>(x: T): any; }
>'' : string
@@ -70,6 +70,7 @@ var p6 = ({ a }) => { };
var p7 = ({ a: { b } }) => { };
>p7 : Symbol(p7, Decl(arrowFunctionExpressions.ts, 21, 3))
>a : Symbol(a)
>b : Symbol(b, Decl(arrowFunctionExpressions.ts, 21, 16))
var p8 = ({ a = 1 }) => { };
@@ -78,6 +79,7 @@ var p8 = ({ a = 1 }) => { };
var p9 = ({ a: { b = 1 } = { b: 1 } }) => { };
>p9 : Symbol(p9, Decl(arrowFunctionExpressions.ts, 23, 3))
>a : Symbol(a)
>b : Symbol(b, Decl(arrowFunctionExpressions.ts, 23, 16))
>b : Symbol(b, Decl(arrowFunctionExpressions.ts, 23, 28))
+3 -3
View File
@@ -24,12 +24,12 @@ var z = Date as any as string;
// Should parse as a union type, not a bitwise 'or' of (32 as number) and 'string'
var j = 32 as number|string;
>j : string | number
>32 as number|string : string | number
>j : number | string
>32 as number|string : number | string
>32 : number
j = '';
>j = '' : string
>j : string | number
>j : number | string
>'' : string
@@ -1,18 +1,21 @@
tests/cases/compiler/assignmentCompat1.ts(4,1): error TS2322: Type '{ [index: string]: any; }' is not assignable to type '{ one: number; }'.
Property 'one' is missing in type '{ [index: string]: any; }'.
tests/cases/compiler/assignmentCompat1.ts(5,1): error TS2322: Type '{ one: number; }' is not assignable to type '{ [index: string]: any; }'.
Index signature is missing in type '{ one: number; }'.
tests/cases/compiler/assignmentCompat1.ts(6,1): error TS2322: Type '{ [index: number]: any; }' is not assignable to type '{ one: number; }'.
Property 'one' is missing in type '{ [index: number]: any; }'.
==== tests/cases/compiler/assignmentCompat1.ts (2 errors) ====
var x = {one: 1};
var y: {[index:string]: any};
x = y;
var x = { one: 1 };
var y: { [index: string]: any };
var z: { [index: number]: any };
x = y; // Error
~
!!! error TS2322: Type '{ [index: string]: any; }' is not assignable to type '{ one: number; }'.
!!! error TS2322: Property 'one' is missing in type '{ [index: string]: any; }'.
y = x;
y = x; // Ok because index signature type is any
x = z; // Error
~
!!! error TS2322: Type '{ one: number; }' is not assignable to type '{ [index: string]: any; }'.
!!! error TS2322: Index signature is missing in type '{ one: number; }'.
!!! error TS2322: Type '{ [index: number]: any; }' is not assignable to type '{ one: number; }'.
!!! error TS2322: Property 'one' is missing in type '{ [index: number]: any; }'.
z = x; // Ok because index signature type is any
+13 -7
View File
@@ -1,12 +1,18 @@
//// [assignmentCompat1.ts]
var x = {one: 1};
var y: {[index:string]: any};
x = y;
y = x;
var x = { one: 1 };
var y: { [index: string]: any };
var z: { [index: number]: any };
x = y; // Error
y = x; // Ok because index signature type is any
x = z; // Error
z = x; // Ok because index signature type is any
//// [assignmentCompat1.js]
var x = { one: 1 };
var y;
x = y;
y = x;
var z;
x = y; // Error
y = x; // Ok because index signature type is any
x = z; // Error
z = x; // Ok because index signature type is any
@@ -1,7 +1,7 @@
tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatBetweenTupleAndArray.ts(17,1): error TS2322: Type '[number, string]' is not assignable to type 'number[]'.
Types of property 'pop' are incompatible.
Type '() => string | number' is not assignable to type '() => number'.
Type 'string | number' is not assignable to type 'number'.
Type '() => number | string' is not assignable to type '() => number'.
Type 'number | string' is not assignable to type 'number'.
Type 'string' is not assignable to type 'number'.
tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatBetweenTupleAndArray.ts(18,1): error TS2322: Type '{}[]' is not assignable to type '[{}]'.
Property '0' is missing in type '{}[]'.
@@ -28,8 +28,8 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme
~~~~~~~~
!!! error TS2322: Type '[number, string]' is not assignable to type 'number[]'.
!!! error TS2322: Types of property 'pop' are incompatible.
!!! error TS2322: Type '() => string | number' is not assignable to type '() => number'.
!!! error TS2322: Type 'string | number' is not assignable to type 'number'.
!!! error TS2322: Type '() => number | string' is not assignable to type '() => number'.
!!! error TS2322: Type 'number | string' is not assignable to type 'number'.
!!! error TS2322: Type 'string' is not assignable to type 'number'.
emptyObjTuple = emptyObjArray;
~~~~~~~~~~~~~

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