Merge branch 'master' into fix4211

This commit is contained in:
Yui T
2015-12-14 21:51:36 -08:00
4998 changed files with 65827 additions and 28698 deletions
+4 -2
View File
@@ -36,11 +36,13 @@ Your pull request should:
The library sources are in: [src/lib](https://github.com/Microsoft/TypeScript/tree/master/src/lib)
To build the library files, run
Library files in `built/local/` are updated by running
```Shell
jake lib
jake
```
The files in `lib/` are used to bootstrap compilation and usually do not need to be updated.
#### `src/lib/dom.generated.d.ts` and `src/lib/webworker.generated.d.ts`
These two files represent the DOM typings and are auto-generated. To make any modifications to them, please submit a PR to https://github.com/Microsoft/TSJS-lib-generator
+16 -7
View File
@@ -40,6 +40,7 @@ var compilerSources = [
"utilities.ts",
"binder.ts",
"checker.ts",
"sourcemap.ts",
"declarationEmitter.ts",
"emitter.ts",
"program.ts",
@@ -59,6 +60,7 @@ var servicesSources = [
"utilities.ts",
"binder.ts",
"checker.ts",
"sourcemap.ts",
"declarationEmitter.ts",
"emitter.ts",
"program.ts",
@@ -111,7 +113,8 @@ var scriptSources = [
"tslint/nextLineRule.ts",
"tslint/noNullRule.ts",
"tslint/preferConstRule.ts",
"tslint/typeOperatorSpacingRule.ts"
"tslint/typeOperatorSpacingRule.ts",
"tslint/noInOperatorRule.ts"
].map(function (f) {
return path.join(scriptsDirectory, f);
});
@@ -475,7 +478,7 @@ compileFile(servicesFile, servicesSources,[builtLocalDirectory, copyright].conca
var nodeDefinitionsFileContents = definitionFileContents + "\r\nexport = ts;";
fs.writeFileSync(nodeDefinitionsFile, nodeDefinitionsFileContents);
// Node package definition file to be distributed without the package. Created by replacing
// Node package definition file to be distributed without the package. Created by replacing
// 'ts' namespace with '"typescript"' as a module.
var nodeStandaloneDefinitionsFileContents = definitionFileContents.replace(/declare (namespace|module) ts/g, 'declare module "typescript"');
fs.writeFileSync(nodeStandaloneDefinitionsFile, nodeStandaloneDefinitionsFileContents);
@@ -541,7 +544,8 @@ compileFile(word2mdJs,
// The generated spec.md; built for the 'generate-spec' task
file(specMd, [word2mdJs, specWord], function () {
var specWordFullPath = path.resolve(specWord);
var cmd = "cscript //nologo " + word2mdJs + ' "' + specWordFullPath + '" ' + specMd;
var specMDFullPath = path.resolve(specMd);
var cmd = "cscript //nologo " + word2mdJs + ' "' + specWordFullPath + '" ' + '"' + specMDFullPath + '"';
console.log(cmd);
child_process.exec(cmd, function () {
complete();
@@ -873,7 +877,8 @@ var tslintRules = ([
"noNullRule",
"preferConstRule",
"booleanTriviaRule",
"typeOperatorSpacingRule"
"typeOperatorSpacingRule",
"noInOperatorRule"
]);
var tslintRulesFiles = tslintRules.map(function(p) {
return path.join(tslintRuleDir, p + ".ts");
@@ -884,7 +889,7 @@ var tslintRulesOutFiles = tslintRules.map(function(p) {
desc("Compiles tslint rules to js");
task("build-rules", tslintRulesOutFiles);
tslintRulesFiles.forEach(function(ruleFile, i) {
compileFile(tslintRulesOutFiles[i], [ruleFile], [ruleFile], [], /*useBuiltCompiler*/ false, /*noOutFile*/ true, /*generateDeclarations*/ false, path.join(builtLocalDirectory, "tslint"));
compileFile(tslintRulesOutFiles[i], [ruleFile], [ruleFile], [], /*useBuiltCompiler*/ false, /*noOutFile*/ true, /*generateDeclarations*/ false, path.join(builtLocalDirectory, "tslint"));
});
function getLinterOptions() {
@@ -924,13 +929,17 @@ var lintTargets = compilerSources
desc("Runs tslint on the compiler sources");
task("lint", ["build-rules"], function() {
var lintOptions = getLinterOptions();
var failed = 0;
for (var i in lintTargets) {
var result = lintFile(lintOptions, lintTargets[i]);
if (result.failureCount > 0) {
console.log(result.output);
fail('Linter errors.', result.failureCount);
failed += result.failureCount;
}
}
if (failed > 0) {
fail('Linter errors.', failed);
}
});
/**
@@ -947,7 +956,7 @@ function lintWatchFile(filename) {
if (event !== "change") {
return;
}
if (!lintSemaphores[filename]) {
lintSemaphores[filename] = true;
lintFileAsync(getLinterOptions(), filename, function(err, result) {
Binary file not shown.
+1 -1
View File
@@ -1323,7 +1323,7 @@ x = "hello"; // Ok
x = 42; // Ok
x = test; // Error, boolean not assignable
x = test ? 5 : "five"; // Ok
x = test ? 0 : false; // Error, number | boolean not asssignable
x = test ? 0 : false; // Error, number | boolean not assignable
```
it is possible to assign 'x' a value of type `string`, `number`, or the union type `string | number`, but not any other type. To access a value in 'x', a type guard can be used to first narrow the type of 'x' to either `string` or `number`:
+1 -1
View File
@@ -1,4 +1,4 @@
# Read this!
These files are not meant to be edited by hand.
If you need to make modifications, the respective files should be changed within the repository's top-level `src` directory.
If you need to make modifications, the respective files should be changed within the repository's top-level `src` directory. Running `jake LKG` will then appropriately update the files in this directory.
+20
View File
@@ -0,0 +1,20 @@
import * as Lint from "tslint/lib/lint";
import * as ts from "typescript";
export class Rule extends Lint.Rules.AbstractRule {
public static FAILURE_STRING = "Don't use the 'in' keyword - use 'hasProperty' to check for key presence instead";
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithWalker(new InWalker(sourceFile, this.getOptions()));
}
}
class InWalker extends Lint.RuleWalker {
visitNode(node: ts.Node) {
super.visitNode(node);
if (node.kind === ts.SyntaxKind.InKeyword && node.parent && node.parent.kind === ts.SyntaxKind.BinaryExpression) {
this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING));
}
}
}
+75 -8
View File
@@ -222,8 +222,21 @@ namespace ts {
case SyntaxKind.ExportAssignment:
return (<ExportAssignment>node).isExportEquals ? "export=" : "default";
case SyntaxKind.BinaryExpression:
// Binary expression case is for JS module 'module.exports = expr'
return "export=";
switch (getSpecialPropertyAssignmentKind(node)) {
case SpecialPropertyAssignmentKind.ModuleExports:
// module.exports = ...
return "export=";
case SpecialPropertyAssignmentKind.ExportsProperty:
case SpecialPropertyAssignmentKind.ThisProperty:
// exports.x = ... or this.y = ...
return ((node as BinaryExpression).left as PropertyAccessExpression).name.text;
case SpecialPropertyAssignmentKind.PrototypeProperty:
// className.prototype.methodName = ...
return (((node as BinaryExpression).left as PropertyAccessExpression).expression as PropertyAccessExpression).name.text;
}
Debug.fail("Unknown binary declaration kind");
break;
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.ClassDeclaration:
return node.flags & NodeFlags.Default ? "default" : undefined;
@@ -1166,11 +1179,25 @@ namespace ts {
return checkStrictModeIdentifier(<Identifier>node);
case SyntaxKind.BinaryExpression:
if (isInJavaScriptFile(node)) {
if (isExportsPropertyAssignment(node)) {
bindExportsPropertyAssignment(<BinaryExpression>node);
}
else if (isModuleExportsAssignment(node)) {
bindModuleExportsAssignment(<BinaryExpression>node);
const specialKind = getSpecialPropertyAssignmentKind(node);
switch (specialKind) {
case SpecialPropertyAssignmentKind.ExportsProperty:
bindExportsPropertyAssignment(<BinaryExpression>node);
break;
case SpecialPropertyAssignmentKind.ModuleExports:
bindModuleExportsAssignment(<BinaryExpression>node);
break;
case SpecialPropertyAssignmentKind.PrototypeProperty:
bindPrototypePropertyAssignment(<BinaryExpression>node);
break;
case SpecialPropertyAssignmentKind.ThisProperty:
bindThisPropertyAssignment(<BinaryExpression>node);
break;
case SpecialPropertyAssignmentKind.None:
// Nothing to do
break;
default:
Debug.fail("Unknown special property assignment kind");
}
}
return checkStrictModeBinaryExpression(<BinaryExpression>node);
@@ -1189,7 +1216,8 @@ namespace ts {
case SyntaxKind.ThisType:
seenThisKeyword = true;
return;
case SyntaxKind.TypePredicate:
return checkTypePredicate(node as TypePredicateNode);
case SyntaxKind.TypeParameter:
return declareSymbolAndAddToSymbolTable(<Declaration>node, SymbolFlags.TypeParameter, SymbolFlags.TypeParameterExcludes);
case SyntaxKind.Parameter:
@@ -1275,6 +1303,17 @@ namespace ts {
}
}
function checkTypePredicate(node: TypePredicateNode) {
const { parameterName, type } = node;
if (parameterName && parameterName.kind === SyntaxKind.Identifier) {
checkStrictModeIdentifier(parameterName as Identifier);
}
if (parameterName && parameterName.kind === SyntaxKind.ThisType) {
seenThisKeyword = true;
}
bind(type);
}
function bindSourceFileIfExternalModule() {
setExportContextFlag(file);
if (isExternalModule(file)) {
@@ -1339,6 +1378,34 @@ namespace ts {
bindExportAssignment(node);
}
function bindThisPropertyAssignment(node: BinaryExpression) {
// Declare a 'member' in case it turns out the container was an ES5 class
if (container.kind === SyntaxKind.FunctionExpression || container.kind === SyntaxKind.FunctionDeclaration) {
container.symbol.members = container.symbol.members || {};
declareSymbol(container.symbol.members, container.symbol, node, SymbolFlags.Property, SymbolFlags.PropertyExcludes);
}
}
function bindPrototypePropertyAssignment(node: BinaryExpression) {
// We saw a node of the form 'x.prototype.y = z'. Declare a 'member' y on x if x was a function.
// Look up the function in the local scope, since prototype assignments should
// follow the function declaration
const classId = <Identifier>(<PropertyAccessExpression>(<PropertyAccessExpression>node.left).expression).expression;
const funcSymbol = container.locals[classId.text];
if (!funcSymbol || !(funcSymbol.flags & SymbolFlags.Function)) {
return;
}
// Set up the members collection if it doesn't exist already
if (!funcSymbol.members) {
funcSymbol.members = {};
}
// Declare the method/property
declareSymbol(funcSymbol.members, funcSymbol, <PropertyAccessExpression>node.left, SymbolFlags.Property, SymbolFlags.PropertyExcludes);
}
function bindCallExpression(node: CallExpression) {
// We're only inspecting call expressions to detect CommonJS modules, so we can skip
// this check if we've already seen the module indicator
+787 -449
View File
File diff suppressed because it is too large Load Diff
+27
View File
@@ -356,6 +356,33 @@ namespace ts {
return result;
}
/**
* Reduce the properties of a map.
*
* @param map The map to reduce
* @param callback An aggregation function that is called for each entry in the map
* @param initial The initial value for the reduction.
*/
export function reduceProperties<T, U>(map: Map<T>, callback: (aggregate: U, value: T, key: string) => U, initial: U): U {
let result = initial;
if (map) {
for (const key in map) {
if (hasProperty(map, key)) {
result = callback(result, map[key], String(key));
}
}
}
return result;
}
/**
* Tests whether a value is an array.
*/
export function isArray(value: any): value is any[] {
return Array.isArray ? Array.isArray(value) : value instanceof Array;
}
export function memoize<T>(callback: () => T): () => T {
let value: T;
return () => {
+4 -4
View File
@@ -1309,6 +1309,9 @@ namespace ts {
}
function emitSignatureDeclaration(node: SignatureDeclaration) {
const prevEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = node;
// Construct signature or constructor type write new Signature
if (node.kind === SyntaxKind.ConstructSignature || node.kind === SyntaxKind.ConstructorType) {
write("new ");
@@ -1321,9 +1324,6 @@ namespace ts {
write("(");
}
const prevEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = node;
// Parameters
emitCommaList(node.parameters, emitParameterDeclaration);
@@ -1675,7 +1675,7 @@ namespace ts {
/* @internal */
export function writeDeclarationFile(declarationFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean, host: EmitHost, resolver: EmitResolver, emitterDiagnostics: DiagnosticCollection) {
const emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit);
const emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath);
const emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit;
if (!emitSkipped) {
const declarationOutput = emitDeclarationResult.referencePathsOutput
+ getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo);
+39 -4
View File
@@ -435,7 +435,7 @@
"category": "Error",
"code": 1147
},
"Cannot compile modules unless the '--module' flag is provided.": {
"Cannot compile modules unless the '--module' flag is provided. Consider setting the 'module' compiler option in a 'tsconfig.json' file.": {
"category": "Error",
"code": 1148
},
@@ -783,7 +783,18 @@
"category": "Error",
"code": 1245
},
"An interface property cannot have an initializer.": {
"category": "Error",
"code": 1246
},
"A type literal property cannot have an initializer.": {
"category": "Error",
"code": 1247
},
"A class member cannot have the '{0}' keyword.": {
"category": "Error",
"code": 1248
},
"'with' statements are not allowed in an async function block.": {
"category": "Error",
"code": 1300
@@ -836,6 +847,10 @@
"category": "Error",
"code": 2307
},
"Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity.": {
"category": "Error",
"code": 2308
},
"An export assignment cannot be used in a module with other exported elements.": {
"category": "Error",
"code": 2309
@@ -852,7 +867,7 @@
"category": "Error",
"code": 2312
},
"Constraint of a type parameter cannot reference any type parameter from the same type parameter list.": {
"Type parameter '{0}' has a circular constraint.": {
"category": "Error",
"code": 2313
},
@@ -892,6 +907,10 @@
"category": "Error",
"code": 2322
},
"Cannot redeclare exported variable '{0}'.": {
"category": "Error",
"code": 2323
},
"Property '{0}' is missing in type '{1}'.": {
"category": "Error",
"code": 2324
@@ -1172,6 +1191,10 @@
"category": "Error",
"code": 2396
},
"Declaration name conflicts with built-in global identifier '{0}'.": {
"category": "Error",
"code": 2397
},
"Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference.": {
"category": "Error",
"code": 2399
@@ -1624,6 +1647,14 @@
"category": "Error",
"code": 2517
},
"A 'this'-based type guard is not compatible with a parameter-based type guard.": {
"category": "Error",
"code": 2518
},
"A 'this'-based type predicate is only allowed within a class or interface's members, get accessors, or return type positions for functions and methods.": {
"category": "Error",
"code": 2519
},
"Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions.": {
"category": "Error",
"code": 2520
@@ -1724,6 +1755,10 @@
"category": "Error",
"code": 2657
},
"Type '{0}' provides no match for the signature '{1}'": {
"category": "Error",
"code": 2658
},
"Import declaration '{0}' is using private name '{1}'.": {
"category": "Error",
"code": 4000
@@ -2430,7 +2465,7 @@
"Not all code paths return a value.": {
"category": "Error",
"code": 7030
},
},
"You cannot rename this element.": {
"category": "Error",
"code": 8000
+165 -548
View File
File diff suppressed because it is too large Load Diff
+69 -28
View File
@@ -1134,6 +1134,14 @@ namespace ts {
return token === t && tryParse(nextTokenCanFollowModifier);
}
function nextTokenIsOnSameLineAndCanFollowModifier() {
nextToken();
if (scanner.hasPrecedingLineBreak()) {
return false;
}
return canFollowModifier();
}
function nextTokenCanFollowModifier() {
if (token === SyntaxKind.ConstKeyword) {
// 'const' is only a modifier if followed by 'enum'.
@@ -1154,11 +1162,7 @@ namespace ts {
return canFollowModifier();
}
nextToken();
if (scanner.hasPrecedingLineBreak()) {
return false;
}
return canFollowModifier();
return nextTokenIsOnSameLineAndCanFollowModifier();
}
function parseAnyContextualModifier(): boolean {
@@ -1959,11 +1963,7 @@ namespace ts {
function parseTypeReferenceOrTypePredicate(): TypeReferenceNode | TypePredicateNode {
const typeName = parseEntityName(/*allowReservedWords*/ false, Diagnostics.Type_expected);
if (typeName.kind === SyntaxKind.Identifier && token === SyntaxKind.IsKeyword && !scanner.hasPrecedingLineBreak()) {
nextToken();
const node = <TypePredicateNode>createNode(SyntaxKind.TypePredicate, typeName.pos);
node.parameterName = <Identifier>typeName;
node.type = parseType();
return finishNode(node);
return parseTypePredicate(typeName as Identifier);
}
const node = <TypeReferenceNode>createNode(SyntaxKind.TypeReference, typeName.pos);
node.typeName = typeName;
@@ -1973,8 +1973,16 @@ namespace ts {
return finishNode(node);
}
function parseThisTypeNode(): TypeNode {
const node = <TypeNode>createNode(SyntaxKind.ThisType);
function parseTypePredicate(lhs: Identifier | ThisTypeNode): TypePredicateNode {
nextToken();
const node = createNode(SyntaxKind.TypePredicate, lhs.pos) as TypePredicateNode;
node.parameterName = lhs;
node.type = parseType();
return finishNode(node);
}
function parseThisTypeNode(): ThisTypeNode {
const node = createNode(SyntaxKind.ThisType) as ThisTypeNode;
nextToken();
return finishNode(node);
}
@@ -2259,6 +2267,14 @@ namespace ts {
property.name = name;
property.questionToken = questionToken;
property.type = parseTypeAnnotation();
if (token === SyntaxKind.EqualsToken) {
// Although type literal properties cannot not have initializers, we attempt
// to parse an initializer so we can report in the checker that an interface
// property or type literal property cannot have an initializer.
property.initializer = parseNonParameterInitializer();
}
parseTypeMemberSemicolon();
return finishNode(property);
}
@@ -2412,8 +2428,15 @@ namespace ts {
return parseStringLiteralTypeNode();
case SyntaxKind.VoidKeyword:
return parseTokenNode<TypeNode>();
case SyntaxKind.ThisKeyword:
return parseThisTypeNode();
case SyntaxKind.ThisKeyword: {
const thisKeyword = parseThisTypeNode();
if (token === SyntaxKind.IsKeyword && !scanner.hasPrecedingLineBreak()) {
return parseTypePredicate(thisKeyword);
}
else {
return thisKeyword;
}
}
case SyntaxKind.TypeOfKeyword:
return parseTypeQuery();
case SyntaxKind.OpenBraceToken:
@@ -3627,7 +3650,7 @@ namespace ts {
parseExpected(SyntaxKind.OpenBraceToken);
if (token !== SyntaxKind.CloseBraceToken) {
node.expression = parseExpression();
node.expression = parseAssignmentExpressionOrHigher();
}
if (inExpressionContext) {
parseExpected(SyntaxKind.CloseBraceToken);
@@ -3969,6 +3992,7 @@ namespace ts {
}
else {
const propertyAssignment = <PropertyAssignment>createNode(SyntaxKind.PropertyAssignment, fullStart);
propertyAssignment.modifiers = modifiers;
propertyAssignment.name = propertyName;
propertyAssignment.questionToken = questionToken;
parseExpected(SyntaxKind.ColonToken);
@@ -4902,7 +4926,7 @@ namespace ts {
if (!decorators) {
decorators = <NodeArray<Decorator>>[];
decorators.pos = scanner.getStartPos();
decorators.pos = decoratorStart;
}
const decorator = <Decorator>createNode(SyntaxKind.Decorator, decoratorStart);
@@ -4915,15 +4939,31 @@ namespace ts {
return decorators;
}
function parseModifiers(): ModifiersArray {
/*
* There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member.
* In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect
* and turns it into a standalone declaration), then it is better to parse it and report an error later.
*
* In such situations, 'permitInvalidConstAsModifier' should be set to true.
*/
function parseModifiers(permitInvalidConstAsModifier?: boolean): ModifiersArray {
let flags = 0;
let modifiers: ModifiersArray;
while (true) {
const modifierStart = scanner.getStartPos();
const modifierKind = token;
if (!parseAnyContextualModifier()) {
break;
if (token === SyntaxKind.ConstKeyword && permitInvalidConstAsModifier) {
// We need to ensure that any subsequent modifiers appear on the same line
// so that when 'const' is a standalone declaration, we don't issue an error.
if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) {
break;
}
}
else {
if (!parseAnyContextualModifier()) {
break;
}
}
if (!modifiers) {
@@ -4968,7 +5008,7 @@ namespace ts {
const fullStart = getNodePos();
const decorators = parseDecorators();
const modifiers = parseModifiers();
const modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true);
const accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers);
if (accessor) {
@@ -5302,16 +5342,17 @@ namespace ts {
}
function parseModuleSpecifier(): Expression {
// We allow arbitrary expressions here, even though the grammar only allows string
// literals. We check to ensure that it is only a string literal later in the grammar
// walker.
const result = parseExpression();
// Ensure the string being required is in our 'identifier' table. This will ensure
// that features like 'find refs' will look inside this file when search for its name.
if (result.kind === SyntaxKind.StringLiteral) {
if (token === SyntaxKind.StringLiteral) {
const result = parseLiteralNode();
internIdentifier((<LiteralExpression>result).text);
return result;
}
else {
// We allow arbitrary expressions here, even though the grammar only allows string
// literals. We check to ensure that it is only a string literal later in the grammar
// check pass.
return parseExpression();
}
return result;
}
function parseNamespaceImport(): NamespaceImport {
+10 -10
View File
@@ -99,7 +99,7 @@ namespace ts {
jsonContent = { typings: undefined };
}
if (jsonContent.typings) {
if (typeof jsonContent.typings === "string") {
const result = loadNodeModuleFromFile(extensions, normalizePath(combinePaths(candidate, jsonContent.typings)), failedLookupLocation, host);
if (result) {
return result;
@@ -661,19 +661,17 @@ namespace ts {
}
function getSemanticDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {
// For JavaScript files, we don't want to report the normal typescript semantic errors.
// Instead, we just report errors for using TypeScript-only constructs from within a
// JavaScript file.
if (isSourceFileJavaScript(sourceFile)) {
return getJavaScriptSemanticDiagnosticsForFile(sourceFile, cancellationToken);
}
return runWithCancellationToken(() => {
const typeChecker = getDiagnosticsProducingTypeChecker();
Debug.assert(!!sourceFile.bindDiagnostics);
const bindDiagnostics = sourceFile.bindDiagnostics;
const checkDiagnostics = typeChecker.getDiagnostics(sourceFile, cancellationToken);
// For JavaScript files, we don't want to report the normal typescript semantic errors.
// Instead, we just report errors for using TypeScript-only constructs from within a
// JavaScript file.
const checkDiagnostics = isSourceFileJavaScript(sourceFile) ?
getJavaScriptSemanticDiagnosticsForFile(sourceFile, cancellationToken) :
typeChecker.getDiagnostics(sourceFile, cancellationToken);
const fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName);
const programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName);
@@ -1079,6 +1077,8 @@ namespace ts {
const importedFile = findSourceFile(resolution.resolvedFileName, toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), /*isDefaultLib*/ false, file, skipTrivia(file.text, file.imports[i].pos), file.imports[i].end);
if (importedFile && resolution.isExternalLibraryImport) {
// Since currently irrespective of allowJs, we only look for supportedTypeScript extension external module files,
// this check is ok. Otherwise this would be never true for javascript file
if (!isExternalModule(importedFile)) {
const start = getTokenPosOfNode(file.imports[i], file);
fileProcessingDiagnostics.add(createFileDiagnostic(file, start, file.imports[i].end - start, Diagnostics.Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition, importedFile.fileName));
@@ -1234,7 +1234,7 @@ namespace ts {
else if (firstExternalModuleSourceFile && languageVersion < ScriptTarget.ES6 && !options.module) {
// We cannot use createDiagnosticFromNode because nodes do not have parents yet
const span = getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator);
programDiagnostics.add(createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided));
programDiagnostics.add(createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file));
}
// Cannot specify module gen target of es6 when below es6
+8 -2
View File
@@ -425,6 +425,12 @@ namespace ts {
/* @internal */
export function skipTrivia(text: string, pos: number, stopAfterLineBreak?: boolean): number {
// Using ! with a greater than test is a fast way of testing the following conditions:
// pos === undefined || pos === null || isNaN(pos) || pos < 0;
if (!(pos >= 0)) {
return pos;
}
// Keep in sync with couldStartTrivia
while (true) {
const ch = text.charCodeAt(pos);
@@ -567,12 +573,12 @@ namespace ts {
}
/**
* Extract comments from text prefixing the token closest following `pos`.
* Extract comments from text prefixing the token closest following `pos`.
* The return value is an array containing a TextRange for each comment.
* Single-line comment ranges include the beginning '//' characters but not the ending line break.
* Multi - line comment ranges include the beginning '/* and ending '<asterisk>/' characters.
* The return value is undefined if no comments were found.
* @param trailing
* @param trailing
* If false, whitespace is skipped until the first line break and comments between that location
* and the next token are returned.
* If true, comments occurring between the given position and the next line break are returned.
+332
View File
@@ -0,0 +1,332 @@
/// <reference path="checker.ts"/>
/* @internal */
namespace ts {
export interface SourceMapWriter {
getSourceMapData(): SourceMapData;
setSourceFile(sourceFile: SourceFile): void;
emitPos(pos: number): void;
emitStart(range: TextRange): void;
emitEnd(range: TextRange): void;
getText(): string;
getSourceMappingURL(): string;
initialize(filePath: string, sourceMapFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean): void;
reset(): void;
}
const nop = <(...args: any[]) => any>Function.prototype;
let nullSourceMapWriter: SourceMapWriter;
export function getNullSourceMapWriter(): SourceMapWriter {
if (nullSourceMapWriter === undefined) {
nullSourceMapWriter = {
getSourceMapData(): SourceMapData { return undefined; },
setSourceFile(sourceFile: SourceFile): void { },
emitStart(range: TextRange): void { },
emitEnd(range: TextRange): void { },
emitPos(pos: number): void { },
getText(): string { return undefined; },
getSourceMappingURL(): string { return undefined; },
initialize(filePath: string, sourceMapFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean): void { },
reset(): void { },
};
}
return nullSourceMapWriter;
}
export function createSourceMapWriter(host: EmitHost, writer: EmitTextWriter): SourceMapWriter {
const compilerOptions = host.getCompilerOptions();
let currentSourceFile: SourceFile;
let sourceMapDir: string; // The directory in which sourcemap will be
// Current source map file and its index in the sources list
let sourceMapSourceIndex: number;
// Last recorded and encoded spans
let lastRecordedSourceMapSpan: SourceMapSpan;
let lastEncodedSourceMapSpan: SourceMapSpan;
let lastEncodedNameIndex: number;
// Source map data
let sourceMapData: SourceMapData;
return {
getSourceMapData: () => sourceMapData,
setSourceFile,
emitPos,
emitStart,
emitEnd,
getText,
getSourceMappingURL,
initialize,
reset,
};
function initialize(filePath: string, sourceMapFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean) {
if (sourceMapData) {
reset();
}
currentSourceFile = undefined;
// Current source map file and its index in the sources list
sourceMapSourceIndex = -1;
// Last recorded and encoded spans
lastRecordedSourceMapSpan = undefined;
lastEncodedSourceMapSpan = {
emittedLine: 1,
emittedColumn: 1,
sourceLine: 1,
sourceColumn: 1,
sourceIndex: 0
};
lastEncodedNameIndex = 0;
// Initialize source map data
sourceMapData = {
sourceMapFilePath: sourceMapFilePath,
jsSourceMappingURL: !compilerOptions.inlineSourceMap ? getBaseFileName(normalizeSlashes(sourceMapFilePath)) : undefined,
sourceMapFile: getBaseFileName(normalizeSlashes(filePath)),
sourceMapSourceRoot: compilerOptions.sourceRoot || "",
sourceMapSources: [],
inputSourceFileNames: [],
sourceMapNames: [],
sourceMapMappings: "",
sourceMapSourcesContent: compilerOptions.inlineSources ? [] : undefined,
sourceMapDecodedMappings: []
};
// Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the
// relative paths of the sources list in the sourcemap
sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot);
if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== CharacterCodes.slash) {
sourceMapData.sourceMapSourceRoot += directorySeparator;
}
if (compilerOptions.mapRoot) {
sourceMapDir = normalizeSlashes(compilerOptions.mapRoot);
if (!isBundledEmit) { // emitting single module file
Debug.assert(sourceFiles.length === 1);
// For modules or multiple emit files the mapRoot will have directory structure like the sources
// So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map
sourceMapDir = getDirectoryPath(getSourceFilePathInNewDir(sourceFiles[0], host, sourceMapDir));
}
if (!isRootedDiskPath(sourceMapDir) && !isUrl(sourceMapDir)) {
// The relative paths are relative to the common directory
sourceMapDir = combinePaths(host.getCommonSourceDirectory(), sourceMapDir);
sourceMapData.jsSourceMappingURL = getRelativePathToDirectoryOrUrl(
getDirectoryPath(normalizePath(filePath)), // get the relative sourceMapDir path based on jsFilePath
combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), // this is where user expects to see sourceMap
host.getCurrentDirectory(),
host.getCanonicalFileName,
/*isAbsolutePathAnUrl*/ true);
}
else {
sourceMapData.jsSourceMappingURL = combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL);
}
}
else {
sourceMapDir = getDirectoryPath(normalizePath(filePath));
}
}
function reset() {
currentSourceFile = undefined;
sourceMapDir = undefined;
sourceMapSourceIndex = undefined;
lastRecordedSourceMapSpan = undefined;
lastEncodedSourceMapSpan = undefined;
lastEncodedNameIndex = undefined;
sourceMapData = undefined;
}
// Encoding for sourcemap span
function encodeLastRecordedSourceMapSpan() {
if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) {
return;
}
let prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn;
// Line/Comma delimiters
if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) {
// Emit comma to separate the entry
if (sourceMapData.sourceMapMappings) {
sourceMapData.sourceMapMappings += ",";
}
}
else {
// Emit line delimiters
for (let encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) {
sourceMapData.sourceMapMappings += ";";
}
prevEncodedEmittedColumn = 1;
}
// 1. Relative Column 0 based
sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn);
// 2. Relative sourceIndex
sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex);
// 3. Relative sourceLine 0 based
sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine);
// 4. Relative sourceColumn 0 based
sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn);
// 5. Relative namePosition 0 based
if (lastRecordedSourceMapSpan.nameIndex >= 0) {
sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex);
lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex;
}
lastEncodedSourceMapSpan = lastRecordedSourceMapSpan;
sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan);
}
function emitPos(pos: number) {
if (pos === -1) {
return;
}
const sourceLinePos = getLineAndCharacterOfPosition(currentSourceFile, pos);
// Convert the location to be one-based.
sourceLinePos.line++;
sourceLinePos.character++;
const emittedLine = writer.getLine();
const emittedColumn = writer.getColumn();
// If this location wasn't recorded or the location in source is going backwards, record the span
if (!lastRecordedSourceMapSpan ||
lastRecordedSourceMapSpan.emittedLine !== emittedLine ||
lastRecordedSourceMapSpan.emittedColumn !== emittedColumn ||
(lastRecordedSourceMapSpan.sourceIndex === sourceMapSourceIndex &&
(lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line ||
(lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) {
// Encode the last recordedSpan before assigning new
encodeLastRecordedSourceMapSpan();
// New span
lastRecordedSourceMapSpan = {
emittedLine: emittedLine,
emittedColumn: emittedColumn,
sourceLine: sourceLinePos.line,
sourceColumn: sourceLinePos.character,
sourceIndex: sourceMapSourceIndex
};
}
else {
// Take the new pos instead since there is no change in emittedLine and column since last location
lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line;
lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character;
lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex;
}
}
function emitStart(range: TextRange) {
const rangeHasDecorators = !!(range as Node).decorators;
emitPos(range.pos !== -1 ? skipTrivia(currentSourceFile.text, rangeHasDecorators ? (range as Node).decorators.end : range.pos) : -1);
}
function emitEnd(range: TextRange) {
emitPos(range.end);
}
function setSourceFile(sourceFile: SourceFile) {
currentSourceFile = sourceFile;
// Add the file to tsFilePaths
// If sourceroot option: Use the relative path corresponding to the common directory path
// otherwise source locations relative to map file location
const sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir;
const source = getRelativePathToDirectoryOrUrl(sourcesDirectoryPath,
currentSourceFile.fileName,
host.getCurrentDirectory(),
host.getCanonicalFileName,
/*isAbsolutePathAnUrl*/ true);
sourceMapSourceIndex = indexOf(sourceMapData.sourceMapSources, source);
if (sourceMapSourceIndex === -1) {
sourceMapSourceIndex = sourceMapData.sourceMapSources.length;
sourceMapData.sourceMapSources.push(source);
// The one that can be used from program to get the actual source file
sourceMapData.inputSourceFileNames.push(sourceFile.fileName);
if (compilerOptions.inlineSources) {
sourceMapData.sourceMapSourcesContent.push(sourceFile.text);
}
}
}
function getText() {
encodeLastRecordedSourceMapSpan();
return stringify({
version: 3,
file: sourceMapData.sourceMapFile,
sourceRoot: sourceMapData.sourceMapSourceRoot,
sources: sourceMapData.sourceMapSources,
names: sourceMapData.sourceMapNames,
mappings: sourceMapData.sourceMapMappings,
sourcesContent: sourceMapData.sourceMapSourcesContent,
});
}
function getSourceMappingURL() {
if (compilerOptions.inlineSourceMap) {
// Encode the sourceMap into the sourceMap url
const base64SourceMapText = convertToBase64(getText());
return sourceMapData.jsSourceMappingURL = `data:application/json;base64,${base64SourceMapText}`;
}
else {
return sourceMapData.jsSourceMappingURL;
}
}
}
const base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
function base64FormatEncode(inValue: number) {
if (inValue < 64) {
return base64Chars.charAt(inValue);
}
throw TypeError(inValue + ": not a 64 based value");
}
function base64VLQFormatEncode(inValue: number) {
// Add a new least significant bit that has the sign of the value.
// if negative number the least significant bit that gets added to the number has value 1
// else least significant bit value that gets added is 0
// eg. -1 changes to binary : 01 [1] => 3
// +1 changes to binary : 01 [0] => 2
if (inValue < 0) {
inValue = ((-inValue) << 1) + 1;
}
else {
inValue = inValue << 1;
}
// Encode 5 bits at a time starting from least significant bits
let encodedStr = "";
do {
let currentDigit = inValue & 31; // 11111
inValue = inValue >> 5;
if (inValue > 0) {
// There are still more digits to decode, set the msb (6th bit)
currentDigit = currentDigit | 32;
}
encodedStr = encodedStr + base64FormatEncode(currentDigit);
} while (inValue > 0);
return encodedStr;
}
}
+58 -7
View File
@@ -47,6 +47,25 @@ namespace ts {
constructor(o: any);
}
declare var ChakraHost: {
args: string[];
currentDirectory: string;
executingFile: string;
newLine?: string;
useCaseSensitiveFileNames?: boolean;
echo(s: string): void;
quit(exitCode?: number): void;
fileExists(path: string): boolean;
directoryExists(path: string): boolean;
createDirectory(path: string): void;
resolvePath(path: string): string;
readFile(path: string): string;
writeFile(path: string, contents: string): void;
readDirectory(path: string, extension?: string, exclude?: string[]): string[];
watchFile?(path: string, callback: (path: string, removed?: boolean) => void): FileWatcher;
watchDirectory?(path: string, callback: (path: string) => void, recursive?: boolean): FileWatcher;
};
export var sys: System = (function () {
function getWScriptSystem(): System {
@@ -194,6 +213,7 @@ namespace ts {
}
};
}
function getNodeSystem(): System {
const _fs = require("fs");
const _path = require("path");
@@ -281,7 +301,7 @@ namespace ts {
// REVIEW: for now this implementation uses polling.
// The advantage of polling is that it works reliably
// on all os and with network mounted files.
// For 90 referenced files, the average time to detect
// For 90 referenced files, the average time to detect
// changes is 2*msInterval (by default 5 seconds).
// The overhead of this is .04 percent (1/2500) with
// average pause of < 1 millisecond (and max
@@ -395,18 +415,13 @@ namespace ts {
// and is more efficient than `fs.watchFile` (ref: https://github.com/nodejs/node/pull/2649
// and https://github.com/Microsoft/TypeScript/issues/4643), therefore
// if the current node.js version is newer than 4, use `fs.watch` instead.
if (isNode4OrLater()) {
// Note: in node the callback of fs.watch is given only the relative file name as a parameter
return _fs.watch(fileName, (eventName: string, relativeFileName: string) => callback(fileName));
}
const watchedFile = watchedFileSet.addFile(fileName, callback);
return {
close: () => watchedFileSet.removeFile(watchedFile)
};
},
watchDirectory: (path, callback, recursive) => {
// Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
// Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
// (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643)
return _fs.watch(
path,
@@ -454,6 +469,37 @@ namespace ts {
}
};
}
function getChakraSystem(): System {
return {
newLine: ChakraHost.newLine || "\r\n",
args: ChakraHost.args,
useCaseSensitiveFileNames: !!ChakraHost.useCaseSensitiveFileNames,
write: ChakraHost.echo,
readFile(path: string, encoding?: string) {
// encoding is automatically handled by the implementation in ChakraHost
return ChakraHost.readFile(path);
},
writeFile(path: string, data: string, writeByteOrderMark?: boolean) {
// If a BOM is required, emit one
if (writeByteOrderMark) {
data = "\uFEFF" + data;
}
ChakraHost.writeFile(path, data);
},
resolvePath: ChakraHost.resolvePath,
fileExists: ChakraHost.fileExists,
directoryExists: ChakraHost.directoryExists,
createDirectory: ChakraHost.createDirectory,
getExecutingFilePath: () => ChakraHost.executingFile,
getCurrentDirectory: () => ChakraHost.currentDirectory,
readDirectory: ChakraHost.readDirectory,
exit: ChakraHost.quit,
};
}
if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") {
return getWScriptSystem();
}
@@ -462,8 +508,13 @@ namespace ts {
// process.browser check excludes webpack and browserify
return getNodeSystem();
}
else if (typeof ChakraHost !== "undefined") {
return getChakraSystem();
}
else {
return undefined; // Unsupported host
}
})();
}
+55 -10
View File
@@ -439,12 +439,16 @@ namespace ts {
export const enum JsxFlags {
None = 0,
/** An element from a named property of the JSX.IntrinsicElements interface */
IntrinsicNamedElement = 1 << 0,
/** An element inferred from the string index signature of the JSX.IntrinsicElements interface */
IntrinsicIndexedElement = 1 << 1,
ClassElement = 1 << 2,
UnknownElement = 1 << 3,
/** An element backed by a class, class-like, or function value */
ValueElement = 1 << 2,
/** Element resolution failed */
UnknownElement = 1 << 4,
IntrinsicElement = IntrinsicNamedElement | IntrinsicIndexedElement
IntrinsicElement = IntrinsicNamedElement | IntrinsicIndexedElement,
}
@@ -587,6 +591,7 @@ namespace ts {
name: PropertyName; // Declared property name
questionToken?: Node; // Present on optional property
type?: TypeNode; // Optional type annotation
initializer?: Expression; // Optional initializer
}
// @kind(SyntaxKind.PropertyDeclaration)
@@ -728,11 +733,15 @@ namespace ts {
// @kind(SyntaxKind.StringKeyword)
// @kind(SyntaxKind.SymbolKeyword)
// @kind(SyntaxKind.VoidKeyword)
// @kind(SyntaxKind.ThisType)
export interface TypeNode extends Node {
_typeNodeBrand: any;
}
// @kind(SyntaxKind.ThisType)
export interface ThisTypeNode extends TypeNode {
_thisTypeNodeBrand: any;
}
export interface FunctionOrConstructorTypeNode extends TypeNode, SignatureDeclaration {
_functionOrConstructorTypeNodeBrand: any;
}
@@ -751,7 +760,7 @@ namespace ts {
// @kind(SyntaxKind.TypePredicate)
export interface TypePredicateNode extends TypeNode {
parameterName: Identifier;
parameterName: Identifier | ThisTypeNode;
type: TypeNode;
}
@@ -1752,7 +1761,7 @@ namespace ts {
export interface SymbolDisplayBuilder {
buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void;
buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void;
buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaraiton?: Node, flags?: TypeFormatFlags): void;
@@ -1815,10 +1824,25 @@ namespace ts {
CannotBeNamed
}
export const enum TypePredicateKind {
This,
Identifier
}
export interface TypePredicate {
kind: TypePredicateKind;
type: Type;
}
// @kind (TypePredicateKind.This)
export interface ThisTypePredicate extends TypePredicate {
_thisTypePredicateBrand: any;
}
// @kind (TypePredicateKind.Identifier)
export interface IdentifierTypePredicate extends TypePredicate {
parameterName: string;
parameterIndex: number;
type: Type;
}
/* @internal */
@@ -1882,6 +1906,7 @@ namespace ts {
getReferencedValueDeclaration(reference: Identifier): Declaration;
getTypeReferenceSerializationKind(typeName: EntityName): TypeReferenceSerializationKind;
isOptionalParameter(node: ParameterDeclaration): boolean;
moduleExportsSomeValue(moduleReferenceExpression: Expression): boolean;
isArgumentsLocalBinding(node: Identifier): boolean;
getExternalModuleFileFromDeclaration(declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration): SourceFile;
}
@@ -1992,6 +2017,7 @@ namespace ts {
type?: Type; // Type of value symbol
declaredType?: Type; // Type of class, interface, enum, type alias, or type parameter
typeParameters?: TypeParameter[]; // Type parameters of type alias (undefined if non-generic)
inferredClassType?: Type; // Type of an inferred ES5 class
instantiations?: Map<Type>; // Instantiations of generic type alias (undefined if non-generic)
mapper?: TypeMapper; // Type mapper for instantiation alias
referenced?: boolean; // True if alias symbol has been referenced as a value
@@ -2000,6 +2026,7 @@ namespace ts {
exportsChecked?: boolean; // True if exports of external module have been checked
isNestedRedeclaration?: boolean; // True if symbol is block scoped redeclaration
bindingElement?: BindingElement; // Binding element associated with property symbol
exportsSomeValue?: boolean; // true if module exports some value (not just types)
}
/* @internal */
@@ -2042,7 +2069,6 @@ namespace ts {
resolvedSymbol?: Symbol; // Cached name resolution result
flags?: NodeCheckFlags; // Set of flags specific to Node
enumMemberValue?: number; // Constant value of enum member
isIllegalTypeReferenceInConstraint?: boolean; // Is type reference in constraint refers to the type parameter from the same list
isVisible?: boolean; // Is this node visible
generatedName?: string; // Generated name for module, enum, or import declaration
generatedNames?: Map<string>; // Generated names table for source file
@@ -2086,6 +2112,7 @@ namespace ts {
ESSymbol = 0x01000000, // Type of symbol primitive introduced in ES6
ThisType = 0x02000000, // This type
ObjectLiteralPatternWithComputedProperties = 0x04000000, // Object literal type implied by binding pattern has computed properties
PredicateType = 0x08000000, // Predicate types are also Boolean types, but should not be considered Intrinsics - there's no way to capture this with flags
/* @internal */
Intrinsic = Any | String | Number | Boolean | ESSymbol | Void | Undefined | Null,
@@ -2097,7 +2124,7 @@ namespace ts {
UnionOrIntersection = Union | Intersection,
StructuredType = ObjectType | Union | Intersection,
/* @internal */
RequiresWidening = ContainsUndefinedOrNull | ContainsObjectLiteral,
RequiresWidening = ContainsUndefinedOrNull | ContainsObjectLiteral | PredicateType,
/* @internal */
PropagatingFlags = ContainsUndefinedOrNull | ContainsObjectLiteral | ContainsAnyFunctionType
}
@@ -2118,6 +2145,11 @@ namespace ts {
intrinsicName: string; // Name of intrinsic type
}
// Predicate types (TypeFlags.Predicate)
export interface PredicateType extends Type {
predicate: ThisTypePredicate | IdentifierTypePredicate;
}
// String literal types (TypeFlags.StringLiteral)
export interface StringLiteralType extends Type {
text: string; // Text of string literal
@@ -2234,7 +2266,6 @@ namespace ts {
declaration: SignatureDeclaration; // Originating declaration
typeParameters: TypeParameter[]; // Type parameters (undefined if non-generic)
parameters: Symbol[]; // Parameters
typePredicate?: TypePredicate; // Type predicate
/* @internal */
resolvedReturnType: Type; // Resolved return type
/* @internal */
@@ -2283,10 +2314,24 @@ namespace ts {
inferUnionTypes: boolean; // Infer union types for disjoint candidates (otherwise undefinedType)
inferences: TypeInferences[]; // Inferences made for each type parameter
inferredTypes: Type[]; // Inferred type for each type parameter
mapper?: TypeMapper; // Type mapper for this inference context
failedTypeParameterIndex?: number; // Index of type parameter for which inference failed
// It is optional because in contextual signature instantiation, nothing fails
}
/* @internal */
export const enum SpecialPropertyAssignmentKind {
None,
/// exports.name = expr
ExportsProperty,
/// module.exports = expr
ModuleExports,
/// className.prototype.name = expr
PrototypeProperty,
/// this.name = expr
ThisProperty
}
export interface DiagnosticMessage {
key: string;
category: DiagnosticCategory;
+91 -45
View File
@@ -342,6 +342,7 @@ namespace ts {
case SyntaxKind.EnumMember:
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionExpression:
case SyntaxKind.MethodDeclaration:
errorNode = (<Declaration>node).name;
break;
}
@@ -692,6 +693,10 @@ namespace ts {
return node && node.kind === SyntaxKind.MethodDeclaration && node.parent.kind === SyntaxKind.ObjectLiteralExpression;
}
export function isIdentifierTypePredicate(predicate: TypePredicate): predicate is IdentifierTypePredicate {
return predicate && predicate.kind === TypePredicateKind.Identifier;
}
export function getContainingFunction(node: Node): FunctionLikeDeclaration {
while (true) {
node = node.parent;
@@ -906,23 +911,6 @@ namespace ts {
return false;
}
export function childIsDecorated(node: Node): boolean {
switch (node.kind) {
case SyntaxKind.ClassDeclaration:
return forEach((<ClassDeclaration>node).members, nodeOrChildIsDecorated);
case SyntaxKind.MethodDeclaration:
case SyntaxKind.SetAccessor:
return forEach((<FunctionLikeDeclaration>node).parameters, nodeIsDecorated);
}
return false;
}
export function nodeOrChildIsDecorated(node: Node): boolean {
return nodeIsDecorated(node) || childIsDecorated(node);
}
export function isPropertyAccessExpression(node: Node): node is PropertyAccessExpression {
return node.kind === SyntaxKind.PropertyAccessExpression;
}
@@ -1080,33 +1068,40 @@ namespace ts {
(<CallExpression>expression).arguments[0].kind === SyntaxKind.StringLiteral;
}
/**
* Returns true if the node is an assignment to a property on the identifier 'exports'.
* This function does not test if the node is in a JavaScript file or not.
*/
export function isExportsPropertyAssignment(expression: Node): boolean {
// of the form 'exports.name = expr' where 'name' and 'expr' are arbitrary
return isInJavaScriptFile(expression) &&
(expression.kind === SyntaxKind.BinaryExpression) &&
((<BinaryExpression>expression).operatorToken.kind === SyntaxKind.EqualsToken) &&
((<BinaryExpression>expression).left.kind === SyntaxKind.PropertyAccessExpression) &&
((<PropertyAccessExpression>(<BinaryExpression>expression).left).expression.kind === SyntaxKind.Identifier) &&
((<Identifier>((<PropertyAccessExpression>(<BinaryExpression>expression).left).expression)).text === "exports");
}
/// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property
/// assignments we treat as special in the binder
export function getSpecialPropertyAssignmentKind(expression: Node): SpecialPropertyAssignmentKind {
if (expression.kind !== SyntaxKind.BinaryExpression) {
return SpecialPropertyAssignmentKind.None;
}
const expr = <BinaryExpression>expression;
if (expr.operatorToken.kind !== SyntaxKind.EqualsToken || expr.left.kind !== SyntaxKind.PropertyAccessExpression) {
return SpecialPropertyAssignmentKind.None;
}
const lhs = <PropertyAccessExpression>expr.left;
if (lhs.expression.kind === SyntaxKind.Identifier) {
const lhsId = <Identifier>lhs.expression;
if (lhsId.text === "exports") {
// exports.name = expr
return SpecialPropertyAssignmentKind.ExportsProperty;
}
else if (lhsId.text === "module" && lhs.name.text === "exports") {
// module.exports = expr
return SpecialPropertyAssignmentKind.ModuleExports;
}
}
else if (lhs.expression.kind === SyntaxKind.ThisKeyword) {
return SpecialPropertyAssignmentKind.ThisProperty;
}
else if (lhs.expression.kind === SyntaxKind.PropertyAccessExpression) {
// chained dot, e.g. x.y.z = expr; this var is the 'x.y' part
const innerPropertyAccess = <PropertyAccessExpression>lhs.expression;
if (innerPropertyAccess.expression.kind === SyntaxKind.Identifier && innerPropertyAccess.name.text === "prototype") {
return SpecialPropertyAssignmentKind.PrototypeProperty;
}
}
/**
* Returns true if the node is an assignment to the property access expression 'module.exports'.
* This function does not test if the node is in a JavaScript file or not.
*/
export function isModuleExportsAssignment(expression: Node): boolean {
// of the form 'module.exports = expr' where 'expr' is arbitrary
return isInJavaScriptFile(expression) &&
(expression.kind === SyntaxKind.BinaryExpression) &&
((<BinaryExpression>expression).operatorToken.kind === SyntaxKind.EqualsToken) &&
((<BinaryExpression>expression).left.kind === SyntaxKind.PropertyAccessExpression) &&
((<PropertyAccessExpression>(<BinaryExpression>expression).left).expression.kind === SyntaxKind.Identifier) &&
((<Identifier>((<PropertyAccessExpression>(<BinaryExpression>expression).left).expression)).text === "module") &&
((<PropertyAccessExpression>(<BinaryExpression>expression).left).name.text === "exports");
return SpecialPropertyAssignmentKind.None;
}
export function getExternalModuleName(node: Node): Expression {
@@ -1906,8 +1901,10 @@ namespace ts {
* Resolves a local path to a path which is absolute to the base of the emit
*/
export function getExternalModuleNameFromPath(host: EmitHost, fileName: string): string {
const dir = toPath(host.getCommonSourceDirectory(), host.getCurrentDirectory(), f => host.getCanonicalFileName(f));
const relativePath = getRelativePathToDirectoryOrUrl(dir, fileName, dir, f => host.getCanonicalFileName(f), /*isAbsolutePathAnUrl*/ false);
const getCanonicalFileName = (f: string) => host.getCanonicalFileName(f);
const dir = toPath(host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName);
const filePath = getNormalizedAbsolutePath(fileName, host.getCurrentDirectory());
const relativePath = getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
return removeFileExtension(relativePath);
}
@@ -2411,6 +2408,55 @@ namespace ts {
return output;
}
/**
* Serialize an object graph into a JSON string. This is intended only for use on an acyclic graph
* as the fallback implementation does not check for circular references by default.
*/
export const stringify: (value: any) => string = typeof JSON !== "undefined" && JSON.stringify
? JSON.stringify
: stringifyFallback;
/**
* Serialize an object graph into a JSON string.
*/
function stringifyFallback(value: any): string {
// JSON.stringify returns `undefined` here, instead of the string "undefined".
return value === undefined ? undefined : stringifyValue(value);
}
function stringifyValue(value: any): string {
return typeof value === "string" ? `"${escapeString(value)}"`
: typeof value === "number" ? isFinite(value) ? String(value) : "null"
: typeof value === "boolean" ? value ? "true" : "false"
: typeof value === "object" && value ? isArray(value) ? cycleCheck(stringifyArray, value) : cycleCheck(stringifyObject, value)
: /*fallback*/ "null";
}
function cycleCheck(cb: (value: any) => string, value: any) {
Debug.assert(!value.hasOwnProperty("__cycle"), "Converting circular structure to JSON");
value.__cycle = true;
const result = cb(value);
delete value.__cycle;
return result;
}
function stringifyArray(value: any) {
return `[${reduceLeft(value, stringifyElement, "")}]`;
}
function stringifyElement(memo: string, value: any) {
return (memo ? memo + "," : memo) + stringifyValue(value);
}
function stringifyObject(value: any) {
return `{${reduceProperties(value, stringifyProperty, "")}}`;
}
function stringifyProperty(memo: string, value: any, key: string) {
return value === undefined || typeof value === "function" || key === "__cycle" ? memo
: (memo ? memo + "," : memo) + `"${escapeString(key)}":${stringifyValue(value)}`;
}
const base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
/**
+1 -1
View File
@@ -142,7 +142,7 @@ class CompilerBaselineRunner extends RunnerBase {
it("Correct JS output for " + fileName, () => {
if (hasNonDtsFiles && this.emit) {
if (result.files.length === 0 && result.errors.length === 0) {
if (!options.noEmit && 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.");
}
+18 -4
View File
@@ -1162,7 +1162,7 @@ namespace FourSlash {
public printCurrentQuickInfo() {
const quickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition);
Harness.IO.log(JSON.stringify(quickInfo));
Harness.IO.log("Quick Info: " + quickInfo.displayParts.map(part => part.text).join(""));
}
public printErrorList() {
@@ -1204,12 +1204,26 @@ namespace FourSlash {
public printMemberListMembers() {
const members = this.getMemberListAtCaret();
Harness.IO.log(JSON.stringify(members));
this.printMembersOrCompletions(members);
}
public printCompletionListMembers() {
const completions = this.getCompletionListAtCaret();
Harness.IO.log(JSON.stringify(completions));
this.printMembersOrCompletions(completions);
}
private printMembersOrCompletions(info: ts.CompletionInfo) {
function pad(s: string, length: number) {
return s + new Array(length - s.length + 1).join(" ");
}
function max<T>(arr: T[], selector: (x: T) => number): number {
return arr.reduce((prev, x) => Math.max(prev, selector(x)), 0);
}
const longestNameLength = max(info.entries, m => m.name.length);
const longestKindLength = max(info.entries, m => m.kind.length);
info.entries.sort((m, n) => m.sortText > n.sortText ? 1 : m.sortText < n.sortText ? -1 : m.name > n.name ? 1 : m.name < n.name ? -1 : 0);
const membersString = info.entries.map(m => `${pad(m.name, longestNameLength)} ${pad(m.kind, longestKindLength)} ${m.kindModifiers}`).join("\n");
Harness.IO.log(membersString);
}
public printReferences() {
@@ -3287,4 +3301,4 @@ namespace FourSlashInterface {
};
}
}
}
}
+12 -4
View File
@@ -908,6 +908,7 @@ namespace Harness {
useCaseSensitiveFileNames?: boolean;
includeBuiltFile?: string;
baselineFile?: string;
libFiles?: string;
}
// Additional options not already in ts.optionDeclarations
@@ -917,6 +918,7 @@ namespace Harness {
{ name: "baselineFile", type: "string" },
{ name: "includeBuiltFile", type: "string" },
{ name: "fileName", type: "string" },
{ name: "libFiles", type: "string" },
{ name: "noErrorTruncation", type: "boolean" }
];
@@ -995,14 +997,11 @@ namespace Harness {
currentDirectory = currentDirectory || Harness.IO.getCurrentDirectory();
// Parse settings
let useCaseSensitiveFileNames = Harness.IO.useCaseSensitiveFileNames();
if (harnessSettings) {
setCompilerOptionsFromHarnessSetting(harnessSettings, options);
}
if (options.useCaseSensitiveFileNames !== undefined) {
useCaseSensitiveFileNames = options.useCaseSensitiveFileNames;
}
const useCaseSensitiveFileNames = options.useCaseSensitiveFileNames !== undefined ? options.useCaseSensitiveFileNames : Harness.IO.useCaseSensitiveFileNames();
const programFiles: TestFile[] = inputFiles.slice();
// Files from built\local that are requested by test "@includeBuiltFiles" to be in the context.
// Treat them as library files, so include them in build, but not in baselines.
@@ -1017,6 +1016,15 @@ namespace Harness {
const fileOutputs: GeneratedFile[] = [];
// Files from tests\lib that are requested by "@libFiles"
if (options.libFiles) {
for (const fileName of options.libFiles.split(",")) {
const libFileName = "tests/lib/" + fileName;
programFiles.push({ unitName: libFileName, content: normalizeLineEndings(IO.readFile(libFileName), Harness.IO.newLine()) });
}
}
const programFileNames = programFiles.map(file => file.unitName);
const compilerHost = createCompilerHost(
+1 -2
View File
@@ -172,7 +172,6 @@ namespace Harness.SourceMapRecoder {
return { error: errorDecodeOfEncodedMapping, sourceMapSpan: decodeOfEncodedMapping };
}
// 5. Check if there is name:
decodeOfEncodedMapping.nameIndex = -1;
if (!isSourceMappingSegmentEnd()) {
prevNameIndex += base64VLQFormatDecode();
decodeOfEncodedMapping.nameIndex = prevNameIndex;
@@ -249,7 +248,7 @@ namespace Harness.SourceMapRecoder {
mapString += " name (" + sourceMapNames[mapEntry.nameIndex] + ")";
}
else {
if (mapEntry.nameIndex !== -1 || getAbsentNameIndex) {
if ((mapEntry.nameIndex && mapEntry.nameIndex !== -1) || getAbsentNameIndex) {
mapString += " nameIndex (" + mapEntry.nameIndex + ")";
}
}
+36 -13
View File
@@ -2058,6 +2058,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven
* Gets or sets the version attribute specified in the declaration of an XML document.
*/
xmlVersion: string;
currentScript: HTMLScriptElement;
adoptNode(source: Node): Node;
captureEvents(): void;
clear(): void;
@@ -2977,6 +2978,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec
webkitRequestFullScreen(): void;
webkitRequestFullscreen(): void;
getElementsByClassName(classNames: string): NodeListOf<Element>;
matches(selector: string): boolean;
addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void;
addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void;
addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void;
@@ -3961,7 +3963,6 @@ interface HTMLElement extends Element {
title: string;
blur(): void;
click(): void;
contains(child: HTMLElement): boolean;
dragDrop(): boolean;
focus(): void;
insertAdjacentElement(position: string, insertedElement: Element): Element;
@@ -6135,7 +6136,7 @@ interface HTMLSelectElement extends HTMLElement {
* Sets or retrieves the name of the object.
*/
name: string;
options: HTMLSelectElement;
options: HTMLCollection;
/**
* When present, marks an element that can't be submitted without a value.
*/
@@ -6421,19 +6422,19 @@ interface HTMLTableElement extends HTMLElement {
/**
* Creates an empty caption element in the table.
*/
createCaption(): HTMLElement;
createCaption(): HTMLTableCaptionElement;
/**
* Creates an empty tBody element in the table.
*/
createTBody(): HTMLElement;
createTBody(): HTMLTableSectionElement;
/**
* Creates an empty tFoot element in the table.
*/
createTFoot(): HTMLElement;
createTFoot(): HTMLTableSectionElement;
/**
* Returns the tHead element object if successful, or null otherwise.
*/
createTHead(): HTMLElement;
createTHead(): HTMLTableSectionElement;
/**
* Deletes the caption element and its contents from the table.
*/
@@ -6455,7 +6456,7 @@ interface HTMLTableElement extends HTMLElement {
* Creates a new row (tr) in the table, and adds the row to the rows collection.
* @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection.
*/
insertRow(index?: number): HTMLElement;
insertRow(index?: number): HTMLTableRowElement;
}
declare var HTMLTableElement: {
@@ -6506,7 +6507,7 @@ interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment {
* Creates a new cell in the table row, and adds the cell to the cells collection.
* @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection.
*/
insertCell(index?: number): HTMLElement;
insertCell(index?: number): HTMLTableCellElement;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -6533,7 +6534,7 @@ interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment {
* Creates a new row (tr) in the table, and adds the row to the rows collection.
* @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection.
*/
insertRow(index?: number): HTMLElement;
insertRow(index?: number): HTMLTableRowElement;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -6922,7 +6923,7 @@ interface IDBDatabase extends EventTarget {
onerror: (ev: Event) => any;
version: string;
close(): void;
createObjectStore(name: string, optionalParameters?: any): IDBObjectStore;
createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore;
deleteObjectStore(name: string): void;
transaction(storeNames: any, mode?: string): IDBTransaction;
addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
@@ -6947,10 +6948,11 @@ declare var IDBFactory: {
}
interface IDBIndex {
keyPath: string;
keyPath: string | string[];
name: string;
objectStore: IDBObjectStore;
unique: boolean;
multiEntry: boolean;
count(key?: any): IDBRequest;
get(key: any): IDBRequest;
getKey(key: any): IDBRequest;
@@ -6987,7 +6989,7 @@ interface IDBObjectStore {
add(value: any, key?: any): IDBRequest;
clear(): IDBRequest;
count(key?: any): IDBRequest;
createIndex(name: string, keyPath: string, optionalParameters?: any): IDBIndex;
createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex;
delete(key: any): IDBRequest;
deleteIndex(indexName: string): void;
get(key: any): IDBRequest;
@@ -7071,7 +7073,7 @@ declare var IDBVersionChangeEvent: {
}
interface ImageData {
data: number[];
data: Uint8ClampedArray;
height: number;
width: number;
}
@@ -7869,6 +7871,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte
getGamepads(): Gamepad[];
javaEnabled(): boolean;
msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void;
vibrate(pattern: number | number[]): boolean;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -7909,6 +7912,7 @@ interface Node extends EventTarget {
normalize(): void;
removeChild(oldChild: Node): Node;
replaceChild(newChild: Node, oldChild: Node): Node;
contains(node: Node): boolean;
ATTRIBUTE_NODE: number;
CDATA_SECTION_NODE: number;
COMMENT_NODE: number;
@@ -12572,6 +12576,16 @@ interface XMLHttpRequestEventTarget {
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
interface IDBObjectStoreParameters {
keyPath?: string | string[];
autoIncrement?: boolean;
}
interface IDBIndexParameters {
unique?: boolean;
multiEntry?: boolean;
}
interface NodeListOf<TNode extends Node> extends NodeList {
length: number;
item(index: number): TNode;
@@ -12607,6 +12621,15 @@ interface ProgressEventInit extends EventInit {
total?: number;
}
interface HTMLTemplateElement extends HTMLElement {
content: DocumentFragment;
}
declare var HTMLTemplateElement: {
prototype: HTMLTemplateElement;
new(): HTMLTemplateElement;
}
declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject;
interface ErrorEventHandler {
+11 -2
View File
@@ -1224,7 +1224,7 @@ declare namespace Reflect {
function isExtensible(target: any): boolean;
function ownKeys(target: any): Array<PropertyKey>;
function preventExtensions(target: any): boolean;
function set(target: any, propertyKey: PropertyKey, value: any, receiver? :any): boolean;
function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean;
function setPrototypeOf(target: any, proto: any): boolean;
}
@@ -1272,7 +1272,16 @@ interface PromiseConstructor {
* @param values An array of Promises.
* @returns A new Promise.
*/
all<T>(values: Iterable<T | PromiseLike<T>>): Promise<T[]>;
all<T1, T2>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>]): Promise<[T1, T2]>;
all<T1, T2, T3>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>]): Promise<[T1, T2, T3]>;
all<T1, T2, T3, T4>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>]): Promise<[T1, T2, T3, T4]>;
all<T1, T2, T3, T4, T5>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>]): Promise<[T1, T2, T3, T4, T5]>;
all<T1, T2, T3, T4, T5, T6>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>]): Promise<[T1, T2, T3, T4, T5, T6]>;
all<T1, T2, T3, T4, T5, T6, T7>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>]): Promise<[T1, T2, T3, T4, T5, T6, T7]>;
all<T1, T2, T3, T4, T5, T6, T7, T8>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>;
all<T1, T2, T3, T4, T5, T6, T7, T8, T9>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>;
all<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>, T10 | PromiseLike<T10>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>;
all<TAll>(values: Iterable<TAll | PromiseLike<TAll>>): Promise<TAll[]>;
/**
* Creates a Promise that is resolved or rejected when any of the provided Promises are resolved
+15 -4
View File
@@ -311,7 +311,7 @@ interface IDBDatabase extends EventTarget {
onerror: (ev: Event) => any;
version: string;
close(): void;
createObjectStore(name: string, optionalParameters?: any): IDBObjectStore;
createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore;
deleteObjectStore(name: string): void;
transaction(storeNames: any, mode?: string): IDBTransaction;
addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
@@ -336,10 +336,11 @@ declare var IDBFactory: {
}
interface IDBIndex {
keyPath: string;
keyPath: string | string[];
name: string;
objectStore: IDBObjectStore;
unique: boolean;
multiEntry: boolean;
count(key?: any): IDBRequest;
get(key: any): IDBRequest;
getKey(key: any): IDBRequest;
@@ -376,7 +377,7 @@ interface IDBObjectStore {
add(value: any, key?: any): IDBRequest;
clear(): IDBRequest;
count(key?: any): IDBRequest;
createIndex(name: string, keyPath: string, optionalParameters?: any): IDBIndex;
createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex;
delete(key: any): IDBRequest;
deleteIndex(indexName: string): void;
get(key: any): IDBRequest;
@@ -460,7 +461,7 @@ declare var IDBVersionChangeEvent: {
}
interface ImageData {
data: number[];
data: Uint8ClampedArray;
height: number;
width: number;
}
@@ -892,6 +893,16 @@ interface WorkerUtils extends Object, WindowBase64 {
setTimeout(handler: any, timeout?: any, ...args: any[]): number;
}
interface IDBObjectStoreParameters {
keyPath?: string | string[];
autoIncrement?: boolean;
}
interface IDBIndexParameters {
unique?: boolean;
multiEntry?: boolean;
}
interface BlobPropertyBag {
type?: string;
endings?: string;
+18 -3
View File
@@ -16,7 +16,7 @@ namespace ts.BreakpointResolver {
let tokenAtLocation = getTokenAtPosition(sourceFile, position);
let lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line;
if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart()).line > lineOfPosition) {
if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) {
// Get previous token if the token is returned starts on new line
// eg: let x =10; |--- cursor is here
// let y = 10;
@@ -39,16 +39,23 @@ namespace ts.BreakpointResolver {
return spanInNode(tokenAtLocation);
function textSpan(startNode: Node, endNode?: Node) {
return createTextSpanFromBounds(startNode.getStart(), (endNode || startNode).getEnd());
const start = startNode.decorators ?
skipTrivia(sourceFile.text, startNode.decorators.end) :
startNode.getStart(sourceFile);
return createTextSpanFromBounds(start, (endNode || startNode).getEnd());
}
function spanInNodeIfStartsOnSameLine(node: Node, otherwiseOnNode?: Node): TextSpan {
if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart()).line) {
if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line) {
return spanInNode(node);
}
return spanInNode(otherwiseOnNode);
}
function spanInNodeArray<T>(nodeArray: NodeArray<T>) {
return createTextSpanFromBounds(skipTrivia(sourceFile.text, nodeArray.pos), nodeArray.end);
}
function spanInPreviousNode(node: Node): TextSpan {
return spanInNode(findPrecedingToken(node.pos, sourceFile));
}
@@ -65,6 +72,11 @@ namespace ts.BreakpointResolver {
return spanInPreviousNode(node);
}
if (node.parent.kind === SyntaxKind.Decorator) {
// Set breakpoint on the decorator emit
return spanInNode(node.parent);
}
if (node.parent.kind === SyntaxKind.ForStatement) {
// For now lets set the span on this expression, fix it later
return textSpan(node);
@@ -207,6 +219,9 @@ namespace ts.BreakpointResolver {
// span in statement
return spanInNode((<WithStatement>node).statement);
case SyntaxKind.Decorator:
return spanInNodeArray(node.parent.decorators);
// No breakpoint in interface, type alias
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.TypeAliasDeclaration:
+34 -47
View File
@@ -31,8 +31,8 @@ namespace ts.formatting {
* the first token in line so it should be indented
*/
interface DynamicIndentation {
getIndentationForToken(tokenLine: number, tokenKind: SyntaxKind): number;
getIndentationForComment(owningToken: SyntaxKind, tokenIndentation: number): number;
getIndentationForToken(tokenLine: number, tokenKind: SyntaxKind, container: Node): number;
getIndentationForComment(owningToken: SyntaxKind, tokenIndentation: number, container: Node): number;
/**
* Indentation for open and close tokens of the node if it is block or another node that needs special indentation
* ... {
@@ -54,7 +54,7 @@ namespace ts.formatting {
* so bar inherits indentation from foo and bar.delta will be 4
*
*/
getDelta(): number;
getDelta(child: TextRangeWithKind): number;
/**
* Formatter calls this function when rule adds or deletes new lines from the text
* so indentation scope can adjust values of indentation and delta.
@@ -282,19 +282,19 @@ namespace ts.formatting {
*/
function getOwnOrInheritedDelta(n: Node, options: FormatCodeOptions, sourceFile: SourceFile): number {
let previousLine = Constants.Unknown;
let childKind = SyntaxKind.Unknown;
let child: Node;
while (n) {
let line = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)).line;
if (previousLine !== Constants.Unknown && line !== previousLine) {
break;
}
if (SmartIndenter.shouldIndentChildNode(n.kind, childKind)) {
if (SmartIndenter.shouldIndentChildNode(n, child)) {
return options.IndentSize;
}
previousLine = line;
childKind = n.kind;
child = n;
n = n.parent;
}
return 0;
@@ -386,34 +386,7 @@ namespace ts.formatting {
effectiveParentStartLine: number): Indentation {
let indentation = inheritedIndentation;
if (indentation === Constants.Unknown) {
if (isSomeBlock(node.kind)) {
// blocks should be indented in
// - other blocks
// - source file
// - switch\default clauses
if (isSomeBlock(parent.kind) ||
parent.kind === SyntaxKind.SourceFile ||
parent.kind === SyntaxKind.CaseClause ||
parent.kind === SyntaxKind.DefaultClause) {
indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta();
}
else {
indentation = parentDynamicIndentation.getIndentation();
}
}
else {
if (SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) {
indentation = parentDynamicIndentation.getIndentation();
}
else {
indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta();
}
}
}
var delta = SmartIndenter.shouldIndentChildNode(node.kind, SyntaxKind.Unknown) ? options.IndentSize : 0;
var delta = SmartIndenter.shouldIndentChildNode(node) ? options.IndentSize : 0;
if (effectiveParentStartLine === startLine) {
// if node is located on the same line with the parent
@@ -422,8 +395,17 @@ namespace ts.formatting {
indentation = startLine === lastIndentedLine
? indentationOnLastIndentedLine
: parentDynamicIndentation.getIndentation();
delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta() + delta);
delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta(node) + delta);
}
else if (indentation === Constants.Unknown) {
if (SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) {
indentation = parentDynamicIndentation.getIndentation();
}
else {
indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node);
}
}
return {
indentation,
delta
@@ -455,7 +437,7 @@ namespace ts.formatting {
function getDynamicIndentation(node: Node, nodeStartLine: number, indentation: number, delta: number): DynamicIndentation {
return {
getIndentationForComment: (kind, tokenIndentation) => {
getIndentationForComment: (kind, tokenIndentation, container) => {
switch (kind) {
// preceding comment to the token that closes the indentation scope inherits the indentation from the scope
// .. {
@@ -464,11 +446,11 @@ namespace ts.formatting {
case SyntaxKind.CloseBraceToken:
case SyntaxKind.CloseBracketToken:
case SyntaxKind.CloseParenToken:
return indentation + delta;
return indentation + getEffectiveDelta(delta, container);
}
return tokenIndentation !== Constants.Unknown ? tokenIndentation : indentation;
},
getIndentationForToken: (line, kind) => {
getIndentationForToken: (line, kind, container) => {
if (nodeStartLine !== line && node.decorators) {
if (kind === getFirstNonDecoratorTokenOfNode(node)) {
// if this token is the first token following the list of decorators, we do not need to indent
@@ -489,13 +471,13 @@ namespace ts.formatting {
return indentation;
default:
// if token line equals to the line of containing node (this is a first token in the node) - use node indentation
return nodeStartLine !== line ? indentation + delta : indentation;
return nodeStartLine !== line ? indentation + getEffectiveDelta(delta, container) : indentation;
}
},
getIndentation: () => indentation,
getDelta: () => delta,
getDelta: child => getEffectiveDelta(delta, child),
recomputeIndentation: lineAdded => {
if (node.parent && SmartIndenter.shouldIndentChildNode(node.parent.kind, node.kind)) {
if (node.parent && SmartIndenter.shouldIndentChildNode(node.parent, node)) {
if (lineAdded) {
indentation += options.IndentSize;
}
@@ -503,14 +485,19 @@ namespace ts.formatting {
indentation -= options.IndentSize;
}
if (SmartIndenter.shouldIndentChildNode(node.kind, SyntaxKind.Unknown)) {
if (SmartIndenter.shouldIndentChildNode(node)) {
delta = options.IndentSize;
}
else {
delta = 0;
}
}
},
}
}
function getEffectiveDelta(delta: number, child: TextRangeWithKind) {
// Delta value should be zero when the node explicitly prevents indentation of the child node
return SmartIndenter.nodeWillIndentChild(node, child, true) ? delta : 0;
}
}
@@ -610,7 +597,7 @@ namespace ts.formatting {
// if child node is a token, it does not impact indentation, proceed it using parent indentation scope rules
let tokenInfo = formattingScanner.readTokenInfo(child);
Debug.assert(tokenInfo.token.end === child.end);
consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation);
consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child);
return inheritedIndentation;
}
@@ -679,7 +666,7 @@ namespace ts.formatting {
}
}
function consumeTokenAndAdvanceScanner(currentTokenInfo: TokenInfo, parent: Node, dynamicIndentation: DynamicIndentation): void {
function consumeTokenAndAdvanceScanner(currentTokenInfo: TokenInfo, parent: Node, dynamicIndentation: DynamicIndentation, container?: Node): void {
Debug.assert(rangeContainsRange(parent, currentTokenInfo.token));
let lastTriviaWasNewLine = formattingScanner.lastTrailingTriviaWasNewLine();
@@ -720,11 +707,11 @@ namespace ts.formatting {
if (indentToken) {
let tokenIndentation = (isTokenInRange && !rangeContainsError(currentTokenInfo.token)) ?
dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind) :
dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind, container) :
Constants.Unknown;
if (currentTokenInfo.leadingTrivia) {
let commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation);
let commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container);
let indentNextTokenOrTrivia = true;
for (let triviaItem of currentTokenInfo.leadingTrivia) {
+7 -7
View File
@@ -123,6 +123,7 @@ namespace ts.formatting {
public SpaceAfterModuleName: Rule;
// Lambda expressions
public SpaceBeforeArrow: Rule;
public SpaceAfterArrow: Rule;
// Optional parameters and let args
@@ -254,7 +255,7 @@ namespace ts.formatting {
// No space before and after indexer
this.NoSpaceBeforeOpenBracket = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.OpenBracketToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.NoSpaceAfterCloseBracket = new Rule(RuleDescriptor.create3(SyntaxKind.CloseBracketToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBeforeBlockInFunctionDeclarationContext ), RuleAction.Delete));
this.NoSpaceAfterCloseBracket = new Rule(RuleDescriptor.create3(SyntaxKind.CloseBracketToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBeforeBlockInFunctionDeclarationContext), RuleAction.Delete));
// Place a space before open brace in a function declaration
this.FunctionOpenBraceLeftTokenRange = Shared.TokenRange.AnyIncludingMultilineComments;
@@ -342,6 +343,7 @@ namespace ts.formatting {
this.SpaceAfterModuleName = new Rule(RuleDescriptor.create1(SyntaxKind.StringLiteral, SyntaxKind.OpenBraceToken), RuleOperation.create2(new RuleOperationContext(Rules.IsModuleDeclContext), RuleAction.Space));
// Lambda expressions
this.SpaceBeforeArrow = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.EqualsGreaterThanToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.SpaceAfterArrow = new Rule(RuleDescriptor.create3(SyntaxKind.EqualsGreaterThanToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
// Optional parameters and let args
@@ -379,8 +381,7 @@ namespace ts.formatting {
this.NoSpaceBeforeTemplateMiddleAndTail = new Rule(RuleDescriptor.create4(Shared.TokenRange.Any, Shared.TokenRange.FromTokens([SyntaxKind.TemplateMiddle, SyntaxKind.TemplateTail])), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
// These rules are higher in priority than user-configurable rules.
this.HighPriorityCommonRules =
[
this.HighPriorityCommonRules = [
this.IgnoreBeforeComment, this.IgnoreAfterLineComment,
this.NoSpaceBeforeColon, this.SpaceAfterColon, this.NoSpaceBeforeQuestionMark, this.SpaceAfterQuestionMarkInConditionalOperator,
this.NoSpaceAfterQuestionMark,
@@ -411,7 +412,7 @@ namespace ts.formatting {
this.NoSpaceAfterConstructor, this.NoSpaceAfterModuleImport,
this.SpaceAfterCertainTypeScriptKeywords, this.SpaceBeforeCertainTypeScriptKeywords,
this.SpaceAfterModuleName,
this.SpaceAfterArrow,
this.SpaceBeforeArrow, this.SpaceAfterArrow,
this.NoSpaceAfterEllipsis,
this.NoSpaceAfterOptionalParameters,
this.NoSpaceBetweenEmptyInterfaceBraceBrackets,
@@ -427,8 +428,7 @@ namespace ts.formatting {
];
// These rules are lower in priority than user-configurable rules.
this.LowPriorityCommonRules =
[
this.LowPriorityCommonRules = [
this.NoSpaceBeforeSemicolon,
this.SpaceBeforeOpenBraceInControl, this.SpaceBeforeOpenBraceInFunction, this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock,
this.NoSpaceBeforeComma,
@@ -732,7 +732,7 @@ namespace ts.formatting {
}
static IsStartOfVariableDeclarationList(context: FormattingContext): boolean {
return context.currentTokenParent.kind === SyntaxKind.VariableDeclarationList &&
return context.currentTokenParent.kind === SyntaxKind.VariableDeclarationList &&
context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos;
}
+17 -11
View File
@@ -68,7 +68,7 @@ namespace ts.formatting {
let indentationDelta: number;
while (current) {
if (positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(current.kind, previous ? previous.kind : SyntaxKind.Unknown)) {
if (positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(current, previous)) {
currentStart = getStartLineAndCharacterForNode(current, sourceFile);
if (nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile)) {
@@ -153,7 +153,7 @@ namespace ts.formatting {
}
// increase indentation if parent node wants its content to be indented and parent and child nodes don't start on the same line
if (shouldIndentChildNode(parent.kind, current.kind) && !parentAndChildShareLine) {
if (shouldIndentChildNode(parent, current) && !parentAndChildShareLine) {
indentationDelta += options.IndentSize;
}
@@ -461,16 +461,15 @@ namespace ts.formatting {
case SyntaxKind.ParenthesizedType:
case SyntaxKind.TaggedTemplateExpression:
case SyntaxKind.AwaitExpression:
case SyntaxKind.NamedImports:
return true;
}
return false;
}
export function shouldIndentChildNode(parent: SyntaxKind, child: SyntaxKind): boolean {
if (nodeContentIsAlwaysIndented(parent)) {
return true;
}
switch (parent) {
export function nodeWillIndentChild(parent: TextRangeWithKind, child: TextRangeWithKind, indentByDefault: boolean) {
let childKind = child ? child.kind : SyntaxKind.Unknown;
switch (parent.kind) {
case SyntaxKind.DoStatement:
case SyntaxKind.WhileStatement:
case SyntaxKind.ForInStatement:
@@ -484,10 +483,17 @@ namespace ts.formatting {
case SyntaxKind.Constructor:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
return child !== SyntaxKind.Block;
default:
return false;
return childKind !== SyntaxKind.Block;
}
// No explicit rule for given nodes so the result will follow the default value argument
return indentByDefault;
}
/*
Function returns true when the parent node should indent the given child by an explicit rule
*/
export function shouldIndentChildNode(parent: TextRangeWithKind, child?: TextRangeWithKind): boolean {
return nodeContentIsAlwaysIndented(parent.kind) || nodeWillIndentChild(parent, child, false);
}
}
}
+26 -22
View File
@@ -1901,7 +1901,7 @@ namespace ts {
sourceMapText = text;
}
else {
Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: " + name);
Debug.assert(outputText === undefined, `Unexpected multiple outputs for the file: '${name}'`);
outputText = text;
}
},
@@ -3751,7 +3751,8 @@ namespace ts {
// Ignore omitted expressions for missing members
if (m.kind !== SyntaxKind.PropertyAssignment &&
m.kind !== SyntaxKind.ShorthandPropertyAssignment &&
m.kind !== SyntaxKind.BindingElement) {
m.kind !== SyntaxKind.BindingElement &&
m.kind !== SyntaxKind.MethodDeclaration) {
continue;
}
@@ -4248,28 +4249,31 @@ namespace ts {
}
else {
// Method/function type parameter
let container = getContainingFunction(location);
if (container) {
let signatureDeclaration = <SignatureDeclaration>getDeclarationOfKind(symbol, SyntaxKind.TypeParameter).parent;
let signature = typeChecker.getSignatureFromDeclaration(signatureDeclaration);
if (signatureDeclaration.kind === SyntaxKind.ConstructSignature) {
displayParts.push(keywordPart(SyntaxKind.NewKeyword));
let declaration = <Node>getDeclarationOfKind(symbol, SyntaxKind.TypeParameter);
Debug.assert(declaration !== undefined);
declaration = declaration.parent;
if (declaration) {
if (isFunctionLikeKind(declaration.kind)) {
const signature = typeChecker.getSignatureFromDeclaration(<SignatureDeclaration>declaration);
if (declaration.kind === SyntaxKind.ConstructSignature) {
displayParts.push(keywordPart(SyntaxKind.NewKeyword));
displayParts.push(spacePart());
}
else if (declaration.kind !== SyntaxKind.CallSignature && (<SignatureDeclaration>declaration).name) {
addFullSymbolName(declaration.symbol);
}
addRange(displayParts, signatureToDisplayParts(typeChecker, signature, sourceFile, TypeFormatFlags.WriteTypeArgumentsOfSignature));
}
else {
// Type alias type parameter
// For example
// type list<T> = T[]; // Both T will go through same code path
displayParts.push(keywordPart(SyntaxKind.TypeKeyword));
displayParts.push(spacePart());
addFullSymbolName(declaration.symbol);
writeTypeParametersOfSymbol(declaration.symbol, sourceFile);
}
else if (signatureDeclaration.kind !== SyntaxKind.CallSignature && signatureDeclaration.name) {
addFullSymbolName(signatureDeclaration.symbol);
}
addRange(displayParts, signatureToDisplayParts(typeChecker, signature, sourceFile, TypeFormatFlags.WriteTypeArgumentsOfSignature));
}
else {
// Type aliash type parameter
// For example
// type list<T> = T[]; // Both T will go through same code path
let declaration = <TypeAliasDeclaration>getDeclarationOfKind(symbol, SyntaxKind.TypeParameter).parent;
displayParts.push(keywordPart(SyntaxKind.TypeKeyword));
displayParts.push(spacePart());
addFullSymbolName(declaration.symbol);
writeTypeParametersOfSymbol(declaration.symbol, sourceFile);
}
}
}
+3 -3
View File
@@ -20,12 +20,12 @@ var Cell = (function () {
function Cell() {
}
return Cell;
})();
}());
var Ship = (function () {
function Ship() {
}
return Ship;
})();
}());
var Board = (function () {
function Board() {
}
@@ -33,4 +33,4 @@ var Board = (function () {
return this.ships.every(function (val) { return val.isSunk; });
};
return Board;
})();
}());
@@ -31,7 +31,7 @@ var A;
this.y = y;
}
return Point;
})();
}());
A.Point = Point;
})(A || (A = {}));
//// [test.js]
@@ -55,7 +55,7 @@ var clodule1 = (function () {
function clodule1() {
}
return clodule1;
})();
}());
var clodule1;
(function (clodule1) {
function f(x) { }
@@ -64,7 +64,7 @@ var clodule2 = (function () {
function clodule2() {
}
return clodule2;
})();
}());
var clodule2;
(function (clodule2) {
var x;
@@ -72,13 +72,13 @@ var clodule2;
function D() {
}
return D;
})();
}());
})(clodule2 || (clodule2 = {}));
var clodule3 = (function () {
function clodule3() {
}
return clodule3;
})();
}());
var clodule3;
(function (clodule3) {
clodule3.y = { id: T };
@@ -87,12 +87,12 @@ var clodule4 = (function () {
function clodule4() {
}
return clodule4;
})();
}());
var clodule4;
(function (clodule4) {
var D = (function () {
function D() {
}
return D;
})();
}());
})(clodule4 || (clodule4 = {}));
@@ -21,7 +21,7 @@ var clodule = (function () {
}
clodule.fn = function (id) { };
return clodule;
})();
}());
var clodule;
(function (clodule) {
// error: duplicate identifier expected
@@ -21,7 +21,7 @@ var clodule = (function () {
}
clodule.fn = function (id) { };
return clodule;
})();
}());
var clodule;
(function (clodule) {
// error: duplicate identifier expected
@@ -21,7 +21,7 @@ var clodule = (function () {
}
clodule.sfn = function (id) { return 42; };
return clodule;
})();
}());
var clodule;
(function (clodule) {
// error: duplicate identifier expected
@@ -30,7 +30,7 @@ var Point = (function () {
}
Point.Origin = function () { return { x: 0, y: 0 }; }; // unexpected error here bug 840246
return Point;
})();
}());
var Point;
(function (Point) {
function Origin() { return null; }
@@ -45,7 +45,7 @@ var A;
}
Point.Origin = function () { return { x: 0, y: 0 }; }; // unexpected error here bug 840246
return Point;
})();
}());
A.Point = Point;
var Point;
(function (Point) {
@@ -30,7 +30,7 @@ var Point = (function () {
}
Point.Origin = function () { return { x: 0, y: 0 }; };
return Point;
})();
}());
var Point;
(function (Point) {
function Origin() { return ""; } // not an error, since not exported
@@ -44,7 +44,7 @@ var A;
}
Point.Origin = function () { return { x: 0, y: 0 }; };
return Point;
})();
}());
A.Point = Point;
var Point;
(function (Point) {
@@ -30,7 +30,7 @@ var Point = (function () {
}
Point.Origin = { x: 0, y: 0 };
return Point;
})();
}());
var Point;
(function (Point) {
Point.Origin = ""; //expected duplicate identifier error
@@ -44,7 +44,7 @@ var A;
}
Point.Origin = { x: 0, y: 0 };
return Point;
})();
}());
A.Point = Point;
var Point;
(function (Point) {
@@ -30,7 +30,7 @@ var Point = (function () {
}
Point.Origin = { x: 0, y: 0 };
return Point;
})();
}());
var Point;
(function (Point) {
var Origin = ""; // not an error, since not exported
@@ -44,7 +44,7 @@ var A;
}
Point.Origin = { x: 0, y: 0 };
return Point;
})();
}());
A.Point = Point;
var Point;
(function (Point) {
@@ -51,7 +51,7 @@ var X;
this.y = y;
}
return Point;
})();
}());
Y.Point = Point;
})(Y = X.Y || (X.Y = {}));
})(X || (X = {}));
@@ -75,7 +75,7 @@ var A = (function () {
function A() {
}
return A;
})();
}());
var A;
(function (A) {
A.Instance = new A();
@@ -9,4 +9,4 @@ var C = (function () {
function C() {
}
return C;
})();
}());
@@ -10,4 +10,4 @@ var C = (function () {
}
C.prototype.foo = function () { };
return C;
})();
}());
@@ -10,4 +10,4 @@ var C = (function () {
}
C.prototype.bar = function () { };
return C;
})();
}());
@@ -9,4 +9,4 @@ var C = (function () {
function C() {
}
return C;
})();
}());
@@ -9,4 +9,4 @@ var C = (function () {
function C() {
}
return C;
})();
}());
@@ -10,4 +10,4 @@ var C = (function () {
}
C.prototype[1] = function () { };
return C;
})();
}());
@@ -10,4 +10,4 @@ var C = (function () {
}
C.prototype["bar"] = function () { };
return C;
})();
}());
@@ -7,4 +7,4 @@ var any = (function () {
function any() {
}
return any;
})();
}());
@@ -14,4 +14,4 @@ var List = (function () {
function List() {
}
return List;
})();
}());
@@ -0,0 +1,23 @@
tests/cases/compiler/ClassDeclaration26.ts(2,22): error TS1005: ';' expected.
tests/cases/compiler/ClassDeclaration26.ts(4,5): error TS1068: Unexpected token. A constructor, method, accessor, or property was expected.
tests/cases/compiler/ClassDeclaration26.ts(4,20): error TS1005: '=' expected.
tests/cases/compiler/ClassDeclaration26.ts(4,23): error TS1005: '=>' expected.
tests/cases/compiler/ClassDeclaration26.ts(5,1): error TS1128: Declaration or statement expected.
==== tests/cases/compiler/ClassDeclaration26.ts (5 errors) ====
class C {
public const var export foo = 10;
~~~~~~
!!! error TS1005: ';' expected.
var constructor() { }
~~~
!!! error TS1068: Unexpected token. A constructor, method, accessor, or property was expected.
~
!!! error TS1005: '=' expected.
~
!!! error TS1005: '=>' expected.
}
~
!!! error TS1128: Declaration or statement expected.
@@ -0,0 +1,15 @@
//// [ClassDeclaration26.ts]
class C {
public const var export foo = 10;
var constructor() { }
}
//// [ClassDeclaration26.js]
var C = (function () {
function C() {
this.foo = 10;
}
return C;
}());
var constructor = function () { };
@@ -8,4 +8,4 @@ var C = (function () {
function C() {
}
return C;
})();
}());
@@ -8,4 +8,4 @@ var C = (function () {
function C() {
}
return C;
})();
}());
@@ -0,0 +1,9 @@
tests/cases/compiler/ClassDeclarationWithInvalidConstOnPropertyDeclaration.ts(2,3): error TS1248: A class member cannot have the 'const' keyword.
==== tests/cases/compiler/ClassDeclarationWithInvalidConstOnPropertyDeclaration.ts (1 errors) ====
class AtomicNumbers {
static const H = 1;
~~~~~~~~~~~~~~~~~~~
!!! error TS1248: A class member cannot have the 'const' keyword.
}
@@ -0,0 +1,12 @@
//// [ClassDeclarationWithInvalidConstOnPropertyDeclaration.ts]
class AtomicNumbers {
static const H = 1;
}
//// [ClassDeclarationWithInvalidConstOnPropertyDeclaration.js]
var AtomicNumbers = (function () {
function AtomicNumbers() {
}
AtomicNumbers.H = 1;
return AtomicNumbers;
}());
@@ -0,0 +1,13 @@
//// [ClassDeclarationWithInvalidConstOnPropertyDeclaration2.ts]
class C {
const
x = 10;
}
//// [ClassDeclarationWithInvalidConstOnPropertyDeclaration2.js]
var C = (function () {
function C() {
this.x = 10;
}
return C;
}());
@@ -0,0 +1,10 @@
=== tests/cases/compiler/ClassDeclarationWithInvalidConstOnPropertyDeclaration2.ts ===
class C {
>C : Symbol(C, Decl(ClassDeclarationWithInvalidConstOnPropertyDeclaration2.ts, 0, 0))
const
>const : Symbol(const, Decl(ClassDeclarationWithInvalidConstOnPropertyDeclaration2.ts, 0, 9))
x = 10;
>x : Symbol(x, Decl(ClassDeclarationWithInvalidConstOnPropertyDeclaration2.ts, 1, 9))
}
@@ -0,0 +1,11 @@
=== tests/cases/compiler/ClassDeclarationWithInvalidConstOnPropertyDeclaration2.ts ===
class C {
>C : C
const
>const : any
x = 10;
>x : number
>10 : number
}
+1 -1
View File
@@ -1,2 +1,2 @@
//// [ES5For-of8.js.map]
{"version":3,"file":"ES5For-of8.js","sourceRoot":"","sources":["ES5For-of8.ts"],"names":["foo"],"mappings":"AAAA;IACIA,MAAMA,CAACA,EAAEA,CAACA,EAAEA,CAACA,EAAEA,CAACA;AACpBA,CAACA;AACD,GAAG,CAAC,CAAY,UAAe,EAAf,MAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,EAA1B,cAAO,EAAP,IAA0B,CAAC;IAA3B,GAAG,EAAE,CAAC,CAAC,SAAA;IACR,IAAI,CAAC,GAAG,GAAG,EAAE,CAAC,CAAC,CAAC;CACnB"}
{"version":3,"file":"ES5For-of8.js","sourceRoot":"","sources":["ES5For-of8.ts"],"names":[],"mappings":"AAAA;IACI,MAAM,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;AACpB,CAAC;AACD,GAAG,CAAC,CAAY,UAAe,EAAf,MAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,EAA1B,cAAO,EAAP,IAA0B,CAAC;IAA3B,GAAG,EAAE,CAAC,CAAC,SAAA;IACR,IAAI,CAAC,GAAG,GAAG,EAAE,CAAC,CAAC,CAAC;CACnB"}
@@ -34,15 +34,15 @@ sourceFile:ES5For-of8.ts
7 > 0
8 > }
9 > ;
1->Emitted(2, 5) Source(2, 5) + SourceIndex(0) name (foo)
2 >Emitted(2, 11) Source(2, 11) + SourceIndex(0) name (foo)
3 >Emitted(2, 12) Source(2, 12) + SourceIndex(0) name (foo)
4 >Emitted(2, 14) Source(2, 14) + SourceIndex(0) name (foo)
5 >Emitted(2, 15) Source(2, 15) + SourceIndex(0) name (foo)
6 >Emitted(2, 17) Source(2, 17) + SourceIndex(0) name (foo)
7 >Emitted(2, 18) Source(2, 18) + SourceIndex(0) name (foo)
8 >Emitted(2, 20) Source(2, 20) + SourceIndex(0) name (foo)
9 >Emitted(2, 21) Source(2, 21) + SourceIndex(0) name (foo)
1->Emitted(2, 5) Source(2, 5) + SourceIndex(0)
2 >Emitted(2, 11) Source(2, 11) + SourceIndex(0)
3 >Emitted(2, 12) Source(2, 12) + SourceIndex(0)
4 >Emitted(2, 14) Source(2, 14) + SourceIndex(0)
5 >Emitted(2, 15) Source(2, 15) + SourceIndex(0)
6 >Emitted(2, 17) Source(2, 17) + SourceIndex(0)
7 >Emitted(2, 18) Source(2, 18) + SourceIndex(0)
8 >Emitted(2, 20) Source(2, 20) + SourceIndex(0)
9 >Emitted(2, 21) Source(2, 21) + SourceIndex(0)
---
>>>}
1 >
@@ -51,8 +51,8 @@ sourceFile:ES5For-of8.ts
1 >
>
2 >}
1 >Emitted(3, 1) Source(3, 1) + SourceIndex(0) name (foo)
2 >Emitted(3, 2) Source(3, 2) + SourceIndex(0) name (foo)
1 >Emitted(3, 1) Source(3, 1) + SourceIndex(0)
2 >Emitted(3, 2) Source(3, 2) + SourceIndex(0)
---
>>>for (var _i = 0, _a = ['a', 'b', 'c']; _i < _a.length; _i++) {
1->
@@ -32,4 +32,4 @@ var StringIterator = (function () {
return this;
};
return StringIterator;
})();
}());
@@ -19,7 +19,7 @@ var M;
}
C.prototype[Symbol.iterator] = function () { };
return C;
})();
}());
M.C = C;
(new C)[Symbol.iterator];
})(M || (M = {}));
@@ -14,5 +14,5 @@ var C = (function () {
}
C.prototype[Symbol.iterator] = function () { };
return C;
})();
}());
(new C)[Symbol.iterator];
@@ -14,5 +14,5 @@ var C = (function () {
}
C.prototype[Symbol.iterator] = function () { };
return C;
})();
}());
(new C)[Symbol.iterator];
@@ -14,5 +14,5 @@ var C = (function () {
}
C.prototype[Symbol.iterator] = function () { };
return C;
})();
}());
(new C)[Symbol.iterator](0); // Should error
@@ -11,5 +11,5 @@ var C = (function () {
}
C.prototype[Symbol.iterator] = function () { };
return C;
})();
}());
(new C)[Symbol.iterator];
@@ -14,5 +14,5 @@ var C = (function () {
}
C.prototype[Symbol.iterator] = function () { };
return C;
})();
}());
(new C)[Symbol.iterator];
@@ -30,7 +30,7 @@ var enumdule;
this.y = y;
}
return Point;
})();
}());
enumdule.Point = Point;
})(enumdule || (enumdule = {}));
var x;
@@ -1,4 +1,4 @@
tests/cases/compiler/ExportAssignment7.ts(1,14): error TS1148: Cannot compile modules unless the '--module' flag is provided.
tests/cases/compiler/ExportAssignment7.ts(1,14): error TS1148: Cannot compile modules unless the '--module' flag is provided. Consider setting the 'module' compiler option in a 'tsconfig.json' file.
tests/cases/compiler/ExportAssignment7.ts(4,1): error TS2309: An export assignment cannot be used in a module with other exported elements.
tests/cases/compiler/ExportAssignment7.ts(4,10): error TS2304: Cannot find name 'B'.
@@ -6,7 +6,7 @@ tests/cases/compiler/ExportAssignment7.ts(4,10): error TS2304: Cannot find name
==== tests/cases/compiler/ExportAssignment7.ts (3 errors) ====
export class C {
~
!!! error TS1148: Cannot compile modules unless the '--module' flag is provided.
!!! error TS1148: Cannot compile modules unless the '--module' flag is provided. Consider setting the 'module' compiler option in a 'tsconfig.json' file.
}
export = B;
@@ -10,5 +10,5 @@ var C = (function () {
function C() {
}
return C;
})();
}());
exports.C = C;
@@ -1,4 +1,4 @@
tests/cases/compiler/ExportAssignment8.ts(1,1): error TS1148: Cannot compile modules unless the '--module' flag is provided.
tests/cases/compiler/ExportAssignment8.ts(1,1): error TS1148: Cannot compile modules unless the '--module' flag is provided. Consider setting the 'module' compiler option in a 'tsconfig.json' file.
tests/cases/compiler/ExportAssignment8.ts(1,1): error TS2309: An export assignment cannot be used in a module with other exported elements.
tests/cases/compiler/ExportAssignment8.ts(1,10): error TS2304: Cannot find name 'B'.
@@ -6,7 +6,7 @@ tests/cases/compiler/ExportAssignment8.ts(1,10): error TS2304: Cannot find name
==== tests/cases/compiler/ExportAssignment8.ts (3 errors) ====
export = B;
~~~~~~~~~~~
!!! error TS1148: Cannot compile modules unless the '--module' flag is provided.
!!! error TS1148: Cannot compile modules unless the '--module' flag is provided. Consider setting the 'module' compiler option in a 'tsconfig.json' file.
~~~~~~~~~~~
!!! error TS2309: An export assignment cannot be used in a module with other exported elements.
~
@@ -10,5 +10,5 @@ var C = (function () {
function C() {
}
return C;
})();
}());
exports.C = C;
@@ -31,6 +31,6 @@ var A;
return 1;
};
return Point2d;
})();
}());
A.Point2d = Point2d;
})(A || (A = {}));
@@ -32,7 +32,7 @@ var A;
function Point() {
}
return Point;
})();
}());
A.Point = Point;
A.Origin = { x: 0, y: 0 };
var Point3d = (function (_super) {
@@ -41,7 +41,7 @@ var A;
_super.apply(this, arguments);
}
return Point3d;
})(Point);
}(Point));
A.Point3d = Point3d;
A.Origin3d = { x: 0, y: 0, z: 0 };
var Line = (function () {
@@ -50,6 +50,6 @@ var A;
this.end = end;
}
return Line;
})();
}());
A.Line = Line;
})(A || (A = {}));
@@ -22,11 +22,11 @@ var A;
function Point() {
}
return Point;
})();
}());
var points = (function () {
function points() {
}
return points;
})();
}());
A.points = points;
})(A || (A = {}));
@@ -36,7 +36,7 @@ var A;
function Point() {
}
return Point;
})();
}());
A.Origin = { x: 0, y: 0 };
var Point3d = (function (_super) {
__extends(Point3d, _super);
@@ -44,7 +44,7 @@ var A;
_super.apply(this, arguments);
}
return Point3d;
})(Point);
}(Point));
A.Point3d = Point3d;
A.Origin3d = { x: 0, y: 0, z: 0 };
var Line = (function () {
@@ -56,6 +56,6 @@ var A;
return null;
};
return Line;
})();
}());
A.Line = Line;
})(A || (A = {}));
@@ -22,7 +22,7 @@ var A;
function Point() {
}
return Point;
})();
}());
A.Point = Point;
var Line = (function () {
function Line(start, end) {
@@ -30,7 +30,7 @@ var A;
this.end = end;
}
return Line;
})();
}());
A.Line = Line;
function fromOrigin(p) {
return new Line({ x: 0, y: 0 }, p);
@@ -22,14 +22,14 @@ var A;
function Point() {
}
return Point;
})();
}());
var Line = (function () {
function Line(start, end) {
this.start = start;
this.end = end;
}
return Line;
})();
}());
A.Line = Line;
function fromOrigin(p) {
return new Line({ x: 0, y: 0 }, p);
@@ -22,7 +22,7 @@ var A;
function Point() {
}
return Point;
})();
}());
A.Point = Point;
var Line = (function () {
function Line(start, end) {
@@ -30,7 +30,7 @@ var A;
this.end = end;
}
return Line;
})();
}());
function fromOrigin(p) {
return new Line({ x: 0, y: 0 }, p);
}
@@ -29,7 +29,7 @@ var A;
this.y = y;
}
return Point;
})();
}());
A.Point = Point;
var B;
(function (B) {
@@ -41,7 +41,7 @@ var A;
return new Line({ x: 0, y: 0 }, p);
};
return Line;
})();
}());
B.Line = Line;
})(B = A.B || (A.B = {}));
})(A || (A = {}));
@@ -20,7 +20,7 @@ var A;
this.y = y;
}
return Point;
})();
}());
A.Origin = { x: 0, y: 0 };
A.Unity = { start: new Point(0, 0), end: new Point(1, 0) };
})(A || (A = {}));
@@ -20,6 +20,6 @@ var A;
this.y = y;
}
return Point;
})();
}());
A.UnitSquare = null;
})(A || (A = {}));
@@ -15,6 +15,6 @@ var A;
function B() {
}
return B;
})();
}());
A.beez2 = new Array();
})(A || (A = {}));
@@ -13,4 +13,4 @@ var C = (function () {
configurable: true
});
return C;
})();
}());
@@ -9,4 +9,4 @@ var C = (function () {
}
C.prototype.foo = function () { };
return C;
})();
}());
@@ -9,4 +9,4 @@ var C = (function () {
}
C.prototype.foo = function () { };
return C;
})();
}());
@@ -9,4 +9,4 @@ var C = (function () {
}
C.prototype[foo] = function () { };
return C;
})();
}());
@@ -9,4 +9,4 @@ var C = (function () {
}
C.prototype. = function () { };
return C;
})();
}());
@@ -8,4 +8,4 @@ var C = (function () {
function C() {
}
return C;
})();
}());
@@ -8,4 +8,4 @@ var C = (function () {
function C() {
}
return C;
})();
}());
@@ -9,4 +9,4 @@ var C = (function () {
}
C.prototype.foo = function () { };
return C;
})();
}());
@@ -19,4 +19,4 @@ var C = (function () {
return bar;
};
return C;
})();
}());
@@ -54,7 +54,7 @@ var X;
this.y = y;
}
return Point;
})();
}());
Y.Point = Point;
})(Y = X.Y || (X.Y = {}));
})(X || (X = {}));
@@ -68,4 +68,4 @@ var A = (function () {
function A() {
}
return A;
})();
}());
@@ -25,7 +25,7 @@ var enumdule;
this.y = y;
}
return Point;
})();
}());
enumdule.Point = Point;
})(enumdule || (enumdule = {}));
var enumdule;
@@ -40,24 +40,24 @@ var A;
function A() {
}
return A;
})();
}());
A_1.A = A;
var AG = (function () {
function AG() {
}
return AG;
})();
}());
A_1.AG = AG;
var A2 = (function () {
function A2() {
}
return A2;
})();
}());
var AG2 = (function () {
function AG2() {
}
return AG2;
})();
}());
})(A || (A = {}));
// no errors expected, these are all exported
var a;
@@ -48,7 +48,7 @@ var B;
this.end = end;
}
return Line;
})();
}());
B.Line = Line;
})(B || (B = {}));
var Geometry;
@@ -45,7 +45,7 @@ var Inner;
function A() {
}
return A;
})();
}());
var B;
(function (B) {
B.a = 1, B.c = 2;
@@ -63,7 +63,7 @@ var Inner;
function D() {
}
return D;
})();
}());
Inner.e1 = new D;
Inner.f1 = new D;
Inner.g1 = new D;

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