merge with master

This commit is contained in:
Vladimir Matveev
2015-10-01 14:05:10 -07:00
311 changed files with 5842 additions and 2976 deletions
+19
View File
@@ -18,6 +18,25 @@
"problemMatcher": [
"$tsc"
]
},
{
"taskName": "lint-server",
"args": [],
"problemMatcher": {
"owner": "typescript",
"fileLocation": ["relative", "${workspaceRoot}"],
"pattern": {
"regexp": "^(warning|error)\\s+([^(]+)\\s+\\((\\d+|\\d+,\\d+|\\d+,\\d+,\\d+,\\d+)\\):\\s+(.*)$",
"severity": 1,
"file": 2,
"location": 3,
"message": 4
},
"watchedTaskBeginsRegExp": "^\\*\\*\\*Lint failure\\*\\*\\*$",
"watchedTaskEndsRegExp": "^\\*\\*\\* Total \\d+ failures\\.$"
},
"showOutput": "always",
"isWatching": true
}
]
}
+85 -8
View File
@@ -4,6 +4,7 @@ var fs = require("fs");
var os = require("os");
var path = require("path");
var child_process = require("child_process");
var Linter = require("tslint");
// Variables
var compilerDirectory = "src/compiler/";
@@ -828,17 +829,93 @@ tslintRulesFiles.forEach(function(ruleFile, i) {
compileFile(tslintRulesOutFiles[i], [ruleFile], [ruleFile], [], /*useBuiltCompiler*/ true, /*noOutFile*/ true, /*generateDeclarations*/ false, path.join(builtLocalDirectory, "tslint"));
});
function getLinterOptions() {
return {
configuration: require("./tslint.json"),
formatter: "prose",
formattersDirectory: undefined,
rulesDirectory: "built/local/tslint"
};
}
function lintFileContents(options, path, contents) {
var ll = new Linter(path, contents, options);
return ll.lint();
}
function lintFile(options, path) {
var contents = fs.readFileSync(path, "utf8");
return lintFileContents(options, path, contents);
}
function lintFileAsync(options, path, cb) {
fs.readFile(path, "utf8", function(err, contents) {
if (err) {
return cb(err);
}
var result = lintFileContents(options, path, contents);
cb(undefined, result);
});
}
var lintTargets = compilerSources.concat(harnessCoreSources);
// if the codebase were free of linter errors we could make jake runtests
// run this task automatically
desc("Runs tslint on the compiler sources");
task("lint", ["build-rules"], function() {
function success(f) { return function() { console.log('SUCCESS: No linter errors in ' + f + '\n'); }};
function failure(f) { return function() { console.log('FAILURE: Please fix linting errors in ' + f + '\n') }};
var lintTargets = compilerSources.concat(harnessCoreSources);
var lintOptions = getLinterOptions();
for (var i in lintTargets) {
var f = lintTargets[i];
var cmd = 'tslint --rules-dir built/local/tslint -c tslint.json ' + f;
exec(cmd, success(f), failure(f));
var result = lintFile(lintOptions, lintTargets[i]);
if (result.failureCount > 0) {
console.log(result.output);
fail('Linter errors.', result.failureCount);
}
}
}, { async: true });
});
/**
* This is required because file watches on Windows get fires _twice_
* when a file changes on some node/windows version configuations
* (node v4 and win 10, for example). By not running a lint for a file
* which already has a pending lint, we avoid duplicating our work.
* (And avoid printing duplicate results!)
*/
var lintSemaphores = {};
function lintWatchFile(filename) {
fs.watch(filename, {persistent: true}, function(event) {
if (event !== "change") {
return;
}
if (!lintSemaphores[filename]) {
lintSemaphores[filename] = true;
lintFileAsync(getLinterOptions(), filename, function(err, result) {
delete lintSemaphores[filename];
if (err) {
console.log(err);
return;
}
if (result.failureCount > 0) {
console.log("***Lint failure***");
for (var i = 0; i < result.failures.length; i++) {
var failure = result.failures[i];
var start = failure.startPosition.lineAndCharacter;
var end = failure.endPosition.lineAndCharacter;
console.log("warning " + filename + " (" + (start.line + 1) + "," + (start.character + 1) + "," + (end.line + 1) + "," + (end.character + 1) + "): " + failure.failure);
}
console.log("*** Total " + result.failureCount + " failures.");
}
});
}
});
}
desc("Watches files for changes to rerun a lint pass");
task("lint-server", ["build-rules"], function() {
console.log("Watching ./src for changes to linted files");
for (var i = 0; i < lintTargets.length; i++) {
lintWatchFile(lintTargets[i]);
}
});
+2 -1
View File
@@ -40,12 +40,13 @@
},
"scripts": {
"pretest": "jake tests",
"test": "jake runtests",
"test": "jake runtests && npm run lint",
"build": "npm run build:compiler && npm run build:tests",
"build:compiler": "jake local",
"build:tests": "jake tests",
"clean": "jake clean",
"jake": "jake",
"lint": "jake lint",
"setup-hooks": "node scripts/link-hooks.js"
},
"browser": {
+5 -5
View File
@@ -5,8 +5,8 @@ const OPTION_CATCH = "check-catch";
const OPTION_ELSE = "check-else";
export class Rule extends Lint.Rules.AbstractRule {
public static CATCH_FAILURE_STRING = "'catch' should be on the line following the previous block's ending curly brace";
public static ELSE_FAILURE_STRING = "'else' should be on the line following the previous block's ending curly brace";
public static CATCH_FAILURE_STRING = "'catch' should not be on the same line as the preceeding block's curly brace";
public static ELSE_FAILURE_STRING = "'else' should not be on the same line as the preceeding block's curly brace";
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithWalker(new NextLineWalker(sourceFile, this.getOptions()));
@@ -25,7 +25,7 @@ class NextLineWalker extends Lint.RuleWalker {
if (this.hasOption(OPTION_ELSE) && !!elseKeyword) {
const thenStatementEndLoc = sourceFile.getLineAndCharacterOfPosition(thenStatement.getEnd());
const elseKeywordLoc = sourceFile.getLineAndCharacterOfPosition(elseKeyword.getStart(sourceFile));
if (thenStatementEndLoc.line !== (elseKeywordLoc.line - 1)) {
if (thenStatementEndLoc.line === elseKeywordLoc.line) {
const failure = this.createFailure(elseKeyword.getStart(sourceFile), elseKeyword.getWidth(sourceFile), Rule.ELSE_FAILURE_STRING);
this.addFailure(failure);
}
@@ -47,7 +47,7 @@ class NextLineWalker extends Lint.RuleWalker {
const catchKeyword = catchClause.getFirstToken(sourceFile);
const tryClosingBraceLoc = sourceFile.getLineAndCharacterOfPosition(tryClosingBrace.getEnd());
const catchKeywordLoc = sourceFile.getLineAndCharacterOfPosition(catchKeyword.getStart(sourceFile));
if (tryClosingBraceLoc.line !== (catchKeywordLoc.line - 1)) {
if (tryClosingBraceLoc.line === catchKeywordLoc.line) {
const failure = this.createFailure(catchKeyword.getStart(sourceFile), catchKeyword.getWidth(sourceFile), Rule.CATCH_FAILURE_STRING);
this.addFailure(failure);
}
@@ -58,4 +58,4 @@ class NextLineWalker extends Lint.RuleWalker {
function getFirstChildOfKind(node: ts.Node, kind: ts.SyntaxKind) {
return node.getChildren().filter((child) => child.kind === kind)[0];
}
}
+12 -1
View File
@@ -103,6 +103,7 @@ namespace ts {
let container: Node;
let blockScopeContainer: Node;
let lastContainer: Node;
let seenThisKeyword: boolean;
// state used by reachability checks
let hasExplicitReturn: boolean;
@@ -351,7 +352,14 @@ namespace ts {
blockScopeContainer.locals = undefined;
}
bindWithReachabilityChecks(node);
if (node.kind === SyntaxKind.InterfaceDeclaration) {
seenThisKeyword = false;
bindWithReachabilityChecks(node);
node.flags = seenThisKeyword ? node.flags | NodeFlags.ContainsThis : node.flags & ~NodeFlags.ContainsThis;
}
else {
bindWithReachabilityChecks(node);
}
container = saveContainer;
parent = saveParent;
@@ -1135,6 +1143,9 @@ namespace ts {
return checkStrictModePrefixUnaryExpression(<PrefixUnaryExpression>node);
case SyntaxKind.WithStatement:
return checkStrictModeWithStatement(<WithStatement>node);
case SyntaxKind.ThisKeyword:
seenThisKeyword = true;
return;
case SyntaxKind.TypeParameter:
return declareSymbolAndAddToSymbolTable(<Declaration>node, SymbolFlags.TypeParameter, SymbolFlags.TypeParameterExcludes);
+321 -143
View File
@@ -38,6 +38,7 @@ namespace ts {
let Signature = objectAllocator.getSignatureConstructor();
let typeCount = 0;
let symbolCount = 0;
let emptyArray: any[] = [];
let emptySymbols: SymbolTable = {};
@@ -54,7 +55,7 @@ namespace ts {
let checker: TypeChecker = {
getNodeCount: () => sum(host.getSourceFiles(), "nodeCount"),
getIdentifierCount: () => sum(host.getSourceFiles(), "identifierCount"),
getSymbolCount: () => sum(host.getSourceFiles(), "symbolCount"),
getSymbolCount: () => sum(host.getSourceFiles(), "symbolCount") + symbolCount,
getTypeCount: () => typeCount,
isUndefinedSymbol: symbol => symbol === undefinedSymbol,
isArgumentsSymbol: symbol => symbol === argumentsSymbol,
@@ -245,6 +246,7 @@ namespace ts {
}
function createSymbol(flags: SymbolFlags, name: string): Symbol {
symbolCount++;
return new Symbol(flags, name);
}
@@ -950,12 +952,6 @@ namespace ts {
return symbol.flags & meaning ? symbol : resolveAlias(symbol);
}
function isExternalModuleNameRelative(moduleName: string): boolean {
// TypeScript 1.0 spec (April 2014): 11.2.1
// An external module name is "relative" if the first term is "." or "..".
return moduleName.substr(0, 2) === "./" || moduleName.substr(0, 3) === "../" || moduleName.substr(0, 2) === ".\\" || moduleName.substr(0, 3) === "..\\";
}
function resolveExternalModuleName(location: Node, moduleReferenceExpression: Expression): Symbol {
if (moduleReferenceExpression.kind !== SyntaxKind.StringLiteral) {
return;
@@ -1595,6 +1591,7 @@ namespace ts {
function buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]) {
let globalFlagsToPass = globalFlags & TypeFormatFlags.WriteOwnNameForAnyLike;
let inObjectTypeLiteral = false;
return writeType(type, globalFlags);
function writeType(type: Type, flags: TypeFormatFlags) {
@@ -1605,6 +1602,12 @@ namespace ts {
? "any"
: (<IntrinsicType>type).intrinsicName);
}
else if (type.flags & TypeFlags.ThisType) {
if (inObjectTypeLiteral) {
writer.reportInaccessibleThisError();
}
writer.writeKeyword("this");
}
else if (type.flags & TypeFlags.Reference) {
writeTypeReference(<TypeReference>type, flags);
}
@@ -1648,11 +1651,10 @@ namespace ts {
}
}
function writeSymbolTypeReference(symbol: Symbol, typeArguments: Type[], pos: number, end: number) {
// Unnamed function expressions, arrow functions, and unnamed class expressions have reserved names that
// we don't want to display
if (!isReservedMemberName(symbol.name)) {
buildSymbolDisplay(symbol, writer, enclosingDeclaration, SymbolFlags.Type);
function writeSymbolTypeReference(symbol: Symbol, typeArguments: Type[], pos: number, end: number, flags: TypeFormatFlags) {
// Unnamed function expressions and arrow functions have reserved names that we don't want to display
if (symbol.flags & SymbolFlags.Class || !isReservedMemberName(symbol.name)) {
buildSymbolDisplay(symbol, writer, enclosingDeclaration, SymbolFlags.Type, SymbolFormatFlags.None, flags);
}
if (pos < end) {
writePunctuation(writer, SyntaxKind.LessThanToken);
@@ -1667,7 +1669,7 @@ namespace ts {
}
function writeTypeReference(type: TypeReference, flags: TypeFormatFlags) {
let typeArguments = type.typeArguments;
let typeArguments = type.typeArguments || emptyArray;
if (type.target === globalArrayType && !(flags & TypeFormatFlags.WriteArrayAsGenericType)) {
writeType(typeArguments[0], TypeFormatFlags.InElementType);
writePunctuation(writer, SyntaxKind.OpenBracketToken);
@@ -1691,12 +1693,13 @@ namespace ts {
// When type parameters are their own type arguments for the whole group (i.e. we have
// the default outer type arguments), we don't show the group.
if (!rangeEquals(outerTypeParameters, typeArguments, start, i)) {
writeSymbolTypeReference(parent, typeArguments, start, i);
writeSymbolTypeReference(parent, typeArguments, start, i, flags);
writePunctuation(writer, SyntaxKind.DotToken);
}
}
}
writeSymbolTypeReference(type.symbol, typeArguments, i, typeArguments.length);
let typeParameterCount = (type.target.typeParameters || emptyArray).length;
writeSymbolTypeReference(type.symbol, typeArguments, i, typeParameterCount, flags);
}
}
@@ -1819,6 +1822,8 @@ namespace ts {
}
}
let saveInObjectTypeLiteral = inObjectTypeLiteral;
inObjectTypeLiteral = true;
writePunctuation(writer, SyntaxKind.OpenBraceToken);
writer.writeLine();
writer.increaseIndent();
@@ -1891,6 +1896,7 @@ namespace ts {
}
writer.decreaseIndent();
writePunctuation(writer, SyntaxKind.CloseBraceToken);
inObjectTypeLiteral = saveInObjectTypeLiteral;
}
}
@@ -2382,7 +2388,7 @@ namespace ts {
if (isBindingPattern(declaration.parent)) {
return getTypeForBindingElement(<BindingElement>declaration);
}
// Use type from type annotation if one is present
if (declaration.type) {
return getTypeFromTypeNode(declaration.type);
@@ -2403,12 +2409,12 @@ namespace ts {
return type;
}
}
// Use the type of the initializer expression if one is present
if (declaration.initializer) {
return checkExpressionCached(declaration.initializer);
}
// If it is a short-hand property assignment, use the type of the identifier
if (declaration.kind === SyntaxKind.ShorthandPropertyAssignment) {
return checkIdentifier(<Identifier>declaration.name);
@@ -2503,10 +2509,10 @@ namespace ts {
// tools see the actual type.
return declaration.kind !== SyntaxKind.PropertyAssignment ? getWidenedType(type) : type;
}
// Rest parameters default to type any[], other parameters default to type any
type = declaration.dotDotDotToken ? anyArrayType : anyType;
// Report implicit any errors unless this is a private property within an ambient declaration
if (reportErrors && compilerOptions.noImplicitAny) {
let root = getRootDeclaration(declaration);
@@ -2892,6 +2898,31 @@ namespace ts {
}
}
// Returns true if the interface given by the symbol is free of "this" references. Specifically, the result is
// true if the interface itself contains no references to "this" in its body, if all base types are interfaces,
// and if none of the base interfaces have a "this" type.
function isIndependentInterface(symbol: Symbol): boolean {
for (let declaration of symbol.declarations) {
if (declaration.kind === SyntaxKind.InterfaceDeclaration) {
if (declaration.flags & NodeFlags.ContainsThis) {
return false;
}
let baseTypeNodes = getInterfaceBaseTypeNodes(<InterfaceDeclaration>declaration);
if (baseTypeNodes) {
for (let node of baseTypeNodes) {
if (isSupportedExpressionWithTypeArguments(node)) {
let baseSymbol = resolveEntityName(node.expression, SymbolFlags.Type, /*ignoreErrors*/ true);
if (!baseSymbol || !(baseSymbol.flags & SymbolFlags.Interface) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) {
return false;
}
}
}
}
}
}
return true;
}
function getDeclaredTypeOfClassOrInterface(symbol: Symbol): InterfaceType {
let links = getSymbolLinks(symbol);
if (!links.declaredType) {
@@ -2899,7 +2930,12 @@ namespace ts {
let type = links.declaredType = <InterfaceType>createObjectType(kind, symbol);
let outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol);
let localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
if (outerTypeParameters || localTypeParameters) {
// A class or interface is generic if it has type parameters or a "this" type. We always give classes a "this" type
// because it is not feasible to analyze all members to determine if the "this" type escapes the class (in particular,
// property types inferred from initializers and method return types inferred from return statements are very hard
// to exhaustively analyze). We give interfaces a "this" type if we can't definitely determine that they are free of
// "this" references.
if (outerTypeParameters || localTypeParameters || kind === TypeFlags.Class || !isIndependentInterface(symbol)) {
type.flags |= TypeFlags.Reference;
type.typeParameters = concatenate(outerTypeParameters, localTypeParameters);
type.outerTypeParameters = outerTypeParameters;
@@ -2908,6 +2944,9 @@ namespace ts {
(<GenericType>type).instantiations[getTypeListId(type.typeParameters)] = <GenericType>type;
(<GenericType>type).target = <GenericType>type;
(<GenericType>type).typeArguments = type.typeParameters;
type.thisType = <TypeParameter>createType(TypeFlags.TypeParameter | TypeFlags.ThisType);
type.thisType.symbol = symbol;
type.thisType.constraint = getTypeWithThisArgument(type);
}
}
return <InterfaceType>links.declaredType;
@@ -2992,6 +3031,82 @@ namespace ts {
return unknownType;
}
// A type reference is considered independent if each type argument is considered independent.
function isIndependentTypeReference(node: TypeReferenceNode): boolean {
if (node.typeArguments) {
for (let typeNode of node.typeArguments) {
if (!isIndependentType(typeNode)) {
return false;
}
}
}
return true;
}
// A type is considered independent if it the any, string, number, boolean, symbol, or void keyword, a string
// literal type, an array with an element type that is considered independent, or a type reference that is
// considered independent.
function isIndependentType(node: TypeNode): boolean {
switch (node.kind) {
case SyntaxKind.AnyKeyword:
case SyntaxKind.StringKeyword:
case SyntaxKind.NumberKeyword:
case SyntaxKind.BooleanKeyword:
case SyntaxKind.SymbolKeyword:
case SyntaxKind.VoidKeyword:
case SyntaxKind.StringLiteral:
return true;
case SyntaxKind.ArrayType:
return isIndependentType((<ArrayTypeNode>node).elementType);
case SyntaxKind.TypeReference:
return isIndependentTypeReference(<TypeReferenceNode>node);
}
return false;
}
// A variable-like declaration is considered independent (free of this references) if it has a type annotation
// that specifies an independent type, or if it has no type annotation and no initializer (and thus of type any).
function isIndependentVariableLikeDeclaration(node: VariableLikeDeclaration): boolean {
return node.type && isIndependentType(node.type) || !node.type && !node.initializer;
}
// A function-like declaration is considered independent (free of this references) if it has a return type
// annotation that is considered independent and if each parameter is considered independent.
function isIndependentFunctionLikeDeclaration(node: FunctionLikeDeclaration): boolean {
if (node.kind !== SyntaxKind.Constructor && (!node.type || !isIndependentType(node.type))) {
return false;
}
for (let parameter of node.parameters) {
if (!isIndependentVariableLikeDeclaration(parameter)) {
return false;
}
}
return true;
}
// Returns true if the class or interface member given by the symbol is free of "this" references. The
// function may return false for symbols that are actually free of "this" references because it is not
// feasible to perform a complete analysis in all cases. In particular, property members with types
// inferred from their initializers and function members with inferred return types are convervatively
// assumed not to be free of "this" references.
function isIndependentMember(symbol: Symbol): boolean {
if (symbol.declarations && symbol.declarations.length === 1) {
let declaration = symbol.declarations[0];
if (declaration) {
switch (declaration.kind) {
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.PropertySignature:
return isIndependentVariableLikeDeclaration(<VariableLikeDeclaration>declaration);
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
case SyntaxKind.Constructor:
return isIndependentFunctionLikeDeclaration(<FunctionLikeDeclaration>declaration);
}
}
}
return false;
}
function createSymbolTable(symbols: Symbol[]): SymbolTable {
let result: SymbolTable = {};
for (let symbol of symbols) {
@@ -3000,10 +3115,12 @@ namespace ts {
return result;
}
function createInstantiatedSymbolTable(symbols: Symbol[], mapper: TypeMapper): SymbolTable {
// The mappingThisOnly flag indicates that the only type parameter being mapped is "this". When the flag is true,
// we check symbols to see if we can quickly conclude they are free of "this" references, thus needing no instantiation.
function createInstantiatedSymbolTable(symbols: Symbol[], mapper: TypeMapper, mappingThisOnly: boolean): SymbolTable {
let result: SymbolTable = {};
for (let symbol of symbols) {
result[symbol.name] = instantiateSymbol(symbol, mapper);
result[symbol.name] = mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper);
}
return result;
}
@@ -3036,44 +3153,57 @@ namespace ts {
return <InterfaceTypeWithDeclaredMembers>type;
}
function resolveClassOrInterfaceMembers(type: InterfaceType): void {
let target = resolveDeclaredMembers(type);
let members = target.symbol.members;
let callSignatures = target.declaredCallSignatures;
let constructSignatures = target.declaredConstructSignatures;
let stringIndexType = target.declaredStringIndexType;
let numberIndexType = target.declaredNumberIndexType;
let baseTypes = getBaseTypes(target);
function getTypeWithThisArgument(type: ObjectType, thisArgument?: Type) {
if (type.flags & TypeFlags.Reference) {
return createTypeReference((<TypeReference>type).target,
concatenate((<TypeReference>type).typeArguments, [thisArgument || (<TypeReference>type).target.thisType]));
}
return type;
}
function resolveObjectTypeMembers(type: ObjectType, source: InterfaceTypeWithDeclaredMembers, typeParameters: TypeParameter[], typeArguments: Type[]) {
let mapper = identityMapper;
let members = source.symbol.members;
let callSignatures = source.declaredCallSignatures;
let constructSignatures = source.declaredConstructSignatures;
let stringIndexType = source.declaredStringIndexType;
let numberIndexType = source.declaredNumberIndexType;
if (!rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) {
mapper = createTypeMapper(typeParameters, typeArguments);
members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1);
callSignatures = instantiateList(source.declaredCallSignatures, mapper, instantiateSignature);
constructSignatures = instantiateList(source.declaredConstructSignatures, mapper, instantiateSignature);
stringIndexType = source.declaredStringIndexType ? instantiateType(source.declaredStringIndexType, mapper) : undefined;
numberIndexType = source.declaredNumberIndexType ? instantiateType(source.declaredNumberIndexType, mapper) : undefined;
}
let baseTypes = getBaseTypes(source);
if (baseTypes.length) {
members = createSymbolTable(target.declaredProperties);
if (members === source.symbol.members) {
members = createSymbolTable(source.declaredProperties);
}
let thisArgument = lastOrUndefined(typeArguments);
for (let baseType of baseTypes) {
addInheritedMembers(members, getPropertiesOfObjectType(baseType));
callSignatures = concatenate(callSignatures, getSignaturesOfType(baseType, SignatureKind.Call));
constructSignatures = concatenate(constructSignatures, getSignaturesOfType(baseType, SignatureKind.Construct));
stringIndexType = stringIndexType || getIndexTypeOfType(baseType, IndexKind.String);
numberIndexType = numberIndexType || getIndexTypeOfType(baseType, IndexKind.Number);
let instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType;
addInheritedMembers(members, getPropertiesOfObjectType(instantiatedBaseType));
callSignatures = concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, SignatureKind.Call));
constructSignatures = concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, SignatureKind.Construct));
stringIndexType = stringIndexType || getIndexTypeOfType(instantiatedBaseType, IndexKind.String);
numberIndexType = numberIndexType || getIndexTypeOfType(instantiatedBaseType, IndexKind.Number);
}
}
setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType);
}
function resolveClassOrInterfaceMembers(type: InterfaceType): void {
resolveObjectTypeMembers(type, resolveDeclaredMembers(type), emptyArray, emptyArray);
}
function resolveTypeReferenceMembers(type: TypeReference): void {
let target = resolveDeclaredMembers(type.target);
let mapper = createTypeMapper(target.typeParameters, type.typeArguments);
let members = createInstantiatedSymbolTable(target.declaredProperties, mapper);
let callSignatures = instantiateList(target.declaredCallSignatures, mapper, instantiateSignature);
let constructSignatures = instantiateList(target.declaredConstructSignatures, mapper, instantiateSignature);
let stringIndexType = target.declaredStringIndexType ? instantiateType(target.declaredStringIndexType, mapper) : undefined;
let numberIndexType = target.declaredNumberIndexType ? instantiateType(target.declaredNumberIndexType, mapper) : undefined;
forEach(getBaseTypes(target), baseType => {
let instantiatedBaseType = instantiateType(baseType, mapper);
addInheritedMembers(members, getPropertiesOfObjectType(instantiatedBaseType));
callSignatures = concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, SignatureKind.Call));
constructSignatures = concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, SignatureKind.Construct));
stringIndexType = stringIndexType || getIndexTypeOfType(instantiatedBaseType, IndexKind.String);
numberIndexType = numberIndexType || getIndexTypeOfType(instantiatedBaseType, IndexKind.Number);
});
setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType);
let source = resolveDeclaredMembers(type.target);
let typeParameters = concatenate(source.typeParameters, [source.thisType]);
let typeArguments = type.typeArguments && type.typeArguments.length === typeParameters.length ?
type.typeArguments : concatenate(type.typeArguments, [type]);
resolveObjectTypeMembers(type, source, typeParameters, typeArguments);
}
function createSignature(declaration: SignatureDeclaration, typeParameters: TypeParameter[], parameters: Symbol[],
@@ -3128,7 +3258,9 @@ namespace ts {
}
function resolveTupleTypeMembers(type: TupleType) {
let arrayType = resolveStructuredTypeMembers(createArrayType(getUnionType(type.elementTypes, /*noSubtypeReduction*/ true)));
let arrayElementType = getUnionType(type.elementTypes, /*noSubtypeReduction*/ true);
// Make the tuple type itself the 'this' type by including an extra type argument
let arrayType = resolveStructuredTypeMembers(createTypeFromGenericGlobalType(globalArrayType, [arrayElementType, type]));
let members = createTupleTypeMemberSymbols(type.elementTypes);
addInheritedMembers(members, arrayType.properties);
setObjectTypeMembers(type, members, arrayType.callSignatures, arrayType.constructSignatures, arrayType.stringIndexType, arrayType.numberIndexType);
@@ -3287,7 +3419,10 @@ namespace ts {
function resolveStructuredTypeMembers(type: ObjectType): ResolvedType {
if (!(<ResolvedType>type).members) {
if (type.flags & (TypeFlags.Class | TypeFlags.Interface)) {
if (type.flags & TypeFlags.Reference) {
resolveTypeReferenceMembers(<TypeReference>type);
}
else if (type.flags & (TypeFlags.Class | TypeFlags.Interface)) {
resolveClassOrInterfaceMembers(<InterfaceType>type);
}
else if (type.flags & TypeFlags.Anonymous) {
@@ -3302,9 +3437,6 @@ namespace ts {
else if (type.flags & TypeFlags.Intersection) {
resolveIntersectionTypeMembers(<IntersectionType>type);
}
else {
resolveTypeReferenceMembers(<TypeReference>type);
}
}
return <ResolvedType>type;
}
@@ -3770,22 +3902,24 @@ namespace ts {
}
function getTypeListId(types: Type[]) {
switch (types.length) {
case 1:
return "" + types[0].id;
case 2:
return types[0].id + "," + types[1].id;
default:
let result = "";
for (let i = 0; i < types.length; i++) {
if (i > 0) {
result += ",";
if (types) {
switch (types.length) {
case 1:
return "" + types[0].id;
case 2:
return types[0].id + "," + types[1].id;
default:
let result = "";
for (let i = 0; i < types.length; i++) {
if (i > 0) {
result += ",";
}
result += types[i].id;
}
result += types[i].id;
}
return result;
return result;
}
}
return "";
}
// This function is used to propagate certain flags when creating new object type references and union types.
@@ -3804,7 +3938,7 @@ namespace ts {
let id = getTypeListId(typeArguments);
let type = target.instantiations[id];
if (!type) {
let flags = TypeFlags.Reference | getPropagatingFlagsOfTypes(typeArguments);
let flags = TypeFlags.Reference | (typeArguments ? getPropagatingFlagsOfTypes(typeArguments) : 0);
type = target.instantiations[id] = <TypeReference>createObjectType(flags, target.symbol);
type.target = target;
type.typeArguments = typeArguments;
@@ -3863,8 +3997,8 @@ namespace ts {
// Get type from reference to class or interface
function getTypeFromClassOrInterfaceReference(node: TypeReferenceNode | ExpressionWithTypeArguments, symbol: Symbol): Type {
let type = getDeclaredTypeOfSymbol(symbol);
let typeParameters = (<InterfaceType>type).localTypeParameters;
let type = <InterfaceType>getDeclaredTypeOfSymbol(symbol);
let typeParameters = type.localTypeParameters;
if (typeParameters) {
if (!node.typeArguments || node.typeArguments.length !== typeParameters.length) {
error(node, Diagnostics.Generic_type_0_requires_1_type_argument_s, typeToString(type, /*enclosingDeclaration*/ undefined, TypeFormatFlags.WriteArrayAsGenericType), typeParameters.length);
@@ -3873,8 +4007,7 @@ namespace ts {
// In a type reference, the outer type parameters of the referenced class or interface are automatically
// supplied as type arguments and the type reference only specifies arguments for the local type parameters
// of the class or interface.
return createTypeReference(<GenericType>type, concatenate((<InterfaceType>type).outerTypeParameters,
map(node.typeArguments, getTypeFromTypeNode)));
return createTypeReference(<GenericType>type, concatenate(type.outerTypeParameters, map(node.typeArguments, getTypeFromTypeNode)));
}
if (node.typeArguments) {
error(node, Diagnostics.Type_0_is_not_generic, typeToString(type));
@@ -4030,20 +4163,20 @@ namespace ts {
/**
* Instantiates a global type that is generic with some element type, and returns that instantiation.
*/
function createTypeFromGenericGlobalType(genericGlobalType: GenericType, elementType: Type): Type {
return <ObjectType>genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, [elementType]) : emptyObjectType;
function createTypeFromGenericGlobalType(genericGlobalType: GenericType, typeArguments: Type[]): Type {
return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType;
}
function createIterableType(elementType: Type): Type {
return createTypeFromGenericGlobalType(globalIterableType, elementType);
return createTypeFromGenericGlobalType(globalIterableType, [elementType]);
}
function createIterableIteratorType(elementType: Type): Type {
return createTypeFromGenericGlobalType(globalIterableIteratorType, elementType);
return createTypeFromGenericGlobalType(globalIterableIteratorType, [elementType]);
}
function createArrayType(elementType: Type): Type {
return createTypeFromGenericGlobalType(globalArrayType, elementType);
return createTypeFromGenericGlobalType(globalArrayType, [elementType]);
}
function getTypeFromArrayTypeNode(node: ArrayTypeNode): Type {
@@ -4232,6 +4365,26 @@ namespace ts {
return links.resolvedType;
}
function getThisType(node: TypeNode): Type {
let container = getThisContainer(node, /*includeArrowFunctions*/ false);
let parent = container && container.parent;
if (parent && (isClassLike(parent) || parent.kind === SyntaxKind.InterfaceDeclaration)) {
if (!(container.flags & NodeFlags.Static)) {
return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType;
}
}
error(node, Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface);
return unknownType;
}
function getTypeFromThisTypeNode(node: TypeNode): Type {
let links = getNodeLinks(node);
if (!links.resolvedType) {
links.resolvedType = getThisType(node);
}
return links.resolvedType;
}
function getTypeFromTypeNode(node: TypeNode): Type {
switch (node.kind) {
case SyntaxKind.AnyKeyword:
@@ -4246,6 +4399,8 @@ namespace ts {
return esSymbolType;
case SyntaxKind.VoidKeyword:
return voidType;
case SyntaxKind.ThisKeyword:
return getTypeFromThisTypeNode(node);
case SyntaxKind.StringLiteral:
return getTypeFromStringLiteral(<StringLiteral>node);
case SyntaxKind.TypeReference:
@@ -4348,7 +4503,7 @@ namespace ts {
}
return t;
};
mapper.context = context;
return mapper;
}
@@ -4700,7 +4855,7 @@ namespace ts {
else {
if (source.flags & TypeFlags.Reference && target.flags & TypeFlags.Reference && (<TypeReference>source).target === (<TypeReference>target).target) {
// We have type references to same target type, see if relationship holds for all type arguments
if (result = typesRelatedTo((<TypeReference>source).typeArguments, (<TypeReference>target).typeArguments, reportErrors)) {
if (result = typeArgumentsRelatedTo(<TypeReference>source, <TypeReference>target, reportErrors)) {
return result;
}
}
@@ -4731,7 +4886,7 @@ namespace ts {
if (source.flags & TypeFlags.ObjectType && target.flags & TypeFlags.ObjectType) {
if (source.flags & TypeFlags.Reference && target.flags & TypeFlags.Reference && (<TypeReference>source).target === (<TypeReference>target).target) {
// We have type references to same target type, see if all type arguments are identical
if (result = typesRelatedTo((<TypeReference>source).typeArguments, (<TypeReference>target).typeArguments, /*reportErrors*/ false)) {
if (result = typeArgumentsRelatedTo(<TypeReference>source, <TypeReference>target, /*reportErrors*/ false)) {
return result;
}
}
@@ -4782,7 +4937,7 @@ namespace ts {
// We know *exactly* where things went wrong when comparing the types.
// Use this property as the error node as this will be more helpful in
// reasoning about what went wrong.
errorNode = prop.valueDeclaration
errorNode = prop.valueDeclaration;
reportError(Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1,
symbolToString(prop),
typeToString(target));
@@ -4853,9 +5008,14 @@ namespace ts {
return result;
}
function typesRelatedTo(sources: Type[], targets: Type[], reportErrors: boolean): Ternary {
function typeArgumentsRelatedTo(source: TypeReference, target: TypeReference, reportErrors: boolean): Ternary {
let sources = source.typeArguments || emptyArray;
let targets = target.typeArguments || emptyArray;
if (sources.length !== targets.length && relation === identityRelation) {
return Ternary.False;
}
let result = Ternary.True;
for (let i = 0, len = sources.length; i < len; i++) {
for (let i = 0; i < targets.length; i++) {
let related = isRelatedTo(sources[i], targets[i], reportErrors);
if (!related) {
return Ternary.False;
@@ -5082,7 +5242,7 @@ namespace ts {
if (kind === SignatureKind.Construct) {
// Only want to compare the construct signatures for abstractness guarantees.
// Because the "abstractness" of a class is the same across all construct signatures
// (internally we are checking the corresponding declaration), it is enough to perform
// the check and report an error once over all pairs of source and target construct signatures.
@@ -5754,9 +5914,10 @@ namespace ts {
}
else if (source.flags & TypeFlags.Reference && target.flags & TypeFlags.Reference && (<TypeReference>source).target === (<TypeReference>target).target) {
// If source and target are references to the same generic type, infer from type arguments
let sourceTypes = (<TypeReference>source).typeArguments;
let targetTypes = (<TypeReference>target).typeArguments;
for (let i = 0; i < sourceTypes.length; i++) {
let sourceTypes = (<TypeReference>source).typeArguments || emptyArray;
let targetTypes = (<TypeReference>target).typeArguments || emptyArray;
let count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length;
for (let i = 0; i < count; i++) {
inferFromTypes(sourceTypes[i], targetTypes[i]);
}
}
@@ -6251,7 +6412,7 @@ namespace ts {
return getUnionType(assignableConstituents);
}
}
if (isTypeAssignableTo(narrowedTypeCandidate, originalType)) {
// Narrow to the target type if it's assignable to the current type
return narrowedTypeCandidate;
@@ -6458,7 +6619,7 @@ namespace ts {
if (isClassLike(container.parent)) {
let symbol = getSymbolOfNode(container.parent);
return container.flags & NodeFlags.Static ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol);
return container.flags & NodeFlags.Static ? getTypeOfSymbol(symbol) : (<InterfaceType>getDeclaredTypeOfSymbol(symbol)).thisType;
}
return anyType;
}
@@ -6478,46 +6639,46 @@ namespace ts {
let classType = classDeclaration && <InterfaceType>getDeclaredTypeOfSymbol(getSymbolOfNode(classDeclaration));
let baseClassType = classType && getBaseTypes(classType)[0];
let container = getSuperContainer(node, /*includeFunctions*/ true);
let container = getSuperContainer(node, /*includeFunctions*/ true);
let needToCaptureLexicalThis = false;
if (!isCallExpression) {
if (!isCallExpression) {
// adjust the container reference in case if super is used inside arrow functions with arbitrary deep nesting
while (container && container.kind === SyntaxKind.ArrowFunction) {
container = getSuperContainer(container, /*includeFunctions*/ true);
needToCaptureLexicalThis = languageVersion < ScriptTarget.ES6;
}
}
let canUseSuperExpression = isLegalUsageOfSuperExpression(container);
let nodeCheckFlag: NodeCheckFlags = 0;
// always set NodeCheckFlags for 'super' expression node
if (canUseSuperExpression) {
if (canUseSuperExpression) {
if ((container.flags & NodeFlags.Static) || isCallExpression) {
nodeCheckFlag = NodeCheckFlags.SuperStatic;
}
else {
nodeCheckFlag = NodeCheckFlags.SuperInstance;
}
getNodeLinks(node).flags |= nodeCheckFlag;
if (needToCaptureLexicalThis) {
// call expressions are allowed only in constructors so they should always capture correct 'this'
// super property access expressions can also appear in arrow functions -
// in this case they should also use correct lexical this
captureLexicalThis(node.parent, container);
}
}
}
if (!baseClassType) {
if (!classDeclaration || !getClassExtendsHeritageClauseElement(classDeclaration)) {
error(node, Diagnostics.super_can_only_be_referenced_in_a_derived_class);
}
return unknownType;
return unknownType;
}
if (!canUseSuperExpression) {
if (container && container.kind === SyntaxKind.ComputedPropertyName) {
error(node, Diagnostics.super_cannot_be_referenced_in_a_computed_property_name);
@@ -6528,20 +6689,20 @@ namespace ts {
else {
error(node, Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class);
}
return unknownType;
}
if (container.kind === SyntaxKind.Constructor && isInConstructorArgumentInitializer(node, container)) {
// issue custom error message for super property access in constructor arguments (to be aligned with old compiler)
error(node, Diagnostics.super_cannot_be_referenced_in_constructor_arguments);
return unknownType;
}
return nodeCheckFlag === NodeCheckFlags.SuperStatic
? getBaseConstructorTypeOfClass(classType)
: baseClassType;
function isLegalUsageOfSuperExpression(container: Node): boolean {
if (!container) {
return false;
@@ -6577,9 +6738,9 @@ namespace ts {
}
}
}
return false;
}
}
}
// Return contextual type of parameter or undefined if no contextual type is available
@@ -7092,7 +7253,7 @@ namespace ts {
}
}
}
return createArrayType(elementTypes.length ? getUnionType(elementTypes) : undefinedType)
return createArrayType(elementTypes.length ? getUnionType(elementTypes) : undefinedType);
}
function isNumericName(name: DeclarationName): boolean {
@@ -7363,7 +7524,7 @@ namespace ts {
// Maybe there's a string indexer?
let indexerType = getIndexTypeOfType(elementAttributesType, IndexKind.String);
if (indexerType) {
correspondingPropType = indexerType
correspondingPropType = indexerType;
}
else {
// If there's no corresponding property with this name, error
@@ -7431,7 +7592,8 @@ namespace ts {
if (!links.resolvedSymbol) {
if (isJsxIntrinsicIdentifier(node.tagName)) {
links.resolvedSymbol = lookupIntrinsicTag(node);
} else {
}
else {
links.resolvedSymbol = lookupClassTag(node);
}
}
@@ -7844,7 +8006,7 @@ namespace ts {
let prop = getPropertyOfType(apparentType, right.text);
if (!prop) {
if (right.text) {
error(right, Diagnostics.Property_0_does_not_exist_on_type_1, declarationNameToString(right), typeToString(type));
error(right, Diagnostics.Property_0_does_not_exist_on_type_1, declarationNameToString(right), typeToString(type.flags & TypeFlags.ThisType ? apparentType : type));
}
return unknownType;
}
@@ -7852,7 +8014,7 @@ namespace ts {
getNodeLinks(node).resolvedSymbol = prop;
if (prop.parent && prop.parent.flags & SymbolFlags.Class) {
checkClassPropertyAccess(node, left, type, prop);
checkClassPropertyAccess(node, left, apparentType, prop);
}
return getTypeOfSymbol(prop);
}
@@ -8054,9 +8216,9 @@ namespace ts {
function reorderCandidates(signatures: Signature[], result: Signature[]): void {
let lastParent: Node;
let lastSymbol: Symbol;
let cutoffIndex: number = 0;
let cutoffIndex = 0;
let index: number;
let specializedIndex: number = -1;
let specializedIndex = -1;
let spliceIndex: number;
Debug.assert(!result.length);
for (let signature of signatures) {
@@ -10639,7 +10801,7 @@ namespace ts {
}
if (!superCallStatement) {
error(node, Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties);
}
}
else {
// In such a required super call, it is a compile-time error for argument expressions to reference this.
markThisReferencesAsErrors(superCallStatement.expression);
@@ -11085,7 +11247,7 @@ namespace ts {
// Spaces for anyting not declared a 'default export'.
let nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces;
let commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces;
let commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces;
@@ -11093,7 +11255,7 @@ namespace ts {
// declaration spaces for exported and non-exported declarations intersect
for (let d of symbol.declarations) {
let declarationSpaces = getDeclarationSpaces(d);
// Only error on the declarations that conributed to the intersecting spaces.
if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) {
error(d.name, Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, declarationNameToString(d.name));
@@ -11920,7 +12082,7 @@ namespace ts {
function checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node: Node) {
// We only disallow modifier on a method declaration if it is a property of object-literal-expression
if (node.modifiers && node.parent.kind === SyntaxKind.ObjectLiteralExpression){
if (node.modifiers && node.parent.kind === SyntaxKind.ObjectLiteralExpression) {
if (isAsyncFunctionLike(node)) {
if (node.modifiers.length > 1) {
return grammarErrorOnFirstToken(node, Diagnostics.Modifiers_cannot_appear_here);
@@ -12647,6 +12809,7 @@ namespace ts {
checkExportsOnMergedDeclarations(node);
let symbol = getSymbolOfNode(node);
let type = <InterfaceType>getDeclaredTypeOfSymbol(symbol);
let typeWithThis = getTypeWithThisArgument(type);
let staticType = <ObjectType>getTypeOfSymbol(symbol);
let baseTypeNode = getClassExtendsHeritageClauseElement(node);
@@ -12665,7 +12828,7 @@ namespace ts {
}
}
}
checkTypeAssignableTo(type, baseType, node.name || node, Diagnostics.Class_0_incorrectly_extends_base_class_1);
checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name || node, Diagnostics.Class_0_incorrectly_extends_base_class_1);
checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node,
Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1);
@@ -12685,7 +12848,7 @@ namespace ts {
let implementedTypeNodes = getClassImplementsHeritageClauseElements(node);
if (implementedTypeNodes) {
forEach(implementedTypeNodes, typeRefNode => {
for (let typeRefNode of implementedTypeNodes) {
if (!isSupportedExpressionWithTypeArguments(typeRefNode)) {
error(typeRefNode.expression, Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments);
}
@@ -12695,14 +12858,14 @@ namespace ts {
if (t !== unknownType) {
let declaredType = (t.flags & TypeFlags.Reference) ? (<TypeReference>t).target : t;
if (declaredType.flags & (TypeFlags.Class | TypeFlags.Interface)) {
checkTypeAssignableTo(type, t, node.name || node, Diagnostics.Class_0_incorrectly_implements_interface_1);
checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, Diagnostics.Class_0_incorrectly_implements_interface_1);
}
else {
error(typeRefNode, Diagnostics.A_class_may_only_implement_another_class_or_interface);
}
}
}
});
}
}
if (produceDiagnostics) {
@@ -12862,7 +13025,7 @@ namespace ts {
let ok = true;
for (let base of baseTypes) {
let properties = getPropertiesOfObjectType(base);
let properties = getPropertiesOfObjectType(getTypeWithThisArgument(base, type.thisType));
for (let prop of properties) {
if (!hasProperty(seen, prop.name)) {
seen[prop.name] = { prop: prop, containingType: base };
@@ -12907,11 +13070,12 @@ namespace ts {
// Only check this symbol once
if (node === firstInterfaceDecl) {
let type = <InterfaceType>getDeclaredTypeOfSymbol(symbol);
let typeWithThis = getTypeWithThisArgument(type);
// run subsequent checks only if first set succeeded
if (checkInheritedPropertiesAreIdentical(type, node.name)) {
forEach(getBaseTypes(type), baseType => {
checkTypeAssignableTo(type, baseType, node.name, Diagnostics.Interface_0_incorrectly_extends_interface_1);
});
for (let baseType of getBaseTypes(type)) {
checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, Diagnostics.Interface_0_incorrectly_extends_interface_1);
}
checkIndexConstraints(type);
}
}
@@ -12967,7 +13131,7 @@ namespace ts {
}
const previousEnumMemberIsNonConstant = autoValue === undefined;
let initializer = member.initializer;
if (initializer) {
autoValue = computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient);
@@ -13006,7 +13170,7 @@ namespace ts {
}
else if (ambient) {
error(initializer, Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression);
}
}
else {
// Only here do we need to check that the initializer is assignable to the enum type.
checkTypeAssignableTo(checkExpression(initializer), enumType, initializer, /*headMessage*/ undefined);
@@ -13281,7 +13445,7 @@ namespace ts {
// Checks for ambient external modules.
if (isAmbientExternalModule) {
if (!isGlobalSourceFile(node.parent)) {
error(node.name, Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules);
error(node.name, Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces);
}
if (isExternalModuleNameRelative(node.name.text)) {
error(node.name, Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name);
@@ -13306,7 +13470,7 @@ namespace ts {
Debug.assert(node.kind === SyntaxKind.Identifier);
return <Identifier>node;
}
function checkExternalImportOrExportDeclaration(node: ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration): boolean {
let moduleName = getExternalModuleName(node);
if (!nodeIsMissing(moduleName) && moduleName.kind !== SyntaxKind.StringLiteral) {
@@ -13933,11 +14097,11 @@ namespace ts {
}
break;
}
if (introducesArgumentsExoticObject(location)) {
copySymbol(argumentsSymbol, meaning);
}
memberFlags = location.flags;
location = location.parent;
}
@@ -14052,7 +14216,21 @@ namespace ts {
}
if (isHeritageClauseElementIdentifier(<EntityName>entityName)) {
let meaning = entityName.parent.kind === SyntaxKind.ExpressionWithTypeArguments ? SymbolFlags.Type : SymbolFlags.Namespace;
let meaning = SymbolFlags.None;
// In an interface or class, we're definitely interested in a type.
if (entityName.parent.kind === SyntaxKind.ExpressionWithTypeArguments) {
meaning = SymbolFlags.Type;
// In a class 'extends' clause we are also looking for a value.
if (isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) {
meaning |= SymbolFlags.Value;
}
}
else {
meaning = SymbolFlags.Namespace;
}
meaning |= SymbolFlags.Alias;
return resolveEntityName(<EntityName>entityName, meaning);
}
@@ -14144,7 +14322,7 @@ namespace ts {
case SyntaxKind.ThisKeyword:
case SyntaxKind.SuperKeyword:
let type = checkExpression(<Expression>node);
let type = isExpression(node) ? checkExpression(<Expression>node) : getTypeFromTypeNode(<TypeNode>node);
return type.symbol;
case SyntaxKind.ConstructorKeyword:
@@ -14409,9 +14587,9 @@ namespace ts {
}
// const enums and modules that contain only const enums are not considered values from the emit perespective
// unless 'preserveConstEnums' option is set to true
return target !== unknownSymbol &&
target &&
target.flags & SymbolFlags.Value &&
return target !== unknownSymbol &&
target &&
target.flags & SymbolFlags.Value &&
(compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target));
}
@@ -14482,7 +14660,7 @@ namespace ts {
function isFunctionType(type: Type): boolean {
return type.flags & TypeFlags.ObjectType && getSignaturesOfType(type, SignatureKind.Call).length > 0;
}
function getTypeReferenceSerializationKind(typeName: EntityName): TypeReferenceSerializationKind {
// Resolve the symbol as a value to ensure the type can be reached at runtime during emit.
let valueSymbol = resolveEntityName(typeName, SymbolFlags.Value, /*ignoreErrors*/ true);
@@ -14495,7 +14673,7 @@ namespace ts {
let typeSymbol = resolveEntityName(typeName, SymbolFlags.Type, /*ignoreErrors*/ true);
// We might not be able to resolve type symbol so use unknown type in that case (eg error case)
if (!typeSymbol) {
return TypeReferenceSerializationKind.ObjectType;
return TypeReferenceSerializationKind.ObjectType;
}
let type = getDeclaredTypeOfSymbol(typeSymbol);
if (type === unknownType) {
+1 -1
View File
@@ -490,7 +490,7 @@ namespace ts {
fileNames = map(<string[]>json["files"], s => combinePaths(basePath, s));
}
else {
errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array"));
errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array"));
}
}
else {
+6 -6
View File
@@ -52,7 +52,7 @@ namespace ts {
function normalizeKey(key: string) {
return getCanonicalFileName(normalizeSlashes(key));
}
function clear() {
files = {};
}
@@ -117,7 +117,7 @@ namespace ts {
return count;
}
export function filter<T>(array: T[], f: (x: T) => boolean): T[]{
export function filter<T>(array: T[], f: (x: T) => boolean): T[] {
let result: T[];
if (array) {
result = [];
@@ -130,7 +130,7 @@ namespace ts {
return result;
}
export function map<T, U>(array: T[], f: (x: T) => U): U[]{
export function map<T, U>(array: T[], f: (x: T) => U): U[] {
let result: U[];
if (array) {
result = [];
@@ -148,7 +148,7 @@ namespace ts {
return array1.concat(array2);
}
export function deduplicate<T>(array: T[]): T[]{
export function deduplicate<T>(array: T[]): T[] {
let result: T[];
if (array) {
result = [];
@@ -486,7 +486,7 @@ namespace ts {
return text1 ? Comparison.GreaterThan : Comparison.LessThan;
}
export function sortAndDeduplicateDiagnostics(diagnostics: Diagnostic[]): Diagnostic[]{
export function sortAndDeduplicateDiagnostics(diagnostics: Diagnostic[]): Diagnostic[] {
return deduplicateSortedDiagnostics(diagnostics.sort(compareDiagnostics));
}
@@ -795,7 +795,7 @@ namespace ts {
VeryAggressive = 3,
}
export module Debug {
export namespace Debug {
let currentAssertionLevel = AssertionLevel.None;
export function shouldAssert(level: AssertionLevel): boolean {
+19 -3
View File
@@ -52,6 +52,7 @@ namespace ts {
let enclosingDeclaration: Node;
let currentSourceFile: SourceFile;
let reportedDeclarationError = false;
let errorNameNode: DeclarationName;
let emitJsDocComments = compilerOptions.removeComments ? function (declaration: Node) { } : writeJsDocComments;
let emit = compilerOptions.stripInternal ? stripInternal : emitNode;
@@ -152,6 +153,7 @@ namespace ts {
function createAndSetNewTextWriterWithSymbolWriter(): EmitTextWriterWithSymbolWriter {
let writer = <EmitTextWriterWithSymbolWriter>createTextWriter(newLine);
writer.trackSymbol = trackSymbol;
writer.reportInaccessibleThisError = reportInaccessibleThisError;
writer.writeKeyword = writer.write;
writer.writeOperator = writer.write;
writer.writePunctuation = writer.write;
@@ -178,9 +180,11 @@ namespace ts {
let nodeToCheck: Node;
if (declaration.kind === SyntaxKind.VariableDeclaration) {
nodeToCheck = declaration.parent.parent;
} else if (declaration.kind === SyntaxKind.NamedImports || declaration.kind === SyntaxKind.ImportSpecifier || declaration.kind === SyntaxKind.ImportClause) {
}
else if (declaration.kind === SyntaxKind.NamedImports || declaration.kind === SyntaxKind.ImportSpecifier || declaration.kind === SyntaxKind.ImportClause) {
Debug.fail("We should be getting ImportDeclaration instead to write");
} else {
}
else {
nodeToCheck = declaration;
}
@@ -257,6 +261,13 @@ namespace ts {
handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning));
}
function reportInaccessibleThisError() {
if (errorNameNode) {
diagnostics.push(createDiagnosticForNode(errorNameNode, Diagnostics.The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary,
declarationNameToString(errorNameNode)));
}
}
function writeTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration, type: TypeNode, getSymbolAccessibilityDiagnostic: GetSymbolAccessibilityDiagnostic) {
writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic;
write(": ");
@@ -265,7 +276,9 @@ namespace ts {
emitType(type);
}
else {
errorNameNode = declaration.name;
resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, TypeFormatFlags.UseTypeOfFunction, writer);
errorNameNode = undefined;
}
}
@@ -277,7 +290,9 @@ namespace ts {
emitType(signature.type);
}
else {
errorNameNode = signature.name;
resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, TypeFormatFlags.UseTypeOfFunction, writer);
errorNameNode = undefined;
}
}
@@ -326,6 +341,7 @@ namespace ts {
case SyntaxKind.BooleanKeyword:
case SyntaxKind.SymbolKeyword:
case SyntaxKind.VoidKeyword:
case SyntaxKind.ThisKeyword:
case SyntaxKind.StringLiteral:
return writeTextOfNode(currentSourceFile, type);
case SyntaxKind.ExpressionWithTypeArguments:
@@ -1068,7 +1084,7 @@ namespace ts {
// emitted: declare var c: number; // instead of declare var c:number, ;
let elements: Node[] = [];
for (let element of bindingPattern.elements) {
if (element.kind !== SyntaxKind.OmittedExpression){
if (element.kind !== SyntaxKind.OmittedExpression) {
elements.push(element);
}
}
+9 -1
View File
@@ -1300,7 +1300,7 @@
"category": "Error",
"code": 2434
},
"Ambient modules cannot be nested in other modules.": {
"Ambient modules cannot be nested in other modules or namespaces.": {
"category": "Error",
"code": 2435
},
@@ -1652,6 +1652,14 @@
"category": "Error",
"code": 2525
},
"A 'this' type is available only in a non-static member of a class or interface.": {
"category": "Error",
"code": 2526
},
"The inferred type of '{0}' references an inaccessible 'this' type. A type annotation is necessary.": {
"category": "Error",
"code": 2527
},
"JSX element attributes type '{0}' must be an object type.": {
"category": "Error",
"code": 2600
+291 -289
View File
@@ -7,6 +7,264 @@ namespace ts {
return isExternalModule(sourceFile) || isDeclarationFile(sourceFile);
}
type DependencyGroup = Array<ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration>;
let entities: Map<number> = {
"quot": 0x0022,
"amp": 0x0026,
"apos": 0x0027,
"lt": 0x003C,
"gt": 0x003E,
"nbsp": 0x00A0,
"iexcl": 0x00A1,
"cent": 0x00A2,
"pound": 0x00A3,
"curren": 0x00A4,
"yen": 0x00A5,
"brvbar": 0x00A6,
"sect": 0x00A7,
"uml": 0x00A8,
"copy": 0x00A9,
"ordf": 0x00AA,
"laquo": 0x00AB,
"not": 0x00AC,
"shy": 0x00AD,
"reg": 0x00AE,
"macr": 0x00AF,
"deg": 0x00B0,
"plusmn": 0x00B1,
"sup2": 0x00B2,
"sup3": 0x00B3,
"acute": 0x00B4,
"micro": 0x00B5,
"para": 0x00B6,
"middot": 0x00B7,
"cedil": 0x00B8,
"sup1": 0x00B9,
"ordm": 0x00BA,
"raquo": 0x00BB,
"frac14": 0x00BC,
"frac12": 0x00BD,
"frac34": 0x00BE,
"iquest": 0x00BF,
"Agrave": 0x00C0,
"Aacute": 0x00C1,
"Acirc": 0x00C2,
"Atilde": 0x00C3,
"Auml": 0x00C4,
"Aring": 0x00C5,
"AElig": 0x00C6,
"Ccedil": 0x00C7,
"Egrave": 0x00C8,
"Eacute": 0x00C9,
"Ecirc": 0x00CA,
"Euml": 0x00CB,
"Igrave": 0x00CC,
"Iacute": 0x00CD,
"Icirc": 0x00CE,
"Iuml": 0x00CF,
"ETH": 0x00D0,
"Ntilde": 0x00D1,
"Ograve": 0x00D2,
"Oacute": 0x00D3,
"Ocirc": 0x00D4,
"Otilde": 0x00D5,
"Ouml": 0x00D6,
"times": 0x00D7,
"Oslash": 0x00D8,
"Ugrave": 0x00D9,
"Uacute": 0x00DA,
"Ucirc": 0x00DB,
"Uuml": 0x00DC,
"Yacute": 0x00DD,
"THORN": 0x00DE,
"szlig": 0x00DF,
"agrave": 0x00E0,
"aacute": 0x00E1,
"acirc": 0x00E2,
"atilde": 0x00E3,
"auml": 0x00E4,
"aring": 0x00E5,
"aelig": 0x00E6,
"ccedil": 0x00E7,
"egrave": 0x00E8,
"eacute": 0x00E9,
"ecirc": 0x00EA,
"euml": 0x00EB,
"igrave": 0x00EC,
"iacute": 0x00ED,
"icirc": 0x00EE,
"iuml": 0x00EF,
"eth": 0x00F0,
"ntilde": 0x00F1,
"ograve": 0x00F2,
"oacute": 0x00F3,
"ocirc": 0x00F4,
"otilde": 0x00F5,
"ouml": 0x00F6,
"divide": 0x00F7,
"oslash": 0x00F8,
"ugrave": 0x00F9,
"uacute": 0x00FA,
"ucirc": 0x00FB,
"uuml": 0x00FC,
"yacute": 0x00FD,
"thorn": 0x00FE,
"yuml": 0x00FF,
"OElig": 0x0152,
"oelig": 0x0153,
"Scaron": 0x0160,
"scaron": 0x0161,
"Yuml": 0x0178,
"fnof": 0x0192,
"circ": 0x02C6,
"tilde": 0x02DC,
"Alpha": 0x0391,
"Beta": 0x0392,
"Gamma": 0x0393,
"Delta": 0x0394,
"Epsilon": 0x0395,
"Zeta": 0x0396,
"Eta": 0x0397,
"Theta": 0x0398,
"Iota": 0x0399,
"Kappa": 0x039A,
"Lambda": 0x039B,
"Mu": 0x039C,
"Nu": 0x039D,
"Xi": 0x039E,
"Omicron": 0x039F,
"Pi": 0x03A0,
"Rho": 0x03A1,
"Sigma": 0x03A3,
"Tau": 0x03A4,
"Upsilon": 0x03A5,
"Phi": 0x03A6,
"Chi": 0x03A7,
"Psi": 0x03A8,
"Omega": 0x03A9,
"alpha": 0x03B1,
"beta": 0x03B2,
"gamma": 0x03B3,
"delta": 0x03B4,
"epsilon": 0x03B5,
"zeta": 0x03B6,
"eta": 0x03B7,
"theta": 0x03B8,
"iota": 0x03B9,
"kappa": 0x03BA,
"lambda": 0x03BB,
"mu": 0x03BC,
"nu": 0x03BD,
"xi": 0x03BE,
"omicron": 0x03BF,
"pi": 0x03C0,
"rho": 0x03C1,
"sigmaf": 0x03C2,
"sigma": 0x03C3,
"tau": 0x03C4,
"upsilon": 0x03C5,
"phi": 0x03C6,
"chi": 0x03C7,
"psi": 0x03C8,
"omega": 0x03C9,
"thetasym": 0x03D1,
"upsih": 0x03D2,
"piv": 0x03D6,
"ensp": 0x2002,
"emsp": 0x2003,
"thinsp": 0x2009,
"zwnj": 0x200C,
"zwj": 0x200D,
"lrm": 0x200E,
"rlm": 0x200F,
"ndash": 0x2013,
"mdash": 0x2014,
"lsquo": 0x2018,
"rsquo": 0x2019,
"sbquo": 0x201A,
"ldquo": 0x201C,
"rdquo": 0x201D,
"bdquo": 0x201E,
"dagger": 0x2020,
"Dagger": 0x2021,
"bull": 0x2022,
"hellip": 0x2026,
"permil": 0x2030,
"prime": 0x2032,
"Prime": 0x2033,
"lsaquo": 0x2039,
"rsaquo": 0x203A,
"oline": 0x203E,
"frasl": 0x2044,
"euro": 0x20AC,
"image": 0x2111,
"weierp": 0x2118,
"real": 0x211C,
"trade": 0x2122,
"alefsym": 0x2135,
"larr": 0x2190,
"uarr": 0x2191,
"rarr": 0x2192,
"darr": 0x2193,
"harr": 0x2194,
"crarr": 0x21B5,
"lArr": 0x21D0,
"uArr": 0x21D1,
"rArr": 0x21D2,
"dArr": 0x21D3,
"hArr": 0x21D4,
"forall": 0x2200,
"part": 0x2202,
"exist": 0x2203,
"empty": 0x2205,
"nabla": 0x2207,
"isin": 0x2208,
"notin": 0x2209,
"ni": 0x220B,
"prod": 0x220F,
"sum": 0x2211,
"minus": 0x2212,
"lowast": 0x2217,
"radic": 0x221A,
"prop": 0x221D,
"infin": 0x221E,
"ang": 0x2220,
"and": 0x2227,
"or": 0x2228,
"cap": 0x2229,
"cup": 0x222A,
"int": 0x222B,
"there4": 0x2234,
"sim": 0x223C,
"cong": 0x2245,
"asymp": 0x2248,
"ne": 0x2260,
"equiv": 0x2261,
"le": 0x2264,
"ge": 0x2265,
"sub": 0x2282,
"sup": 0x2283,
"nsub": 0x2284,
"sube": 0x2286,
"supe": 0x2287,
"oplus": 0x2295,
"otimes": 0x2297,
"perp": 0x22A5,
"sdot": 0x22C5,
"lceil": 0x2308,
"rceil": 0x2309,
"lfloor": 0x230A,
"rfloor": 0x230B,
"lang": 0x2329,
"rang": 0x232A,
"loz": 0x25CA,
"spades": 0x2660,
"clubs": 0x2663,
"hearts": 0x2665,
"diams": 0x2666
};
// Flags enum to track count of temp variables and a few dedicated names
const enum TempFlags {
Auto = 0x00000000, // No preferred name
@@ -189,7 +447,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
/** If removeComments is true, no leading-comments needed to be emitted **/
let emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos: number) { } : emitLeadingCommentsOfPositionWorker;
let moduleEmitDelegates: Map<(node: SourceFile, startIndex: number) => void> = {
[ModuleKind.ES6]: emitES6Module,
[ModuleKind.AMD]: emitAMDModule,
@@ -695,7 +953,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
}
}
function emitNodeWithCommentsAndWithSourcemap(node: Node) {
emitNodeConsideringCommentsOption(node, emitNodeWithSourceMap);
}
@@ -1190,7 +1448,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
function emitJsxElement(openingNode: JsxOpeningLikeElement, children?: JsxChild[]) {
let syntheticReactRef = <Identifier>createSynthesizedNode(SyntaxKind.Identifier);
syntheticReactRef.text = 'React';
syntheticReactRef.text = "React";
syntheticReactRef.parent = openingNode;
// Call React.createElement(tag, ...
@@ -1434,6 +1692,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
let parent = node.parent;
switch (parent.kind) {
case SyntaxKind.ArrayLiteralExpression:
case SyntaxKind.AsExpression:
case SyntaxKind.BinaryExpression:
case SyntaxKind.CallExpression:
case SyntaxKind.CaseClause:
@@ -1524,8 +1783,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
else if (declaration.kind === SyntaxKind.ImportSpecifier) {
// Identifier references named import
write(getGeneratedNameForNode(<ImportDeclaration>declaration.parent.parent.parent));
var name = (<ImportSpecifier>declaration).propertyName || (<ImportSpecifier>declaration).name;
var identifier = getSourceTextOfNodeFromSourceFile(currentSourceFile, name);
let name = (<ImportSpecifier>declaration).propertyName || (<ImportSpecifier>declaration).name;
let identifier = getSourceTextOfNodeFromSourceFile(currentSourceFile, name);
if (languageVersion === ScriptTarget.ES3 && identifier === "default") {
write(`["default"]`);
}
@@ -2068,15 +2327,15 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
return false;
}
function tryGetConstEnumValue(node: Node): number {
if (compilerOptions.isolatedModules) {
return undefined;
}
return node.kind === SyntaxKind.PropertyAccessExpression || node.kind === SyntaxKind.ElementAccessExpression
return node.kind === SyntaxKind.PropertyAccessExpression || node.kind === SyntaxKind.ElementAccessExpression
? resolver.getConstantValue(<PropertyAccessExpression | ElementAccessExpression>node)
: undefined
: undefined;
}
// Returns 'true' if the code was actually indented, false otherwise.
@@ -3146,7 +3405,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
if (modulekind === ModuleKind.System) {
return;
}
if (!exportEquals && exportSpecifiers && hasProperty(exportSpecifiers, name.text)) {
for (let specifier of exportSpecifiers[name.text]) {
writeLine();
@@ -3161,14 +3420,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
}
}
function emitExportSpecifierInSystemModule(specifier: ExportSpecifier): void {
Debug.assert(modulekind === ModuleKind.System);
if (!resolver.getReferencedValueDeclaration(specifier.propertyName || specifier.name) && !resolver.isValueAliasDeclaration(specifier) ) {
return;
}
writeLine();
emitStart(specifier.name);
write(`${exportFunctionForFile}("`);
@@ -5401,14 +5660,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emitExportMemberAssignments(<Identifier>node.name);
}
}
/*
* Some bundlers (SystemJS builder) sometimes want to rename dependencies.
* Here we check if alternative name was provided for a given moduleName and return it if possible.
*/
function tryRenameExternalModule(moduleName: LiteralExpression): string {
if (currentSourceFile.renamedDependencies && hasProperty(currentSourceFile.renamedDependencies, moduleName.text)) {
return `"${currentSourceFile.renamedDependencies[moduleName.text]}"`
return `"${currentSourceFile.renamedDependencies[moduleName.text]}"`;
}
return undefined;
}
@@ -5730,7 +5989,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emitContainingModuleName(node);
if (languageVersion === ScriptTarget.ES3) {
write("[\"default\"] = ");
} else {
}
else {
write(".default = ");
}
emit(node.expression);
@@ -5823,7 +6083,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
function getExternalModuleNameText(importNode: ImportDeclaration | ExportDeclaration | ImportEqualsDeclaration): string {
let moduleName = getExternalModuleName(importNode);
if (moduleName.kind === SyntaxKind.StringLiteral) {
return tryRenameExternalModule(<LiteralExpression>moduleName) || getLiteralText(<LiteralExpression>moduleName);
return tryRenameExternalModule(<LiteralExpression>moduleName) || getLiteralText(<LiteralExpression>moduleName);
}
return undefined;
@@ -6225,7 +6485,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
function emitSetters(exportStarFunction: string, dependencyGroups: DependencyGroup[]) {
write("setters:[");
for (let i = 0; i < dependencyGroups.length; ++i) {
if (i !== 0) {
write(",");
@@ -6233,17 +6493,17 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
writeLine();
increaseIndent();
let group = dependencyGroups[i];
// derive a unique name for parameter from the first named entry in the group
let parameterName = makeUniqueName(forEach(group, getLocalNameForExternalImport) || "");
write(`function (${parameterName}) {`);
increaseIndent();
for(let entry of group) {
for (let entry of group) {
let importVariableName = getLocalNameForExternalImport(entry) || "";
switch (entry.kind) {
case SyntaxKind.ImportDeclaration:
if (!(<ImportDeclaration>entry).importClause) {
@@ -6279,7 +6539,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write(",");
writeLine();
}
let e = (<ExportDeclaration>entry).exportClause.elements[i];
write(`"`);
emitNodeWithCommentsAndWithoutSourcemap(e.name);
@@ -6289,7 +6549,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
decreaseIndent();
writeLine();
write("});")
write("});");
}
else {
writeLine();
@@ -6324,7 +6584,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
// - import declarations are not emitted since they are already handled in setters
// - export declarations with module specifiers are not emitted since they were already written in setters
// - export declarations without module specifiers are emitted preserving the order
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.ImportDeclaration:
continue;
case SyntaxKind.ExportDeclaration:
@@ -6344,15 +6604,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
default:
writeLine();
emit(statement);
}
}
}
decreaseIndent();
writeLine();
write("}"); // execute
}
type DependencyGroup = Array<ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration>;
function emitSystemModule(node: SourceFile, startIndex: number): void {
collectExternalModuleInfo(node);
// System modules has the following shape
@@ -6372,7 +6630,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write(`"${node.moduleName}", `);
}
write("[");
let groupIndices: Map<number> = {};
let dependencyGroups: DependencyGroup[] = [];
@@ -6392,7 +6650,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
if (i !== 0) {
write(", ");
}
write(text);
}
write(`], function(${exportFunctionForFile}) {`);
@@ -7103,7 +7361,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
if (compilerOptions.removeComments) {
return;
}
let leadingComments: CommentRange[];
if (isEmittedNode) {
leadingComments = getLeadingCommentsToEmit(node);
@@ -7236,7 +7494,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
}
}
function emitShebang() {
let shebang = getShebang(currentSourceFile.text);
if (shebang) {
@@ -7253,260 +7511,4 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
}
}
var entities: Map<number> = {
"quot": 0x0022,
"amp": 0x0026,
"apos": 0x0027,
"lt": 0x003C,
"gt": 0x003E,
"nbsp": 0x00A0,
"iexcl": 0x00A1,
"cent": 0x00A2,
"pound": 0x00A3,
"curren": 0x00A4,
"yen": 0x00A5,
"brvbar": 0x00A6,
"sect": 0x00A7,
"uml": 0x00A8,
"copy": 0x00A9,
"ordf": 0x00AA,
"laquo": 0x00AB,
"not": 0x00AC,
"shy": 0x00AD,
"reg": 0x00AE,
"macr": 0x00AF,
"deg": 0x00B0,
"plusmn": 0x00B1,
"sup2": 0x00B2,
"sup3": 0x00B3,
"acute": 0x00B4,
"micro": 0x00B5,
"para": 0x00B6,
"middot": 0x00B7,
"cedil": 0x00B8,
"sup1": 0x00B9,
"ordm": 0x00BA,
"raquo": 0x00BB,
"frac14": 0x00BC,
"frac12": 0x00BD,
"frac34": 0x00BE,
"iquest": 0x00BF,
"Agrave": 0x00C0,
"Aacute": 0x00C1,
"Acirc": 0x00C2,
"Atilde": 0x00C3,
"Auml": 0x00C4,
"Aring": 0x00C5,
"AElig": 0x00C6,
"Ccedil": 0x00C7,
"Egrave": 0x00C8,
"Eacute": 0x00C9,
"Ecirc": 0x00CA,
"Euml": 0x00CB,
"Igrave": 0x00CC,
"Iacute": 0x00CD,
"Icirc": 0x00CE,
"Iuml": 0x00CF,
"ETH": 0x00D0,
"Ntilde": 0x00D1,
"Ograve": 0x00D2,
"Oacute": 0x00D3,
"Ocirc": 0x00D4,
"Otilde": 0x00D5,
"Ouml": 0x00D6,
"times": 0x00D7,
"Oslash": 0x00D8,
"Ugrave": 0x00D9,
"Uacute": 0x00DA,
"Ucirc": 0x00DB,
"Uuml": 0x00DC,
"Yacute": 0x00DD,
"THORN": 0x00DE,
"szlig": 0x00DF,
"agrave": 0x00E0,
"aacute": 0x00E1,
"acirc": 0x00E2,
"atilde": 0x00E3,
"auml": 0x00E4,
"aring": 0x00E5,
"aelig": 0x00E6,
"ccedil": 0x00E7,
"egrave": 0x00E8,
"eacute": 0x00E9,
"ecirc": 0x00EA,
"euml": 0x00EB,
"igrave": 0x00EC,
"iacute": 0x00ED,
"icirc": 0x00EE,
"iuml": 0x00EF,
"eth": 0x00F0,
"ntilde": 0x00F1,
"ograve": 0x00F2,
"oacute": 0x00F3,
"ocirc": 0x00F4,
"otilde": 0x00F5,
"ouml": 0x00F6,
"divide": 0x00F7,
"oslash": 0x00F8,
"ugrave": 0x00F9,
"uacute": 0x00FA,
"ucirc": 0x00FB,
"uuml": 0x00FC,
"yacute": 0x00FD,
"thorn": 0x00FE,
"yuml": 0x00FF,
"OElig": 0x0152,
"oelig": 0x0153,
"Scaron": 0x0160,
"scaron": 0x0161,
"Yuml": 0x0178,
"fnof": 0x0192,
"circ": 0x02C6,
"tilde": 0x02DC,
"Alpha": 0x0391,
"Beta": 0x0392,
"Gamma": 0x0393,
"Delta": 0x0394,
"Epsilon": 0x0395,
"Zeta": 0x0396,
"Eta": 0x0397,
"Theta": 0x0398,
"Iota": 0x0399,
"Kappa": 0x039A,
"Lambda": 0x039B,
"Mu": 0x039C,
"Nu": 0x039D,
"Xi": 0x039E,
"Omicron": 0x039F,
"Pi": 0x03A0,
"Rho": 0x03A1,
"Sigma": 0x03A3,
"Tau": 0x03A4,
"Upsilon": 0x03A5,
"Phi": 0x03A6,
"Chi": 0x03A7,
"Psi": 0x03A8,
"Omega": 0x03A9,
"alpha": 0x03B1,
"beta": 0x03B2,
"gamma": 0x03B3,
"delta": 0x03B4,
"epsilon": 0x03B5,
"zeta": 0x03B6,
"eta": 0x03B7,
"theta": 0x03B8,
"iota": 0x03B9,
"kappa": 0x03BA,
"lambda": 0x03BB,
"mu": 0x03BC,
"nu": 0x03BD,
"xi": 0x03BE,
"omicron": 0x03BF,
"pi": 0x03C0,
"rho": 0x03C1,
"sigmaf": 0x03C2,
"sigma": 0x03C3,
"tau": 0x03C4,
"upsilon": 0x03C5,
"phi": 0x03C6,
"chi": 0x03C7,
"psi": 0x03C8,
"omega": 0x03C9,
"thetasym": 0x03D1,
"upsih": 0x03D2,
"piv": 0x03D6,
"ensp": 0x2002,
"emsp": 0x2003,
"thinsp": 0x2009,
"zwnj": 0x200C,
"zwj": 0x200D,
"lrm": 0x200E,
"rlm": 0x200F,
"ndash": 0x2013,
"mdash": 0x2014,
"lsquo": 0x2018,
"rsquo": 0x2019,
"sbquo": 0x201A,
"ldquo": 0x201C,
"rdquo": 0x201D,
"bdquo": 0x201E,
"dagger": 0x2020,
"Dagger": 0x2021,
"bull": 0x2022,
"hellip": 0x2026,
"permil": 0x2030,
"prime": 0x2032,
"Prime": 0x2033,
"lsaquo": 0x2039,
"rsaquo": 0x203A,
"oline": 0x203E,
"frasl": 0x2044,
"euro": 0x20AC,
"image": 0x2111,
"weierp": 0x2118,
"real": 0x211C,
"trade": 0x2122,
"alefsym": 0x2135,
"larr": 0x2190,
"uarr": 0x2191,
"rarr": 0x2192,
"darr": 0x2193,
"harr": 0x2194,
"crarr": 0x21B5,
"lArr": 0x21D0,
"uArr": 0x21D1,
"rArr": 0x21D2,
"dArr": 0x21D3,
"hArr": 0x21D4,
"forall": 0x2200,
"part": 0x2202,
"exist": 0x2203,
"empty": 0x2205,
"nabla": 0x2207,
"isin": 0x2208,
"notin": 0x2209,
"ni": 0x220B,
"prod": 0x220F,
"sum": 0x2211,
"minus": 0x2212,
"lowast": 0x2217,
"radic": 0x221A,
"prop": 0x221D,
"infin": 0x221E,
"ang": 0x2220,
"and": 0x2227,
"or": 0x2228,
"cap": 0x2229,
"cup": 0x222A,
"int": 0x222B,
"there4": 0x2234,
"sim": 0x223C,
"cong": 0x2245,
"asymp": 0x2248,
"ne": 0x2260,
"equiv": 0x2261,
"le": 0x2264,
"ge": 0x2265,
"sub": 0x2282,
"sup": 0x2283,
"nsub": 0x2284,
"sube": 0x2286,
"supe": 0x2287,
"oplus": 0x2295,
"otimes": 0x2297,
"perp": 0x22A5,
"sdot": 0x22C5,
"lceil": 0x2308,
"rceil": 0x2309,
"lfloor": 0x230A,
"rfloor": 0x230B,
"lang": 0x2329,
"rang": 0x232A,
"loz": 0x25CA,
"spades": 0x2660,
"clubs": 0x2663,
"hearts": 0x2665,
"diams": 0x2666
}
}
+12 -9
View File
@@ -425,7 +425,7 @@ namespace ts {
// Implement the parser as a singleton module. We do this for perf reasons because creating
// parser instances can actually be expensive enough to impact us on projects with many source
// files.
module Parser {
namespace Parser {
// Share a single scanner across all calls to parse a source file. This helps speed things
// up by avoiding the cost of creating/compiling scanners over and over again.
const scanner = createScanner(ScriptTarget.Latest, /*skipTrivia*/ true);
@@ -518,7 +518,7 @@ namespace ts {
//
// Note: any errors at the end of the file that do not precede a regular node, should get
// attached to the EOF token.
let parseErrorBeforeNextFinishedNode: boolean = false;
let parseErrorBeforeNextFinishedNode = false;
export function parseSourceFile(fileName: string, _sourceText: string, languageVersion: ScriptTarget, _syntaxCursor: IncrementalParser.SyntaxCursor, setParentNodes?: boolean): SourceFile {
initializeState(fileName, _sourceText, languageVersion, _syntaxCursor);
@@ -2360,6 +2360,7 @@ namespace ts {
let node = tryParse(parseKeywordAndNoDot);
return node || parseTypeReferenceOrTypePredicate();
case SyntaxKind.VoidKeyword:
case SyntaxKind.ThisKeyword:
return parseTokenNode<TypeNode>();
case SyntaxKind.TypeOfKeyword:
return parseTypeQuery();
@@ -2382,6 +2383,7 @@ namespace ts {
case SyntaxKind.BooleanKeyword:
case SyntaxKind.SymbolKeyword:
case SyntaxKind.VoidKeyword:
case SyntaxKind.ThisKeyword:
case SyntaxKind.TypeOfKeyword:
case SyntaxKind.OpenBraceToken:
case SyntaxKind.OpenBracketToken:
@@ -3938,7 +3940,8 @@ namespace ts {
forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher);
parseExpected(SyntaxKind.CloseParenToken);
forOrForInOrForOfStatement = forOfStatement;
} else {
}
else {
let forStatement = <ForStatement>createNode(SyntaxKind.ForStatement, pos);
forStatement.initializer = initializer;
parseExpected(SyntaxKind.SemicolonToken);
@@ -4825,7 +4828,7 @@ namespace ts {
return finishNode(node);
}
function parseNameOfClassDeclarationOrExpression(): Identifier {
// implements is a future reserved word so
// 'class implements' might mean either
@@ -4836,11 +4839,11 @@ namespace ts {
? parseIdentifier()
: undefined;
}
function isImplementsClause() {
return token === SyntaxKind.ImplementsKeyword && lookAhead(nextTokenIsIdentifierOrKeyword)
return token === SyntaxKind.ImplementsKeyword && lookAhead(nextTokenIsIdentifierOrKeyword);
}
function parseHeritageClauses(isClassHeritageClause: boolean): NodeArray<HeritageClause> {
// ClassTail[Yield,Await] : (Modified) See 14.5
// ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
@@ -5315,7 +5318,7 @@ namespace ts {
Unknown
}
export module JSDocParser {
export namespace JSDocParser {
export function isJSDocType() {
switch (token) {
case SyntaxKind.AsteriskToken:
@@ -5960,7 +5963,7 @@ namespace ts {
}
}
module IncrementalParser {
namespace IncrementalParser {
export function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks: boolean): SourceFile {
aggressiveChecks = aggressiveChecks || Debug.shouldAssert(AssertionLevel.Aggressive);
+122 -119
View File
@@ -9,9 +9,9 @@ namespace ts {
/* @internal */ export let ioWriteTime = 0;
/** The version of the TypeScript compiler release */
let emptyArray: any[] = [];
export const version = "1.7.0";
export function findConfigFile(searchPath: string): string {
@@ -29,36 +29,36 @@ namespace ts {
}
return undefined;
}
export function resolveTripleslashReference(moduleName: string, containingFile: string): string {
let basePath = getDirectoryPath(containingFile);
let referencedFileName = isRootedDiskPath(moduleName) ? moduleName : combinePaths(basePath, moduleName);
return normalizePath(referencedFileName);
}
export function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations {
let moduleResolution = compilerOptions.moduleResolution !== undefined
let moduleResolution = compilerOptions.moduleResolution !== undefined
? compilerOptions.moduleResolution
: compilerOptions.module === ModuleKind.CommonJS ? ModuleResolutionKind.NodeJs : ModuleResolutionKind.Classic;
switch (moduleResolution) {
case ModuleResolutionKind.NodeJs: return nodeModuleNameResolver(moduleName, containingFile, host);
case ModuleResolutionKind.Classic: return classicNameResolver(moduleName, containingFile, compilerOptions, host);
}
}
export function nodeModuleNameResolver(moduleName: string, containingFile: string, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations {
let containingDirectory = getDirectoryPath(containingFile);
let containingDirectory = getDirectoryPath(containingFile);
if (getRootLength(moduleName) !== 0 || nameStartsWithDotSlashOrDotDotSlash(moduleName)) {
let failedLookupLocations: string[] = [];
let candidate = normalizePath(combinePaths(containingDirectory, moduleName));
let resolvedFileName = loadNodeModuleFromFile(candidate, /* loadOnlyDts */ false, failedLookupLocations, host);
if (resolvedFileName) {
return { resolvedModule: { resolvedFileName }, failedLookupLocations };
}
resolvedFileName = loadNodeModuleFromDirectory(candidate, /* loadOnlyDts */ false, failedLookupLocations, host);
return resolvedFileName
? { resolvedModule: { resolvedFileName }, failedLookupLocations }
@@ -68,7 +68,7 @@ namespace ts {
return loadModuleFromNodeModules(moduleName, containingDirectory, host);
}
}
function loadNodeModuleFromFile(candidate: string, loadOnlyDts: boolean, failedLookupLocation: string[], host: ModuleResolutionHost): string {
if (loadOnlyDts) {
return tryLoad(".d.ts");
@@ -76,7 +76,7 @@ namespace ts {
else {
return forEach(supportedExtensions, tryLoad);
}
function tryLoad(ext: string): string {
let fileName = fileExtensionIs(candidate, ext) ? candidate : candidate + ext;
if (host.fileExists(fileName)) {
@@ -88,13 +88,13 @@ namespace ts {
}
}
}
function loadNodeModuleFromDirectory(candidate: string, loadOnlyDts: boolean, failedLookupLocation: string[], host: ModuleResolutionHost): string {
let packageJsonPath = combinePaths(candidate, "package.json");
if (host.fileExists(packageJsonPath)) {
let jsonContent: { typings?: string };
try {
let jsonText = host.readFile(packageJsonPath);
jsonContent = jsonText ? <{ typings?: string }>JSON.parse(jsonText) : { typings: undefined };
@@ -103,7 +103,7 @@ namespace ts {
// gracefully handle if readFile fails or returns not JSON
jsonContent = { typings: undefined };
}
if (jsonContent.typings) {
let result = loadNodeModuleFromFile(normalizePath(combinePaths(candidate, jsonContent.typings)), loadOnlyDts, failedLookupLocation, host);
if (result) {
@@ -115,12 +115,12 @@ namespace ts {
// record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results
failedLookupLocation.push(packageJsonPath);
}
return loadNodeModuleFromFile(combinePaths(candidate, "index"), loadOnlyDts, failedLookupLocation, host);
}
function loadModuleFromNodeModules(moduleName: string, directory: string, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations {
let failedLookupLocations: string[] = [];
let failedLookupLocations: string[] = [];
directory = normalizeSlashes(directory);
while (true) {
let baseName = getBaseFileName(directory);
@@ -131,36 +131,36 @@ namespace ts {
if (result) {
return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations };
}
result = loadNodeModuleFromDirectory(candidate, /* loadOnlyDts */ true, failedLookupLocations, host);
if (result) {
return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations };
}
}
let parentPath = getDirectoryPath(directory);
if (parentPath === directory) {
break;
}
directory = parentPath;
}
return { resolvedModule: undefined, failedLookupLocations };
}
function nameStartsWithDotSlashOrDotDotSlash(name: string) {
let i = name.lastIndexOf("./", 1);
return i === 0 || (i === 1 && name.charCodeAt(0) === CharacterCodes.dot);
}
export function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations {
// module names that contain '!' are used to reference resources and are not resolved to actual files on disk
if (moduleName.indexOf('!') != -1) {
if (moduleName.indexOf("!") != -1) {
return { resolvedModule: undefined, failedLookupLocations: [] };
}
let searchPath = getDirectoryPath(containingFile);
let searchName: string;
@@ -175,7 +175,7 @@ namespace ts {
// 'logical not' handles both undefined and None cases
return undefined;
}
let candidate = searchName + extension;
if (host.fileExists(candidate)) {
return candidate;
@@ -277,8 +277,7 @@ namespace ts {
}
const newLine = getNewLineCharacter(options);
return {
getSourceFile,
getDefaultLibFileName: options => combinePaths(getDirectoryPath(normalizePath(sys.getExecutingFilePath())), getDefaultLibFileName(options)),
@@ -347,26 +346,26 @@ namespace ts {
let start = new Date().getTime();
host = host || createCompilerHost(options);
const resolveModuleNamesWorker = host.resolveModuleNames
? ((moduleNames: string[], containingFile: string) => host.resolveModuleNames(moduleNames, containingFile))
: ((moduleNames: string[], containingFile: string) => map(moduleNames, moduleName => resolveModuleName(moduleName, containingFile, options, host).resolvedModule));
let filesByName = createFileMap<SourceFile>(fileName => host.getCanonicalFileName(fileName));
if (oldProgram) {
// check properties that can affect structure of the program or module resolution strategy
// if any of these properties has changed - structure cannot be reused
let oldOptions = oldProgram.getCompilerOptions();
if ((oldOptions.module !== options.module) ||
(oldOptions.noResolve !== options.noResolve) ||
(oldOptions.target !== options.target) ||
if ((oldOptions.module !== options.module) ||
(oldOptions.noResolve !== options.noResolve) ||
(oldOptions.target !== options.target) ||
(oldOptions.noLib !== options.noLib) ||
(oldOptions.jsx !== options.jsx)) {
oldProgram = undefined;
}
}
if (!tryReuseStructureFromOldProgram()) {
forEach(rootNames, name => processRootFile(name, false));
// Do not process the default library if:
@@ -427,7 +426,7 @@ namespace ts {
if (!oldProgram) {
return false;
}
Debug.assert(!oldProgram.structureIsReused);
// there is an old program, check if we can reuse its structure
@@ -435,7 +434,7 @@ namespace ts {
if (!arrayIsEqualTo(oldRootNames, rootNames)) {
return false;
}
// check if program source files has changed in the way that can affect structure of the program
let newSourceFiles: SourceFile[] = [];
let modifiedSourceFiles: SourceFile[] = [];
@@ -445,7 +444,7 @@ namespace ts {
return false;
}
if (oldSourceFile !== newSourceFile) {
if (oldSourceFile !== newSourceFile) {
if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) {
// value of no-default-lib has changed
// this will affect if default library is injected into the list of files
@@ -457,14 +456,14 @@ namespace ts {
// tripleslash references has changed
return false;
}
// check imports
collectExternalModuleReferences(newSourceFile);
if (!arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) {
// imports has changed
return false;
}
if (resolveModuleNamesWorker) {
let moduleNames = map(newSourceFile.imports, name => name.text);
let resolutions = resolveModuleNamesWorker(moduleNames, newSourceFile.fileName);
@@ -473,11 +472,11 @@ namespace ts {
let newResolution = resolutions[i];
let oldResolution = getResolvedModule(oldSourceFile, moduleNames[i]);
let resolutionChanged = oldResolution
? !newResolution ||
? !newResolution ||
oldResolution.resolvedFileName !== newResolution.resolvedFileName ||
!!oldResolution.isExternalLibraryImport !== !!newResolution.isExternalLibraryImport
: newResolution;
if (resolutionChanged) {
return false;
}
@@ -491,24 +490,24 @@ namespace ts {
// file has no changes - use it as is
newSourceFile = oldSourceFile;
}
// if file has passed all checks it should be safe to reuse it
newSourceFiles.push(newSourceFile);
}
// update fileName -> file mapping
for (let file of newSourceFiles) {
filesByName.set(file.fileName, file);
}
files = newSourceFiles;
fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics();
for (let modifiedFile of modifiedSourceFiles) {
fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile);
}
oldProgram.structureIsReused = true;
return true;
}
@@ -554,7 +553,7 @@ namespace ts {
// This is because in the -out scenario all files need to be emitted, and therefore all
// files need to be type checked. And the way to specify that all files need to be type
// checked is to not pass the file to getEmitResolver.
let emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out)? undefined : sourceFile);
let emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile);
let start = new Date().getTime();
@@ -568,7 +567,9 @@ namespace ts {
}
function getSourceFile(fileName: string) {
return filesByName.get(fileName);
// first try to use file name as is to find file
// then try to convert relative file name to absolute and use it to retrieve source file
return filesByName.get(fileName) || filesByName.get(getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()));
}
function getDiagnosticsHelper(
@@ -656,7 +657,7 @@ namespace ts {
function getOptionsDiagnostics(): Diagnostic[] {
let allDiagnostics: Diagnostic[] = [];
addRange(allDiagnostics, fileProcessingDiagnostics.getGlobalDiagnostics())
addRange(allDiagnostics, fileProcessingDiagnostics.getGlobalDiagnostics());
addRange(allDiagnostics, programDiagnostics.getGlobalDiagnostics());
return sortAndDeduplicateDiagnostics(allDiagnostics);
}
@@ -673,23 +674,29 @@ namespace ts {
function processRootFile(fileName: string, isDefaultLib: boolean) {
processSourceFile(normalizePath(fileName), isDefaultLib);
}
}
function fileReferenceIsEqualTo(a: FileReference, b: FileReference): boolean {
return a.fileName === b.fileName;
}
function moduleNameIsEqualTo(a: LiteralExpression, b: LiteralExpression): boolean {
return a.text === b.text;
}
function collectExternalModuleReferences(file: SourceFile): void {
if (file.imports) {
return;
}
let imports: LiteralExpression[];
for (let node of file.statements) {
collect(node, /* allowRelativeModuleNames */ true);
}
file.imports = imports || emptyArray;
function collect(node: Node, allowRelativeModuleNames: boolean): void {
switch (node.kind) {
case SyntaxKind.ImportDeclaration:
case SyntaxKind.ImportEqualsDeclaration:
@@ -702,7 +709,9 @@ namespace ts {
break;
}
(imports || (imports = [])).push(<LiteralExpression>moduleNameExpr);
if (allowRelativeModuleNames || !isExternalModuleNameRelative((<LiteralExpression>moduleNameExpr).text)) {
(imports || (imports = [])).push(<LiteralExpression>moduleNameExpr);
}
break;
case SyntaxKind.ModuleDeclaration:
if ((<ModuleDeclaration>node).name.kind === SyntaxKind.StringLiteral && (node.flags & NodeFlags.Ambient || isDeclarationFile(file))) {
@@ -712,23 +721,15 @@ namespace ts {
// The StringLiteral must specify a top - level external module name.
// Relative external module names are not permitted
forEachChild((<ModuleDeclaration>node).body, node => {
if (isExternalModuleImportEqualsDeclaration(node) &&
getExternalModuleImportEqualsDeclarationExpression(node).kind === SyntaxKind.StringLiteral) {
let moduleName = <LiteralExpression>getExternalModuleImportEqualsDeclarationExpression(node);
// TypeScript 1.0 spec (April 2014): 12.1.6
// An ExternalImportDeclaration in anAmbientExternalModuleDeclaration may reference other external modules
// only through top - level external module names. Relative external module names are not permitted.
if (moduleName) {
(imports || (imports = [])).push(moduleName);
}
}
// TypeScript 1.0 spec (April 2014): 12.1.6
// An ExternalImportDeclaration in anAmbientExternalModuleDeclaration may reference other external modules
// only through top - level external module names. Relative external module names are not permitted.
collect(node, /* allowRelativeModuleNames */ false);
});
}
break;
}
}
file.imports = imports || emptyArray;
}
function processSourceFile(fileName: string, isDefaultLib: boolean, refFile?: SourceFile, refPos?: number, refEnd?: number) {
@@ -775,60 +776,62 @@ namespace ts {
// Get source file from normalized fileName
function findSourceFile(fileName: string, isDefaultLib: boolean, refFile?: SourceFile, refPos?: number, refEnd?: number): SourceFile {
let canonicalName = host.getCanonicalFileName(normalizeSlashes(fileName));
if (filesByName.contains(canonicalName)) {
if (filesByName.contains(fileName)) {
// We've already looked for this file, use cached result
return getSourceFileFromCache(fileName, canonicalName, /*useAbsolutePath*/ false);
return getSourceFileFromCache(fileName, /*useAbsolutePath*/ false);
}
else {
let normalizedAbsolutePath = getNormalizedAbsolutePath(fileName, host.getCurrentDirectory());
let canonicalAbsolutePath = host.getCanonicalFileName(normalizedAbsolutePath);
if (filesByName.contains(canonicalAbsolutePath)) {
return getSourceFileFromCache(normalizedAbsolutePath, canonicalAbsolutePath, /*useAbsolutePath*/ true);
}
// We haven't looked for this file, do so now and cache result
let file = host.getSourceFile(fileName, options.target, hostErrorMessage => {
if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) {
fileProcessingDiagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos,
Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage));
}
else {
fileProcessingDiagnostics.add(createCompilerDiagnostic(Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage));
}
});
filesByName.set(canonicalName, file);
if (file) {
skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib;
// Set the source file for normalized absolute path
filesByName.set(canonicalAbsolutePath, file);
let basePath = getDirectoryPath(fileName);
if (!options.noResolve) {
processReferencedFiles(file, basePath);
}
// always process imported modules to record module name resolutions
processImportedModules(file, basePath);
if (isDefaultLib) {
file.isDefaultLib = true;
files.unshift(file);
}
else {
files.push(file);
}
}
let normalizedAbsolutePath = getNormalizedAbsolutePath(fileName, host.getCurrentDirectory());
if (filesByName.contains(normalizedAbsolutePath)) {
const file = getSourceFileFromCache(normalizedAbsolutePath, /*useAbsolutePath*/ true);
// we don't have resolution for this relative file name but the match was found by absolute file name
// store resolution for relative name as well
filesByName.set(fileName, file);
return file;
}
function getSourceFileFromCache(fileName: string, canonicalName: string, useAbsolutePath: boolean): SourceFile {
let file = filesByName.get(canonicalName);
// We haven't looked for this file, do so now and cache result
let file = host.getSourceFile(fileName, options.target, hostErrorMessage => {
if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) {
fileProcessingDiagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos,
Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage));
}
else {
fileProcessingDiagnostics.add(createCompilerDiagnostic(Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage));
}
});
filesByName.set(fileName, file);
if (file) {
skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib;
// Set the source file for normalized absolute path
filesByName.set(normalizedAbsolutePath, file);
let basePath = getDirectoryPath(fileName);
if (!options.noResolve) {
processReferencedFiles(file, basePath);
}
// always process imported modules to record module name resolutions
processImportedModules(file, basePath);
if (isDefaultLib) {
file.isDefaultLib = true;
files.unshift(file);
}
else {
files.push(file);
}
}
return file;
function getSourceFileFromCache(fileName: string, useAbsolutePath: boolean): SourceFile {
let file = filesByName.get(fileName);
if (file && host.useCaseSensitiveFileNames()) {
let sourceFileName = useAbsolutePath ? getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory()) : file.fileName;
if (canonicalName !== sourceFileName) {
if (normalizeSlashes(fileName) !== normalizeSlashes(sourceFileName)) {
if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) {
fileProcessingDiagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos,
Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, sourceFileName));
@@ -848,7 +851,7 @@ namespace ts {
processSourceFile(referencedFileName, /* isDefaultLib */ false, file, ref.pos, ref.end);
});
}
function processImportedModules(file: SourceFile, basePath: string) {
collectExternalModuleReferences(file);
if (file.imports.length) {
@@ -862,11 +865,11 @@ namespace ts {
const importedFile = findModuleSourceFile(resolution.resolvedFileName, file.imports[i]);
if (importedFile && resolution.isExternalLibraryImport) {
if (!isExternalModule(importedFile)) {
let 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));
let 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));
}
else if (!fileExtensionIs(importedFile.fileName, ".d.ts")) {
let start = getTokenPosOfNode(file.imports[i], file)
let start = getTokenPosOfNode(file.imports[i], file);
fileProcessingDiagnostics.add(createFileDiagnostic(file, start, file.imports[i].end - start, Diagnostics.Exported_external_package_typings_can_only_be_in_d_ts_files_Please_contact_the_package_author_to_update_the_package_definition));
}
else if (importedFile.referencedFiles.length) {
+5 -3
View File
@@ -224,7 +224,7 @@ namespace ts {
}
// Perform binary search in one of the Unicode range maps
let lo: number = 0;
let lo = 0;
let hi: number = map.length;
let mid: number;
@@ -657,7 +657,7 @@ namespace ts {
export function getTrailingCommentRanges(text: string, pos: number): CommentRange[] {
return getCommentRanges(text, pos, /*trailing*/ true);
}
/** Optionally, get the shebang */
export function getShebang(text: string): string {
return shebangTriviaRegex.test(text)
@@ -1361,7 +1361,9 @@ namespace ts {
if (text.charCodeAt(pos + 1) === CharacterCodes.equals) {
return pos += 2, token = SyntaxKind.LessThanEqualsToken;
}
if (text.charCodeAt(pos + 1) === CharacterCodes.slash && languageVariant === LanguageVariant.JSX) {
if (languageVariant === LanguageVariant.JSX &&
text.charCodeAt(pos + 1) === CharacterCodes.slash &&
text.charCodeAt(pos + 2) !== CharacterCodes.asterisk) {
return pos += 2, token = SyntaxKind.LessThanSlashToken;
}
return pos++, token = SyntaxKind.LessThanToken;
+7 -7
View File
@@ -29,8 +29,8 @@ namespace ts {
declare var process: any;
declare var global: any;
declare var __filename: string;
declare var Buffer: {
new (str: string, encoding?: string): any;
declare var Buffer: {
new (str: string, encoding?: string): any;
};
declare class Enumerator {
@@ -116,7 +116,7 @@ namespace ts {
return path.toLowerCase();
}
function getNames(collection: any): string[]{
function getNames(collection: any): string[] {
let result: string[] = [];
for (let e = new Enumerator(collection); !e.atEnd(); e.moveNext()) {
result.push(e.item().Name);
@@ -270,9 +270,9 @@ namespace ts {
args: process.argv.slice(2),
newLine: _os.EOL,
useCaseSensitiveFileNames: useCaseSensitiveFileNames,
write(s: string): void {
const buffer = new Buffer(s, "utf8");
let offset: number = 0;
write(s: string): void {
const buffer = new Buffer(s, "utf8");
let offset = 0;
let toWrite: number = buffer.length;
let written = 0;
// 1 is a standard descriptor for stdout
@@ -280,7 +280,7 @@ namespace ts {
offset += written;
toWrite -= written;
}
},
},
readFile,
writeFile,
watchFile: (fileName, callback) => {
+18 -6
View File
@@ -86,7 +86,6 @@ namespace ts {
if (diagnostic.file) {
let loc = getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start);
output += `${ diagnostic.file.fileName }(${ loc.line + 1 },${ loc.character + 1 }): `;
}
@@ -102,6 +101,19 @@ namespace ts {
}
}
function reportWatchDiagnostic(diagnostic: Diagnostic) {
let output = new Date().toLocaleTimeString() + " - ";
if (diagnostic.file) {
let loc = getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start);
output += `${ diagnostic.file.fileName }(${ loc.line + 1 },${ loc.character + 1 }): `;
}
output += `${ flattenDiagnosticMessageText(diagnostic.messageText, sys.newLine) }${ sys.newLine }`;
sys.write(output);
}
function padLeft(s: string, length: number) {
while (s.length < length) {
s = " " + s;
@@ -218,7 +230,7 @@ namespace ts {
let result = readConfigFile(configFileName, sys.readFile);
if (result.error) {
reportDiagnostic(result.error);
reportWatchDiagnostic(result.error);
return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
}
@@ -247,7 +259,7 @@ namespace ts {
}
setCachedProgram(compileResult.program);
reportDiagnostic(createCompilerDiagnostic(Diagnostics.Compilation_complete_Watching_for_file_changes));
reportWatchDiagnostic(createCompilerDiagnostic(Diagnostics.Compilation_complete_Watching_for_file_changes));
}
function getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void) {
@@ -309,7 +321,7 @@ namespace ts {
function recompile() {
timerHandle = undefined;
reportDiagnostic(createCompilerDiagnostic(Diagnostics.File_change_detected_Starting_incremental_compilation));
reportWatchDiagnostic(createCompilerDiagnostic(Diagnostics.File_change_detected_Starting_incremental_compilation));
performCompilation();
}
}
@@ -361,7 +373,7 @@ namespace ts {
function compileProgram(): ExitStatus {
let diagnostics: Diagnostic[];
// First get and report any syntactic errors.
diagnostics = program.getSyntacticDiagnostics();
@@ -497,7 +509,7 @@ namespace ts {
function writeConfigFile(options: CompilerOptions, fileNames: string[]) {
let currentDirectory = sys.getCurrentDirectory();
let file = combinePaths(currentDirectory, 'tsconfig.json');
let file = combinePaths(currentDirectory, "tsconfig.json");
if (sys.fileExists(file)) {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.A_tsconfig_json_file_is_already_defined_at_Colon_0, file));
}
+46 -35
View File
@@ -359,25 +359,26 @@ namespace ts {
}
export const enum NodeFlags {
Export = 0x00000001, // Declarations
Ambient = 0x00000002, // Declarations
Public = 0x00000010, // Property/Method
Private = 0x00000020, // Property/Method
Protected = 0x00000040, // Property/Method
Static = 0x00000080, // Property/Method
Abstract = 0x00000100, // Class/Method/ConstructSignature
Async = 0x00000200, // Property/Method/Function
Default = 0x00000400, // Function/Class (export default declaration)
MultiLine = 0x00000800, // Multi-line array or object literal
Synthetic = 0x00001000, // Synthetic node (for full fidelity)
DeclarationFile = 0x00002000, // Node is a .d.ts file
Let = 0x00004000, // Variable declaration
Const = 0x00008000, // Variable declaration
OctalLiteral = 0x00010000, // Octal numeric literal
Namespace = 0x00020000, // Namespace declaration
ExportContext = 0x00040000, // Export context (initialized by binding)
HasImplicitReturn = 0x00080000, // If function implicitly returns on one of codepaths (initialized by binding)
HasExplicitReturn = 0x00100000, // If function has explicit reachable return on one of codepaths (initialized by binding)
Export = 1 << 1, // Declarations
Ambient = 1 << 2, // Declarations
Public = 1 << 3, // Property/Method
Private = 1 << 4, // Property/Method
Protected = 1 << 5, // Property/Method
Static = 1 << 6, // Property/Method
Abstract = 1 << 7, // Class/Method/ConstructSignature
Async = 1 << 8, // Property/Method/Function
Default = 1 << 9, // Function/Class (export default declaration)
MultiLine = 1 << 10, // Multi-line array or object literal
Synthetic = 1 << 11, // Synthetic node (for full fidelity)
DeclarationFile = 1 << 12, // Node is a .d.ts file
Let = 1 << 13, // Variable declaration
Const = 1 << 14, // Variable declaration
OctalLiteral = 1 << 15, // Octal numeric literal
Namespace = 1 << 16, // Namespace declaration
ExportContext = 1 << 17, // Export context (initialized by binding)
ContainsThis = 1 << 18, // Interface contains references to "this"
HasImplicitReturn = 1 << 19, // If function implicitly returns on one of codepaths (initialized by binding)
HasExplicitReturn = 1 << 20, // If function has explicit reachable return on one of codepaths (initialized by binding)
Modifier = Export | Ambient | Public | Private | Protected | Static | Abstract | Default | Async,
AccessibilityModifier = Public | Private | Protected,
@@ -1246,7 +1247,7 @@ namespace ts {
moduleName: string;
referencedFiles: FileReference[];
languageVariant: LanguageVariant;
// this map is used by transpiler to supply alternative names for dependencies (i.e. in case of bundling)
/* @internal */
renamedDependencies?: Map<string>;
@@ -1314,12 +1315,12 @@ namespace ts {
}
export interface Program extends ScriptReferenceHost {
/**
* Get a list of root file names that were passed to a 'createProgram'
*/
getRootFileNames(): string[]
getRootFileNames(): string[];
/**
* Get a list of files in the program
*/
@@ -1498,6 +1499,7 @@ namespace ts {
// declaration emitter to help determine if it should patch up the final declaration file
// with import statements it previously saw (but chose not to emit).
trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void;
reportInaccessibleThisError(): void;
}
export const enum TypeFormatFlags {
@@ -1600,7 +1602,7 @@ namespace ts {
getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number;
getBlockScopedVariableId(node: Identifier): number;
getReferencedValueDeclaration(reference: Identifier): Declaration;
getTypeReferenceSerializationKind(typeName: EntityName): TypeReferenceSerializationKind;
getTypeReferenceSerializationKind(typeName: EntityName): TypeReferenceSerializationKind;
isOptionalParameter(node: ParameterDeclaration): boolean;
}
@@ -1799,6 +1801,7 @@ namespace ts {
/* @internal */
ContainsAnyFunctionType = 0x00800000, // Type is or contains object literal type
ESSymbol = 0x01000000, // Type of symbol primitive introduced in ES6
ThisType = 0x02000000, // This type
/* @internal */
Intrinsic = Any | String | Number | Boolean | ESSymbol | Void | Undefined | Null,
@@ -1844,6 +1847,7 @@ namespace ts {
typeParameters: TypeParameter[]; // Type parameters (undefined if non-generic)
outerTypeParameters: TypeParameter[]; // Outer type parameters (undefined if none)
localTypeParameters: TypeParameter[]; // Local type parameters (undefined if none)
thisType: TypeParameter; // The "this" type (undefined if none)
/* @internal */
resolvedBaseConstructorType?: Type; // Resolved base constructor type of class
/* @internal */
@@ -1858,10 +1862,17 @@ namespace ts {
declaredNumberIndexType: Type; // Declared numeric index type
}
// Type references (TypeFlags.Reference)
// Type references (TypeFlags.Reference). When a class or interface has type parameters or
// a "this" type, references to the class or interface are made using type references. The
// typeArguments property specififes the types to substitute for the type parameters of the
// class or interface and optionally includes an extra element that specifies the type to
// substitute for "this" in the resulting instantiation. When no extra argument is present,
// the type reference itself is substituted for "this". The typeArguments property is undefined
// if the class or interface has no type parameters and the reference isn't specifying an
// explicit "this" argument.
export interface TypeReference extends ObjectType {
target: GenericType; // Type reference target
typeArguments: Type[]; // Type reference type arguments
typeArguments: Type[]; // Type reference type arguments (undefined if none)
}
// Generic class and interface types
@@ -2016,12 +2027,12 @@ namespace ts {
Error,
Message,
}
export const enum ModuleResolutionKind {
Classic = 1,
NodeJs = 2
}
export interface CompilerOptions {
allowNonTsExtensions?: boolean;
charset?: string;
@@ -2282,15 +2293,15 @@ namespace ts {
byteOrderMark = 0xFEFF,
tab = 0x09, // \t
verticalTab = 0x0B, // \v
}
}
export interface ModuleResolutionHost {
fileExists(fileName: string): boolean;
// readFile function is used to read arbitrary text files on disk, i.e. when resolution procedure needs the content of 'package.json'
// to determine location of bundled typings for node module
readFile(fileName: string): string;
}
export interface ResolvedModule {
resolvedFileName: string;
/*
@@ -2301,12 +2312,12 @@ namespace ts {
*/
isExternalLibraryImport?: boolean;
}
export interface ResolvedModuleWithFailedLookupLocations {
resolvedModule: ResolvedModule;
failedLookupLocations: string[];
}
export interface CompilerHost extends ModuleResolutionHost {
getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile;
getCancellationToken?(): CancellationToken;
@@ -2316,7 +2327,7 @@ namespace ts {
getCanonicalFileName(fileName: string): string;
useCaseSensitiveFileNames(): boolean;
getNewLine(): string;
/*
* CompilerHost must either implement resolveModuleNames (in case if it wants to be completely in charge of
* module name resolution) or provide implementation for methods from ModuleResolutionHost (in this case compiler
@@ -2355,7 +2366,7 @@ namespace ts {
// operation caused diagnostics to be returned by storing and comparing the return value
// of this method before/after the operation is performed.
getModificationCount(): number;
/* @internal */ reattachFileDiagnostics(newFile: SourceFile): void;
}
}
+20 -10
View File
@@ -65,7 +65,8 @@ namespace ts {
increaseIndent: () => { },
decreaseIndent: () => { },
clear: () => str = "",
trackSymbol: () => { }
trackSymbol: () => { },
reportInaccessibleThisError: () => { }
};
}
@@ -98,8 +99,8 @@ namespace ts {
}
return true;
}
}
export function hasResolvedModule(sourceFile: SourceFile, moduleNameText: string): boolean {
return sourceFile.resolvedModules && hasProperty(sourceFile.resolvedModules, moduleNameText);
}
@@ -468,13 +469,12 @@ namespace ts {
else if (node.parent.kind === SyntaxKind.PropertyAccessExpression && (<PropertyAccessExpression>node.parent).name === node) {
node = node.parent;
}
// fall through
case SyntaxKind.QualifiedName:
case SyntaxKind.PropertyAccessExpression:
// At this point, node is either a qualified name or an identifier
Debug.assert(node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.QualifiedName || node.kind === SyntaxKind.PropertyAccessExpression,
"'node' was expected to be a qualified name, identifier or property access in 'isTypeNode'.");
case SyntaxKind.QualifiedName:
case SyntaxKind.PropertyAccessExpression:
case SyntaxKind.ThisKeyword:
let parent = node.parent;
if (parent.kind === SyntaxKind.TypeQuery) {
return false;
@@ -733,6 +733,9 @@ namespace ts {
case SyntaxKind.Constructor:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.CallSignature:
case SyntaxKind.ConstructSignature:
case SyntaxKind.IndexSignature:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.SourceFile:
return node;
@@ -895,7 +898,6 @@ namespace ts {
export function isExpression(node: Node): boolean {
switch (node.kind) {
case SyntaxKind.ThisKeyword:
case SyntaxKind.SuperKeyword:
case SyntaxKind.NullKeyword:
case SyntaxKind.TrueKeyword:
@@ -928,6 +930,7 @@ namespace ts {
case SyntaxKind.JsxElement:
case SyntaxKind.JsxSelfClosingElement:
case SyntaxKind.YieldExpression:
case SyntaxKind.AwaitExpression:
return true;
case SyntaxKind.QualifiedName:
while (node.parent.kind === SyntaxKind.QualifiedName) {
@@ -941,6 +944,7 @@ namespace ts {
// fall through
case SyntaxKind.NumericLiteral:
case SyntaxKind.StringLiteral:
case SyntaxKind.ThisKeyword:
let parent = node.parent;
switch (parent.kind) {
case SyntaxKind.VariableDeclaration:
@@ -993,6 +997,12 @@ namespace ts {
return false;
}
export function isExternalModuleNameRelative(moduleName: string): boolean {
// TypeScript 1.0 spec (April 2014): 11.2.1
// An external module name is "relative" if the first term is "." or "..".
return moduleName.substr(0, 2) === "./" || moduleName.substr(0, 3) === "../" || moduleName.substr(0, 2) === ".\\" || moduleName.substr(0, 3) === "..\\";
}
export function isInstantiatedModule(node: ModuleDeclaration, preserveConstEnums: boolean) {
let moduleState = getModuleInstanceState(node);
return moduleState === ModuleInstanceState.Instantiated ||
@@ -1516,12 +1526,12 @@ namespace ts {
function getModificationCount() {
return modificationCount;
}
function reattachFileDiagnostics(newFile: SourceFile): void {
if (!hasProperty(fileDiagnostics, newFile.fileName)) {
return;
}
for (let diagnostic of fileDiagnostics[newFile.fileName]) {
diagnostic.file = newFile;
}
+7 -3
View File
@@ -1,6 +1,7 @@
/// <reference path="harness.ts" />
/// <reference path="runnerbase.ts" />
/// <reference path="typeWriter.ts" />
/* tslint:disable:no-null */
const enum CompilerTestType {
Conformance,
@@ -32,7 +33,8 @@ class CompilerBaselineRunner extends RunnerBase {
}
else if (testType === CompilerTestType.Test262) {
this.testSuiteName = "test262";
} else {
}
else {
this.testSuiteName = "compiler"; // default to this for historical reasons
}
this.basePath += "/" + this.testSuiteName;
@@ -82,7 +84,8 @@ class CompilerBaselineRunner extends RunnerBase {
otherFiles.push({ unitName: rootDir + unit.name, content: unit.content });
}
});
} else {
}
else {
toBeCompiled = units.map(unit => {
return { unitName: rootDir + unit.name, content: unit.content };
});
@@ -193,7 +196,8 @@ class CompilerBaselineRunner extends RunnerBase {
if (jsCode.length > 0) {
return tsCode + "\r\n\r\n" + jsCode;
} else {
}
else {
return null;
}
});
+90 -53
View File
@@ -18,8 +18,9 @@
/// <reference path="harnessLanguageService.ts" />
/// <reference path="harness.ts" />
/// <reference path="fourslashRunner.ts" />
/* tslint:disable:no-null */
module FourSlash {
namespace FourSlash {
ts.disableIncrementalParsing = false;
// Represents a parsed source file with metadata
@@ -258,7 +259,8 @@ module FourSlash {
this.inputFiles[file.fileName] = file.content;
if (!startResolveFileRef && file.fileOptions[metadataOptionNames.resolveReference] === "true") {
startResolveFileRef = file;
} else if (startResolveFileRef) {
}
else if (startResolveFileRef) {
// If entry point for resolving file references is already specified, report duplication error
throw new Error("There exists a Fourslash file which has resolveReference flag specified; remove duplicated resolveReference flag");
}
@@ -361,7 +363,8 @@ module FourSlash {
this.currentCaretPosition = Math.min(this.currentCaretPosition, this.getFileContent(this.activeFile.fileName).length);
if (count > 0) {
this.scenarioActions.push(`<MoveCaretRight NumberOfChars="${count}" />`);
} else {
}
else {
this.scenarioActions.push(`<MoveCaretLeft NumberOfChars="${-count}" />`);
}
}
@@ -436,7 +439,8 @@ module FourSlash {
predicate = function (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) {
return ((errorMinChar >= startPos) && (errorLimChar >= startPos)) ? true : false;
};
} else {
}
else {
predicate = function (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) {
return ((errorMinChar <= startPos) && (errorLimChar <= startPos)) ? true : false;
};
@@ -476,7 +480,8 @@ module FourSlash {
private printErrorLog(expectErrors: boolean, errors: ts.Diagnostic[]) {
if (expectErrors) {
Harness.IO.log("Expected error not found. Error list is:");
} else {
}
else {
Harness.IO.log("Unexpected error(s) found. Error list is:");
}
@@ -549,10 +554,12 @@ module FourSlash {
if (negative) {
this.verifyMemberListIsEmpty(false);
return;
} else {
}
else {
this.scenarioActions.push("<ShowCompletionList />");
}
} else {
}
else {
this.scenarioActions.push("<ShowCompletionList />");
this.scenarioActions.push(`<VerifyCompletionItemsCount Count="${expectedCount}" ${(negative ? "ExpectsFailure=\"true\" " : "")}/>`);
}
@@ -595,14 +602,16 @@ module FourSlash {
public verifyMemberListIsEmpty(negative: boolean) {
if (negative) {
this.scenarioActions.push("<ShowCompletionList />");
} else {
}
else {
this.scenarioActions.push("<ShowCompletionList ExpectsFailure=\"true\" />");
}
let members = this.getMemberListAtCaret();
if ((!members || members.entries.length === 0) && negative) {
this.raiseError("Member list is empty at Caret");
} else if ((members && members.entries.length !== 0) && !negative) {
}
else if ((members && members.entries.length !== 0) && !negative) {
let errorMsg = "\n" + "Member List contains: [" + members.entries[0].name;
for (let i = 1; i < members.entries.length; i++) {
@@ -639,7 +648,8 @@ module FourSlash {
if ((completions && !completions.isNewIdentifierLocation) && !negative) {
this.raiseError("Expected builder completion entry");
} else if ((completions && completions.isNewIdentifierLocation) && negative) {
}
else if ((completions && completions.isNewIdentifierLocation) && negative) {
this.raiseError("Un-expected builder completion entry");
}
}
@@ -832,7 +842,8 @@ module FourSlash {
if (expectedDocumentation != undefined) {
assert.notEqual(actualQuickInfoDocumentation, expectedDocumentation, this.messageAtLastKnownMarker("quick info doc comment"));
}
} else {
}
else {
if (expectedText !== undefined) {
assert.equal(actualQuickInfoText, expectedText, this.messageAtLastKnownMarker("quick info text"));
}
@@ -1014,7 +1025,8 @@ module FourSlash {
if (!actual) {
this.raiseError("Expected signature help to be present, but it wasn't");
}
} else {
}
else {
if (actual) {
this.raiseError(`Expected no signature help, but got "${JSON.stringify(actual)}"`);
}
@@ -1371,7 +1383,8 @@ module FourSlash {
public type(text: string) {
if (text === "") {
this.taoInvalidReason = "Test used empty-insert workaround.";
} else {
}
else {
this.scenarioActions.push(`<InsertText><![CDATA[${text}]]></InsertText>`);
}
@@ -1398,7 +1411,8 @@ module FourSlash {
if (ch === "(" || ch === ",") {
/* Signature help*/
this.languageService.getSignatureHelpItems(this.activeFile.fileName, offset);
} else if (prevChar === " " && /A-Za-z_/.test(ch)) {
}
else if (prevChar === " " && /A-Za-z_/.test(ch)) {
/* Completions */
this.languageService.getCompletionsAtPosition(this.activeFile.fileName, offset);
}
@@ -1547,7 +1561,8 @@ module FourSlash {
if (marker.position < limChar) {
// Marker is inside the edit - mark it as invalidated (?)
marker.position = -1;
} else {
}
else {
// Move marker back/forward by the appropriate amount
marker.position += (minChar - limChar) + text.length;
}
@@ -1568,7 +1583,8 @@ module FourSlash {
public goToDefinition(definitionIndex: number) {
if (definitionIndex === 0) {
this.scenarioActions.push("<GoToDefinition />");
} else {
}
else {
this.taoInvalidReason = "GoToDefinition not supported for non-zero definition indices";
}
@@ -1650,7 +1666,8 @@ module FourSlash {
if (negative) {
assert.notEqual(actualDefinitionName, expectedName, this.messageAtLastKnownMarker("Definition Info Name"));
assert.notEqual(actualDefinitionContainerName, expectedContainerName, this.messageAtLastKnownMarker("Definition Info Container Name"));
} else {
}
else {
assert.equal(actualDefinitionName, expectedName, this.messageAtLastKnownMarker("Definition Info Name"));
assert.equal(actualDefinitionContainerName, expectedContainerName, this.messageAtLastKnownMarker("Definition Info Container Name"));
}
@@ -1897,22 +1914,22 @@ module FourSlash {
if (expected === undefined) {
if (actual) {
this.raiseError(name + ' failed - expected no template but got {newText: \"' + actual.newText + '\" caretOffset: ' + actual.caretOffset + '}');
this.raiseError(name + " failed - expected no template but got {newText: \"" + actual.newText + "\" caretOffset: " + actual.caretOffset + "}");
}
return;
}
else {
if (actual === undefined) {
this.raiseError(name + ' failed - expected the template {newText: \"' + actual.newText + '\" caretOffset: ' + actual.caretOffset + '} but got nothing instead');
this.raiseError(name + " failed - expected the template {newText: \"" + actual.newText + "\" caretOffset: " + actual.caretOffset + "} but got nothing instead");
}
if (actual.newText !== expected.newText) {
this.raiseError(name + ' failed - expected insertion:\n' + this.clarifyNewlines(expected.newText) + '\nactual insertion:\n' + this.clarifyNewlines(actual.newText));
this.raiseError(name + " failed - expected insertion:\n" + this.clarifyNewlines(expected.newText) + "\nactual insertion:\n" + this.clarifyNewlines(actual.newText));
}
if (actual.caretOffset !== expected.caretOffset) {
this.raiseError(name + ' failed - expected caretOffset: ' + expected.caretOffset + ',\nactual caretOffset:' + actual.caretOffset);
this.raiseError(name + " failed - expected caretOffset: " + expected.caretOffset + ",\nactual caretOffset:" + actual.caretOffset);
}
}
}
@@ -1936,9 +1953,11 @@ module FourSlash {
let actualMatchPosition = -1;
if (bracePosition === actual[0].start) {
actualMatchPosition = actual[1].start;
} else if (bracePosition === actual[1].start) {
}
else if (bracePosition === actual[1].start) {
actualMatchPosition = actual[0].start;
} else {
}
else {
this.raiseError(`verifyMatchingBracePosition failed - could not find the brace position: ${bracePosition} in the returned list: (${actual[0].start},${ts.textSpanEnd(actual[0])}) and (${actual[1].start},${ts.textSpanEnd(actual[1])})`);
}
@@ -2108,7 +2127,7 @@ module FourSlash {
let occurrences = this.getOccurrencesAtCurrentPosition();
if (!occurrences || occurrences.length === 0) {
this.raiseError('verifyOccurrencesAtPositionListContains failed - found 0 references, expected at least one.');
this.raiseError("verifyOccurrencesAtPositionListContains failed - found 0 references, expected at least one.");
}
for (let occurrence of occurrences) {
@@ -2140,12 +2159,12 @@ module FourSlash {
}
public verifyDocumentHighlightsAtPositionListContains(fileName: string, start: number, end: number, fileNamesToSearch: string[], kind?: string) {
this.taoInvalidReason = 'verifyDocumentHighlightsAtPositionListContains NYI';
this.taoInvalidReason = "verifyDocumentHighlightsAtPositionListContains NYI";
let documentHighlights = this.getDocumentHighlightsAtCurrentPosition(fileNamesToSearch);
if (!documentHighlights || documentHighlights.length === 0) {
this.raiseError('verifyDocumentHighlightsAtPositionListContains failed - found 0 highlights, expected at least one.');
this.raiseError("verifyDocumentHighlightsAtPositionListContains failed - found 0 highlights, expected at least one.");
}
for (let documentHighlight of documentHighlights) {
@@ -2168,15 +2187,15 @@ module FourSlash {
}
public verifyDocumentHighlightsAtPositionListCount(expectedCount: number, fileNamesToSearch: string[]) {
this.taoInvalidReason = 'verifyDocumentHighlightsAtPositionListCount NYI';
this.taoInvalidReason = "verifyDocumentHighlightsAtPositionListCount NYI";
let documentHighlights = this.getDocumentHighlightsAtCurrentPosition(fileNamesToSearch);
let actualCount = documentHighlights
? documentHighlights.reduce((currentCount, { highlightSpans }) => currentCount + highlightSpans.length, 0)
let actualCount = documentHighlights
? documentHighlights.reduce((currentCount, { highlightSpans }) => currentCount + highlightSpans.length, 0)
: 0;
if (expectedCount !== actualCount) {
this.raiseError('verifyDocumentHighlightsAtPositionListCount failed - actual: ' + actualCount + ', expected:' + expectedCount);
this.raiseError("verifyDocumentHighlightsAtPositionListCount failed - actual: " + actualCount + ", expected:" + expectedCount);
}
}
@@ -2250,10 +2269,12 @@ module FourSlash {
let index = <number>indexOrName;
if (index >= this.testData.files.length) {
throw new Error(`File index (${index}) in openFile was out of range. There are only ${this.testData.files.length} files in this test.`);
} else {
}
else {
result = this.testData.files[index];
}
} else if (typeof indexOrName === "string") {
}
else if (typeof indexOrName === "string") {
let name = <string>indexOrName;
// names are stored in the compiler with this relative path, this allows people to use goTo.file on just the fileName
@@ -2276,7 +2297,8 @@ module FourSlash {
if (!foundIt) {
throw new Error(`No test file named "${name}" exists. Available file names are: ${availableNames.join(", ")}`);
}
} else {
}
else {
throw new Error("Unknown argument type");
}
@@ -2294,7 +2316,8 @@ module FourSlash {
let markerNames: string[] = [];
for (let m in this.testData.markerPositions) markerNames.push(m);
throw new Error(`Unknown marker "${markerName}" Available markers: ${markerNames.map(m => "\"" + m + "\"").join(", ")}`);
} else {
}
else {
return markerPos;
}
}
@@ -2439,13 +2462,15 @@ module FourSlash {
// Append to the current subfile content, inserting a newline needed
if (currentFileContent === null) {
currentFileContent = "";
} else {
}
else {
// End-of-line
currentFileContent = currentFileContent + "\n";
}
currentFileContent = currentFileContent + line.substr(4);
} else if (line.substr(0, 2) === "//") {
}
else if (line.substr(0, 2) === "//") {
// Comment line, check for global/file @options and record them
let match = optionRegex.exec(line.substr(2));
if (match) {
@@ -2475,17 +2500,20 @@ module FourSlash {
currentFileName = basePath + "/" + match[2];
currentFileOptions[match[1]] = match[2];
} else {
}
else {
// Add other fileMetadata flag
currentFileOptions[match[1]] = match[2];
}
}
}
// TODO: should be '==='?
} else if (line == "" || lineLength === 0) {
}
else if (line == "" || lineLength === 0) {
// Previously blank lines between fourslash content caused it to be considered as 2 files,
// Remove this behavior since it just causes errors now
} else {
}
else {
// Empty line or code line, terminate current subfile if there is one
if (currentFileContent) {
let file = parseFileContent(currentFileContent, currentFileName, markerPositions, markers, ranges);
@@ -2555,7 +2583,8 @@ module FourSlash {
try {
// Attempt to parse the marker value as JSON
markerValue = JSON.parse("{ " + text + " }");
} catch (e) {
}
catch (e) {
reportError(fileName, location.sourceLine, location.sourceColumn, "Unable to parse marker text " + e.message);
}
@@ -2591,7 +2620,8 @@ module FourSlash {
let message = "Marker '" + name + "' is duplicated in the source file contents.";
reportError(marker.fileName, location.sourceLine, location.sourceColumn, message);
return null;
} else {
}
else {
markerMap[name] = marker;
markers.push(marker);
return marker;
@@ -2605,7 +2635,7 @@ module FourSlash {
let validMarkerChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz$1234567890_";
/// The file content (minus metacharacters) so far
let output: string = "";
let output = "";
/// The current marker (or maybe multi-line comment?) we're parsing, possibly
let openMarker: ILocationInformation = null;
@@ -2617,22 +2647,23 @@ module FourSlash {
let localRanges: Range[] = [];
/// The latest position of the start of an unflushed plain text area
let lastNormalCharPosition: number = 0;
let lastNormalCharPosition = 0;
/// The total number of metacharacters removed from the file (so far)
let difference: number = 0;
let difference = 0;
/// The fourslash file state object we are generating
let state: State = State.none;
/// Current position data
let line: number = 1;
let column: number = 1;
let line = 1;
let column = 1;
let flush = (lastSafeCharIndex: number) => {
if (lastSafeCharIndex === undefined) {
output = output + content.substr(lastNormalCharPosition);
} else {
}
else {
output = output + content.substr(lastNormalCharPosition, lastSafeCharIndex - lastNormalCharPosition);
}
};
@@ -2655,7 +2686,8 @@ module FourSlash {
flush(i - 1);
lastNormalCharPosition = i + 1;
difference += 2;
} else if (previousChar === "|" && currentChar === "]") {
}
else if (previousChar === "|" && currentChar === "]") {
// found a range end
let rangeStart = openRanges.pop();
if (!rangeStart) {
@@ -2674,7 +2706,8 @@ module FourSlash {
flush(i - 1);
lastNormalCharPosition = i + 1;
difference += 2;
} else if (previousChar === "/" && currentChar === "*") {
}
else if (previousChar === "/" && currentChar === "*") {
// found a possible marker start
state = State.inSlashStarMarker;
openMarker = {
@@ -2683,7 +2716,8 @@ module FourSlash {
sourceLine: line,
sourceColumn: column,
};
} else if (previousChar === "{" && currentChar === "|") {
}
else if (previousChar === "{" && currentChar === "|") {
// found an object marker start
state = State.inObjectMarker;
openMarker = {
@@ -2736,10 +2770,12 @@ module FourSlash {
// Reset the state
openMarker = null;
state = State.none;
} else if (validMarkerChars.indexOf(currentChar) < 0) {
}
else if (validMarkerChars.indexOf(currentChar) < 0) {
if (currentChar === "*" && i < content.length - 1 && content.charAt(i + 1) === "/") {
// The marker is about to be closed, ignore the 'invalid' char
} else {
}
else {
// We've hit a non-valid marker character, so we were actually in a block comment
// Bail out the text we've gathered so far back into the output
flush(i);
@@ -2755,7 +2791,8 @@ module FourSlash {
if (currentChar === "\n" && previousChar === "\r") {
// Ignore trailing \n after a \r
continue;
} else if (currentChar === "\n" || currentChar === "\r") {
}
else if (currentChar === "\n" || currentChar === "\r") {
line++;
column = 1;
continue;
+5 -3
View File
@@ -1,6 +1,7 @@
///<reference path="fourslash.ts" />
///<reference path="harness.ts"/>
///<reference path="runnerbase.ts" />
/* tslint:disable:no-null */
const enum FourSlashTestType {
Native,
@@ -25,8 +26,8 @@ class FourSlashRunner extends RunnerBase {
this.testSuiteName = "fourslash-shims";
break;
case FourSlashTestType.ShimsWithPreprocess:
this.basePath = 'tests/cases/fourslash/shims-pp';
this.testSuiteName = 'fourslash-shims-pp';
this.basePath = "tests/cases/fourslash/shims-pp";
this.testSuiteName = "fourslash-shims-pp";
break;
case FourSlashTestType.Server:
this.basePath = "tests/cases/fourslash/server";
@@ -87,7 +88,8 @@ class FourSlashRunner extends RunnerBase {
FourSlash.xmlData.forEach(xml => {
if (xml.invalidReason !== null) {
lines.push("<!-- Skipped " + xml.originalName + ", reason: " + xml.invalidReason + " -->");
} else {
}
else {
lines.push(" <Scenario Name=\"" + xml.originalName + "\">");
xml.actions.forEach(action => {
lines.push(" " + action);
+63 -46
View File
@@ -23,6 +23,7 @@
/// <reference path="external\chai.d.ts"/>
/// <reference path="sourceMapRecorder.ts"/>
/// <reference path="runnerbase.ts"/>
/* tslint:disable:no-null */
// Block scoped definitions work poorly for global variables, temporarily enable var
/* tslint:disable:no-var-keyword */
@@ -35,7 +36,7 @@ declare var __dirname: string; // Node-specific
var global = <any>Function("return this").call(null);
/* tslint:enable:no-var-keyword */
module Utils {
namespace Utils {
// Setup some globals based on the current environment
export const enum ExecutionEnvironment {
Node,
@@ -54,17 +55,17 @@ module Utils {
return ExecutionEnvironment.Node;
}
}
export let currentExecutionEnvironment = getExecutionEnvironment();
const Buffer: BufferConstructor = currentExecutionEnvironment !== ExecutionEnvironment.Browser
? require("buffer").Buffer
const Buffer: BufferConstructor = currentExecutionEnvironment !== ExecutionEnvironment.Browser
? require("buffer").Buffer
: undefined;
export function encodeString(s: string): string {
return Buffer ? (new Buffer(s)).toString("utf8") : s;
}
export function evalFile(fileContents: string, fileName: string, nodeContext?: any) {
let environment = getExecutionEnvironment();
switch (environment) {
@@ -76,7 +77,8 @@ module Utils {
let vm = require("vm");
if (nodeContext) {
vm.runInNewContext(fileContents, nodeContext, fileName);
} else {
}
else {
vm.runInThisContext(fileContents, fileName);
}
break;
@@ -126,7 +128,8 @@ module Utils {
let cachedResult = cache[key];
if (cachedResult) {
return cachedResult;
} else {
}
else {
return cache[key] = f.apply(this, arguments);
}
});
@@ -396,7 +399,7 @@ module Utils {
}
}
module Harness.Path {
namespace Harness.Path {
export function getFileName(fullPath: string) {
return fullPath.replace(/^.*[\\\/]/, "");
}
@@ -409,7 +412,7 @@ module Harness.Path {
}
}
module Harness {
namespace Harness {
export interface IO {
newLine(): string;
getCurrentDirectory(): string;
@@ -431,11 +434,11 @@ module Harness {
readDirectory(path: string, extension?: string, exclude?: string[]): string[];
}
export var IO: IO;
// harness always uses one kind of new line
const harnessNewLine = "\r\n";
module IOImpl {
namespace IOImpl {
declare class Enumerator {
public atEnd(): boolean;
public moveNext(): boolean;
@@ -443,14 +446,15 @@ module Harness {
constructor(o: any);
}
export module CScript {
export namespace CScript {
let fso: any;
if (global.ActiveXObject) {
fso = new global.ActiveXObject("Scripting.FileSystemObject");
} else {
}
else {
fso = {};
}
export const args = () => ts.sys.args;
export const getExecutingFilePath = () => ts.sys.getExecutingFilePath();
export const exit = (exitCode: number) => ts.sys.exit(exitCode);
@@ -511,16 +515,17 @@ module Harness {
};
}
export module Node {
export namespace Node {
declare let require: any;
let fs: any, pathModule: any;
if (require) {
fs = require("fs");
pathModule = require("path");
} else {
}
else {
fs = pathModule = {};
}
export const resolvePath = (path: string) => ts.sys.resolvePath(path);
export const getCurrentDirectory = () => ts.sys.getCurrentDirectory();
export const newLine = () => harnessNewLine;
@@ -545,7 +550,8 @@ module Harness {
export function deleteFile(path: string) {
try {
fs.unlinkSync(path);
} catch (e) {
}
catch (e) {
}
}
@@ -559,7 +565,8 @@ module Harness {
// Node will just continue to repeat the root path, rather than return null
if (dirPath === path) {
dirPath = null;
} else {
}
else {
return dirPath;
}
}
@@ -596,7 +603,7 @@ module Harness {
};
}
export module Network {
export namespace Network {
let serverRoot = "http://localhost:8888/";
export const newLine = () => harnessNewLine;
@@ -605,10 +612,11 @@ module Harness {
export const args = () => <string[]>[];
export const getExecutingFilePath = () => "";
export const exit = (exitCode: number) => {};
let supportsCodePage = () => false;
module Http {
let supportsCodePage = () => false;
export let log = (s: string) => console.log(s);
namespace Http {
function waitForXHR(xhr: XMLHttpRequest) {
while (xhr.readyState !== 4) { }
return { status: xhr.status, responseText: xhr.responseText };
@@ -683,10 +691,12 @@ module Harness {
if (dirPath.match(/localhost:\d+$/) || dirPath.match(/localhost:\d+\/$/)) {
dirPath = null;
// path + fileName
} else if (dirPath.indexOf(".") === -1) {
}
else if (dirPath.indexOf(".") === -1) {
dirPath = dirPath.substring(0, dirPath.lastIndexOf("/"));
// path
} else {
}
else {
// strip any trailing slash
if (dirPath.match(/.*\/$/)) {
dirPath = dirPath.substring(0, dirPath.length - 2);
@@ -710,7 +720,8 @@ module Harness {
let results = response.responseText.split(",");
if (spec) {
return results.filter(file => spec.test(file));
} else {
}
else {
return results;
}
}
@@ -720,13 +731,12 @@ module Harness {
};
export let listFiles = Utils.memoize(_listFilesImpl);
export let log = (s: string) => console.log(s);
export function readFile(file: string) {
let response = Http.getFileFromServerSync(serverRoot + file);
if (response.status === 200) {
return response.responseText;
} else {
}
else {
return null;
}
}
@@ -754,7 +764,7 @@ module Harness {
}
}
module Harness {
namespace Harness {
let tcServicesFileName = "typescriptServices.js";
export let libFolder: string;
@@ -785,7 +795,7 @@ module Harness {
export let lightMode = false;
/** Functionality for compiling TypeScript code */
export module Compiler {
export namespace Compiler {
/** Aggregate various writes into a single array of lines. Useful for passing to the
* TypeScript compiler to fill with source code or errors.
*/
@@ -864,7 +874,7 @@ module Harness {
languageVersion: ts.ScriptTarget) {
// We'll only assert inletiants outside of light mode.
const shouldAssertInvariants = !Harness.lightMode;
// Only set the parent nodes if we're asserting inletiants. We don't need them otherwise.
let result = ts.createSourceFile(fileName, sourceText, languageVersion, /*setParentNodes:*/ shouldAssertInvariants);
@@ -1102,7 +1112,7 @@ module Harness {
}
let useCaseSensitiveFileNames = options.useCaseSensitiveFileNames !== undefined ? options.useCaseSensitiveFileNames : Harness.IO.useCaseSensitiveFileNames();
let fileOutputs: GeneratedFile[] = [];
let programFiles = inputFiles.concat(includeBuiltFiles).map(file => file.unitName);
@@ -1231,12 +1241,12 @@ module Harness {
.filter(s => s.length > 0)
.map(s => "!!! " + ts.DiagnosticCategory[error.category].toLowerCase() + " TS" + error.code + ": " + s);
errLines.forEach(e => outputLines.push(e));
// do not count errors from lib.d.ts here, they are computed separately as numLibraryDiagnostics
// if lib.d.ts is explicitly included in input files and there are some errors in it (i.e. because of duplicate identifiers)
// then they will be added twice thus triggering 'total errors' assertion with condition
// 'totalErrorsReportedInNonLibraryFiles + numLibraryDiagnostics + numTest262HarnessDiagnostics, diagnostics.length
if (!error.file || !isLibraryFile(error.file.fileName)) {
totalErrorsReportedInNonLibraryFiles++;
}
@@ -1280,7 +1290,8 @@ module Harness {
// On the last line of the file, fake the next line start number so that we handle errors on the last character of the file correctly
if (lineIndex === lines.length - 1) {
nextLineStart = inputFile.content.length;
} else {
}
else {
nextLineStart = lineStarts[lineIndex + 1];
}
// Emit this line from the original file
@@ -1344,7 +1355,7 @@ module Harness {
// FileName header + content
result += "/*====== " + outputFile.fileName + " ======*/\r\n";
result += outputFile.code;
}
@@ -1444,7 +1455,7 @@ module Harness {
}
}
export module TestCaseParser {
export namespace TestCaseParser {
/** all the necessary information to set the right compiler settings */
export interface CompilerSettings {
[name: string]: string;
@@ -1497,7 +1508,8 @@ module Harness {
let metaDataName = testMetaData[1].toLowerCase();
if (metaDataName === "filename") {
currentFileOptions[testMetaData[1]] = testMetaData[2];
} else {
}
else {
continue;
}
@@ -1518,16 +1530,19 @@ module Harness {
currentFileOptions = {};
currentFileName = testMetaData[2];
refs = [];
} else {
}
else {
// First metadata marker in the file
currentFileName = testMetaData[2];
}
} else {
}
else {
// Subfile content line
// Append to the current subfile content, inserting a newline needed
if (currentFileContent === null) {
currentFileContent = "";
} else {
}
else {
// End-of-line
currentFileContent = currentFileContent + "\n";
}
@@ -1553,7 +1568,7 @@ module Harness {
}
/** Support class for baseline files */
export module Baseline {
export namespace Baseline {
export interface BaselineOptions {
Subfolder?: string;
@@ -1581,7 +1596,8 @@ module Harness {
function baselinePath(fileName: string, type: string, baselineFolder: string, subfolder?: string) {
if (subfolder !== undefined) {
return Harness.userSpecifiedRoot + baselineFolder + "/" + subfolder + "/" + type + "/" + fileName;
} else {
}
else {
return Harness.userSpecifiedRoot + baselineFolder + "/" + type + "/" + fileName;
}
}
@@ -1673,7 +1689,8 @@ module Harness {
actual = generateActual(actualFileName, generateContent);
let comparison = compareToBaseline(actual, relativeFileName, opts);
writeComparison(comparison.expected, comparison.actual, relativeFileName, actualFileName, descriptionForDescribe);
} else {
}
else {
actual = generateActual(actualFileName, generateContent);
let comparison = compareToBaseline(actual, relativeFileName, opts);
+35 -35
View File
@@ -3,11 +3,11 @@
/// <reference path="..\server\client.ts" />
/// <reference path="harness.ts" />
module Harness.LanguageService {
namespace Harness.LanguageService {
export class ScriptInfo {
public version: number = 1;
public editRanges: { length: number; textChangeRange: ts.TextChangeRange; }[] = [];
public lineMap: number[] = null;
public lineMap: number[] = undefined;
constructor(public fileName: string, public content: string) {
this.setContent(content);
@@ -95,8 +95,8 @@ module Harness.LanguageService {
let oldShim = <ScriptSnapshotProxy>oldScript;
let range = this.scriptSnapshot.getChangeRange(oldShim.scriptSnapshot);
if (range === null) {
return null;
if (range === undefined) {
return undefined;
}
return JSON.stringify({ span: { start: range.span.start, length: range.span.length }, newLength: range.newLength });
@@ -118,11 +118,11 @@ module Harness.LanguageService {
getPreProcessedFileInfo(fileName: string, fileContents: string): ts.PreProcessedFileInfo;
}
export class LanguageServiceAdapterHost {
export class LanguageServiceAdapterHost {
protected fileNameToScript: ts.Map<ScriptInfo> = {};
constructor(protected cancellationToken = DefaultHostCancellationToken.Instance,
protected settings = ts.getDefaultCompilerOptions()) {
protected settings = ts.getDefaultCompilerOptions()) {
}
public getNewLine(): string {
@@ -145,7 +145,7 @@ module Harness.LanguageService {
public editScript(fileName: string, start: number, end: number, newText: string) {
let script = this.getScriptInfo(fileName);
if (script !== null) {
if (script !== undefined) {
script.editContent(start, end, newText);
return;
}
@@ -169,7 +169,7 @@ module Harness.LanguageService {
}
/// Native adapter
class NativeLanguageServiceHost extends LanguageServiceAdapterHost implements ts.LanguageServiceHost {
class NativeLanguageServiceHost extends LanguageServiceAdapterHost implements ts.LanguageServiceHost {
getCompilationSettings() { return this.settings; }
getCancellationToken() { return this.cancellationToken; }
getCurrentDirectory(): string { return ""; }
@@ -191,7 +191,7 @@ module Harness.LanguageService {
export class NativeLanugageServiceAdapter implements LanguageServiceAdapter {
private host: NativeLanguageServiceHost;
constructor(cancellationToken?: ts.HostCancellationToken, options?: ts.CompilerOptions) {
constructor(cancellationToken?: ts.HostCancellationToken, options?: ts.CompilerOptions) {
this.host = new NativeLanguageServiceHost(cancellationToken, options);
}
getHost() { return this.host; }
@@ -204,14 +204,14 @@ module Harness.LanguageService {
class ShimLanguageServiceHost extends LanguageServiceAdapterHost implements ts.LanguageServiceShimHost, ts.CoreServicesShimHost {
private nativeHost: NativeLanguageServiceHost;
public getModuleResolutionsForFile: (fileName: string)=> string;
public getModuleResolutionsForFile: (fileName: string) => string;
constructor(preprocessToResolve: boolean, cancellationToken?: ts.HostCancellationToken, options?: ts.CompilerOptions) {
super(cancellationToken, options);
this.nativeHost = new NativeLanguageServiceHost(cancellationToken, options);
if (preprocessToResolve) {
let compilerOptions = this.nativeHost.getCompilationSettings()
let compilerOptions = this.nativeHost.getCompilationSettings();
let moduleResolutionHost: ts.ModuleResolutionHost = {
fileExists: fileName => this.getScriptInfo(fileName) !== undefined,
readFile: fileName => {
@@ -230,7 +230,7 @@ module Harness.LanguageService {
}
}
return JSON.stringify(imports);
}
};
}
}
@@ -247,7 +247,7 @@ module Harness.LanguageService {
getScriptFileNames(): string { return JSON.stringify(this.nativeHost.getScriptFileNames()); }
getScriptSnapshot(fileName: string): ts.ScriptSnapshotShim {
let nativeScriptSnapshot = this.nativeHost.getScriptSnapshot(fileName);
return nativeScriptSnapshot && new ScriptSnapshotProxy(nativeScriptSnapshot);
return nativeScriptSnapshot && new ScriptSnapshotProxy(nativeScriptSnapshot);
}
getScriptVersion(fileName: string): string { return this.nativeHost.getScriptVersion(fileName); }
getLocalizedDiagnosticMessages(): string { return JSON.stringify({}); }
@@ -255,17 +255,17 @@ module Harness.LanguageService {
readDirectory(rootDir: string, extension: string): string {
throw new Error("NYI");
}
fileExists(fileName: string) { return this.getScriptInfo(fileName) !== undefined; }
readFile(fileName: string) {
fileExists(fileName: string) { return this.getScriptInfo(fileName) !== undefined; }
readFile(fileName: string) {
let snapshot = this.nativeHost.getScriptSnapshot(fileName);
return snapshot && snapshot.getText(0, snapshot.getLength());
}
}
log(s: string): void { this.nativeHost.log(s); }
trace(s: string): void { this.nativeHost.trace(s); }
error(s: string): void { this.nativeHost.error(s); }
}
class ClassifierShimProxy implements ts.Classifier {
class ClassifierShimProxy implements ts.Classifier {
constructor(private shim: ts.ClassifierShim) {
}
getEncodedLexicalClassifications(text: string, lexState: ts.EndOfLineState, classifyKeywordsInGenerics?: boolean): ts.Classifications {
@@ -302,7 +302,7 @@ module Harness.LanguageService {
if (parsedResult.error) {
throw new Error("Language Service Shim Error: " + JSON.stringify(parsedResult.error));
}
else if (parsedResult.canceled) {
else if (parsedResult.canceled) {
throw new ts.OperationCanceledException();
}
return parsedResult.result;
@@ -369,7 +369,7 @@ module Harness.LanguageService {
getDefinitionAtPosition(fileName: string, position: number): ts.DefinitionInfo[] {
return unwrapJSONCallResult(this.shim.getDefinitionAtPosition(fileName, position));
}
getTypeDefinitionAtPosition(fileName: string, position: number): ts.DefinitionInfo[]{
getTypeDefinitionAtPosition(fileName: string, position: number): ts.DefinitionInfo[] {
return unwrapJSONCallResult(this.shim.getTypeDefinitionAtPosition(fileName, position));
}
getReferencesAtPosition(fileName: string, position: number): ts.ReferenceEntry[] {
@@ -474,19 +474,19 @@ module Harness.LanguageService {
}
// Server adapter
class SessionClientHost extends NativeLanguageServiceHost implements ts.server.SessionClientHost {
class SessionClientHost extends NativeLanguageServiceHost implements ts.server.SessionClientHost {
private client: ts.server.SessionClient;
constructor(cancellationToken: ts.HostCancellationToken, settings: ts.CompilerOptions) {
super(cancellationToken, settings);
}
onMessage(message: string): void {
onMessage(message: string): void {
}
writeMessage(message: string): void {
writeMessage(message: string): void {
}
setClient(client: ts.server.SessionClient) {
@@ -504,7 +504,7 @@ module Harness.LanguageService {
}
}
class SessionServerHost implements ts.server.ServerHost, ts.server.Logger {
class SessionServerHost implements ts.server.ServerHost, ts.server.Logger {
args: string[] = [];
newLine: string;
useCaseSensitiveFileNames: boolean = false;
@@ -513,23 +513,23 @@ module Harness.LanguageService {
this.newLine = this.host.getNewLine();
}
onMessage(message: string): void {
onMessage(message: string): void {
}
writeMessage(message: string): void {
}
write(message: string): void {
write(message: string): void {
this.writeMessage(message);
}
readFile(fileName: string): string {
if (fileName.indexOf(Harness.Compiler.defaultLibFileName) >= 0) {
if (fileName.indexOf(Harness.Compiler.defaultLibFileName) >= 0) {
fileName = Harness.Compiler.defaultLibFileName;
}
let snapshot = this.host.getScriptSnapshot(fileName);
return snapshot && snapshot.getText(0, snapshot.getLength());
}
@@ -567,8 +567,8 @@ module Harness.LanguageService {
readDirectory(path: string, extension?: string): string[] {
throw new Error("Not implemented Yet.");
}
watchFile(fileName: string, callback: (fileName: string) => void): ts.FileWatcher {
watchFile(fileName: string, callback: (fileName: string) => void): ts.FileWatcher {
return { close() { } };
}
@@ -582,7 +582,7 @@ module Harness.LanguageService {
msg(message: string) {
return this.host.log(message);
}
loggingEnabled() {
return true;
}
@@ -602,7 +602,7 @@ module Harness.LanguageService {
startGroup(): void {
}
}
export class ServerLanugageServiceAdapter implements LanguageServiceAdapter {
private host: SessionClientHost;
private client: ts.server.SessionClient;
+3 -2
View File
@@ -1,6 +1,7 @@
/// <reference path="..\..\src\compiler\sys.ts" />
/// <reference path="..\..\src\harness\harness.ts" />
/// <reference path="..\..\src\harness\runnerbase.ts" />
/* tslint:disable:no-null */
interface FileInformation {
contents: string;
@@ -76,7 +77,7 @@ interface PlaybackControl {
endRecord(): void;
}
module Playback {
namespace Playback {
let recordLog: IOLog = undefined;
let replayLog: IOLog = undefined;
let recordLogFileNameBase = "";
@@ -95,7 +96,7 @@ module Playback {
run.reset = () => {
lookup = null;
};
return run;
}
+3 -2
View File
@@ -1,5 +1,6 @@
///<reference path="harness.ts" />
///<reference path="runnerbase.ts" />
/* tslint:disable:no-null */
// Test case is json of below type in tests/cases/project/
interface ProjectRunnerTestCase {
@@ -199,7 +200,7 @@ class ProjectRunner extends RunnerBase {
}
}
function batchCompilerProjectTestCase(moduleKind: ts.ModuleKind): BatchCompileProjectTestCaseResult{
function batchCompilerProjectTestCase(moduleKind: ts.ModuleKind): BatchCompileProjectTestCaseResult {
let nonSubfolderDiskFiles = 0;
let outputFiles: BatchCompileProjectTestCaseEmittedFile[] = [];
@@ -300,7 +301,7 @@ class ProjectRunner extends RunnerBase {
allInputFiles.unshift(findOutpuDtsFile(outputDtsFileName));
}
else {
let outputDtsFileName = ts.removeFileExtension(compilerOptions.outFile|| compilerOptions.out) + ".d.ts";
let outputDtsFileName = ts.removeFileExtension(compilerOptions.outFile || compilerOptions.out) + ".d.ts";
let outputDtsFile = findOutpuDtsFile(outputDtsFileName);
if (!ts.contains(allInputFiles, outputDtsFile)) {
allInputFiles.unshift(outputDtsFile);
+5 -3
View File
@@ -20,8 +20,10 @@
/// <reference path="rwcRunner.ts" />
/// <reference path="harness.ts" />
/* tslint:disable:no-null */
let runners: RunnerBase[] = [];
let iterations: number = 1;
let iterations = 1;
function runTests(runners: RunnerBase[]) {
for (let i = iterations; i > 0; i--) {
@@ -68,10 +70,10 @@ if (testConfigFile !== "") {
case "fourslash-shims":
runners.push(new FourSlashRunner(FourSlashTestType.Shims));
break;
case 'fourslash-shims-pp':
case "fourslash-shims-pp":
runners.push(new FourSlashRunner(FourSlashTestType.ShimsWithPreprocess));
break;
case 'fourslash-server':
case "fourslash-server":
runners.push(new FourSlashRunner(FourSlashTestType.Server));
break;
case "fourslash-generated":
+2 -2
View File
@@ -25,12 +25,12 @@ abstract class RunnerBase {
let fixedPath = path;
// full paths either start with a drive letter or / for *nix, shouldn't have \ in the path at this point
let fullPath = /(\w+:|\/)?([\w+\-\.]|\/)*\.tsx?/g;
let fullPath = /(\w+:|\/)?([\w+\-\.]|\/)*\.tsx?/g;
let fullPathList = fixedPath.match(fullPath);
if (fullPathList) {
fullPathList.forEach((match: string) => fixedPath = fixedPath.replace(match, Harness.Path.getFileName(match)));
}
// when running in the browser the 'full path' is the host name, shows up in error baselines
let localHost = /http:\/localhost:\d+/g;
fixedPath = fixedPath.replace(localHost, "");
+3 -2
View File
@@ -2,8 +2,9 @@
/// <reference path="runnerbase.ts" />
/// <reference path="loggedIO.ts" />
/// <reference path="..\compiler\commandLineParser.ts"/>
/* tslint:disable:no-null */
module RWC {
namespace RWC {
function runWithIOLog(ioLog: IOLog, fn: (oldIO: Harness.IO) => void) {
let oldIO = Harness.IO;
@@ -105,7 +106,7 @@ module RWC {
}
otherFiles.push(getHarnessCompilerInputUnit(fileRead.path));
}
else if (!opts.options.noLib && Harness.isLibraryFile(fileRead.path)){
else if (!opts.options.noLib && Harness.isLibraryFile(fileRead.path)) {
if (!inInputList) {
// If useCustomLibraryFile is true, we will use lib.d.ts from json object
// otherwise use the lib.d.ts from built/local
+4 -4
View File
@@ -15,14 +15,14 @@
///<reference path="harness.ts"/>
module Harness.SourceMapRecoder {
namespace Harness.SourceMapRecoder {
interface SourceMapSpanWithDecodeErrors {
sourceMapSpan: ts.SourceMapSpan;
decodeErrors: string[];
}
module SourceMapDecoder {
namespace SourceMapDecoder {
let sourceMapMappings: string;
let sourceMapNames: string[];
let decodingIndex: number;
@@ -202,7 +202,7 @@ module Harness.SourceMapRecoder {
}
}
module SourceMapSpanWriter {
namespace SourceMapSpanWriter {
let sourceMapRecoder: Compiler.WriterAggregator;
let sourceMapSources: string[];
let sourceMapNames: string[];
@@ -442,7 +442,7 @@ module Harness.SourceMapRecoder {
for (let i = 0; i < sourceMapDataList.length; i++) {
let sourceMapData = sourceMapDataList[i];
let prevSourceFile: ts.SourceFile = null;
let prevSourceFile: ts.SourceFile;
SourceMapSpanWriter.intializeSourceMapSpanWriter(sourceMapRecoder, sourceMapData, jsFiles[i]);
for (let j = 0; j < sourceMapData.sourceMapDecodedMappings.length; j++) {
+1
View File
@@ -1,5 +1,6 @@
/// <reference path="harness.ts" />
/// <reference path="runnerbase.ts" />
/* tslint:disable:no-null */
class Test262BaselineRunner extends RunnerBase {
private static basePath = "internal/cases/test262";
+18 -18
View File
@@ -202,8 +202,8 @@ interface AnalyserNode extends AudioNode {
smoothingTimeConstant: number;
getByteFrequencyData(array: Uint8Array): void;
getByteTimeDomainData(array: Uint8Array): void;
getFloatFrequencyData(array: any): void;
getFloatTimeDomainData(array: any): void;
getFloatFrequencyData(array: Float32Array): void;
getFloatTimeDomainData(array: Float32Array): void;
}
declare var AnalyserNode: {
@@ -290,7 +290,7 @@ interface AudioBuffer {
length: number;
numberOfChannels: number;
sampleRate: number;
getChannelData(channel: number): any;
getChannelData(channel: number): Float32Array;
}
declare var AudioBuffer: {
@@ -334,7 +334,7 @@ interface AudioContext extends EventTarget {
createMediaElementSource(mediaElement: HTMLMediaElement): MediaElementAudioSourceNode;
createOscillator(): OscillatorNode;
createPanner(): PannerNode;
createPeriodicWave(real: any, imag: any): PeriodicWave;
createPeriodicWave(real: Float32Array, imag: Float32Array): PeriodicWave;
createScriptProcessor(bufferSize?: number, numberOfInputChannels?: number, numberOfOutputChannels?: number): ScriptProcessorNode;
createStereoPanner(): StereoPannerNode;
createWaveShaper(): WaveShaperNode;
@@ -392,7 +392,7 @@ interface AudioParam {
linearRampToValueAtTime(value: number, endTime: number): void;
setTargetAtTime(target: number, startTime: number, timeConstant: number): void;
setValueAtTime(value: number, startTime: number): void;
setValueCurveAtTime(values: any, startTime: number, duration: number): void;
setValueCurveAtTime(values: Float32Array, startTime: number, duration: number): void;
}
declare var AudioParam: {
@@ -468,7 +468,7 @@ interface BiquadFilterNode extends AudioNode {
frequency: AudioParam;
gain: AudioParam;
type: string;
getFrequencyResponse(frequencyHz: any, magResponse: any, phaseResponse: any): void;
getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void;
}
declare var BiquadFilterNode: {
@@ -10893,7 +10893,7 @@ declare var WEBGL_depth_texture: {
}
interface WaveShaperNode extends AudioNode {
curve: any;
curve: Float32Array;
oversample: string;
}
@@ -11080,34 +11080,34 @@ interface WebGLRenderingContext {
texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, video: HTMLVideoElement): void;
texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, pixels: ImageData): void;
uniform1f(location: WebGLUniformLocation, x: number): void;
uniform1fv(location: WebGLUniformLocation, v: any): void;
uniform1fv(location: WebGLUniformLocation, v: Float32Array): void;
uniform1i(location: WebGLUniformLocation, x: number): void;
uniform1iv(location: WebGLUniformLocation, v: Int32Array): void;
uniform2f(location: WebGLUniformLocation, x: number, y: number): void;
uniform2fv(location: WebGLUniformLocation, v: any): void;
uniform2fv(location: WebGLUniformLocation, v: Float32Array): void;
uniform2i(location: WebGLUniformLocation, x: number, y: number): void;
uniform2iv(location: WebGLUniformLocation, v: Int32Array): void;
uniform3f(location: WebGLUniformLocation, x: number, y: number, z: number): void;
uniform3fv(location: WebGLUniformLocation, v: any): void;
uniform3fv(location: WebGLUniformLocation, v: Float32Array): void;
uniform3i(location: WebGLUniformLocation, x: number, y: number, z: number): void;
uniform3iv(location: WebGLUniformLocation, v: Int32Array): void;
uniform4f(location: WebGLUniformLocation, x: number, y: number, z: number, w: number): void;
uniform4fv(location: WebGLUniformLocation, v: any): void;
uniform4fv(location: WebGLUniformLocation, v: Float32Array): void;
uniform4i(location: WebGLUniformLocation, x: number, y: number, z: number, w: number): void;
uniform4iv(location: WebGLUniformLocation, v: Int32Array): void;
uniformMatrix2fv(location: WebGLUniformLocation, transpose: boolean, value: any): void;
uniformMatrix3fv(location: WebGLUniformLocation, transpose: boolean, value: any): void;
uniformMatrix4fv(location: WebGLUniformLocation, transpose: boolean, value: any): void;
uniformMatrix2fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array): void;
uniformMatrix3fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array): void;
uniformMatrix4fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array): void;
useProgram(program: WebGLProgram): void;
validateProgram(program: WebGLProgram): void;
vertexAttrib1f(indx: number, x: number): void;
vertexAttrib1fv(indx: number, values: any): void;
vertexAttrib1fv(indx: number, values: Float32Array): void;
vertexAttrib2f(indx: number, x: number, y: number): void;
vertexAttrib2fv(indx: number, values: any): void;
vertexAttrib2fv(indx: number, values: Float32Array): void;
vertexAttrib3f(indx: number, x: number, y: number, z: number): void;
vertexAttrib3fv(indx: number, values: any): void;
vertexAttrib3fv(indx: number, values: Float32Array): void;
vertexAttrib4f(indx: number, x: number, y: number, z: number, w: number): void;
vertexAttrib4fv(indx: number, values: any): void;
vertexAttrib4fv(indx: number, values: Float32Array): void;
vertexAttribPointer(indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void;
viewport(x: number, y: number, width: number, height: number): void;
ACTIVE_ATTRIBUTES: number;
+1 -1
View File
@@ -17,7 +17,7 @@ interface AudioBuffer {
length: number;
numberOfChannels: number;
sampleRate: number;
getChannelData(channel: number): any;
getChannelData(channel: number): Float32Array;
}
declare var AudioBuffer: {
+21 -21
View File
@@ -325,7 +325,7 @@ namespace ts.formatting {
let lastIndentedLine: number;
let indentationOnLastIndentedLine: number;
let edits: TextChange[] = [];
formattingScanner.advance();
@@ -354,12 +354,12 @@ namespace ts.formatting {
* If list element is in the range - its indentation will be equal
* to inherited indentation from its predecessors.
*/
function tryComputeIndentationForListItem(startPos: number,
endPos: number,
parentStartLine: number,
range: TextRange,
function tryComputeIndentationForListItem(startPos: number,
endPos: number,
parentStartLine: number,
range: TextRange,
inheritedIndentation: number): number {
if (rangeOverlapsWithStartEnd(range, startPos, endPos)) {
if (inheritedIndentation !== Constants.Unknown) {
return inheritedIndentation;
@@ -376,7 +376,7 @@ namespace ts.formatting {
return Constants.Unknown;
}
function computeIndentation(
node: TextRangeWithKind,
startLine: number,
@@ -419,8 +419,8 @@ namespace ts.formatting {
// if node is located on the same line with the parent
// - inherit indentation from the parent
// - push children if either parent of node itself has non-zero delta
indentation = startLine === lastIndentedLine
? indentationOnLastIndentedLine
indentation = startLine === lastIndentedLine
? indentationOnLastIndentedLine
: parentDynamicIndentation.getIndentation();
delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta() + delta);
}
@@ -586,7 +586,7 @@ namespace ts.formatting {
if (!rangeOverlapsWithStartEnd(originalRange, child.pos, child.end)) {
return inheritedIndentation;
}
if (child.getFullWidth() === 0) {
return inheritedIndentation;
}
@@ -624,8 +624,8 @@ namespace ts.formatting {
return inheritedIndentation;
}
function processChildNodes(nodes: NodeArray<Node>,
parent: Node,
function processChildNodes(nodes: NodeArray<Node>,
parent: Node,
parentStartLine: number,
parentDynamicIndentation: DynamicIndentation): void {
@@ -751,7 +751,7 @@ namespace ts.formatting {
// indent token only if is it is in target range and does not overlap with any error ranges
if (tokenIndentation !== Constants.Unknown) {
insertIndentation(currentTokenInfo.token.pos, tokenIndentation, lineAdded);
lastIndentedLine = tokenStart.line;
indentationOnLastIndentedLine = tokenIndentation;
}
@@ -772,12 +772,12 @@ namespace ts.formatting {
}
}
function processRange(range: TextRangeWithKind,
rangeStart: LineAndCharacter,
parent: Node,
contextNode: Node,
function processRange(range: TextRangeWithKind,
rangeStart: LineAndCharacter,
parent: Node,
contextNode: Node,
dynamicIndentation: DynamicIndentation): boolean {
let rangeHasError = rangeContainsError(range);
let lineAdded: boolean;
if (!rangeHasError && !previousRangeHasError) {
@@ -787,7 +787,7 @@ namespace ts.formatting {
trimTrailingWhitespacesForLines(originalStart.line, rangeStart.line);
}
else {
lineAdded =
lineAdded =
processPair(range, rangeStart.line, parent, previousRange, previousRangeStartLine, previousParent, contextNode, dynamicIndentation)
}
}
@@ -933,8 +933,8 @@ namespace ts.formatting {
let lineStartPosition = getStartPositionOfLine(line, sourceFile);
let lineEndPosition = getEndLinePosition(line, sourceFile);
// do not trim whitespaces in comments
if (range && isComment(range.kind) && range.pos <= lineEndPosition && range.end > lineEndPosition) {
// do not trim whitespaces in comments or template expression
if (range && (isComment(range.kind) || isStringOrRegularExpressionOrTemplateLiteral(range.kind)) && range.pos <= lineEndPosition && range.end > lineEndPosition) {
continue;
}
+2 -7
View File
@@ -19,13 +19,7 @@ namespace ts.formatting {
}
// no indentation in string \regex\template literals
let precedingTokenIsLiteral =
precedingToken.kind === SyntaxKind.StringLiteral ||
precedingToken.kind === SyntaxKind.RegularExpressionLiteral ||
precedingToken.kind === SyntaxKind.NoSubstitutionTemplateLiteral ||
precedingToken.kind === SyntaxKind.TemplateHead ||
precedingToken.kind === SyntaxKind.TemplateMiddle ||
precedingToken.kind === SyntaxKind.TemplateTail;
let precedingTokenIsLiteral = isStringOrRegularExpressionOrTemplateLiteral(precedingToken.kind);
if (precedingTokenIsLiteral && precedingToken.getStart(sourceFile) <= position && precedingToken.end > position) {
return 0;
}
@@ -404,6 +398,7 @@ namespace ts.formatting {
function nodeContentIsAlwaysIndented(kind: SyntaxKind): boolean {
switch (kind) {
case SyntaxKind.ExpressionStatement:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.ClassExpression:
case SyntaxKind.InterfaceDeclaration:
+10 -5
View File
@@ -725,7 +725,7 @@ namespace ts {
}
getBaseTypes(): ObjectType[] {
return this.flags & (TypeFlags.Class | TypeFlags.Interface)
? this.checker.getBaseTypes(<TypeObject & InterfaceType>this)
? this.checker.getBaseTypes(<InterfaceType><Type>this)
: undefined;
}
}
@@ -3549,6 +3549,9 @@ namespace ts {
if (parent && (parent.kind === SyntaxKind.JsxSelfClosingElement || parent.kind === SyntaxKind.JsxOpeningElement)) {
return <JsxOpeningLikeElement>parent;
}
else if (parent.kind === SyntaxKind.JsxAttribute) {
return <JsxOpeningLikeElement>parent.parent;
}
break;
// The context token is the closing } or " of an attribute, which means
@@ -3659,9 +3662,9 @@ namespace ts {
return containingNodeKind === SyntaxKind.Parameter;
case SyntaxKind.AsKeyword:
containingNodeKind === SyntaxKind.ImportSpecifier ||
containingNodeKind === SyntaxKind.ExportSpecifier ||
containingNodeKind === SyntaxKind.NamespaceImport;
return containingNodeKind === SyntaxKind.ImportSpecifier ||
containingNodeKind === SyntaxKind.ExportSpecifier ||
containingNodeKind === SyntaxKind.NamespaceImport;
case SyntaxKind.ClassKeyword:
case SyntaxKind.EnumKeyword:
@@ -6247,7 +6250,8 @@ namespace ts {
}
return node.parent.kind === SyntaxKind.TypeReference ||
(node.parent.kind === SyntaxKind.ExpressionWithTypeArguments && !isExpressionWithTypeArgumentsInClassExtendsClause(<ExpressionWithTypeArguments>node.parent));
(node.parent.kind === SyntaxKind.ExpressionWithTypeArguments && !isExpressionWithTypeArgumentsInClassExtendsClause(<ExpressionWithTypeArguments>node.parent)) ||
node.kind === SyntaxKind.ThisKeyword && !isExpression(node);
}
function isNamespaceReference(node: Node): boolean {
@@ -7809,6 +7813,7 @@ namespace ts {
case SyntaxKind.GreaterThanEqualsToken:
case SyntaxKind.InstanceOfKeyword:
case SyntaxKind.InKeyword:
case SyntaxKind.AsKeyword:
case SyntaxKind.EqualsEqualsToken:
case SyntaxKind.ExclamationEqualsToken:
case SyntaxKind.EqualsEqualsEqualsToken:
+20 -9
View File
@@ -9,7 +9,7 @@ namespace ts {
export function getEndLinePosition(line: number, sourceFile: SourceFile): number {
Debug.assert(line >= 0);
let lineStarts = sourceFile.getLineStarts();
let lineIndex = line;
if (lineIndex + 1 === lineStarts.length) {
// last line - return EOF
@@ -128,7 +128,8 @@ namespace ts {
return isCompletedNode((<IfStatement>n).thenStatement, sourceFile);
case SyntaxKind.ExpressionStatement:
return isCompletedNode((<ExpressionStatement>n).expression, sourceFile);
return isCompletedNode((<ExpressionStatement>n).expression, sourceFile) ||
hasChildOfKind(n, SyntaxKind.SemicolonToken);
case SyntaxKind.ArrayLiteralExpression:
case SyntaxKind.ArrayBindingPattern:
@@ -170,7 +171,7 @@ namespace ts {
case SyntaxKind.VoidExpression:
case SyntaxKind.YieldExpression:
case SyntaxKind.SpreadElementExpression:
let unaryWordExpression = (<TypeOfExpression|DeleteExpression|VoidExpression|YieldExpression|SpreadElementExpression>n);
let unaryWordExpression = (<TypeOfExpression | DeleteExpression | VoidExpression | YieldExpression | SpreadElementExpression>n);
return isCompletedNode(unaryWordExpression.expression, sourceFile);
case SyntaxKind.TaggedTemplateExpression:
@@ -252,7 +253,7 @@ namespace ts {
});
// Either we didn't find an appropriate list, or the list must contain us.
Debug.assert(!syntaxList || contains(syntaxList.getChildren(), node));
Debug.assert(!syntaxList || contains(syntaxList.getChildren(), node));
return syntaxList;
}
@@ -388,7 +389,7 @@ namespace ts {
// if this is the case - then we should assume that token in question is located in previous child.
if (position < child.end && (nodeHasTokens(child) || child.kind === SyntaxKind.JsxText)) {
const start = child.getStart(sourceFile);
const lookInPreviousChild =
const lookInPreviousChild =
(start >= position) || // cursor in the leading trivia
(child.kind === SyntaxKind.JsxText && start === child.end); // whitespace only JsxText
@@ -425,7 +426,7 @@ namespace ts {
}
}
}
export function isInString(sourceFile: SourceFile, position: number) {
let token = getTokenAtPosition(sourceFile, position);
return token && token.kind === SyntaxKind.StringLiteral && position > token.getStart();
@@ -473,7 +474,7 @@ namespace ts {
let commentRanges = getLeadingCommentRanges(sourceFile.text, token.pos);
return forEach(commentRanges, jsDocPrefix);
function jsDocPrefix(c: CommentRange): boolean {
var text = sourceFile.text;
return text.length >= c.pos + 3 && text[c.pos] === '/' && text[c.pos + 1] === '*' && text[c.pos + 2] === '*';
@@ -562,6 +563,15 @@ namespace ts {
return kind === SyntaxKind.SingleLineCommentTrivia || kind === SyntaxKind.MultiLineCommentTrivia;
}
export function isStringOrRegularExpressionOrTemplateLiteral(kind: SyntaxKind): boolean {
if (kind === SyntaxKind.StringLiteral
|| kind === SyntaxKind.RegularExpressionLiteral
|| isTemplateLiteralKind(kind)) {
return true;
}
return false;
}
export function isPunctuation(kind: SyntaxKind): boolean {
return SyntaxKind.FirstPunctuation <= kind && kind <= SyntaxKind.LastPunctuation;
}
@@ -626,7 +636,8 @@ namespace ts {
increaseIndent: () => { indent++; },
decreaseIndent: () => { indent--; },
clear: resetWriter,
trackSymbol: () => { }
trackSymbol: () => { },
reportInaccessibleThisError: () => { }
};
function writeIndent() {
@@ -689,7 +700,7 @@ namespace ts {
}
export function displayPart(text: string, kind: SymbolDisplayPartKind, symbol?: Symbol): SymbolDisplayPart {
return <SymbolDisplayPart> {
return <SymbolDisplayPart>{
text: text,
kind: SymbolDisplayPartKind[kind]
};
+1 -1
View File
@@ -28,7 +28,7 @@ class Board {
>this.ships.every(function (val) { return val.isSunk; }) : boolean
>this.ships.every : (callbackfn: (value: Ship, index: number, array: Ship[]) => boolean, thisArg?: any) => boolean
>this.ships : Ship[]
>this : Board
>this : this
>ships : Ship[]
>every : (callbackfn: (value: Ship, index: number, array: Ship[]) => boolean, thisArg?: any) => boolean
>function (val) { return val.isSunk; } : (val: Ship) => boolean
@@ -15,11 +15,11 @@ class Point {
>"x=" + this.x : string
>"x=" : string
>this.x : number
>this : Point
>this : this
>x : number
>" y=" : string
>this.y : number
>this : Point
>this : this
>y : number
}
}
@@ -50,7 +50,7 @@ class ColoredPoint extends Point {
>toString : () => string
>" color=" : string
>this.color : string
>this : ColoredPoint
>this : this
>color : string
}
}
@@ -26,7 +26,7 @@ class C2 {
return this.x;
>this.x : IHasVisualizationModel
>this : C2
>this : this
>x : IHasVisualizationModel
}
set A(x) {
@@ -10,7 +10,7 @@ tests/cases/conformance/ambient/ambientErrors.ts(38,13): error TS1039: Initializ
tests/cases/conformance/ambient/ambientErrors.ts(39,23): error TS1183: An implementation cannot be declared in ambient contexts.
tests/cases/conformance/ambient/ambientErrors.ts(40,14): error TS1183: An implementation cannot be declared in ambient contexts.
tests/cases/conformance/ambient/ambientErrors.ts(41,22): error TS1183: An implementation cannot be declared in ambient contexts.
tests/cases/conformance/ambient/ambientErrors.ts(47,20): error TS2435: Ambient modules cannot be nested in other modules.
tests/cases/conformance/ambient/ambientErrors.ts(47,20): error TS2435: Ambient modules cannot be nested in other modules or namespaces.
tests/cases/conformance/ambient/ambientErrors.ts(51,16): error TS2436: Ambient module declaration cannot specify relative module name.
tests/cases/conformance/ambient/ambientErrors.ts(57,5): error TS2309: An export assignment cannot be used in a module with other exported elements.
@@ -88,7 +88,7 @@ tests/cases/conformance/ambient/ambientErrors.ts(57,5): error TS2309: An export
module M2 {
declare module 'nope' { }
~~~~~~
!!! error TS2435: Ambient modules cannot be nested in other modules.
!!! error TS2435: Ambient modules cannot be nested in other modules or namespaces.
}
// Ambient external module with a string literal name that isn't a top level external module name
@@ -1,4 +1,4 @@
tests/cases/compiler/ambientExternalModuleInAnotherExternalModule.ts(5,16): error TS2435: Ambient modules cannot be nested in other modules.
tests/cases/compiler/ambientExternalModuleInAnotherExternalModule.ts(5,16): error TS2435: Ambient modules cannot be nested in other modules or namespaces.
tests/cases/compiler/ambientExternalModuleInAnotherExternalModule.ts(10,22): error TS2307: Cannot find module 'ext'.
@@ -9,7 +9,7 @@ tests/cases/compiler/ambientExternalModuleInAnotherExternalModule.ts(10,22): err
declare module "ext" {
~~~~~
!!! error TS2435: Ambient modules cannot be nested in other modules.
!!! error TS2435: Ambient modules cannot be nested in other modules or namespaces.
export class C { }
}
@@ -1,9 +1,9 @@
tests/cases/conformance/ambient/ambientExternalModuleInsideNonAmbient.ts(2,27): error TS2435: Ambient modules cannot be nested in other modules.
tests/cases/conformance/ambient/ambientExternalModuleInsideNonAmbient.ts(2,27): error TS2435: Ambient modules cannot be nested in other modules or namespaces.
==== tests/cases/conformance/ambient/ambientExternalModuleInsideNonAmbient.ts (1 errors) ====
module M {
export declare module "M" { }
~~~
!!! error TS2435: Ambient modules cannot be nested in other modules.
!!! error TS2435: Ambient modules cannot be nested in other modules or namespaces.
}
@@ -1,7 +1,7 @@
tests/cases/conformance/ambient/ambientExternalModuleInsideNonAmbientExternalModule.ts(1,23): error TS2435: Ambient modules cannot be nested in other modules.
tests/cases/conformance/ambient/ambientExternalModuleInsideNonAmbientExternalModule.ts(1,23): error TS2435: Ambient modules cannot be nested in other modules or namespaces.
==== tests/cases/conformance/ambient/ambientExternalModuleInsideNonAmbientExternalModule.ts (1 errors) ====
export declare module "M" { }
~~~
!!! error TS2435: Ambient modules cannot be nested in other modules.
!!! error TS2435: Ambient modules cannot be nested in other modules or namespaces.
@@ -31,7 +31,7 @@ class TestClass {
this.bar(x); // should not error
>this.bar(x) : void
>this.bar : { (x: string): void; (x: string[]): void; }
>this : TestClass
>this : this
>bar : { (x: string): void; (x: string[]): void; }
>x : any
}
@@ -71,7 +71,7 @@ class TestClass2 {
return this.bar(x); // should not error
>this.bar(x) : number
>this.bar : { (x: string): number; (x: string[]): number; }
>this : TestClass2
>this : this
>bar : { (x: string): number; (x: string[]): number; }
>x : any
}
@@ -10,7 +10,7 @@ class Foo {
this.x = 5;
>this.x = 5 : number
>this.x : number
>this : Foo
>this : this
>x : number
>5 : number
}
@@ -34,6 +34,8 @@ tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(25,5): error
tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(26,5): error TS2322: Type 'StrNum' is not assignable to type '[string]'.
Types of property 'pop' are incompatible.
Type '() => string | number' is not assignable to type '() => string'.
Type 'string | number' is not assignable to type 'string'.
Type 'number' is not assignable to type 'string'.
tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(27,5): error TS2322: Type '{ 0: string; 1: number; }' is not assignable to type '[string]'.
Property 'length' is missing in type '{ 0: string; 1: number; }'.
tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(28,5): error TS2322: Type '[string, number]' is not assignable to type '[number, string]'.
@@ -125,6 +127,8 @@ tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(30,5): error
!!! error TS2322: Type 'StrNum' is not assignable to type '[string]'.
!!! error TS2322: Types of property 'pop' are incompatible.
!!! error TS2322: Type '() => string | number' is not assignable to type '() => string'.
!!! error TS2322: Type 'string | number' is not assignable to type 'string'.
!!! error TS2322: Type 'number' is not assignable to type 'string'.
var m3: [string] = z;
~~
!!! error TS2322: Type '{ 0: string; 1: number; }' is not assignable to type '[string]'.
@@ -51,7 +51,7 @@ module EmptyTypes {
>(this.voidIfAny([4, 2][0])) : number
>this.voidIfAny([4, 2][0]) : number
>this.voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>this : f
>this : this
>voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>[4, 2][0] : number
>[4, 2] : number[]
@@ -64,7 +64,7 @@ module EmptyTypes {
>(this.voidIfAny([4, 2, undefined][0])) : number
>this.voidIfAny([4, 2, undefined][0]) : number
>this.voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>this : f
>this : this
>voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>[4, 2, undefined][0] : number
>[4, 2, undefined] : number[]
@@ -78,7 +78,7 @@ module EmptyTypes {
>(this.voidIfAny([undefined, 2, 4][0])) : number
>this.voidIfAny([undefined, 2, 4][0]) : number
>this.voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>this : f
>this : this
>voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>[undefined, 2, 4][0] : number
>[undefined, 2, 4] : number[]
@@ -92,7 +92,7 @@ module EmptyTypes {
>(this.voidIfAny([null, 2, 4][0])) : number
>this.voidIfAny([null, 2, 4][0]) : number
>this.voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>this : f
>this : this
>voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>[null, 2, 4][0] : number
>[null, 2, 4] : number[]
@@ -106,7 +106,7 @@ module EmptyTypes {
>(this.voidIfAny([2, 4, null][0])) : number
>this.voidIfAny([2, 4, null][0]) : number
>this.voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>this : f
>this : this
>voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>[2, 4, null][0] : number
>[2, 4, null] : number[]
@@ -120,7 +120,7 @@ module EmptyTypes {
>(this.voidIfAny([undefined, 4, null][0])) : number
>this.voidIfAny([undefined, 4, null][0]) : number
>this.voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>this : f
>this : this
>voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>[undefined, 4, null][0] : number
>[undefined, 4, null] : number[]
@@ -134,7 +134,7 @@ module EmptyTypes {
>(this.voidIfAny(['', "q"][0])) : number
>this.voidIfAny(['', "q"][0]) : number
>this.voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>this : f
>this : this
>voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>['', "q"][0] : string
>['', "q"] : string[]
@@ -147,7 +147,7 @@ module EmptyTypes {
>(this.voidIfAny(['', "q", undefined][0])) : number
>this.voidIfAny(['', "q", undefined][0]) : number
>this.voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>this : f
>this : this
>voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>['', "q", undefined][0] : string
>['', "q", undefined] : string[]
@@ -161,7 +161,7 @@ module EmptyTypes {
>(this.voidIfAny([undefined, "q", ''][0])) : number
>this.voidIfAny([undefined, "q", ''][0]) : number
>this.voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>this : f
>this : this
>voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>[undefined, "q", ''][0] : string
>[undefined, "q", ''] : string[]
@@ -175,7 +175,7 @@ module EmptyTypes {
>(this.voidIfAny([null, "q", ''][0])) : number
>this.voidIfAny([null, "q", ''][0]) : number
>this.voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>this : f
>this : this
>voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>[null, "q", ''][0] : string
>[null, "q", ''] : string[]
@@ -189,7 +189,7 @@ module EmptyTypes {
>(this.voidIfAny(["q", '', null][0])) : number
>this.voidIfAny(["q", '', null][0]) : number
>this.voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>this : f
>this : this
>voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>["q", '', null][0] : string
>["q", '', null] : string[]
@@ -203,7 +203,7 @@ module EmptyTypes {
>(this.voidIfAny([undefined, '', null][0])) : number
>this.voidIfAny([undefined, '', null][0]) : number
>this.voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>this : f
>this : this
>voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>[undefined, '', null][0] : string
>[undefined, '', null] : string[]
@@ -217,7 +217,7 @@ module EmptyTypes {
>(this.voidIfAny([[3, 4], [null]][0][0])) : number
>this.voidIfAny([[3, 4], [null]][0][0]) : number
>this.voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>this : f
>this : this
>voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>[[3, 4], [null]][0][0] : number
>[[3, 4], [null]][0] : number[]
@@ -454,7 +454,7 @@ module NonEmptyTypes {
>(this.voidIfAny([4, 2][0])) : number
>this.voidIfAny([4, 2][0]) : number
>this.voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>this : f
>this : this
>voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>[4, 2][0] : number
>[4, 2] : number[]
@@ -467,7 +467,7 @@ module NonEmptyTypes {
>(this.voidIfAny([4, 2, undefined][0])) : number
>this.voidIfAny([4, 2, undefined][0]) : number
>this.voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>this : f
>this : this
>voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>[4, 2, undefined][0] : number
>[4, 2, undefined] : number[]
@@ -481,7 +481,7 @@ module NonEmptyTypes {
>(this.voidIfAny([undefined, 2, 4][0])) : number
>this.voidIfAny([undefined, 2, 4][0]) : number
>this.voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>this : f
>this : this
>voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>[undefined, 2, 4][0] : number
>[undefined, 2, 4] : number[]
@@ -495,7 +495,7 @@ module NonEmptyTypes {
>(this.voidIfAny([null, 2, 4][0])) : number
>this.voidIfAny([null, 2, 4][0]) : number
>this.voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>this : f
>this : this
>voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>[null, 2, 4][0] : number
>[null, 2, 4] : number[]
@@ -509,7 +509,7 @@ module NonEmptyTypes {
>(this.voidIfAny([2, 4, null][0])) : number
>this.voidIfAny([2, 4, null][0]) : number
>this.voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>this : f
>this : this
>voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>[2, 4, null][0] : number
>[2, 4, null] : number[]
@@ -523,7 +523,7 @@ module NonEmptyTypes {
>(this.voidIfAny([undefined, 4, null][0])) : number
>this.voidIfAny([undefined, 4, null][0]) : number
>this.voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>this : f
>this : this
>voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>[undefined, 4, null][0] : number
>[undefined, 4, null] : number[]
@@ -537,7 +537,7 @@ module NonEmptyTypes {
>(this.voidIfAny(['', "q"][0])) : number
>this.voidIfAny(['', "q"][0]) : number
>this.voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>this : f
>this : this
>voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>['', "q"][0] : string
>['', "q"] : string[]
@@ -550,7 +550,7 @@ module NonEmptyTypes {
>(this.voidIfAny(['', "q", undefined][0])) : number
>this.voidIfAny(['', "q", undefined][0]) : number
>this.voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>this : f
>this : this
>voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>['', "q", undefined][0] : string
>['', "q", undefined] : string[]
@@ -564,7 +564,7 @@ module NonEmptyTypes {
>(this.voidIfAny([undefined, "q", ''][0])) : number
>this.voidIfAny([undefined, "q", ''][0]) : number
>this.voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>this : f
>this : this
>voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>[undefined, "q", ''][0] : string
>[undefined, "q", ''] : string[]
@@ -578,7 +578,7 @@ module NonEmptyTypes {
>(this.voidIfAny([null, "q", ''][0])) : number
>this.voidIfAny([null, "q", ''][0]) : number
>this.voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>this : f
>this : this
>voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>[null, "q", ''][0] : string
>[null, "q", ''] : string[]
@@ -592,7 +592,7 @@ module NonEmptyTypes {
>(this.voidIfAny(["q", '', null][0])) : number
>this.voidIfAny(["q", '', null][0]) : number
>this.voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>this : f
>this : this
>voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>["q", '', null][0] : string
>["q", '', null] : string[]
@@ -606,7 +606,7 @@ module NonEmptyTypes {
>(this.voidIfAny([undefined, '', null][0])) : number
>this.voidIfAny([undefined, '', null][0]) : number
>this.voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>this : f
>this : this
>voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>[undefined, '', null][0] : string
>[undefined, '', null] : string[]
@@ -620,7 +620,7 @@ module NonEmptyTypes {
>(this.voidIfAny([[3, 4], [null]][0][0])) : number
>this.voidIfAny([[3, 4], [null]][0][0]) : number
>this.voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>this : f
>this : this
>voidIfAny : { (x: boolean, y?: boolean): number; (x: string, y?: boolean): number; (x: number, y?: boolean): number; }
>[[3, 4], [null]][0][0] : number
>[[3, 4], [null]][0] : number[]
@@ -18,7 +18,7 @@ class Road {
this.cars = cars;
>this.cars = cars : Car[]
>this.cars : Car[]
>this : Road
>this : this
>cars : Car[]
>cars : Car[]
}
+2 -2
View File
@@ -38,12 +38,12 @@ class parser {
this.options = this.options.sort(function(a, b) {
>this.options = this.options.sort(function(a, b) { var aName = a.name.toLowerCase(); var bName = b.name.toLowerCase(); if (aName > bName) { return 1; } else if (aName < bName) { return -1; } else { return 0; } }) : IOptions[]
>this.options : IOptions[]
>this : parser
>this : this
>options : IOptions[]
>this.options.sort(function(a, b) { var aName = a.name.toLowerCase(); var bName = b.name.toLowerCase(); if (aName > bName) { return 1; } else if (aName < bName) { return -1; } else { return 0; } }) : IOptions[]
>this.options.sort : (compareFn?: (a: IOptions, b: IOptions) => number) => IOptions[]
>this.options : IOptions[]
>this : parser
>this : this
>options : IOptions[]
>sort : (compareFn?: (a: IOptions, b: IOptions) => number) => IOptions[]
>function(a, b) { var aName = a.name.toLowerCase(); var bName = b.name.toLowerCase(); if (aName > bName) { return 1; } else if (aName < bName) { return -1; } else { return 0; } } : (a: IOptions, b: IOptions) => number
@@ -129,12 +129,12 @@ class MyClass {
>1 : number
p = (n) => n && this;
>p : (n: any) => MyClass
>(n) => n && this : (n: any) => MyClass
>p : (n: any) => this
>(n) => n && this : (n: any) => this
>n : any
>n && this : MyClass
>n && this : this
>n : any
>this : MyClass
>this : this
fn() {
>fn : () => void
@@ -148,12 +148,12 @@ class MyClass {
>1 : number
var p = (n) => n && this;
>p : (n: any) => MyClass
>(n) => n && this : (n: any) => MyClass
>p : (n: any) => this
>(n) => n && this : (n: any) => this
>n : any
>n && this : MyClass
>n && this : this
>n : any
>this : MyClass
>this : this
}
}
+22
View File
@@ -0,0 +1,22 @@
//// [tests/cases/conformance/expressions/asOperator/asOperator4.ts] ////
//// [foo.ts]
export function foo() { }
//// [bar.ts]
import { foo } from './foo';
// These should emit identically
<any>foo;
(foo as any);
//// [foo.js]
function foo() { }
exports.foo = foo;
//// [bar.js]
var foo_1 = require('./foo');
// These should emit identically
foo_1.foo;
foo_1.foo;
@@ -0,0 +1,16 @@
=== tests/cases/conformance/expressions/asOperator/foo.ts ===
export function foo() { }
>foo : Symbol(foo, Decl(foo.ts, 0, 0))
=== tests/cases/conformance/expressions/asOperator/bar.ts ===
import { foo } from './foo';
>foo : Symbol(foo, Decl(bar.ts, 0, 8))
// These should emit identically
<any>foo;
>foo : Symbol(foo, Decl(bar.ts, 0, 8))
(foo as any);
>foo : Symbol(foo, Decl(bar.ts, 0, 8))
@@ -0,0 +1,19 @@
=== tests/cases/conformance/expressions/asOperator/foo.ts ===
export function foo() { }
>foo : () => void
=== tests/cases/conformance/expressions/asOperator/bar.ts ===
import { foo } from './foo';
>foo : () => void
// These should emit identically
<any>foo;
><any>foo : any
>foo : () => void
(foo as any);
>(foo as any) : any
>foo as any : any
>foo : () => void
@@ -11,11 +11,12 @@ class C {
var fn = async () => await other.apply(this, arguments);
>fn : () => Promise<any>
>async () => await other.apply(this, arguments) : () => Promise<any>
>await other.apply(this, arguments) : any
>other.apply(this, arguments) : any
>other.apply : (thisArg: any, argArray?: any) => any
>other : () => void
>apply : (thisArg: any, argArray?: any) => any
>this : C
>this : this
>arguments : IArguments
}
}
@@ -6,9 +6,10 @@ class C {
>method : () => void
var fn = async () => await this;
>fn : () => Promise<C>
>async () => await this : () => Promise<C>
>this : C
>fn : () => Promise<this>
>async () => await this : () => Promise<this>
>await this : this
>this : this
}
}
@@ -13,6 +13,7 @@ async function func(): Promise<void> {
"before";
var b = await p || a;
>b : Symbol(b, Decl(awaitBinaryExpression1_es6.ts, 4, 7))
>p : Symbol(p, Decl(awaitBinaryExpression1_es6.ts, 1, 11))
>a : Symbol(a, Decl(awaitBinaryExpression1_es6.ts, 0, 11))
"after";
@@ -16,7 +16,8 @@ async function func(): Promise<void> {
var b = await p || a;
>b : boolean
>await p || a : boolean
>p : any
>await p : boolean
>p : Promise<boolean>
>a : boolean
"after";
@@ -13,6 +13,7 @@ async function func(): Promise<void> {
"before";
var b = await p && a;
>b : Symbol(b, Decl(awaitBinaryExpression2_es6.ts, 4, 7))
>p : Symbol(p, Decl(awaitBinaryExpression2_es6.ts, 1, 11))
>a : Symbol(a, Decl(awaitBinaryExpression2_es6.ts, 0, 11))
"after";
@@ -16,7 +16,8 @@ async function func(): Promise<void> {
var b = await p && a;
>b : boolean
>await p && a : boolean
>p : any
>await p : boolean
>p : Promise<boolean>
>a : boolean
"after";
@@ -13,6 +13,7 @@ async function func(): Promise<void> {
"before";
var b = await p + a;
>b : Symbol(b, Decl(awaitBinaryExpression3_es6.ts, 4, 7))
>p : Symbol(p, Decl(awaitBinaryExpression3_es6.ts, 1, 11))
>a : Symbol(a, Decl(awaitBinaryExpression3_es6.ts, 0, 11))
"after";
@@ -16,7 +16,8 @@ async function func(): Promise<void> {
var b = await p + a;
>b : number
>await p + a : number
>p : any
>await p : number
>p : Promise<number>
>a : number
"after";
@@ -13,6 +13,7 @@ async function func(): Promise<void> {
"before";
var b = await p, a;
>b : Symbol(b, Decl(awaitBinaryExpression4_es6.ts, 4, 7))
>p : Symbol(p, Decl(awaitBinaryExpression4_es6.ts, 1, 11))
>a : Symbol(a, Decl(awaitBinaryExpression4_es6.ts, 4, 20))
"after";
@@ -15,7 +15,8 @@ async function func(): Promise<void> {
var b = await p, a;
>b : boolean
>p : any
>await p : boolean
>p : Promise<boolean>
>a : any
"after";
@@ -19,6 +19,7 @@ async function func(): Promise<void> {
>o.a : Symbol(a, Decl(awaitBinaryExpression5_es6.ts, 4, 12))
>o : Symbol(o, Decl(awaitBinaryExpression5_es6.ts, 4, 7))
>a : Symbol(a, Decl(awaitBinaryExpression5_es6.ts, 4, 12))
>p : Symbol(p, Decl(awaitBinaryExpression5_es6.ts, 1, 11))
"after";
}
@@ -22,7 +22,8 @@ async function func(): Promise<void> {
>o.a : boolean
>o : { a: boolean; }
>a : boolean
>p : any
>await p : boolean
>p : Promise<boolean>
"after";
>"after" : string
@@ -42,6 +42,7 @@ async function func(): Promise<void> {
var b = fn(await p, a, a);
>b : Symbol(b, Decl(awaitCallExpression2_es6.ts, 8, 7))
>fn : Symbol(fn, Decl(awaitCallExpression2_es6.ts, 1, 32))
>p : Symbol(p, Decl(awaitCallExpression2_es6.ts, 1, 11))
>a : Symbol(a, Decl(awaitCallExpression2_es6.ts, 0, 11))
>a : Symbol(a, Decl(awaitCallExpression2_es6.ts, 0, 11))
@@ -45,7 +45,8 @@ async function func(): Promise<void> {
>b : void
>fn(await p, a, a) : void
>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void
>p : any
>await p : boolean
>p : Promise<boolean>
>a : boolean
>a : boolean
@@ -43,6 +43,7 @@ async function func(): Promise<void> {
>b : Symbol(b, Decl(awaitCallExpression3_es6.ts, 8, 7))
>fn : Symbol(fn, Decl(awaitCallExpression3_es6.ts, 1, 32))
>a : Symbol(a, Decl(awaitCallExpression3_es6.ts, 0, 11))
>p : Symbol(p, Decl(awaitCallExpression3_es6.ts, 1, 11))
>a : Symbol(a, Decl(awaitCallExpression3_es6.ts, 0, 11))
"after";
@@ -46,7 +46,8 @@ async function func(): Promise<void> {
>fn(a, await p, a) : void
>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void
>a : boolean
>p : any
>await p : boolean
>p : Promise<boolean>
>a : boolean
"after";
@@ -41,6 +41,7 @@ async function func(): Promise<void> {
"before";
var b = (await pfn)(a, a, a);
>b : Symbol(b, Decl(awaitCallExpression4_es6.ts, 8, 7))
>pfn : Symbol(pfn, Decl(awaitCallExpression4_es6.ts, 4, 11))
>a : Symbol(a, Decl(awaitCallExpression4_es6.ts, 0, 11))
>a : Symbol(a, Decl(awaitCallExpression4_es6.ts, 0, 11))
>a : Symbol(a, Decl(awaitCallExpression4_es6.ts, 0, 11))
@@ -45,7 +45,8 @@ async function func(): Promise<void> {
>b : void
>(await pfn)(a, a, a) : void
>(await pfn) : (arg0: boolean, arg1: boolean, arg2: boolean) => void
>pfn : any
>await pfn : (arg0: boolean, arg1: boolean, arg2: boolean) => void
>pfn : Promise<(arg0: boolean, arg1: boolean, arg2: boolean) => void>
>a : boolean
>a : boolean
>a : boolean
@@ -44,6 +44,7 @@ async function func(): Promise<void> {
>o.fn : Symbol(fn, Decl(awaitCallExpression6_es6.ts, 3, 16))
>o : Symbol(o, Decl(awaitCallExpression6_es6.ts, 3, 11))
>fn : Symbol(fn, Decl(awaitCallExpression6_es6.ts, 3, 16))
>p : Symbol(p, Decl(awaitCallExpression6_es6.ts, 1, 11))
>a : Symbol(a, Decl(awaitCallExpression6_es6.ts, 0, 11))
>a : Symbol(a, Decl(awaitCallExpression6_es6.ts, 0, 11))
@@ -47,7 +47,8 @@ async function func(): Promise<void> {
>o.fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void
>o : { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }
>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void
>p : any
>await p : boolean
>p : Promise<boolean>
>a : boolean
>a : boolean
@@ -45,6 +45,7 @@ async function func(): Promise<void> {
>o : Symbol(o, Decl(awaitCallExpression7_es6.ts, 3, 11))
>fn : Symbol(fn, Decl(awaitCallExpression7_es6.ts, 3, 16))
>a : Symbol(a, Decl(awaitCallExpression7_es6.ts, 0, 11))
>p : Symbol(p, Decl(awaitCallExpression7_es6.ts, 1, 11))
>a : Symbol(a, Decl(awaitCallExpression7_es6.ts, 0, 11))
"after";
@@ -48,7 +48,8 @@ async function func(): Promise<void> {
>o : { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }
>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void
>a : boolean
>p : any
>await p : boolean
>p : Promise<boolean>
>a : boolean
"after";
@@ -42,6 +42,7 @@ async function func(): Promise<void> {
var b = (await po).fn(a, a, a);
>b : Symbol(b, Decl(awaitCallExpression8_es6.ts, 8, 7))
>(await po).fn : Symbol(fn, Decl(awaitCallExpression8_es6.ts, 5, 25))
>po : Symbol(po, Decl(awaitCallExpression8_es6.ts, 5, 11))
>fn : Symbol(fn, Decl(awaitCallExpression8_es6.ts, 5, 25))
>a : Symbol(a, Decl(awaitCallExpression8_es6.ts, 0, 11))
>a : Symbol(a, Decl(awaitCallExpression8_es6.ts, 0, 11))
@@ -46,7 +46,8 @@ async function func(): Promise<void> {
>(await po).fn(a, a, a) : void
>(await po).fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void
>(await po) : { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }
>po : any
>await po : { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }
>po : Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>
>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void
>a : boolean
>a : boolean
@@ -24,16 +24,21 @@ async function f() {
let await_a = await a;
>await_a : Symbol(await_a, Decl(awaitUnion_es6.ts, 6, 4))
>a : Symbol(a, Decl(awaitUnion_es6.ts, 0, 11))
let await_b = await b;
>await_b : Symbol(await_b, Decl(awaitUnion_es6.ts, 7, 4))
>b : Symbol(b, Decl(awaitUnion_es6.ts, 1, 11))
let await_c = await c;
>await_c : Symbol(await_c, Decl(awaitUnion_es6.ts, 8, 4))
>c : Symbol(c, Decl(awaitUnion_es6.ts, 2, 11))
let await_d = await d;
>await_d : Symbol(await_d, Decl(awaitUnion_es6.ts, 9, 4))
>d : Symbol(d, Decl(awaitUnion_es6.ts, 3, 11))
let await_e = await e;
>await_e : Symbol(await_e, Decl(awaitUnion_es6.ts, 10, 4))
>e : Symbol(e, Decl(awaitUnion_es6.ts, 4, 11))
}
+10 -5
View File
@@ -24,21 +24,26 @@ async function f() {
let await_a = await a;
>await_a : number | string
>a : any
>await a : number | string
>a : number | string
let await_b = await b;
>await_b : number | string
>b : any
>await b : number | string
>b : PromiseLike<number> | PromiseLike<string>
let await_c = await c;
>await_c : number | string
>c : any
>await c : number | string
>c : PromiseLike<number | string>
let await_d = await d;
>await_d : number | string
>d : any
>await d : number | string
>d : number | PromiseLike<string>
let await_e = await e;
>await_e : number | string
>e : any
>await e : number | string
>e : number | PromiseLike<number | string>
}
@@ -22,8 +22,8 @@ class Greeter {
>() => { var x = this; } : () => void
var x = this;
>x : Greeter
>this : Greeter
>x : this
>this : this
});
});
@@ -13,7 +13,7 @@ class C<T1> extends CBase<T1> {
>CBaseBase : typeof CBaseBase
>Wrapper : Wrapper<T5>
>T1 : T1
>this : C<T1>
>this : this
}
public alsoWorks() {
>alsoWorks : () => void
@@ -22,7 +22,7 @@ class C<T1> extends CBase<T1> {
>new CBase<T1>(this) : CBase<T1>
>CBase : typeof CBase
>T1 : T1
>this : C<T1>
>this : this
}
public method(t: Wrapper<T1>) { }
@@ -32,7 +32,7 @@ module Test {
>name : string
>this.getName() : string
>this.getName : () => string
>this : Bug
>this : this
>getName : () => string
>length : number
>0 : number
@@ -180,7 +180,7 @@ class C {
this.foo(x, y);
>this.foo(x, y) : void
>this.foo : (x: number, y: number, ...z: string[]) => void
>this : C
>this : this
>foo : (x: number, y: number, ...z: string[]) => void
>x : number
>y : number
@@ -188,7 +188,7 @@ class C {
this.foo(x, y, ...z);
>this.foo(x, y, ...z) : void
>this.foo : (x: number, y: number, ...z: string[]) => void
>this : C
>this : this
>foo : (x: number, y: number, ...z: string[]) => void
>x : number
>y : number
@@ -181,7 +181,7 @@ class C {
this.foo(x, y);
>this.foo(x, y) : void
>this.foo : (x: number, y: number, ...z: string[]) => void
>this : C
>this : this
>foo : (x: number, y: number, ...z: string[]) => void
>x : number
>y : number
@@ -189,7 +189,7 @@ class C {
this.foo(x, y, ...z);
>this.foo(x, y, ...z) : void
>this.foo : (x: number, y: number, ...z: string[]) => void
>this : C
>this : this
>foo : (x: number, y: number, ...z: string[]) => void
>x : number
>y : number
@@ -18,7 +18,7 @@ class B extends A {
>() => this.someMethod() : () => void
>this.someMethod() : void
>this.someMethod : () => void
>this : B
>this : this
>someMethod : () => void
someMethod() {}
@@ -20,7 +20,7 @@ class Derived extends Base {
this.p; // OK
>this.p : number
>this : Derived
>this : this
>p : number
}
}
+1 -1
View File
@@ -8,7 +8,7 @@ class A extends B {
>foo : () => void
>this.bar() : void
>this.bar : () => void
>this : A
>this : this
>bar : () => void
}
@@ -11,7 +11,7 @@ class bar {
this.baz = new foo();
>this.baz = new foo() : foo
>this.baz : foo
>this : bar
>this : this
>baz : foo
>new foo() : foo
>foo : typeof foo
@@ -41,7 +41,7 @@ class TextBase implements IText {
return new SubText(this, span);
>new SubText(this, span) : SubText
>SubText : typeof SubText
>this : TextBase
>this : this
>span : TextSpan
}
}
@@ -16,7 +16,7 @@ class c1 {
return this.p1 + b;
>this.p1 + b : number
>this.p1 : number
>this : c1
>this : this
>p1 : number
>b : number
@@ -28,10 +28,10 @@ class c1 {
return this.p2(this.p1);
>this.p2(this.p1) : number
>this.p2 : (b: number) => number
>this : c1
>this : this
>p2 : (b: number) => number
>this.p1 : number
>this : c1
>this : this
>p1 : number
}// trailing comment Getter
@@ -43,11 +43,11 @@ class c1 {
this.p1 = this.p2(value);
>this.p1 = this.p2(value) : number
>this.p1 : number
>this : c1
>this : this
>p1 : number
>this.p2(value) : number
>this.p2 : (b: number) => number
>this : c1
>this : this
>p2 : (b: number) => number
>value : number
@@ -64,7 +64,7 @@ class c1 {
return this.p1 + b;
>this.p1 + b : number
>this.p1 : number
>this : c1
>this : this
>p1 : number
>b : number
@@ -76,10 +76,10 @@ class c1 {
return this.pp2(this.pp1);
>this.pp2(this.pp1) : number
>this.pp2 : (b: number) => number
>this : c1
>this : this
>pp2 : (b: number) => number
>this.pp1 : number
>this : c1
>this : this
>pp1 : number
}
/** setter property*/
@@ -90,11 +90,11 @@ class c1 {
this.pp1 = this.pp2(value);
>this.pp1 = this.pp2(value) : number
>this.pp1 : number
>this : c1
>this : this
>pp1 : number
>this.pp2(value) : number
>this.pp2 : (b: number) => number
>this : c1
>this : this
>pp2 : (b: number) => number
>value : number
}
@@ -158,7 +158,7 @@ class c1 {
return this.nc_p1 + b;
>this.nc_p1 + b : number
>this.nc_p1 : number
>this : c1
>this : this
>nc_p1 : number
>b : number
}
@@ -168,10 +168,10 @@ class c1 {
return this.nc_p2(this.nc_p1);
>this.nc_p2(this.nc_p1) : number
>this.nc_p2 : (b: number) => number
>this : c1
>this : this
>nc_p2 : (b: number) => number
>this.nc_p1 : number
>this : c1
>this : this
>nc_p1 : number
}
public set nc_p3(value: number) {
@@ -181,11 +181,11 @@ class c1 {
this.nc_p1 = this.nc_p2(value);
>this.nc_p1 = this.nc_p2(value) : number
>this.nc_p1 : number
>this : c1
>this : this
>nc_p1 : number
>this.nc_p2(value) : number
>this.nc_p2 : (b: number) => number
>this : c1
>this : this
>nc_p2 : (b: number) => number
>value : number
}
@@ -199,7 +199,7 @@ class c1 {
return this.nc_pp1 + b;
>this.nc_pp1 + b : number
>this.nc_pp1 : number
>this : c1
>this : this
>nc_pp1 : number
>b : number
}
@@ -209,10 +209,10 @@ class c1 {
return this.nc_pp2(this.nc_pp1);
>this.nc_pp2(this.nc_pp1) : number
>this.nc_pp2 : (b: number) => number
>this : c1
>this : this
>nc_pp2 : (b: number) => number
>this.nc_pp1 : number
>this : c1
>this : this
>nc_pp1 : number
}
private set nc_pp3(value: number) {
@@ -222,11 +222,11 @@ class c1 {
this.nc_pp1 = this.nc_pp2(value);
>this.nc_pp1 = this.nc_pp2(value) : number
>this.nc_pp1 : number
>this : c1
>this : this
>nc_pp1 : number
>this.nc_pp2(value) : number
>this.nc_pp2 : (b: number) => number
>this : c1
>this : this
>nc_pp2 : (b: number) => number
>value : number
}
@@ -284,7 +284,7 @@ class c1 {
return this.a_p1 + b;
>this.a_p1 + b : number
>this.a_p1 : number
>this : c1
>this : this
>a_p1 : number
>b : number
}
@@ -295,10 +295,10 @@ class c1 {
return this.a_p2(this.a_p1);
>this.a_p2(this.a_p1) : number
>this.a_p2 : (b: number) => number
>this : c1
>this : this
>a_p2 : (b: number) => number
>this.a_p1 : number
>this : c1
>this : this
>a_p1 : number
}
// setter property
@@ -309,11 +309,11 @@ class c1 {
this.a_p1 = this.a_p2(value);
>this.a_p1 = this.a_p2(value) : number
>this.a_p1 : number
>this : c1
>this : this
>a_p1 : number
>this.a_p2(value) : number
>this.a_p2 : (b: number) => number
>this : c1
>this : this
>a_p2 : (b: number) => number
>value : number
}
@@ -329,7 +329,7 @@ class c1 {
return this.a_p1 + b;
>this.a_p1 + b : number
>this.a_p1 : number
>this : c1
>this : this
>a_p1 : number
>b : number
}
@@ -340,10 +340,10 @@ class c1 {
return this.a_pp2(this.a_pp1);
>this.a_pp2(this.a_pp1) : number
>this.a_pp2 : (b: number) => number
>this : c1
>this : this
>a_pp2 : (b: number) => number
>this.a_pp1 : number
>this : c1
>this : this
>a_pp1 : number
}
// setter property
@@ -354,11 +354,11 @@ class c1 {
this.a_pp1 = this.a_pp2(value);
>this.a_pp1 = this.a_pp2(value) : number
>this.a_pp1 : number
>this : c1
>this : this
>a_pp1 : number
>this.a_pp2(value) : number
>this.a_pp2 : (b: number) => number
>this : c1
>this : this
>a_pp2 : (b: number) => number
>value : number
}
@@ -422,7 +422,7 @@ class c1 {
return this.b_p1 + b;
>this.b_p1 + b : number
>this.b_p1 : number
>this : c1
>this : this
>b_p1 : number
>b : number
}
@@ -433,10 +433,10 @@ class c1 {
return this.b_p2(this.b_p1);
>this.b_p2(this.b_p1) : number
>this.b_p2 : (b: number) => number
>this : c1
>this : this
>b_p2 : (b: number) => number
>this.b_p1 : number
>this : c1
>this : this
>b_p1 : number
}
/** setter property */
@@ -447,11 +447,11 @@ class c1 {
this.b_p1 = this.b_p2(value);
>this.b_p1 = this.b_p2(value) : number
>this.b_p1 : number
>this : c1
>this : this
>b_p1 : number
>this.b_p2(value) : number
>this.b_p2 : (b: number) => number
>this : c1
>this : this
>b_p2 : (b: number) => number
>value : number
}
@@ -467,7 +467,7 @@ class c1 {
return this.b_p1 + b;
>this.b_p1 + b : number
>this.b_p1 : number
>this : c1
>this : this
>b_p1 : number
>b : number
}
@@ -478,10 +478,10 @@ class c1 {
return this.b_pp2(this.b_pp1);
>this.b_pp2(this.b_pp1) : number
>this.b_pp2 : (b: number) => number
>this : c1
>this : this
>b_pp2 : (b: number) => number
>this.b_pp1 : number
>this : c1
>this : this
>b_pp1 : number
}
/** setter property */
@@ -492,11 +492,11 @@ class c1 {
this.b_pp1 = this.b_pp2(value);
>this.b_pp1 = this.b_pp2(value) : number
>this.b_pp1 : number
>this : c1
>this : this
>b_pp1 : number
>this.b_pp2(value) : number
>this.b_pp2 : (b: number) => number
>this : c1
>this : this
>b_pp2 : (b: number) => number
>value : number
}
@@ -704,7 +704,7 @@ class cProperties {
return this.val;
>this.val : number
>this : cProperties
>this : this
>val : number
} // trailing comment of only getter
@@ -713,7 +713,7 @@ class cProperties {
return this.val;
>this.val : number
>this : cProperties
>this : this
>val : number
}
/**setter only property*/
@@ -724,7 +724,7 @@ class cProperties {
this.val = value;
>this.val = value : number
>this.val : number
>this : cProperties
>this : this
>val : number
>value : number
}
@@ -735,7 +735,7 @@ class cProperties {
this.val = value;
>this.val = value : number
>this.val : number
>this : cProperties
>this : this
>val : number
>value : number
@@ -170,7 +170,7 @@ class c2 {
this.c2_p1 = a;
>this.c2_p1 = a : number
>this.c2_p1 : number
>this : c2
>this : this
>c2_p1 : number
>a : number
}
@@ -43,7 +43,7 @@ class c {
return this.b;
>this.b : number
>this : c
>this : this
>b : number
}
@@ -53,7 +53,7 @@ class c {
return this.b;
>this.b : number
>this : c
>this : this
>b : number
}
@@ -65,7 +65,7 @@ class c {
this.b = val;
>this.b = val : number
>this.b : number
>this : c
>this : this
>b : number
>val : number
}
@@ -43,7 +43,7 @@ class c {
return this.b;
>this.b : number
>this : c
>this : this
>b : number
}
@@ -53,7 +53,7 @@ class c {
return this.b;
>this.b : number
>this : c
>this : this
>b : number
}
@@ -65,7 +65,7 @@ class c {
this.b = val;
>this.b = val : number
>this.b : number
>this : c
>this : this
>b : number
>val : number
}
@@ -79,14 +79,14 @@ class Foo {
return new GenericType<string>(this);
>new GenericType<string>(this) : GenericType<string>
>GenericType : typeof GenericType
>this : Foo
>this : this
}
public populate() {
>populate : () => void
this.prop2;
>this.prop2 : BaseCollection<Derived>
>this : Foo
>this : this
>prop2 : BaseCollection<Derived>
}
public get prop2(): BaseCollection<Derived> {
@@ -12,7 +12,7 @@ class C {
[this.bar()]() { }
>this.bar() : number
>this.bar : () => number
>this : C
>this : this
>bar : () => number
};
@@ -12,7 +12,7 @@ class C {
[this.bar()]() { }
>this.bar() : number
>this.bar : () => number
>this : C
>this : this
>bar : () => number
};
@@ -15,7 +15,7 @@ class C {
[this.bar()]() { } // needs capture
>this.bar() : number
>this.bar : () => number
>this : C
>this : this
>bar : () => number
};
@@ -15,7 +15,7 @@ class C {
[this.bar()]() { } // needs capture
>this.bar() : number
>this.bar : () => number
>this : C
>this : this
>bar : () => number
};
@@ -20,7 +20,7 @@ class Rule {
this.name = name;
>this.name = name : string
>this.name : string
>this : Rule
>this : this
>name : string
>name : string
}
@@ -0,0 +1,24 @@
//// [contextualThisType.ts]
interface X {
a: (p: this) => this;
}
interface Y extends X {
}
var x: Y = {
a(p) {
return p;
}
}
var y = x.a(x);
//// [contextualThisType.js]
var x = {
a: function (p) {
return p;
}
};
var y = x.a(x);

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