Merge branch 'master' into generateFactoryMethods

This commit is contained in:
Ron Buckton 2015-07-10 13:53:44 -07:00
commit b3e9c25e84
119 changed files with 2569 additions and 1570 deletions

View file

@ -409,7 +409,7 @@ compileFile(servicesFile, servicesSources, [builtLocalDirectory, copyright].conc
keepComments: true,
noResolve: false,
stripInternal: true,
}, /*callback*/ function () {
}, /*callback*/ function () {
jake.cpR(servicesFile, nodePackageFile, {silent: true});
prependFile(copyright, standaloneDefinitionsFile);
@ -430,9 +430,9 @@ compileFile(serverFile, serverSources,[builtLocalDirectory, copyright].concat(se
var lsslFile = path.join(builtLocalDirectory, "tslssl.js");
compileFile(lsslFile, languageServiceLibrarySources, [builtLocalDirectory, copyright].concat(languageServiceLibrarySources), {
prefixes: [copyright],
useBuiltCompiler: true,
noOutFile: false,
prefixes: [copyright],
useBuiltCompiler: true,
noOutFile: false,
generateDeclarations: true
});
@ -537,7 +537,7 @@ var refTest262Baseline = path.join(internalTests, "baselines/test262/reference")
desc("Builds the test infrastructure using the built compiler");
task("tests", ["local", run].concat(libraryTargets));
function exec(cmd, completeHandler) {
function exec(cmd, completeHandler, errorHandler) {
var ex = jake.createExec([cmd], {windowsVerbatimArguments: true});
// Add listeners for output and error
ex.addListener("stdout", function(output) {
@ -553,7 +553,11 @@ function exec(cmd, completeHandler) {
complete();
});
ex.addListener("error", function(e, status) {
fail("Process exited with code " + status);
if(errorHandler) {
errorHandler(e, status);
} else {
fail("Process exited with code " + status);
}
});
ex.run();
@ -776,7 +780,21 @@ task('tsc-instrumented', [loggedIOJsPath, instrumenterJsPath, tscFile], function
}, { async: true });
desc("Updates the sublime plugin's tsserver");
task("update-sublime", [serverFile], function() {
task("update-sublime", ["local", serverFile], function() {
jake.cpR(serverFile, "../TypeScript-Sublime-Plugin/tsserver/");
jake.cpR(serverFile + ".map", "../TypeScript-Sublime-Plugin/tsserver/");
});
// 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", [], function() {
for(var i in compilerSources) {
var f = compilerSources[i];
var cmd = 'tslint -f ' + f;
exec(cmd,
function() { console.log('SUCCESS: No linter errors'); },
function() { console.log('FAILURE: Please fix linting errors in ' + f + '\n');
});
}
}, { async: true });

View file

@ -33,7 +33,8 @@
"mocha": "latest",
"chai": "latest",
"browserify": "latest",
"istanbul": "latest"
"istanbul": "latest",
"tslint": "latest"
},
"scripts": {
"test": "jake runtests"

View file

@ -74,7 +74,7 @@ fs.readFile('src/compiler/diagnosticInformationMap.generated.ts', 'utf-8', (err,
console.log('Consumed ' + allSrc.length + ' characters of source');
let count = 0;
console.log('== List of errors not used in source ==')
console.log('== List of errors not used in source ==');
for (let errName of errorNames) {
if (allSrc.indexOf(errName) < 0) {
console.log(errName);
@ -84,4 +84,3 @@ fs.readFile('src/compiler/diagnosticInformationMap.generated.ts', 'utf-8', (err,
console.log(count + ' of ' + errorNames.length + ' errors are not used in source');
});
});

View file

@ -11,7 +11,7 @@ namespace ts {
}
export function getModuleInstanceState(node: Node): ModuleInstanceState {
// A module is uninstantiated if it contains only
// A module is uninstantiated if it contains only
// 1. interface declarations, type alias declarations
if (node.kind === SyntaxKind.InterfaceDeclaration || node.kind === SyntaxKind.TypeAliasDeclaration) {
return ModuleInstanceState.NonInstantiated;
@ -53,7 +53,7 @@ namespace ts {
}
const enum ContainerFlags {
// The current node is not a container, and no container manipulation should happen before
// The current node is not a container, and no container manipulation should happen before
// recursing into it.
None = 0,
@ -90,13 +90,13 @@ namespace ts {
let lastContainer: Node;
// If this file is an external module, then it is automatically in strict-mode according to
// ES6. If it is not an external module, then we'll determine if it is in strict mode or
// ES6. If it is not an external module, then we'll determine if it is in strict mode or
// not depending on if we see "use strict" in certain places (or if we hit a class/namespace).
let inStrictMode = !!file.externalModuleIndicator;
let symbolCount = 0;
let Symbol = objectAllocator.getSymbolConstructor();
let classifiableNames: Map<string> = {};
let classifiableNames: Map<string> = {};
if (!file.locals) {
bind(file);
@ -179,7 +179,7 @@ namespace ts {
* @param parent - node's parent declaration.
* @param node - The declaration to be added to the symbol table
* @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.)
* @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations.
* @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations.
*/
function declareSymbol(symbolTable: SymbolTable, parent: Symbol, node: Declaration, includes: SymbolFlags, excludes: SymbolFlags): Symbol {
Debug.assert(!hasDynamicName(node));
@ -192,13 +192,13 @@ namespace ts {
// Check and see if the symbol table already has a symbol with this name. If not,
// create a new symbol with this name and add it to the table. Note that we don't
// give the new symbol any flags *yet*. This ensures that it will not conflict
// give the new symbol any flags *yet*. This ensures that it will not conflict
// with the 'excludes' flags we pass in.
//
// If we do get an existing symbol, see if it conflicts with the new symbol we're
// creating. For example, a 'var' symbol and a 'class' symbol will conflict within
// the same symbol table. If we have a conflict, report the issue on each
// declaration we have for this symbol, and then create a new symbol for this
// the same symbol table. If we have a conflict, report the issue on each
// declaration we have for this symbol, and then create a new symbol for this
// declaration.
//
// If we created a new symbol, either because we didn't have a symbol with this name
@ -259,7 +259,7 @@ namespace ts {
// ExportType, or ExportContainer flag, and an associated export symbol with all the correct flags set
// on it. There are 2 main reasons:
//
// 1. We treat locals and exports of the same name as mutually exclusive within a container.
// 1. We treat locals and exports of the same name as mutually exclusive within a container.
// That means the binder will issue a Duplicate Identifier error if you mix locals and exports
// with the same name in the same container.
// TODO: Make this a more specific error and decouple it from the exclusion logic.
@ -282,11 +282,11 @@ namespace ts {
}
}
// All container nodes are kept on a linked list in declaration order. This list is used by
// the getLocalNameOfContainer function in the type checker to validate that the local name
// All container nodes are kept on a linked list in declaration order. This list is used by
// the getLocalNameOfContainer function in the type checker to validate that the local name
// used for a container is unique.
function bindChildren(node: Node) {
// Before we recurse into a node's chilren, we first save the existing parent, container
// Before we recurse into a node's chilren, we first save the existing parent, container
// and block-container. Then after we pop out of processing the children, we restore
// these saved values.
let saveParent = parent;
@ -295,16 +295,16 @@ namespace ts {
// This node will now be set as the parent of all of its children as we recurse into them.
parent = node;
// Depending on what kind of node this is, we may have to adjust the current container
// and block-container. If the current node is a container, then it is automatically
// considered the current block-container as well. Also, for containers that we know
// may contain locals, we proactively initialize the .locals field. We do this because
// it's highly likely that the .locals will be needed to place some child in (for example,
// a parameter, or variable declaration).
//
//
// However, we do not proactively create the .locals for block-containers because it's
// totally normal and common for block-containers to never actually have a block-scoped
// totally normal and common for block-containers to never actually have a block-scoped
// variable in them. We don't want to end up allocating an object for every 'block' we
// run into when most of them won't be necessary.
//
@ -345,7 +345,7 @@ namespace ts {
case SyntaxKind.TypeLiteral:
case SyntaxKind.ObjectLiteralExpression:
return ContainerFlags.IsContainer;
case SyntaxKind.CallSignature:
case SyntaxKind.ConstructSignature:
case SyntaxKind.IndexSignature:
@ -373,7 +373,7 @@ namespace ts {
case SyntaxKind.Block:
// do not treat blocks directly inside a function as a block-scoped-container.
// Locals that reside in this block should go to the function locals. Othewise 'x'
// Locals that reside in this block should go to the function locals. Othewise 'x'
// would not appear to be a redeclaration of a block scoped local in the following
// example:
//
@ -386,7 +386,7 @@ namespace ts {
// the block, then there would be no collision.
//
// By not creating a new block-scoped-container here, we ensure that both 'var x'
// and 'let x' go into the Function-container's locals, and we do get a collision
// and 'let x' go into the Function-container's locals, and we do get a collision
// conflict.
return isFunctionLike(node.parent) ? ContainerFlags.None : ContainerFlags.IsBlockScopedContainer;
}
@ -484,7 +484,7 @@ namespace ts {
}
function hasExportDeclarations(node: ModuleDeclaration | SourceFile): boolean {
var body = node.kind === SyntaxKind.SourceFile ? node : (<ModuleDeclaration>node).body;
let body = node.kind === SyntaxKind.SourceFile ? node : (<ModuleDeclaration>node).body;
if (body.kind === SyntaxKind.SourceFile || body.kind === SyntaxKind.ModuleBlock) {
for (let stat of (<Block>body).statements) {
if (stat.kind === SyntaxKind.ExportDeclaration || stat.kind === SyntaxKind.ExportAssignment) {
@ -536,8 +536,8 @@ namespace ts {
// For a given function symbol "<...>(...) => T" we want to generate a symbol identical
// to the one we would get for: { <...>(...): T }
//
// We do that by making an anonymous type literal symbol, and then setting the function
// symbol as its sole member. To the rest of the system, this symbol will be indistinguishable
// We do that by making an anonymous type literal symbol, and then setting the function
// symbol as its sole member. To the rest of the system, this symbol will be indistinguishable
// from an actual type literal symbol you would have gotten had you used the long form.
let symbol = createSymbol(SymbolFlags.Signature, getDeclarationName(node));
addDeclarationToSymbol(symbol, node, SymbolFlags.Signature);
@ -638,7 +638,7 @@ namespace ts {
}
function getStrictModeIdentifierMessage(node: Node) {
// Provide specialized messages to help the user understand why we think they're in
// Provide specialized messages to help the user understand why we think they're in
// strict mode.
if (getContainingClass(node)) {
return Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode;
@ -696,7 +696,7 @@ namespace ts {
}
function getStrictModeEvalOrArgumentsMessage(node: Node) {
// Provide specialized messages to help the user understand why we think they're in
// Provide specialized messages to help the user understand why we think they're in
// strict mode.
if (getContainingClass(node)) {
return Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode;
@ -760,24 +760,24 @@ namespace ts {
function bind(node: Node) {
node.parent = parent;
var savedInStrictMode = inStrictMode;
let savedInStrictMode = inStrictMode;
if (!savedInStrictMode) {
updateStrictMode(node);
}
// First we bind declaration nodes to a symbol if possible. We'll both create a symbol
// and then potentially add the symbol to an appropriate symbol table. Possible
// and then potentially add the symbol to an appropriate symbol table. Possible
// destination symbol tables are:
//
//
// 1) The 'exports' table of the current container's symbol.
// 2) The 'members' table of the current container's symbol.
// 3) The 'locals' table of the current container.
//
// However, not all symbols will end up in any of these tables. 'Anonymous' symbols
// However, not all symbols will end up in any of these tables. 'Anonymous' symbols
// (like TypeLiterals for example) will not be put in any table.
bindWorker(node);
// Then we recurse into the children of the node to bind them as well. For certain
// Then we recurse into the children of the node to bind them as well. For certain
// symbols we do specialized work when we recurse. For example, we'll keep track of
// the current 'container' node when it changes. This helps us know which symbol table
// a local should go into for example.
@ -817,7 +817,7 @@ namespace ts {
}
}
}
/// Should be called only on prologue directives (isPrologueDirective(node) should be true)
function isUseStrictPrologueDirective(node: ExpressionStatement): boolean {
let nodeText = getTextOfNodeFromSourceText(file.text, node.expression);
@ -892,7 +892,8 @@ namespace ts {
case SyntaxKind.FunctionExpression:
case SyntaxKind.ArrowFunction:
checkStrictModeFunctionName(<FunctionExpression>node);
return bindAnonymousDeclaration(<FunctionExpression>node, SymbolFlags.Function, "__function");
let bindingName = (<FunctionExpression>node).name ? (<FunctionExpression>node).name.text : "__function";
return bindAnonymousDeclaration(<FunctionExpression>node, SymbolFlags.Function, bindingName);
case SyntaxKind.ClassExpression:
case SyntaxKind.ClassDeclaration:
return bindClassLikeDeclaration(<ClassLikeDeclaration>node);
@ -964,15 +965,16 @@ namespace ts {
bindBlockScopedDeclaration(node, SymbolFlags.Class, SymbolFlags.ClassExcludes);
}
else {
bindAnonymousDeclaration(node, SymbolFlags.Class, "__class");
let bindingName = node.name ? node.name.text : "__class";
bindAnonymousDeclaration(node, SymbolFlags.Class, bindingName);
}
let symbol = node.symbol;
// TypeScript 1.0 spec (April 2014): 8.4
// Every class automatically contains a static property member named 'prototype', the
// Every class automatically contains a static property member named 'prototype', the
// type of which is an instantiation of the class type with type Any supplied as a type
// argument for each type parameter. It is an error to explicitly declare a static
// argument for each type parameter. It is an error to explicitly declare a static
// property member with the name 'prototype'.
//
// Note: we check for this here because this class may be merging into a module. The
@ -998,7 +1000,7 @@ namespace ts {
function bindVariableDeclarationOrBindingElement(node: VariableDeclaration | BindingElement) {
if (inStrictMode) {
checkStrictModeEvalOrArguments(node, node.name)
checkStrictModeEvalOrArguments(node, node.name);
}
if (!isBindingPattern(node.name)) {
@ -1037,7 +1039,7 @@ namespace ts {
declareSymbolAndAddToSymbolTable(node, SymbolFlags.FunctionScopedVariable, SymbolFlags.ParameterExcludes);
}
// If this is a property-parameter, then also declare the property symbol into the
// If this is a property-parameter, then also declare the property symbol into the
// containing class.
if (node.flags & NodeFlags.AccessibilityModifier &&
node.parent.kind === SyntaxKind.Constructor &&
@ -1054,4 +1056,4 @@ namespace ts {
: declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
}
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -5,7 +5,7 @@
namespace ts {
/* @internal */
export var optionDeclarations: CommandLineOption[] = [
export let optionDeclarations: CommandLineOption[] = [
{
name: "charset",
type: "string",
@ -222,11 +222,11 @@ namespace ts {
];
export function parseCommandLine(commandLine: string[]): ParsedCommandLine {
var options: CompilerOptions = {};
var fileNames: string[] = [];
var errors: Diagnostic[] = [];
var shortOptionNames: Map<string> = {};
var optionNameMap: Map<CommandLineOption> = {};
let options: CompilerOptions = {};
let fileNames: string[] = [];
let errors: Diagnostic[] = [];
let shortOptionNames: Map<string> = {};
let optionNameMap: Map<CommandLineOption> = {};
forEach(optionDeclarations, option => {
optionNameMap[option.name.toLowerCase()] = option;
@ -242,9 +242,9 @@ namespace ts {
};
function parseStrings(args: string[]) {
var i = 0;
let i = 0;
while (i < args.length) {
var s = args[i++];
let s = args[i++];
if (s.charCodeAt(0) === CharacterCodes.at) {
parseResponseFile(s.slice(1));
}
@ -257,7 +257,7 @@ namespace ts {
}
if (hasProperty(optionNameMap, s)) {
var opt = optionNameMap[s];
let opt = optionNameMap[s];
// Check to see if no argument was provided (e.g. "--locale" is the last command-line argument).
if (!args[i] && opt.type !== "boolean") {
@ -276,8 +276,8 @@ namespace ts {
break;
// If not a primitive, the possible types are specified in what is effectively a map of options.
default:
var map = <Map<number>>opt.type;
var key = (args[i++] || "").toLowerCase();
let map = <Map<number>>opt.type;
let key = (args[i++] || "").toLowerCase();
if (hasProperty(map, key)) {
options[opt.name] = map[key];
}
@ -297,19 +297,19 @@ namespace ts {
}
function parseResponseFile(fileName: string) {
var text = sys.readFile(fileName);
let text = sys.readFile(fileName);
if (!text) {
errors.push(createCompilerDiagnostic(Diagnostics.File_0_not_found, fileName));
return;
}
var args: string[] = [];
var pos = 0;
let args: string[] = [];
let pos = 0;
while (true) {
while (pos < text.length && text.charCodeAt(pos) <= CharacterCodes.space) pos++;
if (pos >= text.length) break;
var start = pos;
let start = pos;
if (text.charCodeAt(start) === CharacterCodes.doubleQuote) {
pos++;
while (pos < text.length && text.charCodeAt(pos) !== CharacterCodes.doubleQuote) pos++;
@ -335,8 +335,9 @@ namespace ts {
* @param fileName The path to the config file
*/
export function readConfigFile(fileName: string): { config?: any; error?: Diagnostic } {
let text = '';
try {
var text = sys.readFile(fileName);
text = sys.readFile(fileName);
}
catch (e) {
return { error: createCompilerDiagnostic(Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message) };
@ -362,10 +363,10 @@ namespace ts {
* Parse the contents of a config file (tsconfig.json).
* @param json The contents of the config file to parse
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
* file to. e.g. outDir
*/
export function parseConfigFile(json: any, host: ParseConfigHost, basePath: string): ParsedCommandLine {
var errors: Diagnostic[] = [];
let errors: Diagnostic[] = [];
return {
options: getCompilerOptions(),
@ -374,22 +375,22 @@ namespace ts {
};
function getCompilerOptions(): CompilerOptions {
var options: CompilerOptions = {};
var optionNameMap: Map<CommandLineOption> = {};
let options: CompilerOptions = {};
let optionNameMap: Map<CommandLineOption> = {};
forEach(optionDeclarations, option => {
optionNameMap[option.name] = option;
});
var jsonOptions = json["compilerOptions"];
let jsonOptions = json["compilerOptions"];
if (jsonOptions) {
for (var id in jsonOptions) {
for (let id in jsonOptions) {
if (hasProperty(optionNameMap, id)) {
var opt = optionNameMap[id];
var optType = opt.type;
var value = jsonOptions[id];
var expectedType = typeof optType === "string" ? optType : "string";
let opt = optionNameMap[id];
let optType = opt.type;
let value = jsonOptions[id];
let expectedType = typeof optType === "string" ? optType : "string";
if (typeof value === expectedType) {
if (typeof optType !== "string") {
var key = value.toLowerCase();
let key = value.toLowerCase();
if (hasProperty(optType, key)) {
value = optType[key];
}
@ -424,7 +425,7 @@ namespace ts {
}
else {
let exclude = json["exclude"] instanceof Array ? map(<string[]>json["exclude"], normalizeSlashes) : undefined;
let sysFiles = host.readDirectory(basePath, ".ts", exclude).concat(host.readDirectory(basePath, ".tsx", exclude));
let sysFiles = host.readDirectory(basePath, ".ts", exclude).concat(host.readDirectory(basePath, ".tsx", exclude));
for (let i = 0; i < sysFiles.length; i++) {
let name = sysFiles[i];
if (fileExtensionIs(name, ".d.ts")) {
@ -435,7 +436,7 @@ namespace ts {
}
else if (fileExtensionIs(name, ".ts")) {
if (!contains(sysFiles, name + "x")) {
fileNames.push(name)
fileNames.push(name);
}
}
else {

View file

@ -25,7 +25,7 @@ namespace ts {
contains,
remove,
forEachValue: forEachValueInMap
}
};
function set(fileName: string, value: T) {
files[normalizeKey(fileName)] = value;
@ -170,7 +170,7 @@ namespace ts {
to.push(v);
}
}
}
}
export function rangeEquals<T>(array1: T[], array2: T[], pos: number, end: number) {
while (pos < end) {
@ -372,7 +372,7 @@ namespace ts {
}
let text = getLocaleSpecificMessage(message.key);
if (arguments.length > 4) {
text = formatStringFromArgs(text, arguments, 4);
}
@ -542,7 +542,7 @@ namespace ts {
else {
// A part may be an empty string (which is 'falsy') if the path had consecutive slashes,
// e.g. "path//file.ts". Drop these before re-joining the parts.
if(part) {
if (part) {
normalized.push(part);
}
}
@ -600,20 +600,20 @@ namespace ts {
function getNormalizedPathComponentsOfUrl(url: string) {
// Get root length of http://www.website.com/folder1/foler2/
// In this example the root is: http://www.website.com/
// In this example the root is: http://www.website.com/
// normalized path components should be ["http://www.website.com/", "folder1", "folder2"]
let urlLength = url.length;
// Initial root length is http:// part
let rootLength = url.indexOf("://") + "://".length;
while (rootLength < urlLength) {
// Consume all immediate slashes in the protocol
// Consume all immediate slashes in the protocol
// eg.initial rootlength is just file:// but it needs to consume another "/" in file:///
if (url.charCodeAt(rootLength) === CharacterCodes.slash) {
rootLength++;
}
else {
// non slash character means we continue proceeding to next component of root search
// non slash character means we continue proceeding to next component of root search
break;
}
}
@ -626,15 +626,15 @@ namespace ts {
// Find the index of "/" after website.com so the root can be http://www.website.com/ (from existing http://)
let indexOfNextSlash = url.indexOf(directorySeparator, rootLength);
if (indexOfNextSlash !== -1) {
// Found the "/" after the website.com so the root is length of http://www.website.com/
// Found the "/" after the website.com so the root is length of http://www.website.com/
// and get components afetr the root normally like any other folder components
rootLength = indexOfNextSlash + 1;
return normalizedPathComponents(url, rootLength);
}
else {
// Can't find the host assume the rest of the string as component
// Can't find the host assume the rest of the string as component
// but make sure we append "/" to it as root is not joined using "/"
// eg. if url passed in was http://website.com we want to use root as [http://website.com/]
// eg. if url passed in was http://website.com we want to use root as [http://website.com/]
// so that other path manipulations will be correct and it can be merged with relative paths correctly
return [url + directorySeparator];
}
@ -774,7 +774,7 @@ namespace ts {
getSymbolConstructor: () => <any>Symbol,
getTypeConstructor: () => <any>Type,
getSignatureConstructor: () => <any>Signature
}
};
export const enum AssertionLevel {
None = 0,

View file

@ -130,7 +130,7 @@ namespace ts {
moduleElementDeclarationEmitInfo,
synchronousDeclarationOutput: writer.getText(),
referencePathsOutput,
}
};
function hasInternalAnnotation(range: CommentRange) {
let text = currentSourceFile.text;
@ -188,7 +188,7 @@ namespace ts {
if (!moduleElementEmitInfo && asynchronousSubModuleDeclarationEmitInfo) {
moduleElementEmitInfo = forEach(asynchronousSubModuleDeclarationEmitInfo, declEmitInfo => declEmitInfo.node === nodeToCheck ? declEmitInfo : undefined);
}
// If the alias was marked as not visible when we saw its declaration, we would have saved the aliasEmitInfo, but if we haven't yet visited the alias declaration
// then we don't need to write it at this point. We will write it when we actually see its declaration
// Eg.
@ -198,7 +198,7 @@ namespace ts {
// we would write alias foo declaration when we visit it since it would now be marked as visible
if (moduleElementEmitInfo) {
if (moduleElementEmitInfo.node.kind === SyntaxKind.ImportDeclaration) {
// we have to create asynchronous output only after we have collected complete information
// we have to create asynchronous output only after we have collected complete information
// because it is possible to enable multiple bindings as asynchronously visible
moduleElementEmitInfo.isVisible = true;
}
@ -355,6 +355,21 @@ namespace ts {
return emitEntityName(<Identifier>type);
case SyntaxKind.QualifiedName:
return emitEntityName(<QualifiedName>type);
case SyntaxKind.TypePredicate:
return emitTypePredicate(<TypePredicateNode>type);
}
function writeEntityName(entityName: EntityName | Expression) {
if (entityName.kind === SyntaxKind.Identifier) {
writeTextOfNode(currentSourceFile, entityName);
}
else {
let left = entityName.kind === SyntaxKind.QualifiedName ? (<QualifiedName>entityName).left : (<PropertyAccessExpression>entityName).expression;
let right = entityName.kind === SyntaxKind.QualifiedName ? (<QualifiedName>entityName).right : (<PropertyAccessExpression>entityName).name;
writeEntityName(left);
write(".");
writeTextOfNode(currentSourceFile, right);
}
}
function emitEntityName(entityName: EntityName | PropertyAccessExpression) {
@ -364,19 +379,6 @@ namespace ts {
handleSymbolAccessibilityError(visibilityResult);
writeEntityName(entityName);
function writeEntityName(entityName: EntityName | Expression) {
if (entityName.kind === SyntaxKind.Identifier) {
writeTextOfNode(currentSourceFile, entityName);
}
else {
let left = entityName.kind === SyntaxKind.QualifiedName ? (<QualifiedName>entityName).left : (<PropertyAccessExpression>entityName).expression;
let right = entityName.kind === SyntaxKind.QualifiedName ? (<QualifiedName>entityName).right : (<PropertyAccessExpression>entityName).name;
writeEntityName(left);
write(".");
writeTextOfNode(currentSourceFile, right);
}
}
}
function emitExpressionWithTypeArguments(node: ExpressionWithTypeArguments) {
@ -406,6 +408,12 @@ namespace ts {
}
}
function emitTypePredicate(type: TypePredicateNode) {
writeTextOfNode(currentSourceFile, type.parameterName);
write(" is ");
emitType(type.type);
}
function emitTypeQuery(type: TypeQueryNode) {
write("typeof ");
emitEntityName(type.exprName);
@ -608,7 +616,7 @@ namespace ts {
}
function writeImportEqualsDeclaration(node: ImportEqualsDeclaration) {
// note usage of writer. methods instead of aliases created, just to make sure we are using
// note usage of writer. methods instead of aliases created, just to make sure we are using
// correct writer especially to handle asynchronous alias writing
emitJsDocComments(node);
if (node.flags & NodeFlags.Export) {
@ -650,7 +658,7 @@ namespace ts {
function writeImportDeclaration(node: ImportDeclaration) {
if (!node.importClause && !(node.flags & NodeFlags.Export)) {
// do not write non-exported import declarations that don't have import clauses
// do not write non-exported import declarations that don't have import clauses
return;
}
emitJsDocComments(node);
@ -772,7 +780,7 @@ namespace ts {
emitJsDocComments(node);
emitModuleElementDeclarationFlags(node);
if (isConst(node)) {
write("const ")
write("const ");
}
write("enum ");
writeTextOfNode(currentSourceFile, node.name);
@ -1351,7 +1359,7 @@ namespace ts {
return {
diagnosticMessage,
errorNode: <Node>node.name || node,
errorNode: <Node>node.name || node
};
}
}
@ -1525,7 +1533,7 @@ namespace ts {
}
}
}
}
}
}
function emitNode(node: Node) {
@ -1573,7 +1581,7 @@ namespace ts {
? referencedFile.fileName // Declaration file, use declaration file name
: shouldEmitToOwnFile(referencedFile, compilerOptions)
? getOwnEmitOutputFilePath(referencedFile, host, ".d.ts") // Own output file so get the .d.ts file
: removeFileExtension(compilerOptions.out) + ".d.ts";// Global out file
: removeFileExtension(compilerOptions.out) + ".d.ts"; // Global out file
declFileName = getRelativePathToDirectoryOrUrl(
getDirectoryPath(normalizeSlashes(jsFilePath)),
@ -1585,7 +1593,7 @@ namespace ts {
referencePathsOutput += "/// <reference path=\"" + declFileName + "\" />" + newLine;
}
}
/* @internal */
export function writeDeclarationFile(jsFilePath: string, sourceFile: SourceFile, host: EmitHost, resolver: EmitResolver, diagnostics: Diagnostic[]) {
let emitDeclarationResult = emitDeclarations(host, resolver, diagnostics, jsFilePath, sourceFile);
@ -1612,4 +1620,4 @@ namespace ts {
return declarationOutput;
}
}
}
}

View file

@ -129,7 +129,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
let writeLine = writer.writeLine;
let increaseIndent = writer.increaseIndent;
let decreaseIndent = writer.decreaseIndent;
let currentSourceFile: SourceFile;
// name of an exporter function if file is a System external module
// System.register([...], function (<exporter>) {...})
@ -182,10 +182,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
/** Called to before starting the lexical scopes as in function/class in the emitted code because of node
* @param scopeDeclaration node that starts the lexical scope
* @param scopeName Optional name of this scope instead of deducing one from the declaration node */
let scopeEmitStart = function (scopeDeclaration: Node, scopeName?: string) { }
let scopeEmitStart = function(scopeDeclaration: Node, scopeName?: string) { };
/** Called after coming out of the scope */
let scopeEmitEnd = function () { }
let scopeEmitEnd = function() { };
/** Sourcemap data that will get encoded */
let sourceMapData: SourceMapData;
@ -227,7 +227,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
// Note that names generated by makeTempVariableName and makeUniqueName will never conflict.
function makeTempVariableName(flags: TempFlags): string {
if (flags && !(tempFlags & flags)) {
var name = flags === TempFlags._i ? "_i" : "_n"
let name = flags === TempFlags._i ? "_i" : "_n";
if (isUniqueName(name)) {
tempFlags |= flags;
return name;
@ -895,13 +895,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
if (languageVersion < ScriptTarget.ES6 && (isTemplateLiteralKind(node.kind) || node.hasExtendedUnicodeEscape)) {
return getQuotedEscapedLiteralText('"', node.text, '"');
}
// If we don't need to downlevel and we can reach the original source text using
// the node's parent reference, then simply get the text as it was originally written.
if (node.parent) {
return getSourceTextOfNodeFromSourceFile(currentSourceFile, node);
}
// If we can't reach the original source text, use the canonical form if it's a number,
// or an escaped quoted form of the original text if it's string-like.
switch (node.kind) {
@ -931,14 +931,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
// The raw strings contain the (escaped) strings of what the user wrote.
// Examples: `\n` is converted to "\\n", a template string with a newline to "\n".
let text = getSourceTextOfNodeFromSourceFile(currentSourceFile, node);
// text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"),
// thus we need to remove those characters.
// First template piece starts with "`", others with "}"
// Last template piece ends with "`", others with "${"
let isLast = node.kind === SyntaxKind.NoSubstitutionTemplateLiteral || node.kind === SyntaxKind.TemplateTail;
text = text.substring(1, text.length - (isLast ? 1 : 2));
// Newline normalization:
// ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's
// <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for both TV and TRV.
@ -979,7 +979,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emitParenthesizedIf(node.tag, needsParenthesisForPropertyAccessOrInvocation(node.tag));
write("(");
emit(tempVariable);
// Now we emit the expressions
if (node.template.kind === SyntaxKind.TemplateExpression) {
forEach((<TemplateExpression>node.template).templateSpans, templateSpan => {
@ -1042,7 +1042,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
// with the head will force the result up to this point to be a string.
// Emitting a '+ ""' has no semantic effect for middles and tails.
if (templateSpan.literal.text.length !== 0) {
write(" + ")
write(" + ");
emitLiteral(templateSpan.literal);
}
}
@ -1356,7 +1356,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
else if (node.kind === SyntaxKind.ComputedPropertyName) {
// if this is a decorated computed property, we will need to capture the result
// of the property expression so that we can apply decorators later. This is to ensure
// of the property expression so that we can apply decorators later. This is to ensure
// we don't introduce unintended side effects:
//
// class C {
@ -1466,7 +1466,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write("_arguments");
return;
}
let container = resolver.getReferencedExportContainer(node);
if (container) {
if (container.kind === SyntaxKind.SourceFile) {
@ -1550,7 +1550,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write("super");
}
else {
var flags = resolver.getNodeCheckFlags(node);
let flags = resolver.getNodeCheckFlags(node);
if (flags & NodeCheckFlags.SuperInstance) {
write("_super.prototype");
}
@ -1606,7 +1606,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emit(node.expression);
}
}
function emitAwaitExpression(node: AwaitExpression) {
let needsParenthesis = needsParenthesisForAwaitExpressionAsYield(node);
if (needsParenthesis) {
@ -1686,7 +1686,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
group++;
}
if (group > 1) {
if(useConcat) {
if (useConcat) {
write(")");
}
}
@ -1721,7 +1721,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write("{");
if (numElements > 0) {
var properties = node.properties;
let properties = node.properties;
// If we are not doing a downlevel transformation for object literals,
// then try to preserve the original shape of the object literal.
@ -1769,7 +1769,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
// Write out the first non-computed properties
// (or all properties if none of them are computed),
// then emit the rest through indexing on the temp variable.
emit(tempVar)
emit(tempVar);
write(" = ");
emitObjectLiteralBody(node, firstComputedPropertyIndex);
@ -1778,7 +1778,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
let property = properties[i];
emitStart(property)
emitStart(property);
if (property.kind === SyntaxKind.GetAccessor || property.kind === SyntaxKind.SetAccessor) {
// TODO (drosen): Reconcile with 'emitMemberFunctions'.
let accessors = getAllAccessorDeclarations(node.properties, <AccessorDeclaration>property);
@ -1794,7 +1794,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write(", {");
increaseIndent();
if (accessors.getAccessor) {
writeLine()
writeLine();
emitLeadingComments(accessors.getAccessor);
write("get: ");
emitStart(accessors.getAccessor);
@ -1967,8 +1967,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
return false;
}
// Returns 'true' if the code was actually indented, false otherwise.
// If the code is not indented, an optional valueToWriteWhenNotIndenting will be
// Returns 'true' if the code was actually indented, false otherwise.
// If the code is not indented, an optional valueToWriteWhenNotIndenting will be
// emitted instead.
function indentIfOnDifferentLines(parent: Node, node1: Node, node2: Node, valueToWriteWhenNotIndenting?: string): boolean {
let realNodesAreOnDifferentLines = !nodeIsSynthesized(parent) && !nodeEndIsOnSameLineAsNodeStart(node1, node2);
@ -1996,8 +1996,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emit(node.expression);
let indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken);
// 1 .toString is a valid property access, emit a space after the literal
// 1 .toString is a valid property access, emit a space after the literal
let shouldEmitSpace: boolean;
if (!indentedBeforeDot && node.expression.kind === SyntaxKind.NumericLiteral) {
let text = getSourceTextOfNodeFromSourceFile(currentSourceFile, node.expression);
@ -2005,7 +2005,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
if (shouldEmitSpace) {
write(" .");
write(" .");
}
else {
write(".");
@ -2330,14 +2330,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
return isSourceFileLevelDeclarationInSystemJsModule(node, /*isExported*/ false);
}
/*
/*
* Checks if given node is a source file level declaration (not nested in module/function).
* If 'isExported' is true - then declaration must also be exported.
* This function is used in two cases:
* - check if node is a exported source file level value to determine
* - check if node is a exported source file level value to determine
* if we should also export the value after its it changed
* - check if node is a source level declaration to emit it differently,
* i.e non-exported variable statement 'var x = 1' is hoisted so
* - check if node is a source level declaration to emit it differently,
* i.e non-exported variable statement 'var x = 1' is hoisted so
* we we emit variable statement 'var' should be dropped.
*/
function isSourceFileLevelDeclarationInSystemJsModule(node: Node, isExported: boolean): boolean {
@ -2348,7 +2348,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
let current: Node = node;
while (current) {
if (current.kind === SyntaxKind.SourceFile) {
return !isExported || ((getCombinedNodeFlags(node) & NodeFlags.Export) !== 0)
return !isExported || ((getCombinedNodeFlags(node) & NodeFlags.Export) !== 0);
}
else if (isFunctionLike(current) || current.kind === SyntaxKind.ModuleBlock) {
return false;
@ -2406,7 +2406,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
decreaseIndentIf(indentedBeforeColon, indentedAfterColon);
}
// Helper function to decrease the indent if we previously indented. Allows multiple
// Helper function to decrease the indent if we previously indented. Allows multiple
// previous indent values to be considered at a time. This also allows caller to just
// call this once, passing in all their appropriate indent values, instead of needing
// to call this helper function multiple times.
@ -2533,7 +2533,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
if (startPos !== undefined) {
emitToken(tokenKind, startPos);
write(" ")
write(" ");
}
else {
switch (tokenKind) {
@ -2648,13 +2648,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
// all destructuring.
// Note also that because an extra statement is needed to assign to the LHS,
// for-of bodies are always emitted as blocks.
let endPos = emitToken(SyntaxKind.ForKeyword, node.pos);
write(" ");
endPos = emitToken(SyntaxKind.OpenParenToken, endPos);
// Do not emit the LHS let declaration yet, because it might contain destructuring.
// Do not call recordTempDeclaration because we are declaring the temps
// right here. Recording means they will be declared later.
// In the case where the user wrote an identifier as the RHS, like this:
@ -2670,7 +2670,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
// the LHS will be emitted inside the body.
emitStart(node.expression);
write("var ");
// _i = 0
emitNodeWithoutSourceMap(counter);
write(" = 0");
@ -2687,7 +2687,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
write("; ");
// _i < _a.length;
emitStart(node.initializer);
emitNodeWithoutSourceMap(counter);
@ -2698,19 +2698,19 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emitEnd(node.initializer);
write("; ");
// _i++)
emitStart(node.initializer);
emitNodeWithoutSourceMap(counter);
write("++");
emitEnd(node.initializer);
emitToken(SyntaxKind.CloseParenToken, node.expression.end);
// Body
write(" {");
writeLine();
increaseIndent();
// Initialize LHS
// let v = _a[_i];
let rhsIterationValue = factory.createElementAccessExpression(rhsReference, counter);
@ -2796,7 +2796,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emit(node.expression);
endPos = emitToken(SyntaxKind.CloseParenToken, node.expression.end);
write(" ");
emitCaseBlock(node.caseBlock, endPos)
emitCaseBlock(node.caseBlock, endPos);
}
function emitCaseBlock(node: CaseBlock, startPos: number): void {
@ -2898,7 +2898,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
function emitModuleMemberName(node: Declaration) {
emitStart(node.name);
if (getCombinedNodeFlags(node) & NodeFlags.Export) {
var container = getContainingModule(node);
let container = getContainingModule(node);
if (container) {
write(getGeneratedNameForNode(container));
write(".");
@ -2929,7 +2929,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
write(`", `);
emitDeclarationName(node);
write(")")
write(")");
}
else {
if (node.flags & NodeFlags.Default) {
@ -2960,7 +2960,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emitNodeWithoutSourceMap(specifier.name);
write(`", `);
emitExpressionIdentifier(name);
write(")")
write(")");
emitEnd(specifier.name);
}
else {
@ -3227,7 +3227,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emitOptional(" = ", initializer);
if (exportChanged) {
write(")")
write(")");
}
}
}
@ -3527,10 +3527,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emit(node.parameters[0]);
return;
}
emitSignatureParameters(node);
}
function emitAsyncFunctionBodyForES6(node: FunctionLikeDeclaration) {
let promiseConstructor = getEntityNameFromTypeNode(node.type);
let isArrowFunction = node.kind === SyntaxKind.ArrowFunction;
@ -3540,7 +3540,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
// An async function is emit as an outer function that calls an inner
// generator function. To preserve lexical bindings, we pass the current
// `this` and `arguments` objects to `__awaiter`. The generator function
// passed to `__awaiter` is executed inside of the callback to the
// passed to `__awaiter` is executed inside of the callback to the
// promise constructor.
//
// The emit for an async arrow without a lexical `arguments` binding might be:
@ -3608,7 +3608,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
// });
// }
//
// If this is not an async arrow, emit the opening brace of the function body
// and the start of the return statement.
if (!isArrowFunction) {
@ -3617,7 +3617,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
writeLine();
write("return");
}
write(" __awaiter(this");
if (hasLexicalArguments) {
write(", arguments");
@ -3633,7 +3633,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
else {
write(", Promise");
}
// Emit the call to __awaiter.
if (hasLexicalArguments) {
write(", function* (_arguments)");
@ -3641,11 +3641,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
else {
write(", function* ()");
}
// Emit the signature and body for the inner generator function.
emitFunctionBody(node);
write(")");
// If this is not an async arrow, emit the closing brace of the outer function body.
if (!isArrowFunction) {
write(";");
@ -3654,10 +3654,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write("}");
}
}
function emitFunctionBody(node: FunctionLikeDeclaration) {
if (!node.body) {
// There can be no body when there are parse errors. Just emit an empty block
// There can be no body when there are parse errors. Just emit an empty block
// in that case.
write(" { }");
}
@ -3668,7 +3668,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
else {
emitExpressionFunctionBody(node, <Expression>node.body);
}
}
}
}
function emitSignatureAndBody(node: FunctionLikeDeclaration) {
@ -3687,7 +3687,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
else {
emitSignatureParameters(node);
}
let isAsync = isAsyncFunctionLike(node);
if (isAsync && languageVersion === ScriptTarget.ES6) {
emitAsyncFunctionBodyForES6(node);
@ -3695,7 +3695,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
else {
emitFunctionBody(node);
}
if (!isES6ExportedDeclaration(node)) {
emitExportMemberAssignment(node);
}
@ -3718,7 +3718,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
return;
}
// For es6 and higher we can emit the expression as is. However, in the case
// For es6 and higher we can emit the expression as is. However, in the case
// where the expression might end up looking like a block when emitted, we'll
// also wrap it in parentheses first. For example if you have: a => <foo>{}
// then we need to generate: a => ({})
@ -3990,8 +3990,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emitOnlyPinnedOrTripleSlashComments(member);
}
else if (member.kind === SyntaxKind.MethodDeclaration ||
member.kind === SyntaxKind.GetAccessor ||
member.kind === SyntaxKind.SetAccessor) {
member.kind === SyntaxKind.GetAccessor ||
member.kind === SyntaxKind.SetAccessor) {
writeLine();
emitLeadingComments(member);
emitStart(member);
@ -4125,7 +4125,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
emitPropertyDeclarations(node, getInitializedProperties(node, /*static:*/ false));
if (ctor) {
var statements: Node[] = (<Block>ctor.body).statements;
let statements: Node[] = (<Block>ctor.body).statements;
if (superCall) {
statements = statements.slice(1);
}
@ -4235,9 +4235,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
// If the class has static properties, and it's a class expression, then we'll need
// to specialize the emit a bit. for a class expression of the form:
// to specialize the emit a bit. for a class expression of the form:
//
// class C { static a = 1; static b = 2; ... }
// class C { static a = 1; static b = 2; ... }
//
// We'll emit:
//
@ -4254,7 +4254,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write("(");
increaseIndent();
emit(tempVariable);
write(" = ")
write(" = ");
}
write("class");
@ -4265,7 +4265,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emitDeclarationName(node);
}
var baseTypeNode = getClassExtendsHeritageClauseElement(node);
let baseTypeNode = getClassExtendsHeritageClauseElement(node);
if (baseTypeNode) {
write(" extends ");
emit(baseTypeNode.expression);
@ -4283,7 +4283,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
scopeEmitEnd();
// TODO(rbuckton): Need to go back to `let _a = class C {}` approach, removing the defineProperty call for now.
// For a decorated class, we need to assign its name (if it has one). This is because we emit
// the class as a class expression to avoid the double-binding of the identifier:
//
@ -4528,7 +4528,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
//
// The emit for a method is:
//
// Object.defineProperty(C.prototype, "method",
// Object.defineProperty(C.prototype, "method",
// __decorate([
// dec,
// __param(0, dec2),
@ -4536,10 +4536,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
// __metadata("design:paramtypes", [Object]),
// __metadata("design:returntype", void 0)
// ], C.prototype, "method", Object.getOwnPropertyDescriptor(C.prototype, "method")));
//
//
// The emit for an accessor is:
//
// Object.defineProperty(C.prototype, "accessor",
// Object.defineProperty(C.prototype, "accessor",
// __decorate([
// dec
// ], C.prototype, "accessor", Object.getOwnPropertyDescriptor(C.prototype, "accessor")));
@ -4629,7 +4629,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
function shouldEmitTypeMetadata(node: Declaration): boolean {
// This method determines whether to emit the "design:type" metadata based on the node's kind.
// The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata
// The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata
// compiler option is set.
switch (node.kind) {
case SyntaxKind.MethodDeclaration:
@ -4644,7 +4644,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
function shouldEmitReturnTypeMetadata(node: Declaration): boolean {
// This method determines whether to emit the "design:returntype" metadata based on the node's kind.
// The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata
// The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata
// compiler option is set.
switch (node.kind) {
case SyntaxKind.MethodDeclaration:
@ -4655,7 +4655,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
function shouldEmitParamTypesMetadata(node: Declaration): boolean {
// This method determines whether to emit the "design:paramtypes" metadata based on the node's kind.
// The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata
// The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata
// compiler option is set.
switch (node.kind) {
case SyntaxKind.ClassDeclaration:
@ -4672,7 +4672,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
let argumentsWritten = 0;
if (compilerOptions.emitDecoratorMetadata) {
if (shouldEmitTypeMetadata(node)) {
var serializedType = resolver.serializeTypeOfNode(node);
let serializedType = resolver.serializeTypeOfNode(node);
if (serializedType) {
if (writeComma) {
write(", ");
@ -4685,7 +4685,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
}
if (shouldEmitParamTypesMetadata(node)) {
var serializedTypes = resolver.serializeParameterTypesOfNode(node);
let serializedTypes = resolver.serializeParameterTypesOfNode(node);
if (serializedTypes) {
if (writeComma || argumentsWritten) {
write(", ");
@ -4703,7 +4703,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
}
if (shouldEmitReturnTypeMetadata(node)) {
var serializedType = resolver.serializeReturnTypeOfNode(node);
let serializedType = resolver.serializeReturnTypeOfNode(node);
if (serializedType) {
if (writeComma || argumentsWritten) {
write(", ");
@ -5204,7 +5204,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
writeLine();
emitStart(node);
write("export default ");
var expression = node.expression;
let expression = node.expression;
emit(expression);
if (expression.kind !== SyntaxKind.FunctionDeclaration &&
expression.kind !== SyntaxKind.ClassDeclaration) {
@ -5334,7 +5334,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
// do not create variable declaration for exports and imports that lack import clause
let skipNode =
importNode.kind === SyntaxKind.ExportDeclaration ||
(importNode.kind === SyntaxKind.ImportDeclaration && !(<ImportDeclaration>importNode).importClause)
(importNode.kind === SyntaxKind.ImportDeclaration && !(<ImportDeclaration>importNode).importClause);
if (skipNode) {
continue;
@ -5452,14 +5452,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write("}");
decreaseIndent();
writeLine();
write("}")
write("}");
return exportStarFunction;
}
function writeExportedName(node: Identifier | Declaration): void {
// do not record default exports
// they are local to module and never overwritten (explicitly skipped) by star export
// they are local to module and never overwritten (explicitly skipped) by star export
if (node.kind !== SyntaxKind.Identifier && node.flags & NodeFlags.Default) {
return;
}
@ -5485,7 +5485,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
function processTopLevelVariableAndFunctionDeclarations(node: SourceFile): (Identifier | Declaration)[] {
// per ES6 spec:
// per ES6 spec:
// 15.2.1.16.4 ModuleDeclarationInstantiation() Concrete Method
// - var declarations are initialized to undefined - 14.a.ii
// - function/generator declarations are instantiated - 16.a.iv
@ -5540,7 +5540,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
exportedDeclarations.push(local);
}
}
write(";")
write(";");
}
if (hoistedFunctionDeclarations) {
@ -5640,7 +5640,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
// hoist variable if
// - it is not block scoped
// - it is top level block scoped
// if block scoped variables are nested in some another block then
// if block scoped variables are nested in some another block then
// no other functions can use them except ones that are defined at least in the same block
return (getCombinedNodeFlags(node) & NodeFlags.BlockScoped) === 0 ||
getEnclosingBlockScopeContainer(node).kind === SyntaxKind.SourceFile;
@ -5689,8 +5689,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
// }
emitVariableDeclarationsForImports();
writeLine();
var exportedDeclarations = processTopLevelVariableAndFunctionDeclarations(node);
let exportStarFunction = emitLocalStorageForExportedNamesIfNecessary(exportedDeclarations)
let exportedDeclarations = processTopLevelVariableAndFunctionDeclarations(node);
let exportStarFunction = emitLocalStorageForExportedNamesIfNecessary(exportedDeclarations);
writeLine();
write("return {");
increaseIndent();
@ -5767,7 +5767,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
// export {a, b as c}
for (let element of (<NamedImports>namedBindings).elements) {
emitExportMemberAssignments(element.name || element.propertyName);
writeLine()
writeLine();
}
}
}
@ -5806,7 +5806,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
break;
}
write("}")
write("}");
decreaseIndent();
}
write("],");
@ -5832,7 +5832,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
decreaseIndent();
writeLine();
write("}") // execute
write("}"); // execute
}
function emitSystemModule(node: SourceFile, startIndex: number): void {
@ -5840,10 +5840,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
// System modules has the following shape
// System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */})
// 'exports' here is a function 'exports<T>(name: string, value: T): T' that is used to publish exported values.
// 'exports' returns its 'value' argument so in most cases expressions
// 'exports' returns its 'value' argument so in most cases expressions
// that mutate exported values can be rewritten as:
// expr -> exports('name', expr).
// The only exception in this rule is postfix unary operators,
// expr -> exports('name', expr).
// The only exception in this rule is postfix unary operators,
// see comment to 'emitPostfixUnaryExpression' for more details
Debug.assert(!exportFunctionForFile);
// make sure that name of 'exports' function does not conflict with existing identifiers
@ -5852,7 +5852,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
if (node.moduleName) {
write(`"${node.moduleName}", `);
}
write("[")
write("[");
for (let i = 0; i < externalImports.length; ++i) {
let text = getExternalModuleNameText(externalImports[i]);
if (i !== 0) {
@ -5883,13 +5883,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
// `import "module"` or `<amd-dependency path= "a.css" />`
// we need to add modules without alias names to the end of the dependencies list
let aliasedModuleNames: string[] = []; // names of modules with corresponding parameter in the
// factory function.
let unaliasedModuleNames: string[] = []; // names of modules with no corresponding parameters in
// factory function.
let importAliasNames: string[] = []; // names of the parameters in the factory function; these
// parameters need to match the indexes of the corresponding
// module names in aliasedModuleNames.
// names of modules with corresponding parameter in the factory function
let aliasedModuleNames: string[] = [];
// names of modules with no corresponding parameters in factory function
let unaliasedModuleNames: string[] = [];
let importAliasNames: string[] = []; // names of the parameters in the factory function; these
// parameters need to match the indexes of the corresponding
// module names in aliasedModuleNames.
// Fill in amd-dependency tags
for (let amdDependency of node.amdDependencies) {
@ -5996,7 +5996,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emitCaptureThisForNodeIfNecessary(node);
emitLinesStartingAt(node.statements, startIndex);
emitTempDeclarations(/*newLine*/ true);
// Emit exportDefault if it exists will happen as part
// Emit exportDefault if it exists will happen as part
// or normal statement emit.
}
@ -6137,7 +6137,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emitDetachedComments(node);
// emit prologue directives prior to __extends
var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false);
let startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false);
// Only emit helpers if the user did not say otherwise.
if (!compilerOptions.noEmitHelpers) {
@ -6160,7 +6160,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
writeLines(paramHelper);
paramEmitted = true;
}
if (!awaiterEmitted && resolver.getNodeCheckFlags(node) & NodeCheckFlags.EmitAwaiter) {
writeLines(awaiterHelper);
awaiterEmitted = true;
@ -6244,7 +6244,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
return shouldEmitEnumDeclaration(<EnumDeclaration>node);
}
// If this is the expression body of an arrow function that we're down-leveling,
// If this is the expression body of an arrow function that we're down-leveling,
// then we don't want to emit comments when we emit the body. It will have already
// been taken care of when we emitted the 'return' statement for the function
// expression body.
@ -6509,7 +6509,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
function emitTrailingComments(node: Node) {
// Emit the trailing comments only if the parent's end doesn't match
var trailingComments = filterComments(getTrailingCommentsToEmit(node), /*onlyPinnedOrTripleSlashComments:*/ compilerOptions.removeComments);
let trailingComments = filterComments(getTrailingCommentsToEmit(node), /*onlyPinnedOrTripleSlashComments:*/ compilerOptions.removeComments);
// trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/
emitComments(currentSourceFile, writer, trailingComments, /*trailingSeparator*/ false, newLine, writeComment);
@ -6601,4 +6601,4 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
}
}
}
}

View file

@ -402,7 +402,7 @@ namespace ts {
export function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile {
return IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks);
}
/* @internal */
export function parseIsolatedJSDocComment(content: string, start?: number, length?: number) {
return Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length);
@ -577,7 +577,7 @@ namespace ts {
fixupParentReferences(sourceFile);
}
// If this is a javascript file, proactively see if we can get JSDoc comments for
// If this is a javascript file, proactively see if we can get JSDoc comments for
// relevant nodes in the file. We'll use these to provide typing informaion if they're
// available.
if (isJavaScript(fileName)) {
@ -677,17 +677,17 @@ namespace ts {
function setDecoratorContext(val: boolean) {
setContextFlag(val, ParserContextFlags.Decorator);
}
function setAwaitContext(val: boolean) {
setContextFlag(val, ParserContextFlags.Await);
}
function doOutsideOfContext<T>(context: ParserContextFlags, func: () => T): T {
// contextFlagsToClear will contain only the context flags that are
// contextFlagsToClear will contain only the context flags that are
// currently set that we need to temporarily clear
// We don't just blindly reset to the previous flags to ensure
// that we do not mutate cached flags for the incremental
// parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and
// parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and
// HasAggregatedChildData).
let contextFlagsToClear = context & contextFlags;
if (contextFlagsToClear) {
@ -702,13 +702,13 @@ namespace ts {
// no need to do anything special as we are not in any of the requested contexts
return func();
}
function doInsideOfContext<T>(context: ParserContextFlags, func: () => T): T {
// contextFlagsToSet will contain only the context flags that
// are not currently set that we need to temporarily enable.
// We don't just blindly reset to the previous flags to ensure
// that we do not mutate cached flags for the incremental
// parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and
// parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and
// HasAggregatedChildData).
let contextFlagsToSet = context & ~contextFlags;
if (contextFlagsToSet) {
@ -719,11 +719,11 @@ namespace ts {
setContextFlag(false, contextFlagsToSet);
return result;
}
// no need to do anything special as we are already in all of the requested contexts
return func();
}
function allowInAnd<T>(func: () => T): T {
return doOutsideOfContext(ParserContextFlags.DisallowIn, func);
}
@ -731,7 +731,7 @@ namespace ts {
function disallowInAnd<T>(func: () => T): T {
return doInsideOfContext(ParserContextFlags.DisallowIn, func);
}
function doInYieldContext<T>(func: () => T): T {
return doInsideOfContext(ParserContextFlags.Yield, func);
}
@ -743,23 +743,23 @@ namespace ts {
function doInDecoratorContext<T>(func: () => T): T {
return doInsideOfContext(ParserContextFlags.Decorator, func);
}
function doInAwaitContext<T>(func: () => T): T {
return doInsideOfContext(ParserContextFlags.Await, func);
}
function doOutsideOfAwaitContext<T>(func: () => T): T {
return doOutsideOfContext(ParserContextFlags.Await, func);
}
function doInYieldAndAwaitContext<T>(func: () => T): T {
return doInsideOfContext(ParserContextFlags.Yield | ParserContextFlags.Await, func);
}
function doOutsideOfYieldAndAwaitContext<T>(func: () => T): T {
return doOutsideOfContext(ParserContextFlags.Yield | ParserContextFlags.Await, func);
}
function inContext(flags: ParserContextFlags) {
return (contextFlags & flags) !== 0;
}
@ -779,7 +779,7 @@ namespace ts {
function inAwaitContext() {
return inContext(ParserContextFlags.Await);
}
function parseErrorAtCurrentToken(message: DiagnosticMessage, arg0?: any): void {
let start = scanner.getTokenPos();
let length = scanner.getTextPos() - start;
@ -835,7 +835,7 @@ namespace ts {
function scanJsxIdentifier(): SyntaxKind {
return token = scanner.scanJsxIdentifier();
}
function speculationHelper<T>(callback: () => T, isLookAhead: boolean): T {
// Keep track of the state we'll need to rollback to if lookahead fails (or if the
// caller asked us to always reset our state).
@ -895,7 +895,7 @@ namespace ts {
if (token === SyntaxKind.YieldKeyword && inYieldContext()) {
return false;
}
// If we have a 'await' keyword, and we're in the [Await] context, then 'await' is
// considered a keyword and is not an identifier.
if (token === SyntaxKind.AwaitKeyword && inAwaitContext()) {
@ -1093,7 +1093,7 @@ namespace ts {
function parseContextualModifier(t: SyntaxKind): boolean {
return token === t && tryParse(nextTokenCanFollowModifier);
}
function nextTokenCanFollowModifier() {
if (token === SyntaxKind.ConstKeyword) {
// 'const' is only a modifier if followed by 'enum'.
@ -1112,7 +1112,7 @@ namespace ts {
nextToken();
return canFollowModifier();
}
function parseAnyContextualModifier(): boolean {
return isModifier(token) && tryParse(nextTokenCanFollowModifier);
}
@ -1220,7 +1220,7 @@ namespace ts {
// if we see "extends {}" then only treat the {} as what we're extending (and not
// the class body) if we have:
//
// extends {} {
// extends {} {
// extends {},
// extends {} extends
// extends {} implements
@ -1835,7 +1835,7 @@ namespace ts {
do {
templateSpans.push(parseTemplateSpan());
}
while (lastOrUndefined(templateSpans).literal.kind === SyntaxKind.TemplateMiddle)
while (lastOrUndefined(templateSpans).literal.kind === SyntaxKind.TemplateMiddle);
templateSpans.end = getNodeEnd();
template.templateSpans = templateSpans;
@ -1850,7 +1850,7 @@ namespace ts {
let literal: LiteralExpression;
if (token === SyntaxKind.CloseBraceToken) {
reScanTemplateToken()
reScanTemplateToken();
literal = parseLiteralNode();
}
else {
@ -2010,7 +2010,7 @@ namespace ts {
// ambient contexts.
return finishNode(node);
}
function parseBindingElementInitializer(inParameter: boolean) {
return inParameter ? parseParameterInitializer() : parseNonParameterInitializer();
}
@ -2018,7 +2018,7 @@ namespace ts {
function parseParameterInitializer() {
return parseInitializer(/*inParameter*/ true);
}
function fillSignature(
returnToken: SyntaxKind,
yieldContext: boolean,
@ -2056,15 +2056,15 @@ namespace ts {
if (parseExpected(SyntaxKind.OpenParenToken)) {
let savedYieldContext = inYieldContext();
let savedAwaitContext = inAwaitContext();
setYieldContext(yieldContext);
setAwaitContext(awaitContext);
let result = parseDelimitedList(ParsingContext.Parameters, parseParameter);
setYieldContext(savedYieldContext);
setAwaitContext(savedAwaitContext);
if (!parseExpected(SyntaxKind.CloseParenToken) && requireCompleteParameterList) {
// Caller insisted that we had to end with a ) We didn't. So just return
// undefined here.
@ -2079,7 +2079,7 @@ namespace ts {
// then just return an empty set of parameters.
return requireCompleteParameterList ? undefined : createMissingList<ParameterDeclaration>();
}
function parseTypeMemberSemicolon() {
// We allow type members to be separated by commas or (possibly ASI) semicolons.
// First check if it was a comma. If so, we're done with the member.
@ -2171,7 +2171,7 @@ namespace ts {
node.parameters = parseBracketedList(ParsingContext.Parameters, parseParameter, SyntaxKind.OpenBracketToken, SyntaxKind.CloseBracketToken);
node.type = parseTypeAnnotation();
parseTypeMemberSemicolon();
return finishNode(node)
return finishNode(node);
}
function parsePropertyOrMethodSignature(): Declaration {
@ -2462,7 +2462,7 @@ namespace ts {
function parseType(): TypeNode {
// The rules about 'yield' only apply to actual code/expression contexts. They don't
// apply to 'type' contexts. So we disable these parameters here before moving on.
// apply to 'type' contexts. So we disable these parameters here before moving on.
return doOutsideOfContext(ParserContextFlags.TypeExcludesFlags, parseTypeWorker);
}
@ -2550,7 +2550,7 @@ namespace ts {
token !== SyntaxKind.AtToken &&
isStartOfExpression();
}
function allowInAndParseExpression(): Expression {
return allowInAnd(parseExpression);
}
@ -2737,7 +2737,7 @@ namespace ts {
// It's definitely not a parenthesized arrow function expression.
return undefined;
}
// If we definitely have an arrow function, then we can just parse one, not requiring a
// following => or { token. Otherwise, we *might* have an arrow function. Try to parse
// it out, but don't allow any ambiguity, and return 'undefined' if this could be an
@ -2750,12 +2750,12 @@ namespace ts {
// Didn't appear to actually be a parenthesized arrow function. Just bail out.
return undefined;
}
let isAsync = !!(arrowFunction.flags & NodeFlags.Async);
// If we have an arrow, then try to parse the body. Even if not, try to parse if we
// have an opening brace, just in case we're in an error state.
var lastToken = token;
let lastToken = token;
arrowFunction.equalsGreaterThanToken = parseExpectedToken(SyntaxKind.EqualsGreaterThanToken, /*reportAtCurrentPosition*/false, Diagnostics._0_expected, "=>");
arrowFunction.body = (lastToken === SyntaxKind.EqualsGreaterThanToken || lastToken === SyntaxKind.OpenBraceToken)
? parseArrowFunctionExpressionBody(isAsync)
@ -2793,7 +2793,7 @@ namespace ts {
return Tristate.False;
}
}
let first = token;
let second = nextToken();
@ -2881,7 +2881,7 @@ namespace ts {
if (isArrowFunctionInJsx) {
return Tristate.True;
}
return Tristate.False;
}
@ -2898,7 +2898,7 @@ namespace ts {
let node = beginNode(factory.createArrowFunction());
setModifiers(node, parseModifiersForArrowFunction());
let isAsync = !!(node.flags & NodeFlags.Async);
// Arrow functions are never generators.
//
// If we're speculatively parsing a signature for a parenthesized arrow function, then
@ -2955,7 +2955,7 @@ namespace ts {
// Note: even when 'ignoreMissingOpenBrace' is passed as true, parseBody will still error.
return parseFunctionBlock(/*allowYield*/ false, /*allowAwait*/ isAsync, /*ignoreMissingOpenBrace*/ true);
}
return isAsync
? doInAwaitContext(parseAssignmentExpressionOrHigher)
: doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher);
@ -3122,7 +3122,7 @@ namespace ts {
node.expression = parseUnaryExpressionOrHigher();
return finishNode(node);
}
function isAwaitExpression(): boolean {
if (token === SyntaxKind.AwaitKeyword) {
if (inAwaitContext()) {
@ -3147,7 +3147,7 @@ namespace ts {
if (isAwaitExpression()) {
return parseAwaitExpression();
}
switch (token) {
case SyntaxKind.PlusToken:
case SyntaxKind.MinusToken:
@ -3166,7 +3166,7 @@ namespace ts {
if (sourceFile.languageVariant !== LanguageVariant.JSX) {
return parseTypeAssertion();
}
if(lookAhead(nextTokenIsIdentifierOrKeyword)) {
if (lookAhead(nextTokenIsIdentifierOrKeyword)) {
return parseJsxElementOrSelfClosingElement();
}
// Fall through
@ -3296,7 +3296,7 @@ namespace ts {
node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true);
return finishNode(node);
}
function parseJsxElementOrSelfClosingElement(): JsxElement|JsxSelfClosingElement {
let opening = parseJsxOpeningOrSelfClosingElement();
if (opening.kind === SyntaxKind.JsxOpeningElement) {
@ -3338,7 +3338,7 @@ namespace ts {
let saveParsingContext = parsingContext;
parsingContext |= 1 << ParsingContext.JsxChildren;
while(true) {
while (true) {
token = scanner.reScanJsxToken();
if (token === SyntaxKind.LessThanSlashToken) {
break;
@ -3356,7 +3356,7 @@ namespace ts {
return result;
}
function parseJsxOpeningOrSelfClosingElement(): JsxOpeningElement|JsxSelfClosingElement {
let fullStart = scanner.getStartPos();
@ -3381,7 +3381,7 @@ namespace ts {
return finishNode(node);
}
function parseJsxElementName(): EntityName {
scanJsxIdentifier();
let elementName: EntityName = parseIdentifierName();
@ -3466,7 +3466,7 @@ namespace ts {
continue;
}
// when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName
// when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName
if (!inDecoratorContext() && parseOptional(SyntaxKind.OpenBracketToken)) {
let indexedAccess = beginNode(factory.createElementAccessExpression(), expression.pos);
indexedAccess.expression = expression;
@ -3588,7 +3588,7 @@ namespace ts {
case SyntaxKind.CommaToken: // foo<x>,
case SyntaxKind.OpenBraceToken: // foo<x> {
// We don't want to treat these as type arguments. Otherwise we'll parse this
// as an invocation expression. Instead, we want to parse out the expression
// as an invocation expression. Instead, we want to parse out the expression
// in isolation from the type arguments.
default:
@ -3616,7 +3616,7 @@ namespace ts {
case SyntaxKind.OpenBraceToken:
return parseObjectLiteralExpression();
case SyntaxKind.AsyncKeyword:
// Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher.
// Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher.
// If we encounter `async [no LineTerminator here] function` then this is an async
// function; otherwise, its an identifier.
if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) {
@ -3748,12 +3748,12 @@ namespace ts {
if (saveDecoratorContext) {
setDecoratorContext(false);
}
let node = beginNode(factory.createFunctionExpression());
setModifiers(node, parseModifiers());
parseExpected(SyntaxKind.FunctionKeyword);
node.asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken);
let isGenerator = !!node.asteriskToken;
let isAsync = !!(node.flags & NodeFlags.Async);
node.name =
@ -3761,14 +3761,14 @@ namespace ts {
isGenerator ? doInYieldContext(parseOptionalIdentifier) :
isAsync ? doInAwaitContext(parseOptionalIdentifier) :
parseOptionalIdentifier();
fillSignature(SyntaxKind.ColonToken, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, node);
node.body = parseFunctionBlock(/*allowYield*/ isGenerator, /*allowAwait*/ isAsync, /*ignoreMissingOpenBrace*/ false);
if (saveDecoratorContext) {
setDecoratorContext(true);
}
return finishNode(node);
}
@ -3804,11 +3804,11 @@ namespace ts {
function parseFunctionBlock(allowYield: boolean, allowAwait: boolean, ignoreMissingOpenBrace: boolean, diagnosticMessage?: DiagnosticMessage): Block {
let savedYieldContext = inYieldContext();
setYieldContext(allowYield);
let savedAwaitContext = inAwaitContext();
setAwaitContext(allowAwait);
// We may be in a [Decorator] context when parsing a function expression or
// We may be in a [Decorator] context when parsing a function expression or
// arrow function. The body of the function is not in [Decorator] context.
let saveDecoratorContext = inDecoratorContext();
if (saveDecoratorContext) {
@ -4070,7 +4070,7 @@ namespace ts {
nextToken();
return isIdentifierOrKeyword() && !scanner.hasPrecedingLineBreak();
}
function nextTokenIsFunctionKeywordOnSameLine() {
nextToken();
return token === SyntaxKind.FunctionKeyword && !scanner.hasPrecedingLineBreak();
@ -4139,7 +4139,7 @@ namespace ts {
return true;
}
continue;
case SyntaxKind.PublicKeyword:
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
@ -4218,7 +4218,7 @@ namespace ts {
}
function isLetDeclaration() {
// In ES6 'let' always starts a lexical declaration if followed by an identifier or {
// In ES6 'let' always starts a lexical declaration if followed by an identifier or {
// or [.
return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring);
}
@ -4324,7 +4324,7 @@ namespace ts {
default:
if (decorators || modifiers) {
// We reached this point because we encountered decorators and/or modifiers and assumed a declaration
// would follow. For recovery and error reporting purposes, return an incomplete declaration.
// would follow. For recovery and error reporting purposes, return an incomplete declaration.
let node = <MissingDeclaration>createMissingNode(SyntaxKind.MissingDeclaration, /*reportAtCurrentPosition*/ true, Diagnostics.Declaration_expected);
node.pos = fullStart;
node.decorators = decorators;
@ -4539,7 +4539,7 @@ namespace ts {
function parsePropertyOrMethodDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): ClassElement {
let asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken);
let name = parsePropertyName();
// Note: this is not legal as per the grammar. But we allow it in the parser and
// report an error in the grammar checker.
let questionToken = parseOptionalToken(SyntaxKind.QuestionToken);
@ -4683,7 +4683,7 @@ namespace ts {
modifiers = <ModifiersArray>[];
modifiers.pos = modifierStart;
}
flags |= modifierToFlag(modifierKind);
modifiers.push(finishNode(beginNode(factory.createNode(modifierKind), modifierStart)));
}
@ -4708,7 +4708,7 @@ namespace ts {
modifiers.flags = flags;
modifiers.end = scanner.getStartPos();
}
return modifiers;
}
@ -4770,7 +4770,7 @@ namespace ts {
}
function parseClassDeclarationOrExpression(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray, kind: SyntaxKind): ClassLikeDeclaration {
var node = beginNode(factory.createNode<ClassLikeDeclaration>(kind), fullStart);
let node = beginNode(factory.createNode<ClassLikeDeclaration>(kind), fullStart);
node.decorators = decorators;
setModifiers(node, modifiers);
parseExpected(SyntaxKind.ClassKeyword);
@ -4780,7 +4780,7 @@ namespace ts {
if (parseExpected(SyntaxKind.OpenBraceToken)) {
// ClassTail[Yield,Await] : (Modified) See 14.5
// ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
// ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
node.members = parseClassMembers();
parseExpected(SyntaxKind.CloseBraceToken);
}
@ -4997,7 +4997,7 @@ namespace ts {
}
function parseImportClause(identifier: Identifier, fullStart: number) {
//ImportClause:
// ImportClause:
// ImportedDefaultBinding
// NameSpaceImport
// NamedImports
@ -5290,7 +5290,7 @@ namespace ts {
/* @internal */
export function parseJSDocTypeExpression(start: number, length: number): JSDocTypeExpression {
scanner.setText(sourceText, start, length);
// Prime the first token for us to start processing.
token = nextToken();
@ -5305,15 +5305,15 @@ namespace ts {
}
function parseJSDocTopLevelType(): JSDocType {
var type = parseJSDocType();
let type = parseJSDocType();
if (token === SyntaxKind.BarToken) {
var unionType = beginNode(factory.createJSDocUnionType(), type.pos);
let unionType = beginNode(factory.createJSDocUnionType(), type.pos);
unionType.types = parseJSDocTypeList(type);
type = finishNode(unionType);
}
if (token === SyntaxKind.EqualsToken) {
var optionalType = beginNode(factory.createJSDocOptionalType(), type.pos);
let optionalType = beginNode(factory.createJSDocOptionalType(), type.pos);
nextToken();
optionalType.type = type;
type = finishNode(optionalType);
@ -5627,9 +5627,9 @@ namespace ts {
let tags: NodeArray<JSDocTag>;
let pos: number;
// NOTE(cyrusn): This is essentially a handwritten scanner for JSDocComments. I
// considered using an actual Scanner, but this would complicate things. The
// NOTE(cyrusn): This is essentially a handwritten scanner for JSDocComments. I
// considered using an actual Scanner, but this would complicate things. The
// scanner would need to know it was in a Doc Comment. Otherwise, it would then
// produce comments *inside* the doc comment. In the end it was just easier to
// write a simple scanner rather than go that route.
@ -5644,13 +5644,13 @@ namespace ts {
let canParseTag = true;
let seenAsterisk = true;
for (pos = start + "/**".length; pos < end;) {
for (pos = start + "/**".length; pos < end; ) {
let ch = content.charCodeAt(pos);
pos++;
if (ch === CharacterCodes.at && canParseTag) {
parseTag();
// Once we parse out a tag, we cannot keep parsing out tags on this line.
canParseTag = false;
continue;
@ -5916,7 +5916,7 @@ namespace ts {
if (sourceFile.statements.length === 0) {
// If we don't have any statements in the current source file, then there's no real
// way to incrementally parse. So just do a full parse instead.
return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setNodeParents*/ true)
return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setNodeParents*/ true);
}
// Make sure we're not trying to incrementally update a source file more than once. Once
@ -5980,7 +5980,7 @@ namespace ts {
// inconsistent tree. Setting the parents on the new tree should be very fast. We
// will immediately bail out of walking any subtrees when we can see that their parents
// are already correct.
let result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /* setParentNode */ true)
let result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /* setParentNode */ true);
return result;
}
@ -5995,8 +5995,9 @@ namespace ts {
return;
function visitNode(node: IncrementalNode) {
let text = '';
if (aggressiveChecks && shouldCheckNode(node)) {
var text = oldText.substring(node.pos, node.end);
text = oldText.substring(node.pos, node.end);
}
// Ditch any existing LS children we may have created. This way we can avoid
@ -6346,17 +6347,17 @@ namespace ts {
interface IncrementalElement extends TextRange {
parent?: Node;
intersectsChange: boolean
intersectsChange: boolean;
length?: number;
_children: Node[];
}
export interface IncrementalNode extends Node, IncrementalElement {
hasBeenIncrementallyParsed: boolean
hasBeenIncrementallyParsed: boolean;
}
interface IncrementalNodeArray extends NodeArray<IncrementalNode>, IncrementalElement {
length: number
length: number;
}
// Allows finding nodes in the source file at a certain position in an efficient manner.

View file

@ -11,12 +11,12 @@ namespace ts {
export const version = "1.5.3";
export function findConfigFile(searchPath: string): string {
var fileName = "tsconfig.json";
let fileName = "tsconfig.json";
while (true) {
if (sys.fileExists(fileName)) {
return fileName;
}
var parentPath = getDirectoryPath(searchPath);
let parentPath = getDirectoryPath(searchPath);
if (parentPath === searchPath) {
break;
}
@ -35,7 +35,7 @@ namespace ts {
// otherwise use toLowerCase as a canonical form.
return sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
}
// returned by CScript sys environment
let unsupportedFileEncodingErrorCode = -2147024809;
@ -79,7 +79,7 @@ namespace ts {
function writeFile(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void) {
try {
var start = new Date().getTime();
let start = new Date().getTime();
ensureDirectoriesExist(getDirectoryPath(normalizePath(fileName)));
sys.writeFile(fileName, data, writeByteOrderMark);
ioWriteTime += new Date().getTime() - start;
@ -239,8 +239,8 @@ namespace ts {
function emitWorker(program: Program, sourceFile: SourceFile, writeFileCallback: WriteFileCallback, cancellationToken: CancellationToken): EmitResult {
// If the noEmitOnError flag is set, then check if we have any errors so far. If so,
// immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we
// get any preEmit diagnostics, not just the ones
// immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we
// get any preEmit diagnostics, not just the ones
if (options.noEmitOnError && getPreEmitDiagnostics(program, /*sourceFile:*/ undefined, cancellationToken).length > 0) {
return { diagnostics: [], sourceMaps: undefined, emitSkipped: true };
}
@ -311,14 +311,14 @@ namespace ts {
}
catch (e) {
if (e instanceof OperationCanceledException) {
// We were canceled while performing the operation. Because our type checker
// We were canceled while performing the operation. Because our type checker
// might be a bad state, we need to throw it away.
//
// Note: we are overly agressive here. We do not actually *have* to throw away
// the "noDiagnosticsTypeChecker". However, for simplicity, i'd like to keep
// the lifetimes of these two TypeCheckers the same. Also, we generally only
// cancel when the user has made a change anyways. And, in that case, we (the
// program instance) will get thrown away anyways. So trying to keep one of
// program instance) will get thrown away anyways. So trying to keep one of
// these type checkers alive doesn't serve much purpose.
noDiagnosticsTypeChecker = undefined;
diagnosticsProducingTypeChecker = undefined;
@ -341,16 +341,16 @@ namespace ts {
});
}
function getDeclarationDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {
function getDeclarationDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {
return runWithCancellationToken(() => {
if (!isDeclarationFile(sourceFile)) {
let resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken);
// Don't actually write any files since we're just getting diagnostics.
var writeFile: WriteFileCallback = () => { };
let writeFile: WriteFileCallback = () => { };
return ts.getDeclarationDiagnostics(getEmitHost(writeFile), resolver, sourceFile);
}
});
}
}
function getOptionsDiagnostics(): Diagnostic[] {
let allDiagnostics: Diagnostic[] = [];
@ -396,7 +396,7 @@ namespace ts {
}
}
else {
var nonTsFile: SourceFile = options.allowNonTsExtensions && findSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd);
let nonTsFile: SourceFile = options.allowNonTsExtensions && findSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd);
if (!nonTsFile) {
if (options.allowNonTsExtensions) {
diagnostic = Diagnostics.File_0_not_found;
@ -496,7 +496,7 @@ namespace ts {
let moduleNameText = (<LiteralExpression>moduleNameExpr).text;
if (moduleNameText) {
let searchPath = basePath;
let searchName: string;
let searchName: string;
while (true) {
searchName = normalizePath(combinePaths(searchPath, moduleNameText));
if (forEach(supportedExtensions, extension => findModuleSourceFile(searchName + extension, moduleNameExpr))) {
@ -513,7 +513,7 @@ namespace ts {
}
else if (node.kind === SyntaxKind.ModuleDeclaration && (<ModuleDeclaration>node).name.kind === SyntaxKind.StringLiteral && (node.flags & NodeFlags.Ambient || isDeclarationFile(file))) {
// TypeScript 1.0 spec (April 2014): 12.1.6
// An AmbientExternalModuleDeclaration declares an external module.
// An AmbientExternalModuleDeclaration declares an external module.
// This type of declaration is permitted only in the global module.
// The StringLiteral must specify a top - level external module name.
// Relative external module names are not permitted
@ -525,7 +525,7 @@ namespace ts {
let moduleName = nameLiteral.text;
if (moduleName) {
// TypeScript 1.0 spec (April 2014): 12.1.6
// An ExternalImportDeclaration in anAmbientExternalModuleDeclaration may reference other external modules
// An ExternalImportDeclaration in anAmbientExternalModuleDeclaration may reference other external modules
// only through top - level external module names. Relative external module names are not permitted.
let searchName = normalizePath(combinePaths(basePath, moduleName));
forEach(supportedExtensions, extension => findModuleSourceFile(searchName + extension, nameLiteral));
@ -664,7 +664,7 @@ namespace ts {
}
}
else if (firstExternalModuleSourceFile && languageVersion < ScriptTarget.ES6 && !options.module) {
// We cannot use createDiagnosticFromNode because nodes do not have parents yet
// We cannot use createDiagnosticFromNode because nodes do not have parents yet
let span = getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator);
diagnostics.add(createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided));
}
@ -691,7 +691,7 @@ namespace ts {
}
if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== directorySeparator) {
// Make sure directory path ends with directory separator so this string can directly
// Make sure directory path ends with directory separator so this string can directly
// used to replace with "" to get the relative path of the source file and the relative path doesn't
// start with / making it rooted path
commonSourceDirectory += directorySeparator;
@ -707,12 +707,12 @@ namespace ts {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_noEmit_cannot_be_specified_with_option_declaration));
}
}
if (options.emitDecoratorMetadata &&
!options.experimentalDecorators) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_experimentalDecorators_must_also_be_specified_when_option_emitDecoratorMetadata_is_specified));
}
if (options.experimentalAsyncFunctions &&
options.target !== ScriptTarget.ES6) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_experimentalAsyncFunctions_cannot_be_specified_when_targeting_ES5_or_lower));

View file

@ -32,13 +32,13 @@ namespace ts {
setScriptTarget(scriptTarget: ScriptTarget): void;
setLanguageVariant(variant: LanguageVariant): void;
setTextPos(textPos: number): void;
// Invokes the provided callback then unconditionally restores the scanner to the state it
// Invokes the provided callback then unconditionally restores the scanner to the state it
// was in immediately prior to invoking the callback. The result of invoking the callback
// is returned from this function.
lookAhead<T>(callback: () => T): T;
// Invokes the provided callback. If the callback returns something falsy, then it restores
// the scanner to the state it was in immediately prior to invoking the callback. If the
// the scanner to the state it was in immediately prior to invoking the callback. If the
// callback returns something truthy, then the scanner state is not rolled back. The result
// of invoking the callback is returned from this function.
tryScan<T>(callback: () => T): T;
@ -275,7 +275,7 @@ namespace ts {
return textToToken[s];
}
/* @internal */
/* @internal */
export function computeLineStarts(text: string): number[] {
let result: number[] = new Array();
let pos = 0;
@ -307,22 +307,22 @@ namespace ts {
return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character);
}
/* @internal */
/* @internal */
export function computePositionOfLineAndCharacter(lineStarts: number[], line: number, character: number): number {
Debug.assert(line >= 0 && line < lineStarts.length);
return lineStarts[line] + character;
}
/* @internal */
/* @internal */
export function getLineStarts(sourceFile: SourceFile): number[] {
return sourceFile.lineMap || (sourceFile.lineMap = computeLineStarts(sourceFile.text));
}
/* @internal */
/* @internal */
export function computeLineAndCharacterOfPosition(lineStarts: number[], position: number) {
let lineNumber = binarySearch(lineStarts, position);
if (lineNumber < 0) {
// If the actual position was not found,
// If the actual position was not found,
// the binary search returns the negative value of the next line start
// e.g. if the line starts at [5, 10, 23, 80] and the position requested was 20
// then the search will return -2
@ -355,125 +355,125 @@ namespace ts {
ch === CharacterCodes.mathematicalSpace ||
ch === CharacterCodes.ideographicSpace ||
ch === CharacterCodes.byteOrderMark;
}
}
export function isLineBreak(ch: number): boolean {
// ES5 7.3:
// The ECMAScript line terminator characters are listed in Table 3.
// Table 3: Line Terminator Characters
// Code Unit Value Name Formal Name
// \u000A Line Feed <LF>
// \u000D Carriage Return <CR>
// \u2028 Line separator <LS>
// \u2029 Paragraph separator <PS>
// Only the characters in Table 3 are treated as line terminators. Other new line or line
// breaking characters are treated as white space but not as line terminators.
export function isLineBreak(ch: number): boolean {
// ES5 7.3:
// The ECMAScript line terminator characters are listed in Table 3.
// Table 3: Line Terminator Characters
// Code Unit Value Name Formal Name
// \u000A Line Feed <LF>
// \u000D Carriage Return <CR>
// \u2028 Line separator <LS>
// \u2029 Paragraph separator <PS>
// Only the characters in Table 3 are treated as line terminators. Other new line or line
// breaking characters are treated as white space but not as line terminators.
return ch === CharacterCodes.lineFeed ||
ch === CharacterCodes.carriageReturn ||
ch === CharacterCodes.lineSeparator ||
ch === CharacterCodes.paragraphSeparator;
}
return ch === CharacterCodes.lineFeed ||
ch === CharacterCodes.carriageReturn ||
ch === CharacterCodes.lineSeparator ||
ch === CharacterCodes.paragraphSeparator;
}
function isDigit(ch: number): boolean {
return ch >= CharacterCodes._0 && ch <= CharacterCodes._9;
}
function isDigit(ch: number): boolean {
return ch >= CharacterCodes._0 && ch <= CharacterCodes._9;
}
/* @internal */
export function isOctalDigit(ch: number): boolean {
return ch >= CharacterCodes._0 && ch <= CharacterCodes._7;
}
/* @internal */
export function isOctalDigit(ch: number): boolean {
return ch >= CharacterCodes._0 && ch <= CharacterCodes._7;
}
export function couldStartTrivia(text: string, pos: number): boolean {
// Keep in sync with skipTrivia
let ch = text.charCodeAt(pos);
switch (ch) {
case CharacterCodes.carriageReturn:
case CharacterCodes.lineFeed:
case CharacterCodes.tab:
case CharacterCodes.verticalTab:
case CharacterCodes.formFeed:
case CharacterCodes.space:
case CharacterCodes.slash:
// starts of normal trivia
case CharacterCodes.lessThan:
case CharacterCodes.equals:
case CharacterCodes.greaterThan:
// Starts of conflict marker trivia
return true;
default:
return ch > CharacterCodes.maxAsciiCharacter;
}
}
export function couldStartTrivia(text: string, pos: number): boolean {
// Keep in sync with skipTrivia
let ch = text.charCodeAt(pos);
switch (ch) {
case CharacterCodes.carriageReturn:
case CharacterCodes.lineFeed:
case CharacterCodes.tab:
case CharacterCodes.verticalTab:
case CharacterCodes.formFeed:
case CharacterCodes.space:
case CharacterCodes.slash:
// starts of normal trivia
case CharacterCodes.lessThan:
case CharacterCodes.equals:
case CharacterCodes.greaterThan:
// Starts of conflict marker trivia
return true;
default:
return ch > CharacterCodes.maxAsciiCharacter;
}
}
/* @internal */
export function skipTrivia(text: string, pos: number, stopAfterLineBreak?: boolean): number {
// Keep in sync with couldStartTrivia
while (true) {
let ch = text.charCodeAt(pos);
switch (ch) {
case CharacterCodes.carriageReturn:
if (text.charCodeAt(pos + 1) === CharacterCodes.lineFeed) {
pos++;
}
case CharacterCodes.lineFeed:
pos++;
if (stopAfterLineBreak) {
return pos;
}
continue;
case CharacterCodes.tab:
case CharacterCodes.verticalTab:
case CharacterCodes.formFeed:
case CharacterCodes.space:
pos++;
continue;
case CharacterCodes.slash:
if (text.charCodeAt(pos + 1) === CharacterCodes.slash) {
pos += 2;
while (pos < text.length) {
if (isLineBreak(text.charCodeAt(pos))) {
break;
}
pos++;
}
continue;
}
if (text.charCodeAt(pos + 1) === CharacterCodes.asterisk) {
pos += 2;
while (pos < text.length) {
if (text.charCodeAt(pos) === CharacterCodes.asterisk && text.charCodeAt(pos + 1) === CharacterCodes.slash) {
pos += 2;
break;
}
pos++;
}
continue;
}
break;
/* @internal */
export function skipTrivia(text: string, pos: number, stopAfterLineBreak?: boolean): number {
// Keep in sync with couldStartTrivia
while (true) {
let ch = text.charCodeAt(pos);
switch (ch) {
case CharacterCodes.carriageReturn:
if (text.charCodeAt(pos + 1) === CharacterCodes.lineFeed) {
pos++;
}
case CharacterCodes.lineFeed:
pos++;
if (stopAfterLineBreak) {
return pos;
}
continue;
case CharacterCodes.tab:
case CharacterCodes.verticalTab:
case CharacterCodes.formFeed:
case CharacterCodes.space:
pos++;
continue;
case CharacterCodes.slash:
if (text.charCodeAt(pos + 1) === CharacterCodes.slash) {
pos += 2;
while (pos < text.length) {
if (isLineBreak(text.charCodeAt(pos))) {
break;
}
pos++;
}
continue;
}
if (text.charCodeAt(pos + 1) === CharacterCodes.asterisk) {
pos += 2;
while (pos < text.length) {
if (text.charCodeAt(pos) === CharacterCodes.asterisk && text.charCodeAt(pos + 1) === CharacterCodes.slash) {
pos += 2;
break;
}
pos++;
}
continue;
}
break;
case CharacterCodes.lessThan:
case CharacterCodes.equals:
case CharacterCodes.greaterThan:
if (isConflictMarkerTrivia(text, pos)) {
pos = scanConflictMarkerTrivia(text, pos);
continue;
}
break;
case CharacterCodes.lessThan:
case CharacterCodes.equals:
case CharacterCodes.greaterThan:
if (isConflictMarkerTrivia(text, pos)) {
pos = scanConflictMarkerTrivia(text, pos);
continue;
}
break;
default:
if (ch > CharacterCodes.maxAsciiCharacter && (isWhiteSpace(ch) || isLineBreak(ch))) {
pos++;
continue;
}
break;
}
return pos;
}
}
default:
if (ch > CharacterCodes.maxAsciiCharacter && (isWhiteSpace(ch) || isLineBreak(ch))) {
pos++;
continue;
}
break;
}
return pos;
}
}
// All conflict markers consist of the same character repeated seven times. If it is
// a <<<<<<< or >>>>>>> marker then it is also followd by a space.
// All conflict markers consist of the same character repeated seven times. If it is
// a <<<<<<< or >>>>>>> marker then it is also followd by a space.
let mergeConflictMarkerLength = "<<<<<<<".length;
function isConflictMarkerTrivia(text: string, pos: number) {
@ -528,12 +528,12 @@ namespace ts {
return pos;
}
// Extract comments from the given source text starting at the given position. If trailing is
// false, whitespace is skipped until the first line break and comments between that location
// and the next token are returned.If trailing is true, comments occurring between the given
// position and the next line break are returned.The return value is an array containing a
// TextRange for each comment. Single-line comment ranges include the beginning '//' characters
// but not the ending line break. Multi - line comment ranges include the beginning '/* and
// Extract comments from the given source text starting at the given position. If trailing is
// false, whitespace is skipped until the first line break and comments between that location
// and the next token are returned.If trailing is true, comments occurring between the given
// position and the next line break are returned.The return value is an array containing a
// TextRange for each comment. Single-line comment ranges include the beginning '//' characters
// but not the ending line break. Multi - line comment ranges include the beginning '/* and
// ending '*/' characters.The return value is undefined if no comments were found.
function getCommentRanges(text: string, pos: number, trailing: boolean): CommentRange[] {
let result: CommentRange[];
@ -629,9 +629,9 @@ namespace ts {
ch >= CharacterCodes._0 && ch <= CharacterCodes._9 || ch === CharacterCodes.$ || ch === CharacterCodes._ ||
ch > CharacterCodes.maxAsciiCharacter && isUnicodeIdentifierPart(ch, languageVersion);
}
/* @internal */
// Creates a scanner over a (possibly unspecified) range of a piece of text.
/* @internal */
// Creates a scanner over a (possibly unspecified) range of a piece of text.
export function createScanner(languageVersion: ScriptTarget,
skipTrivia: boolean,
languageVariant = LanguageVariant.Standard,
@ -640,16 +640,16 @@ namespace ts {
start?: number,
length?: number): Scanner {
// Current position (end position of text of current token)
let pos: number;
let pos: number;
// end of text
let end: number;
let end: number;
// Start position of whitespace before current token
let startPos: number;
let startPos: number;
// Start position of text of current token
let tokenPos: number;
let tokenPos: number;
let token: SyntaxKind;
let tokenValue: string;
@ -735,7 +735,7 @@ namespace ts {
}
return +(text.substring(start, pos));
}
/**
* Scans the given number of hexadecimal digits in the text,
* returning -1 if the given number is unavailable.
@ -743,7 +743,7 @@ namespace ts {
function scanExactNumberOfHexDigits(count: number): number {
return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false);
}
/**
* Scans as many hexadecimal digits as are available in the text,
* returning -1 if the given number of digits was unavailable.
@ -821,7 +821,7 @@ namespace ts {
pos++;
let start = pos;
let contents = ""
let contents = "";
let resultingToken: SyntaxKind;
while (true) {
@ -916,13 +916,13 @@ namespace ts {
pos++;
return scanExtendedUnicodeEscape();
}
// '\uDDDD'
return scanHexadecimalEscape(/*numDigits*/ 4)
return scanHexadecimalEscape(/*numDigits*/ 4);
case CharacterCodes.x:
// '\xDD'
return scanHexadecimalEscape(/*numDigits*/ 2)
return scanHexadecimalEscape(/*numDigits*/ 2);
// when encountering a LineContinuation (i.e. a backslash and a line terminator sequence),
// the line terminator is interpreted to be "the empty code unit sequence".
@ -934,31 +934,31 @@ namespace ts {
case CharacterCodes.lineFeed:
case CharacterCodes.lineSeparator:
case CharacterCodes.paragraphSeparator:
return ""
return "";
default:
return String.fromCharCode(ch);
}
}
function scanHexadecimalEscape(numDigits: number): string {
let escapedValue = scanExactNumberOfHexDigits(numDigits);
if (escapedValue >= 0) {
return String.fromCharCode(escapedValue);
}
else {
error(Diagnostics.Hexadecimal_digit_expected);
return ""
return "";
}
}
function scanExtendedUnicodeEscape(): string {
let escapedValue = scanMinimumNumberOfHexDigits(1);
let isInvalidExtendedEscape = false;
// Validate the value of the digit
if (escapedValue < 0) {
error(Diagnostics.Hexadecimal_digit_expected)
error(Diagnostics.Hexadecimal_digit_expected);
isInvalidExtendedEscape = true;
}
else if (escapedValue > 0x10FFFF) {
@ -985,18 +985,18 @@ namespace ts {
return utf16EncodeAsString(escapedValue);
}
// Derived from the 10.1.1 UTF16Encoding of the ES6 Spec.
function utf16EncodeAsString(codePoint: number): string {
Debug.assert(0x0 <= codePoint && codePoint <= 0x10FFFF);
if (codePoint <= 65535) {
return String.fromCharCode(codePoint);
}
let codeUnit1 = Math.floor((codePoint - 65536) / 1024) + 0xD800;
let codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00;
return String.fromCharCode(codeUnit1, codeUnit2);
}
@ -1058,7 +1058,7 @@ namespace ts {
let value = 0;
// For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b.
// Similarly valid octalIntegerLiteral must have at least one octal digit following o or O.
let numberOfDigits = 0;
let numberOfDigits = 0;
while (true) {
let ch = text.charCodeAt(pos);
let valueOfCh = ch - CharacterCodes._0;
@ -1132,7 +1132,7 @@ namespace ts {
tokenValue = scanString();
return token = SyntaxKind.StringLiteral;
case CharacterCodes.backtick:
return token = scanTemplateAndSetTokenValue()
return token = scanTemplateAndSetTokenValue();
case CharacterCodes.percent:
if (text.charCodeAt(pos + 1) === CharacterCodes.equals) {
return pos += 2, token = SyntaxKind.PercentEqualsToken;
@ -1444,14 +1444,14 @@ namespace ts {
// regex. Report error and return what we have so far.
if (p >= end) {
tokenIsUnterminated = true;
error(Diagnostics.Unterminated_regular_expression_literal)
error(Diagnostics.Unterminated_regular_expression_literal);
break;
}
let ch = text.charCodeAt(p);
if (isLineBreak(ch)) {
tokenIsUnterminated = true;
error(Diagnostics.Unterminated_regular_expression_literal)
error(Diagnostics.Unterminated_regular_expression_literal);
break;
}
@ -1543,7 +1543,7 @@ namespace ts {
let ch = text.charCodeAt(pos);
if (ch === CharacterCodes.minus || ((firstCharPosition === pos) ? isIdentifierStart(ch) : isIdentifierPart(ch))) {
pos++;
}
}
else {
break;
}
@ -1552,7 +1552,7 @@ namespace ts {
}
return token;
}
function speculationHelper<T>(callback: () => T, isLookahead: boolean): T {
let savePos = pos;
let saveStartPos = startPos;

View file

@ -41,16 +41,16 @@ namespace ts {
function getWScriptSystem(): System {
var fso = new ActiveXObject("Scripting.FileSystemObject");
let fso = new ActiveXObject("Scripting.FileSystemObject");
var fileStream = new ActiveXObject("ADODB.Stream");
let fileStream = new ActiveXObject("ADODB.Stream");
fileStream.Type = 2 /*text*/;
var binaryStream = new ActiveXObject("ADODB.Stream");
let binaryStream = new ActiveXObject("ADODB.Stream");
binaryStream.Type = 1 /*binary*/;
var args: string[] = [];
for (var i = 0; i < WScript.Arguments.length; i++) {
let args: string[] = [];
for (let i = 0; i < WScript.Arguments.length; i++) {
args[i] = WScript.Arguments.Item(i);
}
@ -68,7 +68,7 @@ namespace ts {
// Load file and read the first two bytes into a string with no interpretation
fileStream.Charset = "x-ansi";
fileStream.LoadFromFile(fileName);
var bom = fileStream.ReadText(2) || "";
let bom = fileStream.ReadText(2) || "";
// Position must be at 0 before encoding can be changed
fileStream.Position = 0;
// [0xFF,0xFE] and [0xFE,0xFF] mean utf-16 (little or big endian), otherwise default to utf-8
@ -114,28 +114,28 @@ namespace ts {
}
function getNames(collection: any): string[]{
var result: string[] = [];
for (var e = new Enumerator(collection); !e.atEnd(); e.moveNext()) {
let result: string[] = [];
for (let e = new Enumerator(collection); !e.atEnd(); e.moveNext()) {
result.push(e.item().Name);
}
return result.sort();
}
function readDirectory(path: string, extension?: string, exclude?: string[]): string[] {
var result: string[] = [];
let result: string[] = [];
exclude = map(exclude, s => getCanonicalPath(combinePaths(path, s)));
visitDirectory(path);
return result;
function visitDirectory(path: string) {
var folder = fso.GetFolder(path || ".");
var files = getNames(folder.files);
let folder = fso.GetFolder(path || ".");
let files = getNames(folder.files);
for (let current of files) {
let name = combinePaths(path, current);
if ((!extension || fileExtensionIs(name, extension)) && !contains(exclude, getCanonicalPath(name))) {
result.push(name);
}
}
var subfolders = getNames(folder.subfolders);
let subfolders = getNames(folder.subfolders);
for (let current of subfolders) {
let name = combinePaths(path, current);
if (!contains(exclude, getCanonicalPath(name))) {
@ -197,14 +197,14 @@ namespace ts {
if (!_fs.existsSync(fileName)) {
return undefined;
}
var buffer = _fs.readFileSync(fileName);
var len = buffer.length;
let buffer = _fs.readFileSync(fileName);
let len = buffer.length;
if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) {
// Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js,
// flip all byte pairs and treat as little endian.
len &= ~1;
for (var i = 0; i < len; i += 2) {
var temp = buffer[i];
for (let i = 0; i < len; i += 2) {
let temp = buffer[i];
buffer[i] = buffer[i + 1];
buffer[i + 1] = temp;
}
@ -236,17 +236,17 @@ namespace ts {
}
function readDirectory(path: string, extension?: string, exclude?: string[]): string[] {
var result: string[] = [];
let result: string[] = [];
exclude = map(exclude, s => getCanonicalPath(combinePaths(path, s)));
visitDirectory(path);
return result;
function visitDirectory(path: string) {
var files = _fs.readdirSync(path || ".").sort();
var directories: string[] = [];
let files = _fs.readdirSync(path || ".").sort();
let directories: string[] = [];
for (let current of files) {
var name = combinePaths(path, current);
let name = combinePaths(path, current);
if (!contains(exclude, getCanonicalPath(name))) {
var stat = _fs.statSync(name);
let stat = _fs.statSync(name);
if (stat.isFile()) {
if (!extension || fileExtensionIs(name, extension)) {
result.push(name);
@ -331,4 +331,4 @@ namespace ts {
return undefined; // Unsupported host
}
})();
}
}

View file

@ -11,15 +11,15 @@ namespace ts {
* and if it is, attempts to set the appropriate language.
*/
function validateLocaleAndSetLanguage(locale: string, errors: Diagnostic[]): boolean {
var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase());
let matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase());
if (!matchResult) {
errors.push(createCompilerDiagnostic(Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, 'en', 'ja-jp'));
return false;
}
var language = matchResult[1];
var territory = matchResult[3];
let language = matchResult[1];
let territory = matchResult[3];
// First try the entire locale, then fall back to just language if that's all we have.
if (!trySetLanguageAndTerritory(language, territory, errors) &&
@ -33,10 +33,10 @@ namespace ts {
}
function trySetLanguageAndTerritory(language: string, territory: string, errors: Diagnostic[]): boolean {
var compilerFilePath = normalizePath(sys.getExecutingFilePath());
var containingDirectoryPath = getDirectoryPath(compilerFilePath);
let compilerFilePath = normalizePath(sys.getExecutingFilePath());
let containingDirectoryPath = getDirectoryPath(compilerFilePath);
var filePath = combinePaths(containingDirectoryPath, language);
let filePath = combinePaths(containingDirectoryPath, language);
if (territory) {
filePath = filePath + "-" + territory;
@ -49,8 +49,9 @@ namespace ts {
}
// TODO: Add codePage support for readFile?
let fileContents = '';
try {
var fileContents = sys.readFile(filePath);
fileContents = sys.readFile(filePath);
}
catch (e) {
errors.push(createCompilerDiagnostic(Diagnostics.Unable_to_open_file_0, filePath));
@ -68,7 +69,7 @@ namespace ts {
}
function countLines(program: Program): number {
var count = 0;
let count = 0;
forEach(program.getSourceFiles(), file => {
count += getLineStarts(file).length;
});
@ -76,27 +77,27 @@ namespace ts {
}
function getDiagnosticText(message: DiagnosticMessage, ...args: any[]): string {
var diagnostic = createCompilerDiagnostic.apply(undefined, arguments);
let diagnostic = createCompilerDiagnostic.apply(undefined, arguments);
return <string>diagnostic.messageText;
}
function reportDiagnostic(diagnostic: Diagnostic) {
var output = "";
let output = "";
if (diagnostic.file) {
var loc = getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start);
let loc = getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start);
output += `${ diagnostic.file.fileName }(${ loc.line + 1 },${ loc.character + 1 }): `;
}
var category = DiagnosticCategory[diagnostic.category].toLowerCase();
let category = DiagnosticCategory[diagnostic.category].toLowerCase();
output += `${ category } TS${ diagnostic.code }: ${ flattenDiagnosticMessageText(diagnostic.messageText, sys.newLine) }${ sys.newLine }`;
sys.write(output);
}
function reportDiagnostics(diagnostics: Diagnostic[]) {
for (var i = 0; i < diagnostics.length; i++) {
for (let i = 0; i < diagnostics.length; i++) {
reportDiagnostic(diagnostics[i]);
}
}
@ -133,15 +134,15 @@ namespace ts {
}
export function executeCommandLine(args: string[]): void {
var commandLine = parseCommandLine(args);
var configFileName: string; // Configuration file name (if any)
var configFileWatcher: FileWatcher; // Configuration file watcher
var cachedProgram: Program; // Program cached from last compilation
var rootFileNames: string[]; // Root fileNames for compilation
var compilerOptions: CompilerOptions; // Compiler options for compilation
var compilerHost: CompilerHost; // Compiler host
var hostGetSourceFile: typeof compilerHost.getSourceFile; // getSourceFile method from default host
var timerHandle: number; // Handle for 0.25s wait timer
let commandLine = parseCommandLine(args);
let configFileName: string; // Configuration file name (if any)
let configFileWatcher: FileWatcher; // Configuration file watcher
let cachedProgram: Program; // Program cached from last compilation
let rootFileNames: string[]; // Root fileNames for compilation
let compilerOptions: CompilerOptions; // Compiler options for compilation
let compilerHost: CompilerHost; // Compiler host
let hostGetSourceFile: typeof compilerHost.getSourceFile; // getSourceFile method from default host
let timerHandle: number; // Handle for 0.25s wait timer
if (commandLine.options.locale) {
if (!isJSONSupported()) {
@ -181,7 +182,7 @@ namespace ts {
}
}
else if (commandLine.fileNames.length === 0 && isJSONSupported()) {
var searchPath = normalizePath(sys.getCurrentDirectory());
let searchPath = normalizePath(sys.getCurrentDirectory());
configFileName = findConfigFile(searchPath);
}
@ -247,14 +248,14 @@ namespace ts {
function getSourceFile(fileName: string, languageVersion: ScriptTarget, onError ?: (message: string) => void) {
// Return existing SourceFile object if one is available
if (cachedProgram) {
var sourceFile = cachedProgram.getSourceFile(fileName);
let sourceFile = cachedProgram.getSourceFile(fileName);
// A modified source file has no watcher and should not be reused
if (sourceFile && sourceFile.fileWatcher) {
return sourceFile;
}
}
// Use default host function
var sourceFile = hostGetSourceFile(fileName, languageVersion, onError);
let sourceFile = hostGetSourceFile(fileName, languageVersion, onError);
if (sourceFile && compilerOptions.watch) {
// Attach a file watcher
sourceFile.fileWatcher = sys.watchFile(sourceFile.fileName, () => sourceFileChanged(sourceFile));
@ -265,7 +266,7 @@ namespace ts {
// Change cached program to the given program
function setCachedProgram(program: Program) {
if (cachedProgram) {
var newSourceFiles = program ? program.getSourceFiles() : undefined;
let newSourceFiles = program ? program.getSourceFiles() : undefined;
forEach(cachedProgram.getSourceFiles(), sourceFile => {
if (!(newSourceFiles && contains(newSourceFiles, sourceFile))) {
if (sourceFile.fileWatcher) {
@ -316,8 +317,8 @@ namespace ts {
checkTime = 0;
emitTime = 0;
var program = createProgram(fileNames, compilerOptions, compilerHost);
var exitStatus = compileProgram();
let program = createProgram(fileNames, compilerOptions, compilerHost);
let exitStatus = compileProgram();
if (compilerOptions.listFiles) {
forEach(program.getSourceFiles(), file => {
@ -326,7 +327,7 @@ namespace ts {
}
if (compilerOptions.diagnostics) {
var memoryUsed = sys.getMemoryUsage ? sys.getMemoryUsage() : -1;
let memoryUsed = sys.getMemoryUsage ? sys.getMemoryUsage() : -1;
reportCountStatistic("Files", program.getSourceFiles().length);
reportCountStatistic("Lines", countLines(program));
reportCountStatistic("Nodes", program.getNodeCount());
@ -354,18 +355,18 @@ namespace ts {
return { program, exitStatus };
function compileProgram(): ExitStatus {
// First get any syntactic errors.
var diagnostics = program.getSyntacticDiagnostics();
// First get any syntactic errors.
let diagnostics = program.getSyntacticDiagnostics();
reportDiagnostics(diagnostics);
// If we didn't have any syntactic errors, then also try getting the global and
// If we didn't have any syntactic errors, then also try getting the global and
// semantic errors.
if (diagnostics.length === 0) {
var diagnostics = program.getGlobalDiagnostics();
let diagnostics = program.getGlobalDiagnostics();
reportDiagnostics(diagnostics);
if (diagnostics.length === 0) {
var diagnostics = program.getSemanticDiagnostics();
let diagnostics = program.getSemanticDiagnostics();
reportDiagnostics(diagnostics);
}
}
@ -378,7 +379,7 @@ namespace ts {
}
// Otherwise, emit and report any errors we ran into.
var emitOutput = program.emit();
let emitOutput = program.emit();
reportDiagnostics(emitOutput.diagnostics);
// If the emitter didn't emit anything, then pass that value along.
@ -401,22 +402,22 @@ namespace ts {
}
function printHelp() {
var output = "";
let output = "";
// We want to align our "syntax" and "examples" commands to a certain margin.
var syntaxLength = getDiagnosticText(Diagnostics.Syntax_Colon_0, "").length;
var examplesLength = getDiagnosticText(Diagnostics.Examples_Colon_0, "").length;
var marginLength = Math.max(syntaxLength, examplesLength);
let syntaxLength = getDiagnosticText(Diagnostics.Syntax_Colon_0, "").length;
let examplesLength = getDiagnosticText(Diagnostics.Examples_Colon_0, "").length;
let marginLength = Math.max(syntaxLength, examplesLength);
// Build up the syntactic skeleton.
var syntax = makePadding(marginLength - syntaxLength);
let syntax = makePadding(marginLength - syntaxLength);
syntax += "tsc [" + getDiagnosticText(Diagnostics.options) + "] [" + getDiagnosticText(Diagnostics.file) + " ...]";
output += getDiagnosticText(Diagnostics.Syntax_Colon_0, syntax);
output += sys.newLine + sys.newLine;
// Build up the list of examples.
var padding = makePadding(marginLength);
let padding = makePadding(marginLength);
output += getDiagnosticText(Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + sys.newLine;
output += padding + "tsc --out file.js file.ts" + sys.newLine;
output += padding + "tsc @args.txt" + sys.newLine;
@ -425,17 +426,17 @@ namespace ts {
output += getDiagnosticText(Diagnostics.Options_Colon) + sys.newLine;
// Sort our options by their names, (e.g. "--noImplicitAny" comes before "--watch")
var optsList = filter(optionDeclarations.slice(), v => !v.experimental);
let optsList = filter(optionDeclarations.slice(), v => !v.experimental);
optsList.sort((a, b) => compareValues<string>(a.name.toLowerCase(), b.name.toLowerCase()));
// We want our descriptions to align at the same column in our output,
// so we keep track of the longest option usage string.
var marginLength = 0;
var usageColumn: string[] = []; // Things like "-d, --declaration" go in here.
var descriptionColumn: string[] = [];
marginLength = 0;
let usageColumn: string[] = []; // Things like "-d, --declaration" go in here.
let descriptionColumn: string[] = [];
for (var i = 0; i < optsList.length; i++) {
var option = optsList[i];
for (let i = 0; i < optsList.length; i++) {
let option = optsList[i];
// If an option lacks a description,
// it is not officially supported.
@ -443,7 +444,7 @@ namespace ts {
continue;
}
var usageText = " ";
let usageText = " ";
if (option.shortName) {
usageText += "-" + option.shortName;
usageText += getParamType(option);
@ -461,15 +462,15 @@ namespace ts {
}
// Special case that can't fit in the loop.
var usageText = " @<" + getDiagnosticText(Diagnostics.file) + ">";
let usageText = " @<" + getDiagnosticText(Diagnostics.file) + ">";
usageColumn.push(usageText);
descriptionColumn.push(getDiagnosticText(Diagnostics.Insert_command_line_options_and_files_from_a_file));
marginLength = Math.max(usageText.length, marginLength);
// Print out each row, aligning all the descriptions on the same column.
for (var i = 0; i < usageColumn.length; i++) {
var usage = usageColumn[i];
var description = descriptionColumn[i];
for (let i = 0; i < usageColumn.length; i++) {
let usage = usageColumn[i];
let description = descriptionColumn[i];
output += usage + makePadding(marginLength - usage.length + 2) + description + sys.newLine;
}

View file

@ -273,7 +273,7 @@ namespace ts {
// Module references
ExternalModuleReference,
//JSX
// JSX
JsxElement,
JsxSelfClosingElement,
JsxOpeningElement,
@ -405,10 +405,10 @@ namespace ts {
// Context flags set directly by the parser.
ParserGeneratedFlags = DisallowIn | Yield | Decorator | ThisNodeHasError | Await,
// Exclude these flags when parsing a Type
TypeExcludesFlags = Yield | Await,
TypeExcludesFlags = Yield | Await,
// Context flags computed by aggregating child flags upwards.
// Used during incremental parsing to determine if this node or any of its children had an
@ -1300,7 +1300,7 @@ namespace ts {
// @kind(SyntaxKind.ModuleBlock)
export interface ModuleBlock extends Node, Statement {
statements: NodeArray<Statement>
statements: NodeArray<Statement>;
}
// @kind(SyntaxKind.ImportEqualsDeclaration)
@ -1450,7 +1450,7 @@ namespace ts {
// @kind(SyntaxKind.JSDocTypeReference)
export interface JSDocTypeReference extends JSDocType {
name: EntityName;
typeArguments: NodeArray<JSDocType>
typeArguments: NodeArray<JSDocType>;
}
// @kind(SyntaxKind.JSDocOptionalType)
@ -1489,8 +1489,8 @@ namespace ts {
// @factoryhidden("decorators", true)
// @factoryhidden("modifiers", true)
export interface JSDocRecordMember extends PropertySignature {
name: Identifier | LiteralExpression,
type?: JSDocType
name: Identifier | LiteralExpression;
type?: JSDocType;
}
// @kind(SyntaxKind.JSDocComment)
@ -1596,7 +1596,7 @@ namespace ts {
export interface CancellationToken {
isCancellationRequested(): boolean;
/** @throws OperationCanceledException if isCancellationRequested is true */
throwIfCancellationRequested(): void;
}
@ -1625,7 +1625,7 @@ namespace ts {
getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
/**
/**
* Gets a type checker that can be used to semantically analyze source fils in the program.
*/
getTypeChecker(): TypeChecker;
@ -1646,15 +1646,15 @@ namespace ts {
export interface SourceMapSpan {
/** Line number in the .js file. */
emittedLine: number;
emittedLine: number;
/** Column number in the .js file. */
emittedColumn: number;
emittedColumn: number;
/** Line number in the .ts file. */
sourceLine: number;
sourceLine: number;
/** Column number in the .ts file. */
sourceColumn: number;
sourceColumn: number;
/** Optional name (index into names array) associated with this span. */
nameIndex?: number;
nameIndex?: number;
/** .ts file (index into sources array) associated with this span */
sourceIndex: number;
}
@ -1808,7 +1808,7 @@ namespace ts {
NotAccessible,
CannotBeNamed
}
export interface TypePredicate {
parameterName: string;
parameterIndex: number;
@ -1828,7 +1828,7 @@ namespace ts {
/* @internal */
export interface SymbolAccessiblityResult extends SymbolVisibilityResult {
errorModuleName?: string // If the symbol is not visible from module, module's name
errorModuleName?: string; // If the symbol is not visible from module, module's name
}
/* @internal */
@ -1939,7 +1939,7 @@ namespace ts {
Export = ExportNamespace | ExportType | ExportValue,
/* @internal */
// The set of things we consider semantically classifiable. Used to speed up the LS during
// The set of things we consider semantically classifiable. Used to speed up the LS during
// classification.
Classifiable = Class | Enum | TypeAlias | Interface | TypeParameter | Module,
}
@ -1959,7 +1959,7 @@ namespace ts {
/* @internal */ constEnumOnlyModule?: boolean; // True if module contains only const enums or other modules with only const enums
}
/* @internal */
/* @internal */
export interface SymbolLinks {
target?: Symbol; // Resolved (non-alias) target of an alias
type?: Type; // Type of value symbol
@ -1974,14 +1974,14 @@ namespace ts {
isNestedRedeclaration?: boolean; // True if symbol is block scoped redeclaration
}
/* @internal */
/* @internal */
export interface TransientSymbol extends Symbol, SymbolLinks { }
export interface SymbolTable {
[index: string]: Symbol;
}
/* @internal */
/* @internal */
export const enum NodeCheckFlags {
TypeChecked = 0x00000001, // Node has been type checked
LexicalThis = 0x00000002, // Lexical 'this' reference
@ -2003,7 +2003,7 @@ namespace ts {
LexicalModuleMergesWithClass= 0x00008000, // Instantiated lexical module declaration is merged with a previous class declaration.
}
/* @internal */
/* @internal */
export interface NodeLinks {
resolvedType?: Type; // Cached type of type node
resolvedAwaitedType?: Type; // Cached awaited type of type node
@ -2050,16 +2050,16 @@ namespace ts {
ContainsObjectLiteral = 0x00200000, // Type is or contains object literal type
ESSymbol = 0x00400000, // Type of symbol primitive introduced in ES6
/* @internal */
/* @internal */
Intrinsic = Any | String | Number | Boolean | ESSymbol | Void | Undefined | Null,
/* @internal */
/* @internal */
Primitive = String | Number | Boolean | ESSymbol | Void | Undefined | Null | StringLiteral | Enum,
StringLike = String | StringLiteral,
NumberLike = Number | Enum,
ObjectType = Class | Interface | Reference | Tuple | Anonymous,
UnionOrIntersection = Union | Intersection,
StructuredType = ObjectType | Union | Intersection,
/* @internal */
/* @internal */
RequiresWidening = ContainsUndefinedOrNull | ContainsObjectLiteral
}
@ -2070,7 +2070,7 @@ namespace ts {
symbol?: Symbol; // Symbol associated with type (if any)
}
/* @internal */
/* @internal */
// Intrinsic types (TypeFlags.Intrinsic)
export interface IntrinsicType extends Type {
intrinsicName: string; // Name of intrinsic type

View file

@ -3,9 +3,9 @@
/* @internal */
namespace ts {
export interface ReferencePathMatchResult {
fileReference?: FileReference
diagnosticMessage?: DiagnosticMessage
isNoDefaultLib?: boolean
fileReference?: FileReference;
diagnosticMessage?: DiagnosticMessage;
isNoDefaultLib?: boolean;
}
export interface SynthesizedNode extends Node {
@ -16,9 +16,11 @@ namespace ts {
export function getDeclarationOfKind(symbol: Symbol, kind: SyntaxKind): Declaration {
let declarations = symbol.declarations;
for (let declaration of declarations) {
if (declaration.kind === kind) {
return declaration;
if (declarations) {
for (let declaration of declarations) {
if (declaration.kind === kind) {
return declaration;
}
}
}
@ -70,7 +72,7 @@ namespace ts {
}
export function releaseStringWriter(writer: StringSymbolWriter) {
writer.clear()
writer.clear();
stringWriters.push(writer);
}
@ -81,7 +83,7 @@ namespace ts {
// Returns true if this node contains a parse error anywhere underneath it.
export function containsParseError(node: Node): boolean {
aggregateChildData(node);
return (node.parserContextFlags & ParserContextFlags.ThisNodeOrAnySubNodesHasError) !== 0
return (node.parserContextFlags & ParserContextFlags.ThisNodeOrAnySubNodesHasError) !== 0;
}
function aggregateChildData(node: Node): void {
@ -92,7 +94,7 @@ namespace ts {
let thisNodeOrAnySubNodesHasError = ((node.parserContextFlags & ParserContextFlags.ThisNodeHasError) !== 0) ||
forEachChild(node, containsParseError);
// If so, mark ourselves accordingly.
// If so, mark ourselves accordingly.
if (thisNodeOrAnySubNodesHasError) {
node.parserContextFlags |= ParserContextFlags.ThisNodeOrAnySubNodesHasError;
}
@ -129,13 +131,13 @@ namespace ts {
// Returns true if this node is missing from the actual source code. 'missing' is different
// from 'undefined/defined'. When a node is undefined (which can happen for optional nodes
// in the tree), it is definitel missing. HOwever, a node may be defined, but still be
// in the tree), it is definitel missing. HOwever, a node may be defined, but still be
// missing. This happens whenever the parser knows it needs to parse something, but can't
// get anything in the source code that it expects at that location. For example:
//
// let a: ;
//
// Here, the Type in the Type-Annotation is not-optional (as there is a colon in the source
// Here, the Type in the Type-Annotation is not-optional (as there is a colon in the source
// code). So the parser will attempt to parse out a type, and will create an actual node.
// However, this node will be 'missing' in the sense that no actual source-code/tokens are
// contained within it.
@ -166,7 +168,7 @@ namespace ts {
return getTokenPosOfNode(node, sourceFile);
}
return skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end);
return skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end);
}
export function getSourceTextOfNodeFromSourceFile(sourceFile: SourceFile, node: Node, includeTrivia = false): string {
@ -211,7 +213,7 @@ namespace ts {
isCatchClauseVariableDeclaration(declaration);
}
// Gets the nearest enclosing block scope container that has the provided node
// Gets the nearest enclosing block scope container that has the provided node
// as a descendant, that is not the provided node.
export function getEnclosingBlockScopeContainer(node: Node): Node {
let current = node.parent;
@ -307,7 +309,7 @@ namespace ts {
}
if (errorNode === undefined) {
// If we don't have a better node, then just set the error on the first token of
// If we don't have a better node, then just set the error on the first token of
// construct.
return getSpanOfTokenAtPosition(sourceFile, node.pos);
}
@ -339,10 +341,10 @@ namespace ts {
return node;
}
// Returns the node flags for this node and all relevant parent nodes. This is done so that
// Returns the node flags for this node and all relevant parent nodes. This is done so that
// nodes like variable declarations and binding elements can returned a view of their flags
// that includes the modifiers from their container. i.e. flags like export/declare aren't
// stored on the variable declaration directly, but on the containing variable statement
// stored on the variable declaration directly, but on the containing variable statement
// (if it has one). Similarly, flags for let/const are store on the variable declaration
// list. By calling this function, all those flags are combined so that the client can treat
// the node as if it actually had those flags.
@ -406,7 +408,7 @@ namespace ts {
}
}
export let fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*<reference\s+path\s*=\s*)('|")(.+?)\2.*?\/>/
export let fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*<reference\s+path\s*=\s*)('|")(.+?)\2.*?\/>/;
export function isTypeNode(node: Node): boolean {
if (SyntaxKind.FirstTypeNode <= node.kind && node.kind <= SyntaxKind.LastTypeNode) {
@ -662,7 +664,7 @@ namespace ts {
node = node.parent;
break;
case SyntaxKind.Decorator:
// Decorators are always applied outside of the body of a class or method.
// Decorators are always applied outside of the body of a class or method.
if (node.parent.kind === SyntaxKind.Parameter && isClassElement(node.parent.parent)) {
// If the decorator's parent is a Parameter, we resolve the this container from
// the grandparent class declaration.
@ -717,7 +719,7 @@ namespace ts {
node = node.parent;
break;
case SyntaxKind.Decorator:
// Decorators are always applied outside of the body of a class or method.
// Decorators are always applied outside of the body of a class or method.
if (node.parent.kind === SyntaxKind.Parameter && isClassElement(node.parent.parent)) {
// If the decorator's parent is a Parameter, we resolve the this container from
// the grandparent class declaration.
@ -746,14 +748,14 @@ namespace ts {
}
}
}
export function getEntityNameFromTypeNode(node: TypeNode): EntityName | Expression {
if (node) {
if (node) {
switch (node.kind) {
case SyntaxKind.TypeReference:
return (<TypeReferenceNode>node).typeName;
case SyntaxKind.ExpressionWithTypeArguments:
return (<ExpressionWithTypeArguments>node).expression
return (<ExpressionWithTypeArguments>node).expression;
case SyntaxKind.Identifier:
case SyntaxKind.QualifiedName:
return (<EntityName><Node>node);
@ -767,7 +769,7 @@ namespace ts {
if (node.kind === SyntaxKind.TaggedTemplateExpression) {
return (<TaggedTemplateExpression>node).tag;
}
// Will either be a CallExpression, NewExpression, or Decorator.
return (<CallExpression | Decorator>node).expression;
}
@ -949,7 +951,7 @@ namespace ts {
}
export function isInstantiatedModule(node: ModuleDeclaration, preserveConstEnums: boolean) {
let moduleState = getModuleInstanceState(node)
let moduleState = getModuleInstanceState(node);
return moduleState === ModuleInstanceState.Instantiated ||
(preserveConstEnums && moduleState === ModuleInstanceState.ConstEnumOnly);
}
@ -1031,7 +1033,7 @@ namespace ts {
export function getCorrespondingJSDocParameterTag(parameter: ParameterDeclaration): JSDocParameterTag {
if (parameter.name && parameter.name.kind === SyntaxKind.Identifier) {
// If it's a parameter, see if the parent has a jsdoc comment with an @param
// If it's a parameter, see if the parent has a jsdoc comment with an @param
// annotation.
let parameterName = (<Identifier>parameter.name).text;
@ -1286,7 +1288,7 @@ namespace ts {
if (isNoDefaultLibRegEx.exec(comment)) {
return {
isNoDefaultLib: true
}
};
}
else {
let matchResult = fullTripleSlashReferencePathRegEx.exec(comment);
@ -1402,7 +1404,7 @@ namespace ts {
}
return node;
}
export function nodeStartsNewLexicalEnvironment(n: Node): boolean {
return isFunctionLike(n) || n.kind === SyntaxKind.ModuleDeclaration || n.kind === SyntaxKind.SourceFile;
}
@ -1489,7 +1491,7 @@ namespace ts {
}
}
}
// This consists of the first 19 unprintable ASCII characters, canonical escapes, lineSeparator,
// paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in
// the language service. These characters should be escaped when printing, and if any characters are added,
@ -1941,7 +1943,7 @@ namespace ts {
return false;
}
}
export function isRightSideOfQualifiedNameOrPropertyAccess(node: Node) {
return (node.parent.kind === SyntaxKind.QualifiedName && (<QualifiedName>node.parent).right === node) ||
(node.parent.kind === SyntaxKind.PropertyAccessExpression && (<PropertyAccessExpression>node.parent).name === node);
@ -1960,7 +1962,7 @@ namespace ts {
}
/**
* Replace each instance of non-ascii characters by one, two, three, or four escape sequences
* Replace each instance of non-ascii characters by one, two, three, or four escape sequences
* representing the UTF-8 encoding of the character, and return the expanded char code list.
*/
function getExpandedCharCodes(input: string): number[] {
@ -2003,7 +2005,7 @@ namespace ts {
* Converts a string to a base-64 encoded ASCII string.
*/
export function convertToBase64(input: string): string {
var result = "";
let result = "";
let charCodes = getExpandedCharCodes(input);
let i = 0;
let length = charCodes.length;
@ -2045,7 +2047,7 @@ namespace ts {
return lineFeed;
}
else if (sys) {
return sys.newLine
return sys.newLine;
}
return carriageReturnLineFeed;
}
@ -2057,11 +2059,11 @@ namespace ts {
}
export function textSpanEnd(span: TextSpan) {
return span.start + span.length
return span.start + span.length;
}
export function textSpanIsEmpty(span: TextSpan) {
return span.length === 0
return span.length === 0;
}
export function textSpanContainsPosition(span: TextSpan, position: number) {
@ -2089,7 +2091,7 @@ namespace ts {
}
export function textSpanIntersectsWithTextSpan(span: TextSpan, other: TextSpan) {
return other.start <= textSpanEnd(span) && textSpanEnd(other) >= span.start
return other.start <= textSpanEnd(span) && textSpanEnd(other) >= span.start;
}
export function textSpanIntersectsWith(span: TextSpan, start: number, length: number) {
@ -2150,10 +2152,10 @@ namespace ts {
export let unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0);
/**
* Called to merge all the changes that occurred across several versions of a script snapshot
* Called to merge all the changes that occurred across several versions of a script snapshot
* into a single change. i.e. if a user keeps making successive edits to a script we will
* have a text change from V1 to V2, V2 to V3, ..., Vn.
*
* have a text change from V1 to V2, V2 to V3, ..., Vn.
*
* This function will then merge those changes into a single change range valid between V1 and
* Vn.
*/
@ -2184,17 +2186,17 @@ namespace ts {
//
// 0 10 20 30 40 50 60 70 80 90 100
// -------------------------------------------------------------------------------------------------------
// | /
// | /----
// T1 | /----
// | /----
// | /----
// | /
// | /----
// T1 | /----
// | /----
// | /----
// -------------------------------------------------------------------------------------------------------
// | \
// | \
// T2 | \
// | \
// | \
// | \
// | \
// T2 | \
// | \
// | \
// -------------------------------------------------------------------------------------------------------
//
// Merging these turns out to not be too difficult. First, determining the new start of the change is trivial
@ -2202,17 +2204,17 @@ namespace ts {
//
// 0 10 20 30 40 50 60 70 80 90 100
// ------------------------------------------------------------*------------------------------------------
// | /
// | /----
// T1 | /----
// | /----
// | /----
// | /
// | /----
// T1 | /----
// | /----
// | /----
// ----------------------------------------$-------------------$------------------------------------------
// . | \
// . | \
// T2 . | \
// . | \
// . | \
// . | \
// . | \
// T2 . | \
// . | \
// . | \
// ----------------------------------------------------------------------*--------------------------------
//
// (Note the dots represent the newly inferrred start.
@ -2223,22 +2225,22 @@ namespace ts {
//
// 0 10 20 30 40 50 60 70 80 90 100
// --------------------------------------------------------------------------------*----------------------
// | /
// | /----
// T1 | /----
// | /----
// | /----
// | /
// | /----
// T1 | /----
// | /----
// | /----
// ------------------------------------------------------------$------------------------------------------
// . | \
// . | \
// T2 . | \
// . | \
// . | \
// . | \
// . | \
// T2 . | \
// . | \
// . | \
// ----------------------------------------------------------------------*--------------------------------
//
// In other words (in this case), we're recognizing that the second edit happened after where the first edit
// ended with a delta of 20 characters (60 - 40). Thus, if we go back in time to where the first edit started
// that's the same as if we started at char 80 instead of 60.
// that's the same as if we started at char 80 instead of 60.
//
// As it so happens, the same logic applies if the second edit precedes the first edit. In that case rahter
// than pusing the first edit forward to match the second, we'll push the second edit forward to match the
@ -2248,7 +2250,7 @@ namespace ts {
// semantics: { { start: 10, length: 70 }, newLength: 60 }
//
// The math then works out as follows.
// If we have { oldStart1, oldEnd1, newEnd1 } and { oldStart2, oldEnd2, newEnd2 } then we can compute the
// If we have { oldStart1, oldEnd1, newEnd1 } and { oldStart2, oldEnd2, newEnd2 } then we can compute the
// final result like so:
//
// {

View file

@ -704,13 +704,61 @@ module FourSlash {
}
}
public verifyCompletionListDoesNotContain(symbol: string) {
/**
* Verify that the completion list does NOT contain the given symbol.
* The symbol is considered matched with the symbol in the list if and only if all given parameters must matched.
* When any parameter is omitted, the parameter is ignored during comparison and assumed that the parameter with
* that property of the symbol in the list.
* @param symbol the name of symbol
* @param expectedText the text associated with the symbol
* @param expectedDocumentation the documentation text associated with the symbol
* @param expectedKind the kind of symbol (see ScriptElementKind)
*/
public verifyCompletionListDoesNotContain(symbol: string, expectedText?: string, expectedDocumentation?: string, expectedKind?: string) {
let that = this;
function filterByTextOrDocumentation(entry: ts.CompletionEntry) {
let details = that.getCompletionEntryDetails(entry.name);
let documentation = ts.displayPartsToString(details.documentation);
let text = ts.displayPartsToString(details.displayParts);
if (expectedText && expectedDocumentation) {
return (documentation === expectedDocumentation && text === expectedText) ? true : false;
}
else if (expectedText && !expectedDocumentation) {
return text === expectedText ? true : false;
}
else if (expectedDocumentation && !expectedText) {
return documentation === expectedDocumentation ? true : false;
}
// Because expectedText and expectedDocumentation are undefined, we assume that
// users don't care to compare them so we will treat that entry as if the entry has matching text and documentation
// and keep it in the list of filtered entry.
return true;
}
this.scenarioActions.push('<ShowCompletionList />');
this.scenarioActions.push('<VerifyCompletionDoesNotContainItem ItemName="' + escapeXmlAttributeValue(symbol) + '" />');
var completions = this.getCompletionListAtCaret();
if (completions && completions.entries.filter(e => e.name === symbol).length !== 0) {
this.raiseError('Completion list did contain ' + symbol);
if (completions) {
let filterCompletions = completions.entries.filter(e => e.name === symbol);
filterCompletions = expectedKind ? filterCompletions.filter(e => e.kind === expectedKind) : filterCompletions;
filterCompletions = filterCompletions.filter(filterByTextOrDocumentation);
if (filterCompletions.length !== 0) {
// After filtered using all present criterion, if there are still symbol left in the list
// then these symbols must meet the criterion for Not supposed to be in the list. So we
// raise an error
let error = "Completion list did contain \'" + symbol + "\'.";
let details = this.getCompletionEntryDetails(filterCompletions[0].name);
if (expectedText) {
error += "Expected text: " + expectedText + " to equal: " + ts.displayPartsToString(details.displayParts) + ".";
}
if (expectedDocumentation) {
error += "Expected documentation: " + expectedDocumentation + " to equal: " + ts.displayPartsToString(details.documentation) + ".";
}
if (expectedKind) {
error += "Expected kind: " + expectedKind + " to equal: " + filterCompletions[0].kind + "."
}
this.raiseError(error);
}
}
}
@ -2167,7 +2215,7 @@ module FourSlash {
var itemsString = items.map((item) => JSON.stringify({ name: item.name, kind: item.kind })).join(",\n");
this.raiseError('Expected "' + JSON.stringify({ name: name, text: text, documentation: documentation, kind: kind }) + '" to be in list [' + itemsString + ']');
this.raiseError('Expected "' + JSON.stringify({ name, text, documentation, kind }) + '" to be in list [' + itemsString + ']');
}
private findFile(indexOrName: any) {

View file

@ -35,9 +35,9 @@ class FourSlashRunner extends RunnerBase {
this.tests = this.enumerateFiles(this.basePath, /\.ts/i, { recursive: false });
}
this.tests.forEach((fn: string) => {
describe(fn, () => {
fn = ts.normalizeSlashes(fn);
this.tests.forEach((fn: string) => {
describe(fn, () => {
fn = ts.normalizeSlashes(fn);
var justName = fn.replace(/^.*[\\\/]/, '');
// Convert to relative path
@ -45,7 +45,7 @@ class FourSlashRunner extends RunnerBase {
if (testIndex >= 0) fn = fn.substr(testIndex);
if (justName && !justName.match(/fourslash\.ts$/i) && !justName.match(/\.d\.ts$/i)) {
it(this.testSuiteName + ' test ' + justName + ' runs correctly',() => {
it(this.testSuiteName + ' test ' + justName + ' runs correctly', () => {
FourSlash.runFourSlashTest(this.basePath, this.testType, fn);
});
}

View file

@ -2254,12 +2254,12 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven
* @param elementId String that specifies the ID value. Case-insensitive.
*/
getElementById(elementId: string): HTMLElement;
getElementsByClassName(classNames: string): NodeList;
getElementsByClassName(classNames: string): NodeListOf<Element>;
/**
* Gets a collection of objects based on the value of the NAME or ID attribute.
* @param elementName Gets a collection of objects based on the value of the NAME or ID attribute.
*/
getElementsByName(elementName: string): NodeList;
getElementsByName(elementName: string): NodeListOf<Element>;
/**
* Retrieves a collection of objects based on the specified element name.
* @param name Specifies the name of an element.
@ -2437,8 +2437,8 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven
getElementsByTagName(tagname: "wbr"): NodeListOf<HTMLElement>;
getElementsByTagName(tagname: "x-ms-webview"): NodeListOf<MSHTMLWebViewElement>;
getElementsByTagName(tagname: "xmp"): NodeListOf<HTMLBlockElement>;
getElementsByTagName(tagname: string): NodeList;
getElementsByTagNameNS(namespaceURI: string, localName: string): NodeList;
getElementsByTagName(tagname: string): NodeListOf<Element>;
getElementsByTagNameNS(namespaceURI: string, localName: string): NodeListOf<Element>;
/**
* Returns an object representing the current selection of the document that is loaded into the object displaying a webpage.
*/
@ -2711,6 +2711,8 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec
scrollTop: number;
scrollWidth: number;
tagName: string;
id: string;
className: string;
getAttribute(name?: string): string;
getAttributeNS(namespaceURI: string, localName: string): string;
getAttributeNode(name: string): Attr;
@ -2890,8 +2892,8 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec
getElementsByTagName(name: "wbr"): NodeListOf<HTMLElement>;
getElementsByTagName(name: "x-ms-webview"): NodeListOf<MSHTMLWebViewElement>;
getElementsByTagName(name: "xmp"): NodeListOf<HTMLBlockElement>;
getElementsByTagName(name: string): NodeList;
getElementsByTagNameNS(namespaceURI: string, localName: string): NodeList;
getElementsByTagName(name: string): NodeListOf<Element>;
getElementsByTagNameNS(namespaceURI: string, localName: string): NodeListOf<Element>;
hasAttribute(name: string): boolean;
hasAttributeNS(namespaceURI: string, localName: string): boolean;
msGetRegionContent(): MSRangeCollection;
@ -3072,7 +3074,7 @@ interface FormData {
declare var FormData: {
prototype: FormData;
new(): FormData;
new (form?: HTMLFormElement): FormData;
}
interface GainNode extends AudioNode {
@ -3809,14 +3811,12 @@ declare var HTMLDocument: {
interface HTMLElement extends Element {
accessKey: string;
children: HTMLCollection;
className: string;
contentEditable: string;
dataset: DOMStringMap;
dir: string;
draggable: boolean;
hidden: boolean;
hideFocus: boolean;
id: string;
innerHTML: string;
innerText: string;
isContentEditable: boolean;
@ -3903,7 +3903,7 @@ interface HTMLElement extends Element {
contains(child: HTMLElement): boolean;
dragDrop(): boolean;
focus(): void;
getElementsByClassName(classNames: string): NodeList;
getElementsByClassName(classNames: string): NodeListOf<Element>;
insertAdjacentElement(position: string, insertedElement: Element): Element;
insertAdjacentHTML(where: string, html: string): void;
insertAdjacentText(where: string, text: string): void;
@ -8715,6 +8715,7 @@ declare var SVGDescElement: {
interface SVGElement extends Element {
id: string;
className: any;
onclick: (ev: MouseEvent) => any;
ondblclick: (ev: MouseEvent) => any;
onfocusin: (ev: FocusEvent) => any;
@ -11984,6 +11985,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window
toolbar: BarProp;
top: Window;
window: Window;
URL: URL;
alert(message?: any): void;
blur(): void;
cancelAnimationFrame(handle: number): void;
@ -12487,7 +12489,7 @@ interface NavigatorStorageUtils {
interface NodeSelector {
querySelector(selectors: string): Element;
querySelectorAll(selectors: string): NodeList;
querySelectorAll(selectors: string): NodeListOf<Element>;
}
interface RandomSource {
@ -12535,7 +12537,7 @@ interface SVGLocatable {
}
interface SVGStylable {
className: SVGAnimatedString;
className: any;
style: CSSStyleDeclaration;
}
@ -12622,7 +12624,7 @@ interface EventListenerObject {
declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject;
interface ErrorEventHandler {
(event: Event | string, source?: string, fileno?: number, columnNumber?: number): void;
(message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void;
}
interface PositionCallback {
(position: Position): void;
@ -12798,6 +12800,7 @@ declare var styleMedia: StyleMedia;
declare var toolbar: BarProp;
declare var top: Window;
declare var window: Window;
declare var URL: URL;
declare function alert(message?: any): void;
declare function blur(): void;
declare function cancelAnimationFrame(handle: number): void;

View file

@ -228,7 +228,7 @@ namespace ts.NavigationBar {
function merge(target: ts.NavigationBarItem, source: ts.NavigationBarItem) {
// First, add any spans in the source to the target.
target.spans.push.apply(target.spans, source.spans);
addRange(target.spans, source.spans);
if (source.childItems) {
if (!target.childItems) {
@ -465,7 +465,7 @@ namespace ts.NavigationBar {
// are not properties will be filtered out later by createChildItem.
let nodes: Node[] = removeDynamicallyNamedProperties(node);
if (constructor) {
nodes.push.apply(nodes, filter(constructor.parameters, p => !isBindingPattern(p.name)));
addRange(nodes, filter(constructor.parameters, p => !isBindingPattern(p.name)));
}
childItems = getItemsWorker(sortNodes(nodes), createChildItem);

View file

@ -345,7 +345,7 @@ namespace ts {
ts.forEach(getJsDocCommentTextRange(declaration.parent, sourceFileOfDeclaration), jsDocCommentTextRange => {
let cleanedParamJsDocComment = getCleanedParamJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration);
if (cleanedParamJsDocComment) {
jsDocCommentParts.push.apply(jsDocCommentParts, cleanedParamJsDocComment);
addRange(jsDocCommentParts, cleanedParamJsDocComment);
}
});
}
@ -365,7 +365,7 @@ namespace ts {
declaration.kind === SyntaxKind.VariableDeclaration ? declaration.parent.parent : declaration, sourceFileOfDeclaration), jsDocCommentTextRange => {
let cleanedJsDocComment = getCleanedJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration);
if (cleanedJsDocComment) {
jsDocCommentParts.push.apply(jsDocCommentParts, cleanedJsDocComment);
addRange(jsDocCommentParts, cleanedJsDocComment);
}
});
}
@ -1428,6 +1428,9 @@ namespace ts {
// class X {}
export const classElement = "class";
// var x = class X {}
export const localClassElement = "local class";
// interface Y {}
export const interfaceElement = "interface";
@ -2799,18 +2802,15 @@ namespace ts {
program.getGlobalDiagnostics(cancellationToken));
}
/// Completion
function getCompletionEntryDisplayNameForSymbol(symbol: Symbol, target: ScriptTarget, performCharacterChecks: boolean): string {
let displayName = symbol.getName();
if (displayName) {
// If this is the default export, get the name of the declaration if it exists
if (displayName === "default") {
let localSymbol = getLocalSymbolForExportDefault(symbol);
if (localSymbol && localSymbol.name) {
displayName = symbol.valueDeclaration.localSymbol.name;
}
}
/**
* Get the name to be display in completion from a given symbol.
*
* @return undefined if the name is of external module otherwise a name with striped of any quote
*/
function getCompletionEntryDisplayNameForSymbol(symbol: Symbol, target: ScriptTarget, performCharacterChecks: boolean, location: Node): string {
let displayName: string = getDeclaredName(program.getTypeChecker(), symbol, location);
if (displayName) {
let firstCharCode = displayName.charCodeAt(0);
// First check of the displayName is not external module; if it is an external module, it is not valid entry
if ((symbol.flags & SymbolFlags.Namespace) && (firstCharCode === CharacterCodes.singleQuote || firstCharCode === CharacterCodes.doubleQuote)) {
@ -2823,37 +2823,38 @@ namespace ts {
return getCompletionEntryDisplayName(displayName, target, performCharacterChecks);
}
function getCompletionEntryDisplayName(displayName: string, target: ScriptTarget, performCharacterChecks: boolean): string {
if (!displayName) {
/**
* Get a displayName from a given for completion list, performing any necessary quotes stripping
* and checking whether the name is valid identifier name.
*/
function getCompletionEntryDisplayName(name: string, target: ScriptTarget, performCharacterChecks: boolean): string {
if (!name) {
return undefined;
}
let firstCharCode = displayName.charCodeAt(0);
if (displayName.length >= 2 &&
firstCharCode === displayName.charCodeAt(displayName.length - 1) &&
(firstCharCode === CharacterCodes.singleQuote || firstCharCode === CharacterCodes.doubleQuote)) {
// If the user entered name for the symbol was quoted, removing the quotes is not enough, as the name could be an
// invalid identifier name. We need to check if whatever was inside the quotes is actually a valid identifier name.
displayName = displayName.substring(1, displayName.length - 1);
}
name = stripQuotes(name);
if (!displayName) {
if (!name) {
return undefined;
}
// If the user entered name for the symbol was quoted, removing the quotes is not enough, as the name could be an
// invalid identifier name. We need to check if whatever was inside the quotes is actually a valid identifier name.
// e.g "b a" is valid quoted name but when we strip off the quotes, it is invalid.
// We, thus, need to check if whatever was inside the quotes is actually a valid identifier name.
if (performCharacterChecks) {
if (!isIdentifierStart(displayName.charCodeAt(0), target)) {
if (!isIdentifierStart(name.charCodeAt(0), target)) {
return undefined;
}
for (let i = 1, n = displayName.length; i < n; i++) {
if (!isIdentifierPart(displayName.charCodeAt(i), target)) {
for (let i = 1, n = name.length; i < n; i++) {
if (!isIdentifierPart(name.charCodeAt(i), target)) {
return undefined;
}
}
}
return unescapeIdentifier(displayName);
return name;
}
function getCompletionData(fileName: string, position: number) {
@ -2892,33 +2893,36 @@ namespace ts {
log("getCompletionData: Get previous token 2: " + (new Date().getTime() - start));
}
// Check if this is a valid completion location
if (contextToken && isCompletionListBlocker(contextToken)) {
log("Returning an empty list because completion was requested in an invalid position.");
return undefined;
}
let options = program.getCompilerOptions();
let jsx = options.jsx !== JsxEmit.None;
let target = options.target;
// Find the node where completion is requested on, in the case of a completion after
// a dot, it is the member access expression other wise, it is a request for all
// visible symbols in the scope, and the node is the current location.
// Find the node where completion is requested on.
// Also determine whether we are trying to complete with members of that node
// or attributes of a JSX tag.
let node = currentToken;
let isRightOfDot = false;
let isRightOfOpenTag = false;
let location = getTouchingPropertyName(sourceFile, position);
if(contextToken) {
let kind = contextToken.kind;
if (kind === SyntaxKind.DotToken && contextToken.parent.kind === SyntaxKind.PropertyAccessExpression) {
node = (<PropertyAccessExpression>contextToken.parent).expression;
isRightOfDot = true;
if (contextToken) {
// Bail out if this is a known invalid completion location
if (isCompletionListBlocker(contextToken)) {
log("Returning an empty list because completion was requested in an invalid position.");
return undefined;
}
else if (kind === SyntaxKind.DotToken && contextToken.parent.kind === SyntaxKind.QualifiedName) {
node = (<QualifiedName>contextToken.parent).left;
isRightOfDot = true;
let { parent, kind } = contextToken;
if (kind === SyntaxKind.DotToken) {
if (parent.kind === SyntaxKind.PropertyAccessExpression) {
node = (<PropertyAccessExpression>contextToken.parent).expression;
isRightOfDot = true;
}
else if (parent.kind === SyntaxKind.QualifiedName) {
node = (<QualifiedName>contextToken.parent).left;
isRightOfDot = true;
}
else {
// There is nothing that precedes the dot, so this likely just a stray character
// or leading into a '...' token. Just bail out instead.
return undefined;
}
}
else if (kind === SyntaxKind.LessThanToken && sourceFile.languageVariant === LanguageVariant.JSX) {
isRightOfOpenTag = true;
@ -3010,68 +3014,21 @@ namespace ts {
}
function tryGetGlobalSymbols(): boolean {
let objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken);
let jsxContainer = tryGetContainingJsxElement(contextToken);
if (objectLikeContainer) {
// We're looking up possible property names from contextual/inferred/declared type.
isMemberCompletion = true;
let objectLikeContainer: ObjectLiteralExpression | BindingPattern;
let importClause: ImportClause;
let jsxContainer: JsxOpeningLikeElement;
let typeForObject: Type;
let existingMembers: Declaration[];
if (objectLikeContainer.kind === SyntaxKind.ObjectLiteralExpression) {
// We are completing on contextual types, but may also include properties
// other than those within the declared type.
isNewIdentifierLocation = true;
typeForObject = typeChecker.getContextualType(<ObjectLiteralExpression>objectLikeContainer);
existingMembers = (<ObjectLiteralExpression>objectLikeContainer).properties;
}
else if (objectLikeContainer.kind === SyntaxKind.ObjectBindingPattern) {
// We are *only* completing on properties from the type being destructured.
isNewIdentifierLocation = false;
typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer);
existingMembers = (<BindingPattern>objectLikeContainer).elements;
}
else {
Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind);
}
if (!typeForObject) {
return false;
}
let typeMembers = typeChecker.getPropertiesOfType(typeForObject);
if (typeMembers && typeMembers.length > 0) {
// Add filtered items to the completion list
symbols = filterObjectMembersList(typeMembers, existingMembers);
}
return true;
if (objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken)) {
return tryGetObjectLikeCompletionSymbols(objectLikeContainer);
}
else if (getAncestor(contextToken, SyntaxKind.ImportClause)) {
// cursor is in import clause
if (importClause = <ImportClause>getAncestor(contextToken, SyntaxKind.ImportClause)) {
// cursor is in an import clause
// try to show exported member for imported module
isMemberCompletion = true;
isNewIdentifierLocation = true;
if (showCompletionsInImportsClause(contextToken)) {
let importDeclaration = <ImportDeclaration>getAncestor(contextToken, SyntaxKind.ImportDeclaration);
Debug.assert(importDeclaration !== undefined);
let exports: Symbol[];
if (importDeclaration.moduleSpecifier) {
let moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(importDeclaration.moduleSpecifier);
if (moduleSpecifierSymbol) {
exports = typeChecker.getExportsOfModule(moduleSpecifierSymbol);
}
}
//let exports = typeInfoResolver.getExportsOfImportDeclaration(importDeclaration);
symbols = exports ? filterModuleExports(exports, importDeclaration) : emptyArray;
}
return true;
return tryGetImportClauseCompletionSymbols(importClause);
}
else if (jsxContainer) {
if (jsxContainer = tryGetContainingJsxElement(contextToken)) {
let attrsType: Type;
if ((jsxContainer.kind === SyntaxKind.JsxSelfClosingElement) || (jsxContainer.kind === SyntaxKind.JsxOpeningElement)) {
// Cursor is inside a JSX self-closing element or opening element
@ -3144,16 +3101,16 @@ namespace ts {
return scope;
}
function isCompletionListBlocker(previousToken: Node): boolean {
function isCompletionListBlocker(contextToken: Node): boolean {
let start = new Date().getTime();
let result = isInStringOrRegularExpressionOrTemplateLiteral(previousToken) ||
isIdentifierDefinitionLocation(previousToken) ||
isRightOfIllegalDot(previousToken);
let result = isInStringOrRegularExpressionOrTemplateLiteral(contextToken) ||
isIdentifierDefinitionLocation(contextToken) ||
isDotOfNumericLiteral(contextToken);
log("getCompletionsAtPosition: isCompletionListBlocker: " + (new Date().getTime() - start));
return result;
}
function showCompletionsInImportsClause(node: Node): boolean {
function shouldShowCompletionsInImportsClause(node: Node): boolean {
if (node) {
// import {|
// import {a,|
@ -3227,12 +3184,12 @@ namespace ts {
return false;
}
function isInStringOrRegularExpressionOrTemplateLiteral(previousToken: Node): boolean {
if (previousToken.kind === SyntaxKind.StringLiteral
|| previousToken.kind === SyntaxKind.RegularExpressionLiteral
|| isTemplateLiteralKind(previousToken.kind)) {
let start = previousToken.getStart();
let end = previousToken.getEnd();
function isInStringOrRegularExpressionOrTemplateLiteral(contextToken: Node): boolean {
if (contextToken.kind === SyntaxKind.StringLiteral
|| contextToken.kind === SyntaxKind.RegularExpressionLiteral
|| isTemplateLiteralKind(contextToken.kind)) {
let start = contextToken.getStart();
let end = contextToken.getEnd();
// To be "in" one of these literals, the position has to be:
// 1. entirely within the token text.
@ -3243,14 +3200,94 @@ namespace ts {
}
if (position === end) {
return !!(<LiteralExpression>previousToken).isUnterminated ||
previousToken.kind === SyntaxKind.RegularExpressionLiteral;
return !!(<LiteralExpression>contextToken).isUnterminated
|| contextToken.kind === SyntaxKind.RegularExpressionLiteral;
}
}
return false;
}
/**
* Aggregates relevant symbols for completion in object literals and object binding patterns.
* Relevant symbols are stored in the captured 'symbols' variable.
*
* @returns true if 'symbols' was successfully populated; false otherwise.
*/
function tryGetObjectLikeCompletionSymbols(objectLikeContainer: ObjectLiteralExpression | BindingPattern): boolean {
// We're looking up possible property names from contextual/inferred/declared type.
isMemberCompletion = true;
let typeForObject: Type;
let existingMembers: Declaration[];
if (objectLikeContainer.kind === SyntaxKind.ObjectLiteralExpression) {
// We are completing on contextual types, but may also include properties
// other than those within the declared type.
isNewIdentifierLocation = true;
typeForObject = typeChecker.getContextualType(<ObjectLiteralExpression>objectLikeContainer);
existingMembers = (<ObjectLiteralExpression>objectLikeContainer).properties;
}
else if (objectLikeContainer.kind === SyntaxKind.ObjectBindingPattern) {
// We are *only* completing on properties from the type being destructured.
isNewIdentifierLocation = false;
typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer);
existingMembers = (<BindingPattern>objectLikeContainer).elements;
}
else {
Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind);
}
if (!typeForObject) {
return false;
}
let typeMembers = typeChecker.getPropertiesOfType(typeForObject);
if (typeMembers && typeMembers.length > 0) {
// Add filtered items to the completion list
symbols = filterObjectMembersList(typeMembers, existingMembers);
}
return true;
}
/**
* Aggregates relevant symbols for completion in import clauses; for instance,
*
* import { $ } from "moduleName";
*
* Relevant symbols are stored in the captured 'symbols' variable.
*
* @returns true if 'symbols' was successfully populated; false otherwise.
*/
function tryGetImportClauseCompletionSymbols(importClause: ImportClause): boolean {
// cursor is in import clause
// try to show exported member for imported module
if (shouldShowCompletionsInImportsClause(contextToken)) {
isMemberCompletion = true;
isNewIdentifierLocation = false;
let importDeclaration = <ImportDeclaration>importClause.parent;
Debug.assert(importDeclaration !== undefined && importDeclaration.kind === SyntaxKind.ImportDeclaration);
let exports: Symbol[];
let moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(importDeclaration.moduleSpecifier);
if (moduleSpecifierSymbol) {
exports = typeChecker.getExportsOfModule(moduleSpecifierSymbol);
}
//let exports = typeInfoResolver.getExportsOfImportDeclaration(importDeclaration);
symbols = exports ? filterModuleExports(exports, importDeclaration) : emptyArray;
}
else {
isMemberCompletion = false;
isNewIdentifierLocation = true;
}
return true;
}
/**
* Returns the immediate owning object literal or binding pattern of a context token,
* on the condition that one exists and that the context implies completion should be given.
@ -3318,101 +3355,98 @@ namespace ts {
return false;
}
function isIdentifierDefinitionLocation(previousToken: Node): boolean {
if (previousToken) {
let containingNodeKind = previousToken.parent.kind;
switch (previousToken.kind) {
case SyntaxKind.CommaToken:
return containingNodeKind === SyntaxKind.VariableDeclaration ||
containingNodeKind === SyntaxKind.VariableDeclarationList ||
containingNodeKind === SyntaxKind.VariableStatement ||
containingNodeKind === SyntaxKind.EnumDeclaration || // enum a { foo, |
isFunction(containingNodeKind) ||
containingNodeKind === SyntaxKind.ClassDeclaration || // class A<T, |
containingNodeKind === SyntaxKind.FunctionDeclaration || // function A<T, |
containingNodeKind === SyntaxKind.InterfaceDeclaration || // interface A<T, |
containingNodeKind === SyntaxKind.ArrayBindingPattern; // var [x, y|
function isIdentifierDefinitionLocation(contextToken: Node): boolean {
let containingNodeKind = contextToken.parent.kind;
switch (contextToken.kind) {
case SyntaxKind.CommaToken:
return containingNodeKind === SyntaxKind.VariableDeclaration ||
containingNodeKind === SyntaxKind.VariableDeclarationList ||
containingNodeKind === SyntaxKind.VariableStatement ||
containingNodeKind === SyntaxKind.EnumDeclaration || // enum a { foo, |
isFunction(containingNodeKind) ||
containingNodeKind === SyntaxKind.ClassDeclaration || // class A<T, |
containingNodeKind === SyntaxKind.FunctionDeclaration || // function A<T, |
containingNodeKind === SyntaxKind.InterfaceDeclaration || // interface A<T, |
containingNodeKind === SyntaxKind.ArrayBindingPattern; // var [x, y|
case SyntaxKind.DotToken:
return containingNodeKind === SyntaxKind.ArrayBindingPattern; // var [.|
case SyntaxKind.DotToken:
return containingNodeKind === SyntaxKind.ArrayBindingPattern; // var [.|
case SyntaxKind.ColonToken:
return containingNodeKind === SyntaxKind.BindingElement; // var {x :html|
case SyntaxKind.ColonToken:
return containingNodeKind === SyntaxKind.BindingElement; // var {x :html|
case SyntaxKind.OpenBracketToken:
return containingNodeKind === SyntaxKind.ArrayBindingPattern; // var [x|
case SyntaxKind.OpenBracketToken:
return containingNodeKind === SyntaxKind.ArrayBindingPattern; // var [x|
case SyntaxKind.OpenParenToken:
return containingNodeKind === SyntaxKind.CatchClause ||
isFunction(containingNodeKind);
case SyntaxKind.OpenParenToken:
return containingNodeKind === SyntaxKind.CatchClause ||
isFunction(containingNodeKind);
case SyntaxKind.OpenBraceToken:
return containingNodeKind === SyntaxKind.EnumDeclaration || // enum a { |
containingNodeKind === SyntaxKind.InterfaceDeclaration || // interface a { |
containingNodeKind === SyntaxKind.TypeLiteral; // let x : { |
case SyntaxKind.OpenBraceToken:
return containingNodeKind === SyntaxKind.EnumDeclaration || // enum a { |
containingNodeKind === SyntaxKind.InterfaceDeclaration || // interface a { |
containingNodeKind === SyntaxKind.TypeLiteral; // let x : { |
case SyntaxKind.SemicolonToken:
return containingNodeKind === SyntaxKind.PropertySignature &&
previousToken.parent && previousToken.parent.parent &&
(previousToken.parent.parent.kind === SyntaxKind.InterfaceDeclaration || // interface a { f; |
previousToken.parent.parent.kind === SyntaxKind.TypeLiteral); // let x : { a; |
case SyntaxKind.SemicolonToken:
return containingNodeKind === SyntaxKind.PropertySignature &&
contextToken.parent && contextToken.parent.parent &&
(contextToken.parent.parent.kind === SyntaxKind.InterfaceDeclaration || // interface a { f; |
contextToken.parent.parent.kind === SyntaxKind.TypeLiteral); // let x : { a; |
case SyntaxKind.LessThanToken:
return containingNodeKind === SyntaxKind.ClassDeclaration || // class A< |
containingNodeKind === SyntaxKind.FunctionDeclaration || // function A< |
containingNodeKind === SyntaxKind.InterfaceDeclaration || // interface A< |
isFunction(containingNodeKind);
case SyntaxKind.LessThanToken:
return containingNodeKind === SyntaxKind.ClassDeclaration || // class A< |
containingNodeKind === SyntaxKind.FunctionDeclaration || // function A< |
containingNodeKind === SyntaxKind.InterfaceDeclaration || // interface A< |
isFunction(containingNodeKind);
case SyntaxKind.StaticKeyword:
return containingNodeKind === SyntaxKind.PropertyDeclaration;
case SyntaxKind.StaticKeyword:
return containingNodeKind === SyntaxKind.PropertyDeclaration;
case SyntaxKind.DotDotDotToken:
return containingNodeKind === SyntaxKind.Parameter ||
containingNodeKind === SyntaxKind.Constructor ||
(previousToken.parent && previousToken.parent.parent &&
previousToken.parent.parent.kind === SyntaxKind.ArrayBindingPattern); // var [...z|
case SyntaxKind.DotDotDotToken:
return containingNodeKind === SyntaxKind.Parameter ||
(contextToken.parent && contextToken.parent.parent &&
contextToken.parent.parent.kind === SyntaxKind.ArrayBindingPattern); // var [...z|
case SyntaxKind.PublicKeyword:
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
return containingNodeKind === SyntaxKind.Parameter;
case SyntaxKind.PublicKeyword:
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
return containingNodeKind === SyntaxKind.Parameter;
case SyntaxKind.ClassKeyword:
case SyntaxKind.EnumKeyword:
case SyntaxKind.InterfaceKeyword:
case SyntaxKind.FunctionKeyword:
case SyntaxKind.VarKeyword:
case SyntaxKind.GetKeyword:
case SyntaxKind.SetKeyword:
case SyntaxKind.ImportKeyword:
case SyntaxKind.LetKeyword:
case SyntaxKind.ConstKeyword:
case SyntaxKind.YieldKeyword:
case SyntaxKind.TypeKeyword: // type htm|
return true;
}
case SyntaxKind.ClassKeyword:
case SyntaxKind.EnumKeyword:
case SyntaxKind.InterfaceKeyword:
case SyntaxKind.FunctionKeyword:
case SyntaxKind.VarKeyword:
case SyntaxKind.GetKeyword:
case SyntaxKind.SetKeyword:
case SyntaxKind.ImportKeyword:
case SyntaxKind.LetKeyword:
case SyntaxKind.ConstKeyword:
case SyntaxKind.YieldKeyword:
case SyntaxKind.TypeKeyword: // type htm|
return true;
}
// Previous token may have been a keyword that was converted to an identifier.
switch (previousToken.getText()) {
case "class":
case "interface":
case "enum":
case "function":
case "var":
case "static":
case "let":
case "const":
case "yield":
return true;
}
// Previous token may have been a keyword that was converted to an identifier.
switch (contextToken.getText()) {
case "class":
case "interface":
case "enum":
case "function":
case "var":
case "static":
case "let":
case "const":
case "yield":
return true;
}
return false;
}
function isRightOfIllegalDot(previousToken: Node): boolean {
if (previousToken && previousToken.kind === SyntaxKind.NumericLiteral) {
let text = previousToken.getFullText();
function isDotOfNumericLiteral(contextToken: Node): boolean {
if (contextToken.kind === SyntaxKind.NumericLiteral) {
let text = contextToken.getFullText();
return text.charAt(text.length - 1) === ".";
}
@ -3430,6 +3464,11 @@ namespace ts {
importDeclaration.importClause.namedBindings.kind === SyntaxKind.NamedImports) {
forEach((<NamedImports>importDeclaration.importClause.namedBindings).elements, el => {
// If this is the current item we are editing right now, do not filter it out
if (el.getStart() <= position && position <= el.getEnd()) {
return;
}
let name = el.propertyName || el.name;
exisingImports[name.text] = true;
});
@ -3484,23 +3523,29 @@ namespace ts {
return filteredMembers;
}
function filterJsxAttributes(attributes: NodeArray<JsxAttribute | JsxSpreadAttribute>, symbols: Symbol[]): Symbol[] {
let seenNames: Map<boolean> = {};
for (let attr of attributes) {
// If this is the current item we are editing right now, do not filter it out
if (attr.getStart() <= position && position <= attr.getEnd()) {
continue;
}
if (attr.kind === SyntaxKind.JsxAttribute) {
seenNames[(<JsxAttribute>attr).name.text] = true;
}
}
let result: Symbol[] = [];
for (let sym of symbols) {
if (!seenNames[sym.name]) {
result.push(sym);
}
}
return result;
}
}
function filterJsxAttributes(attributes: NodeArray<JsxAttribute|JsxSpreadAttribute>, symbols: Symbol[]): Symbol[] {
let seenNames: Map<boolean> = {};
for(let attr of attributes) {
if(attr.kind === SyntaxKind.JsxAttribute) {
seenNames[(<JsxAttribute>attr).name.text] = true;
}
}
let result: Symbol[] = [];
for(let sym of symbols) {
if(!seenNames[sym.name]) {
result.push(sym);
}
}
return result;
}
function getCompletionsAtPosition(fileName: string, position: number): CompletionInfo {
synchronizeHostData();
@ -3563,7 +3608,7 @@ namespace ts {
// Try to get a valid display name for this symbol, if we could not find one, then ignore it.
// We would like to only show things that can be added after a dot, so for instance numeric properties can
// not be accessed with a dot (a.1 <- invalid)
let displayName = getCompletionEntryDisplayNameForSymbol(symbol, program.getCompilerOptions().target, /*performCharacterChecks:*/ true);
let displayName = getCompletionEntryDisplayNameForSymbol(symbol, program.getCompilerOptions().target, /*performCharacterChecks:*/ true, location);
if (!displayName) {
return undefined;
}
@ -3620,7 +3665,7 @@ namespace ts {
// We don't need to perform character checks here because we're only comparing the
// name against 'entryName' (which is known to be good), not building a new
// completion entry.
let symbol = forEach(symbols, s => getCompletionEntryDisplayNameForSymbol(s, target, /*performCharacterChecks:*/ false) === entryName ? s : undefined);
let symbol = forEach(symbols, s => getCompletionEntryDisplayNameForSymbol(s, target, /*performCharacterChecks:*/ false, location) === entryName ? s : undefined);
if (symbol) {
let { displayParts, documentation, symbolKind } = getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, getValidSourceFile(fileName), location, location, SemanticMeaning.All);
@ -3653,7 +3698,8 @@ namespace ts {
function getSymbolKind(symbol: Symbol, location: Node): string {
let flags = symbol.getFlags();
if (flags & SymbolFlags.Class) return ScriptElementKind.classElement;
if (flags & SymbolFlags.Class) return getDeclarationOfKind(symbol, SyntaxKind.ClassExpression) ?
ScriptElementKind.localClassElement : ScriptElementKind.classElement;
if (flags & SymbolFlags.Enum) return ScriptElementKind.enumElement;
if (flags & SymbolFlags.TypeAlias) return ScriptElementKind.typeElement;
if (flags & SymbolFlags.Interface) return ScriptElementKind.interfaceElement;
@ -3821,7 +3867,7 @@ namespace ts {
displayParts.push(spacePart());
}
if (!(type.flags & TypeFlags.Anonymous)) {
displayParts.push.apply(displayParts, symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, SymbolFormatFlags.WriteTypeParametersOrArguments));
addRange(displayParts, symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, SymbolFormatFlags.WriteTypeParametersOrArguments));
}
addSignatureDisplayParts(signature, allSignatures, TypeFormatFlags.WriteArrowStyleSignature);
break;
@ -3862,7 +3908,16 @@ namespace ts {
}
}
if (symbolFlags & SymbolFlags.Class && !hasAddedSymbolInfo) {
displayParts.push(keywordPart(SyntaxKind.ClassKeyword));
if (getDeclarationOfKind(symbol, SyntaxKind.ClassExpression)) {
// Special case for class expressions because we would like to indicate that
// the class name is local to the class body (similar to function expression)
// (local class) class <className>
pushTypePart(ScriptElementKind.localClassElement);
}
else {
// Class declaration has name which is not local.
displayParts.push(keywordPart(SyntaxKind.ClassKeyword));
}
displayParts.push(spacePart());
addFullSymbolName(symbol);
writeTypeParametersOfSymbol(symbol, sourceFile);
@ -3882,7 +3937,7 @@ namespace ts {
displayParts.push(spacePart());
displayParts.push(operatorPart(SyntaxKind.EqualsToken));
displayParts.push(spacePart());
displayParts.push.apply(displayParts, typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration));
addRange(displayParts, typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration));
}
if (symbolFlags & SymbolFlags.Enum) {
addNewLineIfDisplayPartsExist();
@ -3928,7 +3983,7 @@ namespace ts {
else if (signatureDeclaration.kind !== SyntaxKind.CallSignature && signatureDeclaration.name) {
addFullSymbolName(signatureDeclaration.symbol);
}
displayParts.push.apply(displayParts, signatureToDisplayParts(typeChecker, signature, sourceFile, TypeFormatFlags.WriteTypeArgumentsOfSignature));
addRange(displayParts, signatureToDisplayParts(typeChecker, signature, sourceFile, TypeFormatFlags.WriteTypeArgumentsOfSignature));
}
}
if (symbolFlags & SymbolFlags.EnumMember) {
@ -3989,10 +4044,10 @@ namespace ts {
let typeParameterParts = mapToDisplayParts(writer => {
typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplay(<TypeParameter>type, writer, enclosingDeclaration);
});
displayParts.push.apply(displayParts, typeParameterParts);
addRange(displayParts, typeParameterParts);
}
else {
displayParts.push.apply(displayParts, typeToDisplayParts(typeChecker, type, enclosingDeclaration));
addRange(displayParts, typeToDisplayParts(typeChecker, type, enclosingDeclaration));
}
}
else if (symbolFlags & SymbolFlags.Function ||
@ -4026,7 +4081,7 @@ namespace ts {
function addFullSymbolName(symbol: Symbol, enclosingDeclaration?: Node) {
let fullSymbolDisplayParts = symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration || sourceFile, /*meaning*/ undefined,
SymbolFormatFlags.WriteTypeParametersOrArguments | SymbolFormatFlags.UseOnlyExternalAliasing);
displayParts.push.apply(displayParts, fullSymbolDisplayParts);
addRange(displayParts, fullSymbolDisplayParts);
}
function addPrefixForAnyFunctionOrVar(symbol: Symbol, symbolKind: string) {
@ -4056,7 +4111,7 @@ namespace ts {
}
function addSignatureDisplayParts(signature: Signature, allSignatures: Signature[], flags?: TypeFormatFlags) {
displayParts.push.apply(displayParts, signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | TypeFormatFlags.WriteTypeArgumentsOfSignature));
addRange(displayParts, signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | TypeFormatFlags.WriteTypeArgumentsOfSignature));
if (allSignatures.length > 1) {
displayParts.push(spacePart());
displayParts.push(punctuationPart(SyntaxKind.OpenParenToken));
@ -4073,7 +4128,7 @@ namespace ts {
let typeParameterParts = mapToDisplayParts(writer => {
typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration);
});
displayParts.push.apply(displayParts, typeParameterParts);
addRange(displayParts, typeParameterParts);
}
}
@ -5068,7 +5123,7 @@ namespace ts {
// Get the text to search for.
// Note: if this is an external module symbol, the name doesn't include quotes.
let declaredName = getDeclaredName(typeChecker, symbol, node);
let declaredName = stripQuotes(getDeclaredName(typeChecker, symbol, node));
// Try to get the smallest valid scope that we can limit our search to;
// otherwise we'll need to search globally (i.e. include each file).
@ -5145,10 +5200,10 @@ namespace ts {
* a reference to a symbol can occur anywhere.
*/
function getSymbolScope(symbol: Symbol): Node {
// If this is the symbol of a function expression, then named references
// are limited to its own scope.
// If this is the symbol of a named function expression or named class expression,
// then named references are limited to its own scope.
let valueDeclaration = symbol.valueDeclaration;
if (valueDeclaration && valueDeclaration.kind === SyntaxKind.FunctionExpression) {
if (valueDeclaration && (valueDeclaration.kind === SyntaxKind.FunctionExpression || valueDeclaration.kind === SyntaxKind.ClassExpression)) {
return valueDeclaration;
}
@ -5587,7 +5642,7 @@ namespace ts {
// type to the search set
if (isNameOfPropertyAssignment(location)) {
forEach(getPropertySymbolsFromContextualType(location), contextualSymbol => {
result.push.apply(result, typeChecker.getRootSymbols(contextualSymbol));
addRange(result, typeChecker.getRootSymbols(contextualSymbol));
});
/* Because in short-hand property assignment, location has two meaning : property name and as value of the property
@ -6819,7 +6874,7 @@ namespace ts {
}
}
let displayName = getDeclaredName(typeChecker, symbol, node);
let displayName = stripQuotes(getDeclaredName(typeChecker, symbol, node));
let kind = getSymbolKind(symbol, node);
if (kind) {
return {

View file

@ -550,7 +550,7 @@ namespace ts.SignatureHelp {
let suffixDisplayParts: SymbolDisplayPart[] = [];
if (callTargetDisplayParts) {
prefixDisplayParts.push.apply(prefixDisplayParts, callTargetDisplayParts);
addRange(prefixDisplayParts, callTargetDisplayParts);
}
if (isTypeParameterList) {
@ -560,12 +560,12 @@ namespace ts.SignatureHelp {
suffixDisplayParts.push(punctuationPart(SyntaxKind.GreaterThanToken));
let parameterParts = mapToDisplayParts(writer =>
typeChecker.getSymbolDisplayBuilder().buildDisplayForParametersAndDelimiters(candidateSignature.parameters, writer, invocation));
suffixDisplayParts.push.apply(suffixDisplayParts, parameterParts);
addRange(suffixDisplayParts, parameterParts);
}
else {
let typeParameterParts = mapToDisplayParts(writer =>
typeChecker.getSymbolDisplayBuilder().buildDisplayForTypeParametersAndDelimiters(candidateSignature.typeParameters, writer, invocation));
prefixDisplayParts.push.apply(prefixDisplayParts, typeParameterParts);
addRange(prefixDisplayParts, typeParameterParts);
prefixDisplayParts.push(punctuationPart(SyntaxKind.OpenParenToken));
let parameters = candidateSignature.parameters;
@ -575,7 +575,7 @@ namespace ts.SignatureHelp {
let returnTypeParts = mapToDisplayParts(writer =>
typeChecker.getSymbolDisplayBuilder().buildReturnTypeDisplay(candidateSignature, writer, invocation));
suffixDisplayParts.push.apply(suffixDisplayParts, returnTypeParts);
addRange(suffixDisplayParts, returnTypeParts);
return {
isVariadic: candidateSignature.hasRestParameter,

View file

@ -667,7 +667,7 @@ namespace ts {
let name = typeChecker.symbolToString(localExportDefaultSymbol || symbol);
return stripQuotes(name);
return name;
}
export function isImportOrExportSpecifierName(location: Node): boolean {
@ -676,9 +676,16 @@ namespace ts {
(<ImportOrExportSpecifier>location.parent).propertyName === location;
}
/**
* Strip off existed single quotes or double quotes from a given string
*
* @return non-quoted string
*/
export function stripQuotes(name: string) {
let length = name.length;
if (length >= 2 && name.charCodeAt(0) === CharacterCodes.doubleQuote && name.charCodeAt(length - 1) === CharacterCodes.doubleQuote) {
if (length >= 2 &&
name.charCodeAt(0) === name.charCodeAt(length - 1) &&
(name.charCodeAt(0) === CharacterCodes.doubleQuote || name.charCodeAt(0) === CharacterCodes.singleQuote)) {
return name.substring(1, length - 1);
};
return name;

View file

@ -28,13 +28,13 @@ function M() {
}
var v = new m<number>();
>v : <number>
>new m<number>() : <number>
>v : C<number>
>new m<number>() : C<number>
>m : typeof C
return v.f<string>();
>v.f<string>() : { t: string; x: number; }
>v.f : <T>() => { t: T; x: number; }
>v : <number>
>v : C<number>
>f : <T>() => { t: T; x: number; }
}

View file

@ -26,6 +26,19 @@ export function fooWithSingleOverload(a: any) {
return a;
}
export function fooWithTypePredicate(a: any): a is number {
return true;
}
export function fooWithTypePredicateAndMulitpleParams(a: any, b: any, c: any): a is number {
return true;
}
export function fooWithTypeTypePredicateAndGeneric<T>(a: any): a is T {
return true;
}
export function fooWithTypeTypePredicateAndRestParam(a: any, ...rest): a is number {
return true;
}
/** This comment should appear for nonExportedFoo*/
function nonExportedFoo() {
}
@ -92,6 +105,26 @@ function fooWithSingleOverload(a) {
return a;
}
exports.fooWithSingleOverload = fooWithSingleOverload;
function fooWithTypePredicate(a) {
return true;
}
exports.fooWithTypePredicate = fooWithTypePredicate;
function fooWithTypePredicateAndMulitpleParams(a, b, c) {
return true;
}
exports.fooWithTypePredicateAndMulitpleParams = fooWithTypePredicateAndMulitpleParams;
function fooWithTypeTypePredicateAndGeneric(a) {
return true;
}
exports.fooWithTypeTypePredicateAndGeneric = fooWithTypeTypePredicateAndGeneric;
function fooWithTypeTypePredicateAndRestParam(a) {
var rest = [];
for (var _i = 1; _i < arguments.length; _i++) {
rest[_i - 1] = arguments[_i];
}
return true;
}
exports.fooWithTypeTypePredicateAndRestParam = fooWithTypeTypePredicateAndRestParam;
/** This comment should appear for nonExportedFoo*/
function nonExportedFoo() {
}
@ -144,6 +177,10 @@ export declare function fooWithRestParameters(a: string, ...rests: string[]): st
export declare function fooWithOverloads(a: string): string;
export declare function fooWithOverloads(a: number): number;
export declare function fooWithSingleOverload(a: string): string;
export declare function fooWithTypePredicate(a: any): a is number;
export declare function fooWithTypePredicateAndMulitpleParams(a: any, b: any, c: any): a is number;
export declare function fooWithTypeTypePredicateAndGeneric<T>(a: any): a is T;
export declare function fooWithTypeTypePredicateAndRestParam(a: any, ...rest: any[]): a is number;
//// [declFileFunctions_1.d.ts]
/** This comment should appear for foo*/
declare function globalfoo(): void;

View file

@ -57,49 +57,83 @@ export function fooWithSingleOverload(a: any) {
>a : Symbol(a, Decl(declFileFunctions_0.ts, 21, 38))
}
export function fooWithTypePredicate(a: any): a is number {
>fooWithTypePredicate : Symbol(fooWithTypePredicate, Decl(declFileFunctions_0.ts, 23, 1))
>a : Symbol(a, Decl(declFileFunctions_0.ts, 25, 37))
>a : Symbol(a, Decl(declFileFunctions_0.ts, 25, 37))
return true;
}
export function fooWithTypePredicateAndMulitpleParams(a: any, b: any, c: any): a is number {
>fooWithTypePredicateAndMulitpleParams : Symbol(fooWithTypePredicateAndMulitpleParams, Decl(declFileFunctions_0.ts, 27, 1))
>a : Symbol(a, Decl(declFileFunctions_0.ts, 28, 54))
>b : Symbol(b, Decl(declFileFunctions_0.ts, 28, 61))
>c : Symbol(c, Decl(declFileFunctions_0.ts, 28, 69))
>a : Symbol(a, Decl(declFileFunctions_0.ts, 28, 54))
return true;
}
export function fooWithTypeTypePredicateAndGeneric<T>(a: any): a is T {
>fooWithTypeTypePredicateAndGeneric : Symbol(fooWithTypeTypePredicateAndGeneric, Decl(declFileFunctions_0.ts, 30, 1))
>T : Symbol(T, Decl(declFileFunctions_0.ts, 31, 51))
>a : Symbol(a, Decl(declFileFunctions_0.ts, 31, 54))
>a : Symbol(a, Decl(declFileFunctions_0.ts, 31, 54))
>T : Symbol(T, Decl(declFileFunctions_0.ts, 31, 51))
return true;
}
export function fooWithTypeTypePredicateAndRestParam(a: any, ...rest): a is number {
>fooWithTypeTypePredicateAndRestParam : Symbol(fooWithTypeTypePredicateAndRestParam, Decl(declFileFunctions_0.ts, 33, 1))
>a : Symbol(a, Decl(declFileFunctions_0.ts, 34, 53))
>rest : Symbol(rest, Decl(declFileFunctions_0.ts, 34, 60))
>a : Symbol(a, Decl(declFileFunctions_0.ts, 34, 53))
return true;
}
/** This comment should appear for nonExportedFoo*/
function nonExportedFoo() {
>nonExportedFoo : Symbol(nonExportedFoo, Decl(declFileFunctions_0.ts, 23, 1))
>nonExportedFoo : Symbol(nonExportedFoo, Decl(declFileFunctions_0.ts, 36, 1))
}
/** This is comment for function signature*/
function nonExportedFooWithParameters(/** this is comment about a*/a: string,
>nonExportedFooWithParameters : Symbol(nonExportedFooWithParameters, Decl(declFileFunctions_0.ts, 27, 1))
>a : Symbol(a, Decl(declFileFunctions_0.ts, 29, 38))
>nonExportedFooWithParameters : Symbol(nonExportedFooWithParameters, Decl(declFileFunctions_0.ts, 40, 1))
>a : Symbol(a, Decl(declFileFunctions_0.ts, 42, 38))
/** this is comment for b*/
b: number) {
>b : Symbol(b, Decl(declFileFunctions_0.ts, 29, 77))
>b : Symbol(b, Decl(declFileFunctions_0.ts, 42, 77))
var d = a;
>d : Symbol(d, Decl(declFileFunctions_0.ts, 32, 7))
>a : Symbol(a, Decl(declFileFunctions_0.ts, 29, 38))
>d : Symbol(d, Decl(declFileFunctions_0.ts, 45, 7))
>a : Symbol(a, Decl(declFileFunctions_0.ts, 42, 38))
}
function nonExportedFooWithRestParameters(a: string, ...rests: string[]) {
>nonExportedFooWithRestParameters : Symbol(nonExportedFooWithRestParameters, Decl(declFileFunctions_0.ts, 33, 1))
>a : Symbol(a, Decl(declFileFunctions_0.ts, 34, 42))
>rests : Symbol(rests, Decl(declFileFunctions_0.ts, 34, 52))
>nonExportedFooWithRestParameters : Symbol(nonExportedFooWithRestParameters, Decl(declFileFunctions_0.ts, 46, 1))
>a : Symbol(a, Decl(declFileFunctions_0.ts, 47, 42))
>rests : Symbol(rests, Decl(declFileFunctions_0.ts, 47, 52))
return a + rests.join("");
>a : Symbol(a, Decl(declFileFunctions_0.ts, 34, 42))
>a : Symbol(a, Decl(declFileFunctions_0.ts, 47, 42))
>rests.join : Symbol(Array.join, Decl(lib.d.ts, 1035, 31))
>rests : Symbol(rests, Decl(declFileFunctions_0.ts, 34, 52))
>rests : Symbol(rests, Decl(declFileFunctions_0.ts, 47, 52))
>join : Symbol(Array.join, Decl(lib.d.ts, 1035, 31))
}
function nonExportedFooWithOverloads(a: string): string;
>nonExportedFooWithOverloads : Symbol(nonExportedFooWithOverloads, Decl(declFileFunctions_0.ts, 36, 1), Decl(declFileFunctions_0.ts, 38, 56), Decl(declFileFunctions_0.ts, 39, 56))
>a : Symbol(a, Decl(declFileFunctions_0.ts, 38, 37))
>nonExportedFooWithOverloads : Symbol(nonExportedFooWithOverloads, Decl(declFileFunctions_0.ts, 49, 1), Decl(declFileFunctions_0.ts, 51, 56), Decl(declFileFunctions_0.ts, 52, 56))
>a : Symbol(a, Decl(declFileFunctions_0.ts, 51, 37))
function nonExportedFooWithOverloads(a: number): number;
>nonExportedFooWithOverloads : Symbol(nonExportedFooWithOverloads, Decl(declFileFunctions_0.ts, 36, 1), Decl(declFileFunctions_0.ts, 38, 56), Decl(declFileFunctions_0.ts, 39, 56))
>a : Symbol(a, Decl(declFileFunctions_0.ts, 39, 37))
>nonExportedFooWithOverloads : Symbol(nonExportedFooWithOverloads, Decl(declFileFunctions_0.ts, 49, 1), Decl(declFileFunctions_0.ts, 51, 56), Decl(declFileFunctions_0.ts, 52, 56))
>a : Symbol(a, Decl(declFileFunctions_0.ts, 52, 37))
function nonExportedFooWithOverloads(a: any): any {
>nonExportedFooWithOverloads : Symbol(nonExportedFooWithOverloads, Decl(declFileFunctions_0.ts, 36, 1), Decl(declFileFunctions_0.ts, 38, 56), Decl(declFileFunctions_0.ts, 39, 56))
>a : Symbol(a, Decl(declFileFunctions_0.ts, 40, 37))
>nonExportedFooWithOverloads : Symbol(nonExportedFooWithOverloads, Decl(declFileFunctions_0.ts, 49, 1), Decl(declFileFunctions_0.ts, 51, 56), Decl(declFileFunctions_0.ts, 52, 56))
>a : Symbol(a, Decl(declFileFunctions_0.ts, 53, 37))
return a;
>a : Symbol(a, Decl(declFileFunctions_0.ts, 40, 37))
>a : Symbol(a, Decl(declFileFunctions_0.ts, 53, 37))
}
=== tests/cases/compiler/declFileFunctions_1.ts ===

View file

@ -60,6 +60,44 @@ export function fooWithSingleOverload(a: any) {
>a : any
}
export function fooWithTypePredicate(a: any): a is number {
>fooWithTypePredicate : (a: any) => a is number
>a : any
>a : any
return true;
>true : boolean
}
export function fooWithTypePredicateAndMulitpleParams(a: any, b: any, c: any): a is number {
>fooWithTypePredicateAndMulitpleParams : (a: any, b: any, c: any) => a is number
>a : any
>b : any
>c : any
>a : any
return true;
>true : boolean
}
export function fooWithTypeTypePredicateAndGeneric<T>(a: any): a is T {
>fooWithTypeTypePredicateAndGeneric : <T>(a: any) => a is T
>T : T
>a : any
>a : any
>T : T
return true;
>true : boolean
}
export function fooWithTypeTypePredicateAndRestParam(a: any, ...rest): a is number {
>fooWithTypeTypePredicateAndRestParam : (a: any, ...rest: any[]) => a is number
>a : any
>rest : any[]
>a : any
return true;
>true : boolean
}
/** This comment should appear for nonExportedFoo*/
function nonExportedFoo() {
>nonExportedFoo : () => void

View file

@ -5,9 +5,9 @@ var maybeArray: number | number[];
if (Array.isArray(maybeArray)) {
>Array.isArray(maybeArray) : boolean
>Array.isArray : (arg: any) => boolean
>Array.isArray : (arg: any) => arg is any[]
>Array : ArrayConstructor
>isArray : (arg: any) => boolean
>isArray : (arg: any) => arg is any[]
>maybeArray : number | number[]
maybeArray.length; // OK

View file

@ -0,0 +1,25 @@
//// [modifierOnClassDeclarationMemberInFunction.ts]
function f() {
class C {
public baz = 1;
static foo() { }
public bar() { }
}
}
//// [modifierOnClassDeclarationMemberInFunction.js]
function f() {
var C = (function () {
function C() {
this.baz = 1;
}
C.foo = function () { };
C.prototype.bar = function () { };
return C;
})();
}
//// [modifierOnClassDeclarationMemberInFunction.d.ts]
declare function f(): void;

View file

@ -0,0 +1,18 @@
=== tests/cases/conformance/classes/classDeclarations/modifierOnClassDeclarationMemberInFunction.ts ===
function f() {
>f : Symbol(f, Decl(modifierOnClassDeclarationMemberInFunction.ts, 0, 0))
class C {
>C : Symbol(C, Decl(modifierOnClassDeclarationMemberInFunction.ts, 1, 14))
public baz = 1;
>baz : Symbol(baz, Decl(modifierOnClassDeclarationMemberInFunction.ts, 2, 13))
static foo() { }
>foo : Symbol(C.foo, Decl(modifierOnClassDeclarationMemberInFunction.ts, 3, 23))
public bar() { }
>bar : Symbol(bar, Decl(modifierOnClassDeclarationMemberInFunction.ts, 4, 24))
}
}

View file

@ -0,0 +1,19 @@
=== tests/cases/conformance/classes/classDeclarations/modifierOnClassDeclarationMemberInFunction.ts ===
function f() {
>f : () => void
class C {
>C : C
public baz = 1;
>baz : number
>1 : number
static foo() { }
>foo : () => void
public bar() { }
>bar : () => void
}
}

View file

@ -0,0 +1,25 @@
//// [modifierOnClassExpressionMemberInFunction.ts]
function g() {
var x = class C {
public prop1 = 1;
private foo() { }
static prop2 = 43;
}
}
//// [modifierOnClassExpressionMemberInFunction.js]
function g() {
var x = (function () {
function C() {
this.prop1 = 1;
}
C.prototype.foo = function () { };
C.prop2 = 43;
return C;
})();
}
//// [modifierOnClassExpressionMemberInFunction.d.ts]
declare function g(): void;

View file

@ -0,0 +1,19 @@
=== tests/cases/conformance/classes/classExpressions/modifierOnClassExpressionMemberInFunction.ts ===
function g() {
>g : Symbol(g, Decl(modifierOnClassExpressionMemberInFunction.ts, 0, 0))
var x = class C {
>x : Symbol(x, Decl(modifierOnClassExpressionMemberInFunction.ts, 2, 7))
>C : Symbol(C, Decl(modifierOnClassExpressionMemberInFunction.ts, 2, 11))
public prop1 = 1;
>prop1 : Symbol(C.prop1, Decl(modifierOnClassExpressionMemberInFunction.ts, 2, 21))
private foo() { }
>foo : Symbol(C.foo, Decl(modifierOnClassExpressionMemberInFunction.ts, 3, 25))
static prop2 = 43;
>prop2 : Symbol(C.prop2, Decl(modifierOnClassExpressionMemberInFunction.ts, 4, 25))
}
}

View file

@ -0,0 +1,22 @@
=== tests/cases/conformance/classes/classExpressions/modifierOnClassExpressionMemberInFunction.ts ===
function g() {
>g : () => void
var x = class C {
>x : typeof C
>class C { public prop1 = 1; private foo() { } static prop2 = 43; } : typeof C
>C : typeof C
public prop1 = 1;
>prop1 : number
>1 : number
private foo() { }
>foo : () => void
static prop2 = 43;
>prop2 : number
>43 : number
}
}

View file

@ -0,0 +1,31 @@
tests/cases/conformance/jsx/file.tsx(9,14): error TS2322: Type 'number' is not assignable to type 'string'.
==== tests/cases/conformance/jsx/react.d.ts (0 errors) ====
declare module JSX {
interface Element { }
interface IntrinsicElements {
}
interface ElementAttributesProperty {
props;
}
}
interface Props {
foo: string;
}
==== tests/cases/conformance/jsx/file.tsx (1 errors) ====
export class MyComponent {
render() {
}
props: { foo: string; }
}
<MyComponent foo="bar" />; // ok
<MyComponent foo={0} />; // should be an error
~~~~~~~
!!! error TS2322: Type 'number' is not assignable to type 'string'.

View file

@ -0,0 +1,42 @@
//// [tests/cases/conformance/jsx/tsxAttributeResolution9.tsx] ////
//// [react.d.ts]
declare module JSX {
interface Element { }
interface IntrinsicElements {
}
interface ElementAttributesProperty {
props;
}
}
interface Props {
foo: string;
}
//// [file.tsx]
export class MyComponent {
render() {
}
props: { foo: string; }
}
<MyComponent foo="bar" />; // ok
<MyComponent foo={0} />; // should be an error
//// [file.jsx]
define(["require", "exports"], function (require, exports) {
var MyComponent = (function () {
function MyComponent() {
}
MyComponent.prototype.render = function () {
};
return MyComponent;
})();
exports.MyComponent = MyComponent;
<MyComponent foo="bar"/>; // ok
<MyComponent foo={0}/>; // should be an error
});

View file

@ -0,0 +1,47 @@
=== tests/cases/conformance/jsx/react.d.ts ===
declare module JSX {
>JSX : Symbol(JSX, Decl(react.d.ts, 0, 0))
interface Element { }
>Element : Symbol(Element, Decl(react.d.ts, 1, 20))
interface IntrinsicElements {
>IntrinsicElements : Symbol(IntrinsicElements, Decl(react.d.ts, 2, 22))
}
interface ElementAttributesProperty {
>ElementAttributesProperty : Symbol(ElementAttributesProperty, Decl(react.d.ts, 4, 2))
props;
>props : Symbol(props, Decl(react.d.ts, 5, 38))
}
}
interface Props {
>Props : Symbol(Props, Decl(react.d.ts, 8, 1))
foo: string;
>foo : Symbol(foo, Decl(react.d.ts, 10, 17))
}
=== tests/cases/conformance/jsx/file.tsx ===
export class MyComponent {
>MyComponent : Symbol(MyComponent, Decl(file.tsx, 0, 0))
render() {
>render : Symbol(render, Decl(file.tsx, 0, 26))
}
props: { foo: string; }
>props : Symbol(props, Decl(file.tsx, 2, 3))
>foo : Symbol(foo, Decl(file.tsx, 4, 10))
}
<MyComponent foo="bar" />; // ok
>MyComponent : Symbol(MyComponent, Decl(file.tsx, 0, 0))
>foo : Symbol(unknown)
<MyComponent foo={0} />; // should be an error
>MyComponent : Symbol(MyComponent, Decl(file.tsx, 0, 0))
>foo : Symbol(unknown)

View file

@ -0,0 +1,49 @@
=== tests/cases/conformance/jsx/react.d.ts ===
declare module JSX {
>JSX : any
interface Element { }
>Element : Element
interface IntrinsicElements {
>IntrinsicElements : IntrinsicElements
}
interface ElementAttributesProperty {
>ElementAttributesProperty : ElementAttributesProperty
props;
>props : any
}
}
interface Props {
>Props : Props
foo: string;
>foo : string
}
=== tests/cases/conformance/jsx/file.tsx ===
export class MyComponent {
>MyComponent : MyComponent
render() {
>render : () => void
}
props: { foo: string; }
>props : { foo: string; }
>foo : string
}
<MyComponent foo="bar" />; // ok
><MyComponent foo="bar" /> : JSX.Element
>MyComponent : typeof MyComponent
>foo : any
<MyComponent foo={0} />; // should be an error
><MyComponent foo={0} /> : JSX.Element
>MyComponent : typeof MyComponent
>foo : any

View file

@ -0,0 +1,36 @@
//// [tests/cases/conformance/jsx/tsxElementResolution19.tsx] ////
//// [react.d.ts]
declare module "react" {
}
//// [file1.tsx]
declare module JSX {
interface Element { }
}
export class MyClass { }
//// [file2.tsx]
// Should not elide React import
import * as React from 'react';
import {MyClass} from './file1';
<MyClass />;
//// [file1.js]
define(["require", "exports"], function (require, exports) {
var MyClass = (function () {
function MyClass() {
}
return MyClass;
})();
exports.MyClass = MyClass;
});
//// [file2.js]
define(["require", "exports", 'react', './file1'], function (require, exports, React, file1_1) {
React.createElement(file1_1.MyClass, null);
});

View file

@ -0,0 +1,28 @@
=== tests/cases/conformance/jsx/react.d.ts ===
No type information for this code.declare module "react" {
No type information for this code.
No type information for this code.}
No type information for this code.
No type information for this code.=== tests/cases/conformance/jsx/file1.tsx ===
declare module JSX {
>JSX : Symbol(JSX, Decl(file1.tsx, 0, 0))
interface Element { }
>Element : Symbol(Element, Decl(file1.tsx, 0, 20))
}
export class MyClass { }
>MyClass : Symbol(MyClass, Decl(file1.tsx, 2, 1))
=== tests/cases/conformance/jsx/file2.tsx ===
// Should not elide React import
import * as React from 'react';
>React : Symbol(React, Decl(file2.tsx, 2, 6))
import {MyClass} from './file1';
>MyClass : Symbol(MyClass, Decl(file2.tsx, 3, 8))
<MyClass />;
>MyClass : Symbol(MyClass, Decl(file2.tsx, 3, 8))

View file

@ -0,0 +1,29 @@
=== tests/cases/conformance/jsx/react.d.ts ===
No type information for this code.declare module "react" {
No type information for this code.
No type information for this code.}
No type information for this code.
No type information for this code.=== tests/cases/conformance/jsx/file1.tsx ===
declare module JSX {
>JSX : any
interface Element { }
>Element : Element
}
export class MyClass { }
>MyClass : MyClass
=== tests/cases/conformance/jsx/file2.tsx ===
// Should not elide React import
import * as React from 'react';
>React : typeof React
import {MyClass} from './file1';
>MyClass : typeof MyClass
<MyClass />;
><MyClass /> : any
>MyClass : typeof MyClass

View file

@ -5,6 +5,7 @@ declare module JSX {
[s: string]: any;
}
}
declare var React: any;
var p;
var selfClosed1 = <div />;

View file

@ -12,133 +12,135 @@ declare module JSX {
>s : Symbol(s, Decl(tsxReactEmit1.tsx, 3, 3))
}
}
declare var React: any;
>React : Symbol(React, Decl(tsxReactEmit1.tsx, 6, 11))
var p;
>p : Symbol(p, Decl(tsxReactEmit1.tsx, 7, 3))
>p : Symbol(p, Decl(tsxReactEmit1.tsx, 8, 3))
var selfClosed1 = <div />;
>selfClosed1 : Symbol(selfClosed1, Decl(tsxReactEmit1.tsx, 8, 3))
>selfClosed1 : Symbol(selfClosed1, Decl(tsxReactEmit1.tsx, 9, 3))
>div : Symbol(JSX.IntrinsicElements, Decl(tsxReactEmit1.tsx, 1, 22))
var selfClosed2 = <div x="1" />;
>selfClosed2 : Symbol(selfClosed2, Decl(tsxReactEmit1.tsx, 9, 3))
>selfClosed2 : Symbol(selfClosed2, Decl(tsxReactEmit1.tsx, 10, 3))
>div : Symbol(JSX.IntrinsicElements, Decl(tsxReactEmit1.tsx, 1, 22))
>x : Symbol(unknown)
var selfClosed3 = <div x='1' />;
>selfClosed3 : Symbol(selfClosed3, Decl(tsxReactEmit1.tsx, 10, 3))
>selfClosed3 : Symbol(selfClosed3, Decl(tsxReactEmit1.tsx, 11, 3))
>div : Symbol(JSX.IntrinsicElements, Decl(tsxReactEmit1.tsx, 1, 22))
>x : Symbol(unknown)
var selfClosed4 = <div x="1" y='0' />;
>selfClosed4 : Symbol(selfClosed4, Decl(tsxReactEmit1.tsx, 11, 3))
>selfClosed4 : Symbol(selfClosed4, Decl(tsxReactEmit1.tsx, 12, 3))
>div : Symbol(JSX.IntrinsicElements, Decl(tsxReactEmit1.tsx, 1, 22))
>x : Symbol(unknown)
>y : Symbol(unknown)
var selfClosed5 = <div x={0} y='0' />;
>selfClosed5 : Symbol(selfClosed5, Decl(tsxReactEmit1.tsx, 12, 3))
>selfClosed5 : Symbol(selfClosed5, Decl(tsxReactEmit1.tsx, 13, 3))
>div : Symbol(JSX.IntrinsicElements, Decl(tsxReactEmit1.tsx, 1, 22))
>x : Symbol(unknown)
>y : Symbol(unknown)
var selfClosed6 = <div x={"1"} y='0' />;
>selfClosed6 : Symbol(selfClosed6, Decl(tsxReactEmit1.tsx, 13, 3))
>selfClosed6 : Symbol(selfClosed6, Decl(tsxReactEmit1.tsx, 14, 3))
>div : Symbol(JSX.IntrinsicElements, Decl(tsxReactEmit1.tsx, 1, 22))
>x : Symbol(unknown)
>y : Symbol(unknown)
var selfClosed7 = <div x={p} y='p' b />;
>selfClosed7 : Symbol(selfClosed7, Decl(tsxReactEmit1.tsx, 14, 3))
>selfClosed7 : Symbol(selfClosed7, Decl(tsxReactEmit1.tsx, 15, 3))
>div : Symbol(JSX.IntrinsicElements, Decl(tsxReactEmit1.tsx, 1, 22))
>x : Symbol(unknown)
>y : Symbol(unknown)
>b : Symbol(unknown)
var openClosed1 = <div></div>;
>openClosed1 : Symbol(openClosed1, Decl(tsxReactEmit1.tsx, 16, 3))
>openClosed1 : Symbol(openClosed1, Decl(tsxReactEmit1.tsx, 17, 3))
>div : Symbol(JSX.IntrinsicElements, Decl(tsxReactEmit1.tsx, 1, 22))
var openClosed2 = <div n='m'>foo</div>;
>openClosed2 : Symbol(openClosed2, Decl(tsxReactEmit1.tsx, 17, 3))
>openClosed2 : Symbol(openClosed2, Decl(tsxReactEmit1.tsx, 18, 3))
>div : Symbol(JSX.IntrinsicElements, Decl(tsxReactEmit1.tsx, 1, 22))
>n : Symbol(unknown)
var openClosed3 = <div n='m'>{p}</div>;
>openClosed3 : Symbol(openClosed3, Decl(tsxReactEmit1.tsx, 18, 3))
>openClosed3 : Symbol(openClosed3, Decl(tsxReactEmit1.tsx, 19, 3))
>div : Symbol(JSX.IntrinsicElements, Decl(tsxReactEmit1.tsx, 1, 22))
>n : Symbol(unknown)
var openClosed4 = <div n='m'>{p < p}</div>;
>openClosed4 : Symbol(openClosed4, Decl(tsxReactEmit1.tsx, 19, 3))
>openClosed4 : Symbol(openClosed4, Decl(tsxReactEmit1.tsx, 20, 3))
>div : Symbol(JSX.IntrinsicElements, Decl(tsxReactEmit1.tsx, 1, 22))
>n : Symbol(unknown)
>p : Symbol(p, Decl(tsxReactEmit1.tsx, 7, 3))
>p : Symbol(p, Decl(tsxReactEmit1.tsx, 7, 3))
>p : Symbol(p, Decl(tsxReactEmit1.tsx, 8, 3))
>p : Symbol(p, Decl(tsxReactEmit1.tsx, 8, 3))
var openClosed5 = <div n='m' b>{p > p}</div>;
>openClosed5 : Symbol(openClosed5, Decl(tsxReactEmit1.tsx, 20, 3))
>openClosed5 : Symbol(openClosed5, Decl(tsxReactEmit1.tsx, 21, 3))
>div : Symbol(JSX.IntrinsicElements, Decl(tsxReactEmit1.tsx, 1, 22))
>n : Symbol(unknown)
>b : Symbol(unknown)
>p : Symbol(p, Decl(tsxReactEmit1.tsx, 7, 3))
>p : Symbol(p, Decl(tsxReactEmit1.tsx, 7, 3))
>p : Symbol(p, Decl(tsxReactEmit1.tsx, 8, 3))
>p : Symbol(p, Decl(tsxReactEmit1.tsx, 8, 3))
class SomeClass {
>SomeClass : Symbol(SomeClass, Decl(tsxReactEmit1.tsx, 20, 45))
>SomeClass : Symbol(SomeClass, Decl(tsxReactEmit1.tsx, 21, 45))
f() {
>f : Symbol(f, Decl(tsxReactEmit1.tsx, 22, 17))
>f : Symbol(f, Decl(tsxReactEmit1.tsx, 23, 17))
var rewrites1 = <div>{() => this}</div>;
>rewrites1 : Symbol(rewrites1, Decl(tsxReactEmit1.tsx, 24, 5))
>rewrites1 : Symbol(rewrites1, Decl(tsxReactEmit1.tsx, 25, 5))
>div : Symbol(JSX.IntrinsicElements, Decl(tsxReactEmit1.tsx, 1, 22))
>this : Symbol(SomeClass, Decl(tsxReactEmit1.tsx, 20, 45))
>this : Symbol(SomeClass, Decl(tsxReactEmit1.tsx, 21, 45))
var rewrites2 = <div>{[p, ...p, p]}</div>;
>rewrites2 : Symbol(rewrites2, Decl(tsxReactEmit1.tsx, 25, 5))
>rewrites2 : Symbol(rewrites2, Decl(tsxReactEmit1.tsx, 26, 5))
>div : Symbol(JSX.IntrinsicElements, Decl(tsxReactEmit1.tsx, 1, 22))
>p : Symbol(p, Decl(tsxReactEmit1.tsx, 7, 3))
>p : Symbol(p, Decl(tsxReactEmit1.tsx, 7, 3))
>p : Symbol(p, Decl(tsxReactEmit1.tsx, 7, 3))
>p : Symbol(p, Decl(tsxReactEmit1.tsx, 8, 3))
>p : Symbol(p, Decl(tsxReactEmit1.tsx, 8, 3))
>p : Symbol(p, Decl(tsxReactEmit1.tsx, 8, 3))
var rewrites3 = <div>{{p}}</div>;
>rewrites3 : Symbol(rewrites3, Decl(tsxReactEmit1.tsx, 26, 5))
>rewrites3 : Symbol(rewrites3, Decl(tsxReactEmit1.tsx, 27, 5))
>div : Symbol(JSX.IntrinsicElements, Decl(tsxReactEmit1.tsx, 1, 22))
>p : Symbol(p, Decl(tsxReactEmit1.tsx, 26, 25))
>p : Symbol(p, Decl(tsxReactEmit1.tsx, 27, 25))
var rewrites4 = <div a={() => this}></div>;
>rewrites4 : Symbol(rewrites4, Decl(tsxReactEmit1.tsx, 28, 5))
>rewrites4 : Symbol(rewrites4, Decl(tsxReactEmit1.tsx, 29, 5))
>div : Symbol(JSX.IntrinsicElements, Decl(tsxReactEmit1.tsx, 1, 22))
>a : Symbol(unknown)
>this : Symbol(SomeClass, Decl(tsxReactEmit1.tsx, 20, 45))
>this : Symbol(SomeClass, Decl(tsxReactEmit1.tsx, 21, 45))
var rewrites5 = <div a={[p, ...p, p]}></div>;
>rewrites5 : Symbol(rewrites5, Decl(tsxReactEmit1.tsx, 29, 5))
>rewrites5 : Symbol(rewrites5, Decl(tsxReactEmit1.tsx, 30, 5))
>div : Symbol(JSX.IntrinsicElements, Decl(tsxReactEmit1.tsx, 1, 22))
>a : Symbol(unknown)
>p : Symbol(p, Decl(tsxReactEmit1.tsx, 7, 3))
>p : Symbol(p, Decl(tsxReactEmit1.tsx, 7, 3))
>p : Symbol(p, Decl(tsxReactEmit1.tsx, 7, 3))
>p : Symbol(p, Decl(tsxReactEmit1.tsx, 8, 3))
>p : Symbol(p, Decl(tsxReactEmit1.tsx, 8, 3))
>p : Symbol(p, Decl(tsxReactEmit1.tsx, 8, 3))
var rewrites6 = <div a={{p}}></div>;
>rewrites6 : Symbol(rewrites6, Decl(tsxReactEmit1.tsx, 30, 5))
>rewrites6 : Symbol(rewrites6, Decl(tsxReactEmit1.tsx, 31, 5))
>div : Symbol(JSX.IntrinsicElements, Decl(tsxReactEmit1.tsx, 1, 22))
>a : Symbol(unknown)
>p : Symbol(p, Decl(tsxReactEmit1.tsx, 30, 27))
>p : Symbol(p, Decl(tsxReactEmit1.tsx, 31, 27))
}
}
var whitespace1 = <div> </div>;
>whitespace1 : Symbol(whitespace1, Decl(tsxReactEmit1.tsx, 34, 3))
>whitespace1 : Symbol(whitespace1, Decl(tsxReactEmit1.tsx, 35, 3))
>div : Symbol(JSX.IntrinsicElements, Decl(tsxReactEmit1.tsx, 1, 22))
var whitespace2 = <div> {p} </div>;
>whitespace2 : Symbol(whitespace2, Decl(tsxReactEmit1.tsx, 35, 3))
>whitespace2 : Symbol(whitespace2, Decl(tsxReactEmit1.tsx, 36, 3))
>div : Symbol(JSX.IntrinsicElements, Decl(tsxReactEmit1.tsx, 1, 22))
var whitespace3 = <div>
>whitespace3 : Symbol(whitespace3, Decl(tsxReactEmit1.tsx, 36, 3))
>whitespace3 : Symbol(whitespace3, Decl(tsxReactEmit1.tsx, 37, 3))
>div : Symbol(JSX.IntrinsicElements, Decl(tsxReactEmit1.tsx, 1, 22))
{p}

View file

@ -12,6 +12,8 @@ declare module JSX {
>s : string
}
}
declare var React: any;
>React : any
var p;
>p : any

View file

@ -5,6 +5,7 @@ declare module JSX {
[s: string]: any;
}
}
declare var React: any;
var p1, p2, p3;
var spreads1 = <div {...p1}>{p2}</div>;

View file

@ -12,32 +12,34 @@ declare module JSX {
>s : Symbol(s, Decl(tsxReactEmit2.tsx, 3, 3))
}
}
declare var React: any;
>React : Symbol(React, Decl(tsxReactEmit2.tsx, 6, 11))
var p1, p2, p3;
>p1 : Symbol(p1, Decl(tsxReactEmit2.tsx, 7, 3))
>p2 : Symbol(p2, Decl(tsxReactEmit2.tsx, 7, 7))
>p3 : Symbol(p3, Decl(tsxReactEmit2.tsx, 7, 11))
>p1 : Symbol(p1, Decl(tsxReactEmit2.tsx, 8, 3))
>p2 : Symbol(p2, Decl(tsxReactEmit2.tsx, 8, 7))
>p3 : Symbol(p3, Decl(tsxReactEmit2.tsx, 8, 11))
var spreads1 = <div {...p1}>{p2}</div>;
>spreads1 : Symbol(spreads1, Decl(tsxReactEmit2.tsx, 8, 3))
>spreads1 : Symbol(spreads1, Decl(tsxReactEmit2.tsx, 9, 3))
>div : Symbol(JSX.IntrinsicElements, Decl(tsxReactEmit2.tsx, 1, 22))
var spreads2 = <div {...p1}>{p2}</div>;
>spreads2 : Symbol(spreads2, Decl(tsxReactEmit2.tsx, 9, 3))
>spreads2 : Symbol(spreads2, Decl(tsxReactEmit2.tsx, 10, 3))
>div : Symbol(JSX.IntrinsicElements, Decl(tsxReactEmit2.tsx, 1, 22))
var spreads3 = <div x={p3} {...p1}>{p2}</div>;
>spreads3 : Symbol(spreads3, Decl(tsxReactEmit2.tsx, 10, 3))
>spreads3 : Symbol(spreads3, Decl(tsxReactEmit2.tsx, 11, 3))
>div : Symbol(JSX.IntrinsicElements, Decl(tsxReactEmit2.tsx, 1, 22))
>x : Symbol(unknown)
var spreads4 = <div {...p1} x={p3} >{p2}</div>;
>spreads4 : Symbol(spreads4, Decl(tsxReactEmit2.tsx, 11, 3))
>spreads4 : Symbol(spreads4, Decl(tsxReactEmit2.tsx, 12, 3))
>div : Symbol(JSX.IntrinsicElements, Decl(tsxReactEmit2.tsx, 1, 22))
>x : Symbol(unknown)
var spreads5 = <div x={p2} {...p1} y={p3}>{p2}</div>;
>spreads5 : Symbol(spreads5, Decl(tsxReactEmit2.tsx, 12, 3))
>spreads5 : Symbol(spreads5, Decl(tsxReactEmit2.tsx, 13, 3))
>div : Symbol(JSX.IntrinsicElements, Decl(tsxReactEmit2.tsx, 1, 22))
>x : Symbol(unknown)
>y : Symbol(unknown)

View file

@ -12,6 +12,8 @@ declare module JSX {
>s : string
}
}
declare var React: any;
>React : any
var p1, p2, p3;
>p1 : any

View file

@ -1,6 +1,7 @@
//// [tsxReactEmit3.tsx]
declare module JSX { interface Element { } }
declare var React: any;
declare var Foo, Bar, baz;

View file

@ -4,15 +4,18 @@ declare module JSX { interface Element { } }
>JSX : Symbol(JSX, Decl(tsxReactEmit3.tsx, 0, 0))
>Element : Symbol(Element, Decl(tsxReactEmit3.tsx, 1, 20))
declare var React: any;
>React : Symbol(React, Decl(tsxReactEmit3.tsx, 2, 11))
declare var Foo, Bar, baz;
>Foo : Symbol(Foo, Decl(tsxReactEmit3.tsx, 3, 11))
>Bar : Symbol(Bar, Decl(tsxReactEmit3.tsx, 3, 16))
>baz : Symbol(baz, Decl(tsxReactEmit3.tsx, 3, 21))
>Foo : Symbol(Foo, Decl(tsxReactEmit3.tsx, 4, 11))
>Bar : Symbol(Bar, Decl(tsxReactEmit3.tsx, 4, 16))
>baz : Symbol(baz, Decl(tsxReactEmit3.tsx, 4, 21))
<Foo> <Bar> q </Bar> <Bar/> s <Bar/><Bar/></Foo>;
>Foo : Symbol(Foo, Decl(tsxReactEmit3.tsx, 3, 11))
>Bar : Symbol(Bar, Decl(tsxReactEmit3.tsx, 3, 16))
>Bar : Symbol(Bar, Decl(tsxReactEmit3.tsx, 3, 16))
>Bar : Symbol(Bar, Decl(tsxReactEmit3.tsx, 3, 16))
>Bar : Symbol(Bar, Decl(tsxReactEmit3.tsx, 3, 16))
>Foo : Symbol(Foo, Decl(tsxReactEmit3.tsx, 4, 11))
>Bar : Symbol(Bar, Decl(tsxReactEmit3.tsx, 4, 16))
>Bar : Symbol(Bar, Decl(tsxReactEmit3.tsx, 4, 16))
>Bar : Symbol(Bar, Decl(tsxReactEmit3.tsx, 4, 16))
>Bar : Symbol(Bar, Decl(tsxReactEmit3.tsx, 4, 16))

View file

@ -4,6 +4,9 @@ declare module JSX { interface Element { } }
>JSX : any
>Element : Element
declare var React: any;
>React : any
declare var Foo, Bar, baz;
>Foo : any
>Bar : any

View file

@ -1,4 +1,4 @@
tests/cases/conformance/jsx/tsxReactEmit4.tsx(11,5): error TS2304: Cannot find name 'blah'.
tests/cases/conformance/jsx/tsxReactEmit4.tsx(12,5): error TS2304: Cannot find name 'blah'.
==== tests/cases/conformance/jsx/tsxReactEmit4.tsx (1 errors) ====
@ -8,6 +8,7 @@ tests/cases/conformance/jsx/tsxReactEmit4.tsx(11,5): error TS2304: Cannot find n
[s: string]: any;
}
}
declare var React: any;
var p;
var openClosed1 = <div>

View file

@ -5,6 +5,7 @@ declare module JSX {
[s: string]: any;
}
}
declare var React: any;
var p;
var openClosed1 = <div>

View file

@ -5,6 +5,7 @@ declare module JSX {
[s: string]: any;
}
}
declare var React: any;
// THIS FILE HAS TEST-SIGNIFICANT LEADING/TRAILING
// WHITESPACE, DO NOT RUN 'FORMAT DOCUMENT' ON IT

View file

@ -12,12 +12,14 @@ declare module JSX {
>s : Symbol(s, Decl(tsxReactEmitWhitespace.tsx, 3, 3))
}
}
declare var React: any;
>React : Symbol(React, Decl(tsxReactEmitWhitespace.tsx, 6, 11))
// THIS FILE HAS TEST-SIGNIFICANT LEADING/TRAILING
// WHITESPACE, DO NOT RUN 'FORMAT DOCUMENT' ON IT
var p = 0;
>p : Symbol(p, Decl(tsxReactEmitWhitespace.tsx, 10, 3))
>p : Symbol(p, Decl(tsxReactEmitWhitespace.tsx, 11, 3))
// Emit " "
<div> </div>;

View file

@ -12,6 +12,8 @@ declare module JSX {
>s : string
}
}
declare var React: any;
>React : any
// THIS FILE HAS TEST-SIGNIFICANT LEADING/TRAILING
// WHITESPACE, DO NOT RUN 'FORMAT DOCUMENT' ON IT

View file

@ -0,0 +1,22 @@
//// [typeArgumentInferenceWithClassExpression1.ts]
function foo<T>(x = class { static prop: T }): T {
return undefined;
}
foo(class { static prop = "hello" }).length;
//// [typeArgumentInferenceWithClassExpression1.js]
function foo(x) {
if (x === void 0) { x = (function () {
function class_1() {
}
return class_1;
})(); }
return undefined;
}
foo((function () {
function class_2() {
}
class_2.prop = "hello";
return class_2;
})()).length;

View file

@ -0,0 +1,19 @@
=== tests/cases/conformance/es6/classExpressions/typeArgumentInferenceWithClassExpression1.ts ===
function foo<T>(x = class { static prop: T }): T {
>foo : Symbol(foo, Decl(typeArgumentInferenceWithClassExpression1.ts, 0, 0))
>T : Symbol(T, Decl(typeArgumentInferenceWithClassExpression1.ts, 0, 13))
>x : Symbol(x, Decl(typeArgumentInferenceWithClassExpression1.ts, 0, 16))
>prop : Symbol((Anonymous class).prop, Decl(typeArgumentInferenceWithClassExpression1.ts, 0, 27))
>T : Symbol(T, Decl(typeArgumentInferenceWithClassExpression1.ts, 0, 13))
>T : Symbol(T, Decl(typeArgumentInferenceWithClassExpression1.ts, 0, 13))
return undefined;
>undefined : Symbol(undefined)
}
foo(class { static prop = "hello" }).length;
>foo(class { static prop = "hello" }).length : Symbol(String.length, Decl(lib.d.ts, 414, 19))
>foo : Symbol(foo, Decl(typeArgumentInferenceWithClassExpression1.ts, 0, 0))
>prop : Symbol((Anonymous class).prop, Decl(typeArgumentInferenceWithClassExpression1.ts, 4, 11))
>length : Symbol(String.length, Decl(lib.d.ts, 414, 19))

View file

@ -0,0 +1,23 @@
=== tests/cases/conformance/es6/classExpressions/typeArgumentInferenceWithClassExpression1.ts ===
function foo<T>(x = class { static prop: T }): T {
>foo : <T>(x?: typeof (Anonymous class)) => T
>T : T
>x : typeof (Anonymous class)
>class { static prop: T } : typeof (Anonymous class)
>prop : T
>T : T
>T : T
return undefined;
>undefined : undefined
}
foo(class { static prop = "hello" }).length;
>foo(class { static prop = "hello" }).length : number
>foo(class { static prop = "hello" }) : string
>foo : <T>(x?: typeof (Anonymous class)) => T
>class { static prop = "hello" } : typeof (Anonymous class)
>prop : string
>"hello" : string
>length : number

View file

@ -0,0 +1,16 @@
tests/cases/conformance/es6/classExpressions/typeArgumentInferenceWithClassExpression2.ts(6,5): error TS2345: Argument of type 'typeof (Anonymous class)' is not assignable to parameter of type 'typeof (Anonymous class)'.
Type '(Anonymous class)' is not assignable to type 'foo<{}>.'.
Property 'prop' is missing in type '(Anonymous class)'.
==== tests/cases/conformance/es6/classExpressions/typeArgumentInferenceWithClassExpression2.ts (1 errors) ====
function foo<T>(x = class { prop: T }): T {
return undefined;
}
// Should not infer string because it is a static property
foo(class { static prop = "hello" }).length;
~~~~~
!!! error TS2345: Argument of type 'typeof (Anonymous class)' is not assignable to parameter of type 'typeof (Anonymous class)'.
!!! error TS2345: Type '(Anonymous class)' is not assignable to type 'foo<{}>.'.
!!! error TS2345: Property 'prop' is missing in type '(Anonymous class)'.

View file

@ -0,0 +1,24 @@
//// [typeArgumentInferenceWithClassExpression2.ts]
function foo<T>(x = class { prop: T }): T {
return undefined;
}
// Should not infer string because it is a static property
foo(class { static prop = "hello" }).length;
//// [typeArgumentInferenceWithClassExpression2.js]
function foo(x) {
if (x === void 0) { x = (function () {
function class_1() {
}
return class_1;
})(); }
return undefined;
}
// Should not infer string because it is a static property
foo((function () {
function class_2() {
}
class_2.prop = "hello";
return class_2;
})()).length;

View file

@ -0,0 +1,22 @@
//// [typeArgumentInferenceWithClassExpression3.ts]
function foo<T>(x = class { prop: T }): T {
return undefined;
}
foo(class { prop = "hello" }).length;
//// [typeArgumentInferenceWithClassExpression3.js]
function foo(x) {
if (x === void 0) { x = (function () {
function class_1() {
}
return class_1;
})(); }
return undefined;
}
foo((function () {
function class_2() {
this.prop = "hello";
}
return class_2;
})()).length;

View file

@ -0,0 +1,19 @@
=== tests/cases/conformance/es6/classExpressions/typeArgumentInferenceWithClassExpression3.ts ===
function foo<T>(x = class { prop: T }): T {
>foo : Symbol(foo, Decl(typeArgumentInferenceWithClassExpression3.ts, 0, 0))
>T : Symbol(T, Decl(typeArgumentInferenceWithClassExpression3.ts, 0, 13))
>x : Symbol(x, Decl(typeArgumentInferenceWithClassExpression3.ts, 0, 16))
>prop : Symbol((Anonymous class).prop, Decl(typeArgumentInferenceWithClassExpression3.ts, 0, 27))
>T : Symbol(T, Decl(typeArgumentInferenceWithClassExpression3.ts, 0, 13))
>T : Symbol(T, Decl(typeArgumentInferenceWithClassExpression3.ts, 0, 13))
return undefined;
>undefined : Symbol(undefined)
}
foo(class { prop = "hello" }).length;
>foo(class { prop = "hello" }).length : Symbol(String.length, Decl(lib.d.ts, 414, 19))
>foo : Symbol(foo, Decl(typeArgumentInferenceWithClassExpression3.ts, 0, 0))
>prop : Symbol((Anonymous class).prop, Decl(typeArgumentInferenceWithClassExpression3.ts, 4, 11))
>length : Symbol(String.length, Decl(lib.d.ts, 414, 19))

View file

@ -0,0 +1,23 @@
=== tests/cases/conformance/es6/classExpressions/typeArgumentInferenceWithClassExpression3.ts ===
function foo<T>(x = class { prop: T }): T {
>foo : <T>(x?: typeof (Anonymous class)) => T
>T : T
>x : typeof (Anonymous class)
>class { prop: T } : typeof (Anonymous class)
>prop : T
>T : T
>T : T
return undefined;
>undefined : undefined
}
foo(class { prop = "hello" }).length;
>foo(class { prop = "hello" }).length : number
>foo(class { prop = "hello" }) : string
>foo : <T>(x?: typeof (Anonymous class)) => T
>class { prop = "hello" } : typeof (Anonymous class)
>prop : string
>"hello" : string
>length : number

View file

@ -23,19 +23,19 @@ class C extends A {
}
declare function isA(p1: any): p1 is A;
>isA : (p1: any) => boolean
>isA : (p1: any) => p1 is A
>p1 : any
>p1 : any
>A : A
declare function isB(p1: any): p1 is B;
>isB : (p1: any) => boolean
>isB : (p1: any) => p1 is B
>p1 : any
>p1 : any
>B : B
declare function isC(p1: any): p1 is C;
>isC : (p1: any) => boolean
>isC : (p1: any) => p1 is C
>p1 : any
>p1 : any
>C : C
@ -55,7 +55,7 @@ var b: B;
// Basic
if (isC(a)) {
>isC(a) : boolean
>isC : (p1: any) => boolean
>isC : (p1: any) => p1 is C
>a : A
a.propC;
@ -71,7 +71,7 @@ var subType: C;
if(isA(subType)) {
>isA(subType) : boolean
>isA : (p1: any) => boolean
>isA : (p1: any) => p1 is A
>subType : C
subType.propC;
@ -88,7 +88,7 @@ var union: A | B;
if(isA(union)) {
>isA(union) : boolean
>isA : (p1: any) => boolean
>isA : (p1: any) => p1 is A
>union : A | B
union.propA;
@ -111,7 +111,7 @@ interface I1 {
// The parameter index and argument index for the type guard target is matching.
// The type predicate type is assignable to the parameter type.
declare function isC_multipleParams(p1, p2): p1 is C;
>isC_multipleParams : (p1: any, p2: any) => boolean
>isC_multipleParams : (p1: any, p2: any) => p1 is C
>p1 : any
>p2 : any
>p1 : any
@ -119,7 +119,7 @@ declare function isC_multipleParams(p1, p2): p1 is C;
if (isC_multipleParams(a, 0)) {
>isC_multipleParams(a, 0) : boolean
>isC_multipleParams : (p1: any, p2: any) => boolean
>isC_multipleParams : (p1: any, p2: any) => p1 is C
>a : A
>0 : number
@ -131,10 +131,10 @@ if (isC_multipleParams(a, 0)) {
// Methods
var obj: {
>obj : { func1(p1: A): boolean; }
>obj : { func1(p1: A): p1 is C; }
func1(p1: A): p1 is C;
>func1 : (p1: A) => boolean
>func1 : (p1: A) => p1 is C
>p1 : A
>A : A
>p1 : any
@ -144,7 +144,7 @@ class D {
>D : D
method1(p1: A): p1 is C {
>method1 : (p1: A) => boolean
>method1 : (p1: A) => p1 is C
>p1 : A
>A : A
>p1 : any
@ -157,8 +157,8 @@ class D {
// Arrow function
let f1 = (p1: A): p1 is C => false;
>f1 : (p1: A) => boolean
>(p1: A): p1 is C => false : (p1: A) => boolean
>f1 : (p1: A) => p1 is C
>(p1: A): p1 is C => false : (p1: A) => p1 is C
>p1 : A
>A : A
>p1 : any
@ -167,8 +167,8 @@ let f1 = (p1: A): p1 is C => false;
// Function type
declare function f2(p1: (p1: A) => p1 is C);
>f2 : (p1: (p1: A) => boolean) => any
>p1 : (p1: A) => boolean
>f2 : (p1: (p1: A) => p1 is C) => any
>p1 : (p1: A) => p1 is C
>p1 : A
>A : A
>p1 : any
@ -177,8 +177,8 @@ declare function f2(p1: (p1: A) => p1 is C);
// Function expressions
f2(function(p1: A): p1 is C {
>f2(function(p1: A): p1 is C { return true;}) : any
>f2 : (p1: (p1: A) => boolean) => any
>function(p1: A): p1 is C { return true;} : (p1: A) => boolean
>f2 : (p1: (p1: A) => p1 is C) => any
>function(p1: A): p1 is C { return true;} : (p1: A) => p1 is C
>p1 : A
>A : A
>p1 : any
@ -198,21 +198,21 @@ acceptingBoolean(isA(a));
>acceptingBoolean(isA(a)) : any
>acceptingBoolean : (a: boolean) => any
>isA(a) : boolean
>isA : (p1: any) => boolean
>isA : (p1: any) => p1 is A
>a : A
// Type predicates with different parameter name.
declare function acceptingTypeGuardFunction(p1: (item) => item is A);
>acceptingTypeGuardFunction : (p1: (item: any) => boolean) => any
>p1 : (item: any) => boolean
>acceptingTypeGuardFunction : (p1: (item: any) => item is A) => any
>p1 : (item: any) => item is A
>item : any
>item : any
>A : A
acceptingTypeGuardFunction(isA);
>acceptingTypeGuardFunction(isA) : any
>acceptingTypeGuardFunction : (p1: (item: any) => boolean) => any
>isA : (p1: any) => boolean
>acceptingTypeGuardFunction : (p1: (item: any) => item is A) => any
>isA : (p1: any) => p1 is A
// Binary expressions
let union2: C | B;
@ -225,7 +225,7 @@ let union3: boolean | B = isA(union2) || union2;
>B : B
>isA(union2) || union2 : boolean | B
>isA(union2) : boolean
>isA : (p1: any) => boolean
>isA : (p1: any) => p1 is A
>union2 : B | C
>union2 : B

View file

@ -12,15 +12,15 @@ tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(46,56)
tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(60,7): error TS2339: Property 'propB' does not exist on type 'A'.
tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(65,7): error TS2339: Property 'propB' does not exist on type 'A'.
tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(70,7): error TS2339: Property 'propB' does not exist on type 'A'.
tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(75,46): error TS2345: Argument of type '(p1: any) => boolean' is not assignable to parameter of type '(p1: any) => boolean'.
tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(75,46): error TS2345: Argument of type '(p1: any) => p1 is C' is not assignable to parameter of type '(p1: any) => p1 is B'.
Type predicate 'p1 is C' is not assignable to 'p1 is B'.
Type 'C' is not assignable to type 'B'.
tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(79,1): error TS2322: Type '(p1: any, p2: any) => boolean' is not assignable to type '(p1: any, p2: any) => boolean'.
tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(79,1): error TS2322: Type '(p1: any, p2: any) => boolean' is not assignable to type '(p1: any, p2: any) => p1 is A'.
Signature '(p1: any, p2: any): boolean' must have a type predicate.
tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(85,1): error TS2322: Type '(p1: any, p2: any) => boolean' is not assignable to type '(p1: any, p2: any) => boolean'.
tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(85,1): error TS2322: Type '(p1: any, p2: any) => p2 is A' is not assignable to type '(p1: any, p2: any) => p1 is A'.
Type predicate 'p2 is A' is not assignable to 'p1 is A'.
Parameter 'p2' is not in the same position as parameter 'p1'.
tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(91,1): error TS2322: Type '(p1: any, p2: any, p3: any) => boolean' is not assignable to type '(p1: any, p2: any) => boolean'.
tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(91,1): error TS2322: Type '(p1: any, p2: any, p3: any) => p1 is A' is not assignable to type '(p1: any, p2: any) => p1 is A'.
tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(96,9): error TS1228: A type predicate is only allowed in return type position for functions and methods.
tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(97,16): error TS1228: A type predicate is only allowed in return type position for functions and methods.
tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(98,20): error TS1228: A type predicate is only allowed in return type position for functions and methods.
@ -141,7 +141,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(137,39
declare function acceptingDifferentSignatureTypeGuardFunction(p1: (p1) => p1 is B);
acceptingDifferentSignatureTypeGuardFunction(isC);
~~~
!!! error TS2345: Argument of type '(p1: any) => boolean' is not assignable to parameter of type '(p1: any) => boolean'.
!!! error TS2345: Argument of type '(p1: any) => p1 is C' is not assignable to parameter of type '(p1: any) => p1 is B'.
!!! error TS2345: Type predicate 'p1 is C' is not assignable to 'p1 is B'.
!!! error TS2345: Type 'C' is not assignable to type 'B'.
@ -149,7 +149,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(137,39
var assign1: (p1, p2) => p1 is A;
assign1 = function(p1, p2): boolean {
~~~~~~~
!!! error TS2322: Type '(p1: any, p2: any) => boolean' is not assignable to type '(p1: any, p2: any) => boolean'.
!!! error TS2322: Type '(p1: any, p2: any) => boolean' is not assignable to type '(p1: any, p2: any) => p1 is A'.
!!! error TS2322: Signature '(p1: any, p2: any): boolean' must have a type predicate.
return true;
};
@ -158,7 +158,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(137,39
var assign2: (p1, p2) => p1 is A;
assign2 = function(p1, p2): p2 is A {
~~~~~~~
!!! error TS2322: Type '(p1: any, p2: any) => boolean' is not assignable to type '(p1: any, p2: any) => boolean'.
!!! error TS2322: Type '(p1: any, p2: any) => p2 is A' is not assignable to type '(p1: any, p2: any) => p1 is A'.
!!! error TS2322: Type predicate 'p2 is A' is not assignable to 'p1 is A'.
!!! error TS2322: Parameter 'p2' is not in the same position as parameter 'p1'.
return true;
@ -168,7 +168,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(137,39
var assign3: (p1, p2) => p1 is A;
assign3 = function(p1, p2, p3): p1 is A {
~~~~~~~
!!! error TS2322: Type '(p1: any, p2: any, p3: any) => boolean' is not assignable to type '(p1: any, p2: any) => boolean'.
!!! error TS2322: Type '(p1: any, p2: any, p3: any) => p1 is A' is not assignable to type '(p1: any, p2: any) => p1 is A'.
return true;
};

View file

@ -23,13 +23,13 @@ class C extends A {
}
declare function isB(p1): p1 is B;
>isB : (p1: any) => boolean
>isB : (p1: any) => p1 is B
>p1 : any
>p1 : any
>B : B
declare function isC(p1): p1 is C;
>isC : (p1: any) => boolean
>isC : (p1: any) => p1 is C
>p1 : any
>p1 : any
>C : C
@ -48,7 +48,7 @@ declare function funA<T>(p1: (p1) => T): T;
>T : T
declare function funB<T>(p1: (p1) => T, p2: any): p2 is T;
>funB : <T>(p1: (p1: any) => T, p2: any) => boolean
>funB : <T>(p1: (p1: any) => T, p2: any) => p2 is T
>T : T
>p1 : (p1: any) => T
>p1 : any
@ -58,18 +58,18 @@ declare function funB<T>(p1: (p1) => T, p2: any): p2 is T;
>T : T
declare function funC<T>(p1: (p1) => p1 is T): T;
>funC : <T>(p1: (p1: any) => boolean) => T
>funC : <T>(p1: (p1: any) => p1 is T) => T
>T : T
>p1 : (p1: any) => boolean
>p1 : (p1: any) => p1 is T
>p1 : any
>p1 : any
>T : T
>T : T
declare function funD<T>(p1: (p1) => p1 is T, p2: any): p2 is T;
>funD : <T>(p1: (p1: any) => boolean, p2: any) => boolean
>funD : <T>(p1: (p1: any) => p1 is T, p2: any) => p2 is T
>T : T
>p1 : (p1: any) => boolean
>p1 : (p1: any) => p1 is T
>p1 : any
>p1 : any
>T : T
@ -78,10 +78,10 @@ declare function funD<T>(p1: (p1) => p1 is T, p2: any): p2 is T;
>T : T
declare function funE<T, U>(p1: (p1) => p1 is T, p2: U): T;
>funE : <T, U>(p1: (p1: any) => boolean, p2: U) => T
>funE : <T, U>(p1: (p1: any) => p1 is T, p2: U) => T
>T : T
>U : U
>p1 : (p1: any) => boolean
>p1 : (p1: any) => p1 is T
>p1 : any
>p1 : any
>T : T
@ -97,11 +97,11 @@ let test1: boolean = funA(isB);
>test1 : boolean
>funA(isB) : boolean
>funA : <T>(p1: (p1: any) => T) => T
>isB : (p1: any) => boolean
>isB : (p1: any) => p1 is B
if (funB(retC, a)) {
>funB(retC, a) : boolean
>funB : <T>(p1: (p1: any) => T, p2: any) => boolean
>funB : <T>(p1: (p1: any) => T, p2: any) => p2 is T
>retC : (x: any) => C
>a : A
@ -114,13 +114,13 @@ let test2: B = funC(isB);
>test2 : B
>B : B
>funC(isB) : B
>funC : <T>(p1: (p1: any) => boolean) => T
>isB : (p1: any) => boolean
>funC : <T>(p1: (p1: any) => p1 is T) => T
>isB : (p1: any) => p1 is B
if (funD(isC, a)) {
>funD(isC, a) : boolean
>funD : <T>(p1: (p1: any) => boolean, p2: any) => boolean
>isC : (p1: any) => boolean
>funD : <T>(p1: (p1: any) => p1 is T, p2: any) => p2 is T
>isC : (p1: any) => p1 is C
>a : A
a.propC;
@ -132,7 +132,7 @@ let test3: B = funE(isB, 1);
>test3 : B
>B : B
>funE(isB, 1) : B
>funE : <T, U>(p1: (p1: any) => boolean, p2: U) => T
>isB : (p1: any) => boolean
>funE : <T, U>(p1: (p1: any) => p1 is T, p2: U) => T
>isB : (p1: any) => p1 is B
>1 : number

View file

@ -29,7 +29,7 @@ var strOrNum: string | number;
>strOrNum : string | number
function isC1(x: any): x is C1 {
>isC1 : (x: any) => boolean
>isC1 : (x: any) => x is C1
>x : any
>x : any
>C1 : C1
@ -39,7 +39,7 @@ function isC1(x: any): x is C1 {
}
function isC2(x: any): x is C2 {
>isC2 : (x: any) => boolean
>isC2 : (x: any) => x is C2
>x : any
>x : any
>C2 : C2
@ -49,7 +49,7 @@ function isC2(x: any): x is C2 {
}
function isD1(x: any): x is D1 {
>isD1 : (x: any) => boolean
>isD1 : (x: any) => x is D1
>x : any
>x : any
>D1 : D1
@ -68,7 +68,7 @@ str = isC1(c1Orc2) && c1Orc2.p1; // C1
>str : string
>isC1(c1Orc2) && c1Orc2.p1 : string
>isC1(c1Orc2) : boolean
>isC1 : (x: any) => boolean
>isC1 : (x: any) => x is C1
>c1Orc2 : C1 | C2
>c1Orc2.p1 : string
>c1Orc2 : C1
@ -79,7 +79,7 @@ num = isC2(c1Orc2) && c1Orc2.p2; // C2
>num : number
>isC2(c1Orc2) && c1Orc2.p2 : number
>isC2(c1Orc2) : boolean
>isC2 : (x: any) => boolean
>isC2 : (x: any) => x is C2
>c1Orc2 : C1 | C2
>c1Orc2.p2 : number
>c1Orc2 : C2
@ -90,7 +90,7 @@ str = isD1(c1Orc2) && c1Orc2.p1; // D1
>str : string
>isD1(c1Orc2) && c1Orc2.p1 : string
>isD1(c1Orc2) : boolean
>isD1 : (x: any) => boolean
>isD1 : (x: any) => x is D1
>c1Orc2 : C1 | C2
>c1Orc2.p1 : string
>c1Orc2 : D1
@ -101,7 +101,7 @@ num = isD1(c1Orc2) && c1Orc2.p3; // D1
>num : number
>isD1(c1Orc2) && c1Orc2.p3 : number
>isD1(c1Orc2) : boolean
>isD1 : (x: any) => boolean
>isD1 : (x: any) => x is D1
>c1Orc2 : C1 | C2
>c1Orc2.p3 : number
>c1Orc2 : D1
@ -117,7 +117,7 @@ num = isC2(c2Ord1) && c2Ord1.p2; // C2
>num : number
>isC2(c2Ord1) && c2Ord1.p2 : number
>isC2(c2Ord1) : boolean
>isC2 : (x: any) => boolean
>isC2 : (x: any) => x is C2
>c2Ord1 : C2 | D1
>c2Ord1.p2 : number
>c2Ord1 : C2
@ -128,7 +128,7 @@ num = isD1(c2Ord1) && c2Ord1.p3; // D1
>num : number
>isD1(c2Ord1) && c2Ord1.p3 : number
>isD1(c2Ord1) : boolean
>isD1 : (x: any) => boolean
>isD1 : (x: any) => x is D1
>c2Ord1 : C2 | D1
>c2Ord1.p3 : number
>c2Ord1 : D1
@ -139,7 +139,7 @@ str = isD1(c2Ord1) && c2Ord1.p1; // D1
>str : string
>isD1(c2Ord1) && c2Ord1.p1 : string
>isD1(c2Ord1) : boolean
>isD1 : (x: any) => boolean
>isD1 : (x: any) => x is D1
>c2Ord1 : C2 | D1
>c2Ord1.p1 : string
>c2Ord1 : D1
@ -151,7 +151,7 @@ var r2: C2 | D1 = isC1(c2Ord1) && c2Ord1; // C2 | D1
>D1 : D1
>isC1(c2Ord1) && c2Ord1 : D1
>isC1(c2Ord1) : boolean
>isC1 : (x: any) => boolean
>isC1 : (x: any) => x is C1
>c2Ord1 : C2 | D1
>c2Ord1 : D1

View file

@ -48,7 +48,7 @@ var strOrNum: string | number;
function isC1(x: any): x is C1 {
>isC1 : (x: any) => boolean
>isC1 : (x: any) => x is C1
>x : any
>x : any
>C1 : C1
@ -58,7 +58,7 @@ function isC1(x: any): x is C1 {
}
function isC2(x: any): x is C2 {
>isC2 : (x: any) => boolean
>isC2 : (x: any) => x is C2
>x : any
>x : any
>C2 : C2
@ -68,7 +68,7 @@ function isC2(x: any): x is C2 {
}
function isD1(x: any): x is D1 {
>isD1 : (x: any) => boolean
>isD1 : (x: any) => x is D1
>x : any
>x : any
>D1 : D1
@ -99,7 +99,7 @@ str = isC1(c1Orc2) && c1Orc2.p1; // C1
>str : string
>isC1(c1Orc2) && c1Orc2.p1 : string
>isC1(c1Orc2) : boolean
>isC1 : (x: any) => boolean
>isC1 : (x: any) => x is C1
>c1Orc2 : C1 | C2
>c1Orc2.p1 : string
>c1Orc2 : C1
@ -110,7 +110,7 @@ num = isC2(c1Orc2) && c1Orc2.p2; // C2
>num : number
>isC2(c1Orc2) && c1Orc2.p2 : number
>isC2(c1Orc2) : boolean
>isC2 : (x: any) => boolean
>isC2 : (x: any) => x is C2
>c1Orc2 : C1 | C2
>c1Orc2.p2 : number
>c1Orc2 : C2
@ -121,7 +121,7 @@ str = isD1(c1Orc2) && c1Orc2.p1; // D1
>str : string
>isD1(c1Orc2) && c1Orc2.p1 : string
>isD1(c1Orc2) : boolean
>isD1 : (x: any) => boolean
>isD1 : (x: any) => x is D1
>c1Orc2 : C1 | C2
>c1Orc2.p1 : string
>c1Orc2 : D1
@ -132,7 +132,7 @@ num = isD1(c1Orc2) && c1Orc2.p3; // D1
>num : number
>isD1(c1Orc2) && c1Orc2.p3 : number
>isD1(c1Orc2) : boolean
>isD1 : (x: any) => boolean
>isD1 : (x: any) => x is D1
>c1Orc2 : C1 | C2
>c1Orc2.p3 : number
>c1Orc2 : D1
@ -148,7 +148,7 @@ num = isC2(c2Ord1) && c2Ord1.p2; // C2
>num : number
>isC2(c2Ord1) && c2Ord1.p2 : number
>isC2(c2Ord1) : boolean
>isC2 : (x: any) => boolean
>isC2 : (x: any) => x is C2
>c2Ord1 : C2 | D1
>c2Ord1.p2 : number
>c2Ord1 : C2
@ -159,7 +159,7 @@ num = isD1(c2Ord1) && c2Ord1.p3; // D1
>num : number
>isD1(c2Ord1) && c2Ord1.p3 : number
>isD1(c2Ord1) : boolean
>isD1 : (x: any) => boolean
>isD1 : (x: any) => x is D1
>c2Ord1 : C2 | D1
>c2Ord1.p3 : number
>c2Ord1 : D1
@ -170,7 +170,7 @@ str = isD1(c2Ord1) && c2Ord1.p1; // D1
>str : string
>isD1(c2Ord1) && c2Ord1.p1 : string
>isD1(c2Ord1) : boolean
>isD1 : (x: any) => boolean
>isD1 : (x: any) => x is D1
>c2Ord1 : C2 | D1
>c2Ord1.p1 : string
>c2Ord1 : D1
@ -182,7 +182,7 @@ var r2: C2 | D1 = isC1(c2Ord1) && c2Ord1; // C2 | D1
>D1 : D1
>isC1(c2Ord1) && c2Ord1 : D1
>isC1(c2Ord1) : boolean
>isC1 : (x: any) => boolean
>isC1 : (x: any) => x is C1
>c2Ord1 : C2 | D1
>c2Ord1 : D1

View file

@ -28,6 +28,19 @@ export function fooWithSingleOverload(a: any) {
return a;
}
export function fooWithTypePredicate(a: any): a is number {
return true;
}
export function fooWithTypePredicateAndMulitpleParams(a: any, b: any, c: any): a is number {
return true;
}
export function fooWithTypeTypePredicateAndGeneric<T>(a: any): a is T {
return true;
}
export function fooWithTypeTypePredicateAndRestParam(a: any, ...rest): a is number {
return true;
}
/** This comment should appear for nonExportedFoo*/
function nonExportedFoo() {
}

View file

@ -0,0 +1,9 @@
// @declaration: true
function f() {
class C {
public baz = 1;
static foo() { }
public bar() { }
}
}

View file

@ -0,0 +1,10 @@
// @declaration: true
// @declaration: true
function g() {
var x = class C {
public prop1 = 1;
private foo() { }
static prop2 = 43;
}
}

View file

@ -0,0 +1,5 @@
function foo<T>(x = class { static prop: T }): T {
return undefined;
}
foo(class { static prop = "hello" }).length;

View file

@ -0,0 +1,6 @@
function foo<T>(x = class { prop: T }): T {
return undefined;
}
// Should not infer string because it is a static property
foo(class { static prop = "hello" }).length;

View file

@ -0,0 +1,5 @@
function foo<T>(x = class { prop: T }): T {
return undefined;
}
foo(class { prop = "hello" }).length;

View file

@ -1,15 +0,0 @@
// OK
<test1 x={0}/>; // OK
<test1 />; // OK
<test1 data-x={true}/>; // OK
<test2 reqd='true'/>; // OK
<test2 reqd={'true'}/>; // OK
// Errors
<test1 x={'0'}/>; // Error, '0' is not number
<test1 y={0}/>; // Error, no property "y"
<test1 y="foo"/>; // Error, no property "y"
<test1 x="32"/>; // Error, "32" is not number
// TODO attribute 'var' should be parseable
// <test1 var="10" />; // Error, no 'var' property
<test2 />; // Error, missing reqd
<test2 reqd={10}/>; // Error, reqd is not string

View file

@ -1,5 +0,0 @@
// OK
<test1 c1={function (x) { return x.length; }}/>; // OK
<test1 data-c1={function (x) { return x.leng; }}/>; // OK
// Errors
<test1 c1={function (x) { return x.leng; }}/>; // Error, no leng on 'string'

View file

@ -1,21 +0,0 @@
// OK
var obj1 = { x: 'foo' };
<test1 {...obj1}/>;
// Error, x is not string
var obj2 = { x: 32 };
<test1 {...obj2}/>;
// Error, x is missing
var obj3 = { y: 32 };
<test1 {...obj3}/>;
// OK
var obj4 = { x: 32, y: 32 };
<test1 {...obj4} x="ok"/>;
// Error
var obj5 = { x: 32, y: 32 };
<test1 x="ok" {...obj5}/>;
// OK
var obj6 = { x: 'ok', y: 32, extra: 100 };
<test1 {...obj6}/>;
// Error
var obj7 = { x: 'foo' };
<test1 x={32} {...obj7}/>;

View file

@ -1,4 +0,0 @@
// OK
<test1 {...{ x: function (n) { return 0; } }}/>;
// Error, no member 'len' on 'string'
<test1 {...{ x: function (n) { return n.len; } }}/>;

View file

@ -1,11 +0,0 @@
function make1(obj) {
return <test1 {...obj}/>; // OK
}
function make2(obj) {
return <test1 {...obj}/>; // Error (x is number, not string)
}
function make3(obj) {
return <test1 {...obj}/>; // Error, missing x
}
<test1 {...{}}/>; // Error, missing x
<test2 {...{}}/>; // OK

View file

@ -0,0 +1,27 @@
//@jsx: preserve
//@module: amd
//@filename: react.d.ts
declare module JSX {
interface Element { }
interface IntrinsicElements {
}
interface ElementAttributesProperty {
props;
}
}
interface Props {
foo: string;
}
//@filename: file.tsx
export class MyComponent {
render() {
}
props: { foo: string; }
}
<MyComponent foo="bar" />; // ok
<MyComponent foo={0} />; // should be an error

View file

@ -1,4 +0,0 @@
// OK
<div />;
// Fail
<span />;

View file

@ -1,6 +0,0 @@
var Obj1;
<Obj1 x={10}/>; // OK
var Obj2;
<Obj2 x={10}/>; // Error
var Obj3;
<Obj3 x={10}/>; // OK

View file

@ -1,9 +0,0 @@
var obj1;
<obj1 x={10}/>; // OK
var obj2;
<obj2 x={10}/>; // OK
var obj3;
<obj3 x={10}/>; // Error
var obj4;
<obj4 x={10}/>; // OK
<obj4 x={'10'}/>; // Error

View file

@ -1,2 +0,0 @@
var obj1;
<obj1 x={10}/>; // Error

View file

@ -1,2 +0,0 @@
var obj1;
<obj1 x={10}/>; // OK

View file

@ -1,2 +0,0 @@
var obj1;
<obj1 x={10}/>; // Error

View file

@ -1,2 +0,0 @@
var obj1;
<obj1 x={10}/>; // Error (JSX.Element is missing)

View file

@ -0,0 +1,21 @@
//@jsx: react
//@module: amd
//@filename: react.d.ts
declare module "react" {
}
//@filename: file1.tsx
declare module JSX {
interface Element { }
}
export class MyClass { }
//@filename: file2.tsx
// Should not elide React import
import * as React from 'react';
import {MyClass} from './file1';
<MyClass />;

View file

@ -1,14 +0,0 @@
var my;
(function (my) {
})(my || (my = {}));
// OK
<my.div n='x'/>;
// Error
<my.other />;
var q;
(function (q) {
// OK
<mine.div n='x'/>;
// Error
<mine.non />;
})(q || (q = {}));

View file

@ -1,15 +0,0 @@
// Error
var div = 3;
<div />;
// OK
function fact() { return null; }
<fact />;
// Error
function fnum() { return 42; }
<fnum />;
var obj1;
<obj1 />; // OK, prefer construct signatures
var obj2;
<obj2 />; // Error
var obj3;
<obj3 />; // Error

View file

@ -1,6 +0,0 @@
var obj1;
<obj1 />; // Error, return type is not an object type
var obj2;
<obj2 />; // Error, return type is not an object type
var obj3;
<obj3 x={42}/>; // OK

View file

@ -1,34 +0,0 @@
var p;
/*
var selfClosed1 = <div />;
var selfClosed2 = <div x="1" />;
var selfClosed3 = <div x='1' />;
var selfClosed4 = <div x="1" y='0' />;
var selfClosed5 = <div x={0} y='0' />;
var selfClosed6 = <div x={"1"} y='0' />;
var selfClosed7 = <div x={p} y='p' />;
var openClosed1 = <div></div>;
var openClosed2 = <div n='m'>foo</div>;
var openClosed3 = <div n='m'>{p}</div>;
var openClosed4 = <div n='m'>{p < p}</div>;
var openClosed5 = <div n='m'>{p > p}</div>;
*/
var SomeClass = (function () {
function SomeClass() {
}
SomeClass.prototype.f = function () {
var _this = this;
var rewrites1 = <div>{function () { return _this; }}</div>;
var rewrites4 = <div a={function () { return _this; }}></div>;
};
return SomeClass;
})();
/*
var q = () => this;
var rewrites2 = <div>{[p, ...p, p]}</div>;
var rewrites3 = <div>{{p}}</div>;
var rewrites5 = <div a={[p, ...p, p]}></div>;
var rewrites6 = <div a={{p}}></div>;
*/

View file

@ -1,41 +0,0 @@
var M;
(function (M) {
var Foo = (function () {
function Foo() {
}
return Foo;
})();
M.Foo = Foo;
var S;
(function (S) {
var Bar = (function () {
function Bar() {
}
return Bar;
})();
S.Bar = Bar;
})(S = M.S || (M.S = {}));
})(M || (M = {}));
var M;
(function (M) {
// Emit M.Foo
M.Foo, <M.Foo />;
var S;
(function (S) {
// Emit M.Foo
M.Foo, <M.Foo />;
// Emit S.Bar
S.Bar, <S.Bar />;
})(S = M.S || (M.S = {}));
})(M || (M = {}));
var M;
(function (M) {
// Emit M.S.Bar
M.S.Bar, <M.S.Bar />;
})(M || (M = {}));
var M;
(function (M_1) {
var M = 100;
// Emit M_1.Foo
M_1.Foo, <M_1.Foo />;
})(M || (M = {}));

View file

@ -6,6 +6,7 @@ declare module JSX {
[s: string]: any;
}
}
declare var React: any;
var p;
var selfClosed1 = <div />;

View file

@ -6,6 +6,7 @@ declare module JSX {
[s: string]: any;
}
}
declare var React: any;
var p1, p2, p3;
var spreads1 = <div {...p1}>{p2}</div>;

View file

@ -2,6 +2,7 @@
//@filename: test.tsx
declare module JSX { interface Element { } }
declare var React: any;
declare var Foo, Bar, baz;

View file

@ -6,6 +6,7 @@ declare module JSX {
[s: string]: any;
}
}
declare var React: any;
var p;
var openClosed1 = <div>

View file

@ -6,6 +6,7 @@ declare module JSX {
[s: string]: any;
}
}
declare var React: any;
// THIS FILE HAS TEST-SIGNIFICANT LEADING/TRAILING
// WHITESPACE, DO NOT RUN 'FORMAT DOCUMENT' ON IT

View file

@ -1,32 +0,0 @@
/// <reference path='fourslash.ts'/>
// @Filename: m1.ts
////export var foo: number = 1;
////export function bar() { return 10; }
////export function baz() { return 10; }
// @Filename: m2.ts
////import {/*1*/, /*2*/ from "m1"
////import {/*3*/} from "m1"
////import {foo,/*4*/ from "m1"
////import {bar as /*5*/, /*6*/ from "m1"
////import {foo, bar, baz as b,/*7*/} from "m1"
function verifyCompletionAtMarker(marker: string, ...completions: string[]) {
goTo.marker(marker);
if (completions.length) {
for (var i = 0; i < completions.length; ++i) {
verify.completionListContains(completions[i]);
}
}
else {
verify.completionListIsEmpty();
}
}
verifyCompletionAtMarker("1", "foo", "bar", "baz");
verifyCompletionAtMarker("2", "foo", "bar", "baz");
verifyCompletionAtMarker("3", "foo", "bar", "baz");
verifyCompletionAtMarker("4", "bar", "baz");
verifyCompletionAtMarker("5");
verifyCompletionAtMarker("6", "foo", "baz");
verifyCompletionAtMarker("7");

View file

@ -0,0 +1,7 @@
/// <reference path="fourslash.ts" />
////let v = [1,2,3,4];
////let x = [.../**/
goTo.marker();
verify.completionListContains("v");

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