Merge branch 'master' into commonCompilerOptionsWithBuild

This commit is contained in:
Sheetal Nandi
2018-09-14 10:08:34 -07:00
205 changed files with 3267 additions and 2057 deletions
+45 -36
View File
@@ -234,13 +234,17 @@ namespace ts {
}
if (symbolFlags & SymbolFlags.Value) {
const { valueDeclaration } = symbol;
if (!valueDeclaration ||
(isAssignmentDeclaration(valueDeclaration) && !isAssignmentDeclaration(node)) ||
(valueDeclaration.kind !== node.kind && isEffectiveModuleDeclaration(valueDeclaration))) {
// other kinds of value declarations take precedence over modules and assignment declarations
symbol.valueDeclaration = node;
}
setValueDeclaration(symbol, node);
}
}
function setValueDeclaration(symbol: Symbol, node: Declaration): void {
const { valueDeclaration } = symbol;
if (!valueDeclaration ||
(isAssignmentDeclaration(valueDeclaration) && !isAssignmentDeclaration(node)) ||
(valueDeclaration.kind !== node.kind && isEffectiveModuleDeclaration(valueDeclaration))) {
// other kinds of value declarations take precedence over modules and assignment declarations
symbol.valueDeclaration = node;
}
}
@@ -288,7 +292,7 @@ namespace ts {
// module.exports = ...
return InternalSymbolName.ExportEquals;
case SyntaxKind.BinaryExpression:
if (getSpecialPropertyAssignmentKind(node as BinaryExpression) === SpecialPropertyAssignmentKind.ModuleExports) {
if (getAssignmentDeclarationKind(node as BinaryExpression) === AssignmentDeclarationKind.ModuleExports) {
// module.exports = ...
return InternalSymbolName.ExportEquals;
}
@@ -374,8 +378,8 @@ namespace ts {
// prototype symbols like methods.
symbolTable.set(name, symbol = createSymbol(SymbolFlags.None, name));
}
else if (!(includes & SymbolFlags.Variable && symbol.flags & SymbolFlags.JSContainer)) {
// JSContainers are allowed to merge with variables, no matter what other flags they have.
else if (!(includes & SymbolFlags.Variable && symbol.flags & SymbolFlags.Assignment)) {
// Assignment declarations are allowed to merge with variables, no matter what other flags they have.
if (isNamedDeclaration(node)) {
node.name.parent = node;
}
@@ -461,7 +465,7 @@ namespace ts {
// during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation
// and this case is specially handled. Module augmentations should only be merged with original module definition
// and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed.
if (isJSDocTypeAlias(node)) Debug.assert(isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file.
if (isJSDocTypeAlias(node)) Debug.assert(isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file.
if ((!isAmbientModule(node) && (hasExportModifier || container.flags & NodeFlags.ExportContext)) || isJSDocTypeAlias(node)) {
if (hasModifier(node, ModifierFlags.Default) && !getDeclarationName(node)) {
return declareSymbol(container.symbol.exports!, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default!
@@ -2009,7 +2013,7 @@ namespace ts {
function bindJSDoc(node: Node) {
if (hasJSDocNodes(node)) {
if (isInJavaScriptFile(node)) {
if (isInJSFile(node)) {
for (const j of node.jsDoc!) {
bind(j);
}
@@ -2075,7 +2079,7 @@ namespace ts {
if (isSpecialPropertyDeclaration(node as PropertyAccessExpression)) {
bindSpecialPropertyDeclaration(node as PropertyAccessExpression);
}
if (isInJavaScriptFile(node) &&
if (isInJSFile(node) &&
file.commonJsModuleIndicator &&
isModuleExportsPropertyAccessExpression(node as PropertyAccessExpression) &&
!lookupSymbolForNameWorker(blockScopeContainer, "module" as __String)) {
@@ -2084,27 +2088,27 @@ namespace ts {
}
break;
case SyntaxKind.BinaryExpression:
const specialKind = getSpecialPropertyAssignmentKind(node as BinaryExpression);
const specialKind = getAssignmentDeclarationKind(node as BinaryExpression);
switch (specialKind) {
case SpecialPropertyAssignmentKind.ExportsProperty:
case AssignmentDeclarationKind.ExportsProperty:
bindExportsPropertyAssignment(node as BinaryExpression);
break;
case SpecialPropertyAssignmentKind.ModuleExports:
case AssignmentDeclarationKind.ModuleExports:
bindModuleExportsAssignment(node as BinaryExpression);
break;
case SpecialPropertyAssignmentKind.PrototypeProperty:
case AssignmentDeclarationKind.PrototypeProperty:
bindPrototypePropertyAssignment((node as BinaryExpression).left as PropertyAccessEntityNameExpression, node);
break;
case SpecialPropertyAssignmentKind.Prototype:
case AssignmentDeclarationKind.Prototype:
bindPrototypeAssignment(node as BinaryExpression);
break;
case SpecialPropertyAssignmentKind.ThisProperty:
case AssignmentDeclarationKind.ThisProperty:
bindThisPropertyAssignment(node as BinaryExpression);
break;
case SpecialPropertyAssignmentKind.Property:
case AssignmentDeclarationKind.Property:
bindSpecialPropertyAssignment(node as BinaryExpression);
break;
case SpecialPropertyAssignmentKind.None:
case AssignmentDeclarationKind.None:
// Nothing to do
break;
default:
@@ -2184,7 +2188,7 @@ namespace ts {
return bindFunctionExpression(<FunctionExpression>node);
case SyntaxKind.CallExpression:
if (isInJavaScriptFile(node)) {
if (isInJSFile(node)) {
bindCallExpression(<CallExpression>node);
}
break;
@@ -2286,14 +2290,19 @@ namespace ts {
bindAnonymousDeclaration(node, SymbolFlags.Alias, getDeclarationName(node)!);
}
else {
const flags = node.kind === SyntaxKind.ExportAssignment && exportAssignmentIsAlias(node)
const flags = exportAssignmentIsAlias(node)
// An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression;
? SymbolFlags.Alias
// An export default clause with any other expression exports a value
: SymbolFlags.Property;
// If there is an `export default x;` alias declaration, can't `export default` anything else.
// (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.)
declareSymbol(container.symbol.exports, container.symbol, node, flags, SymbolFlags.All);
const symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, SymbolFlags.All);
if (node.isExportEquals) {
// Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set.
setValueDeclaration(symbol, node);
}
}
}
@@ -2361,7 +2370,7 @@ namespace ts {
const lhs = node.left as PropertyAccessEntityNameExpression;
const symbol = forEachIdentifierInEntityName(lhs.expression, /*parent*/ undefined, (id, symbol) => {
if (symbol) {
addDeclarationToSymbol(symbol, id, SymbolFlags.Module | SymbolFlags.JSContainer);
addDeclarationToSymbol(symbol, id, SymbolFlags.Module | SymbolFlags.Assignment);
}
return symbol;
});
@@ -2394,7 +2403,7 @@ namespace ts {
}
function bindThisPropertyAssignment(node: BinaryExpression | PropertyAccessExpression) {
Debug.assert(isInJavaScriptFile(node));
Debug.assert(isInJSFile(node));
const thisContainer = getThisContainer(node, /*includeArrowFunctions*/ false);
switch (thisContainer.kind) {
case SyntaxKind.FunctionDeclaration:
@@ -2482,7 +2491,7 @@ namespace ts {
const lhs = node.left as PropertyAccessEntityNameExpression;
// Class declarations in Typescript do not allow property declarations
const parentSymbol = lookupSymbolForPropertyAccess(lhs.expression);
if (!isInJavaScriptFile(node) && !isFunctionSymbol(parentSymbol)) {
if (!isInJSFile(node) && !isFunctionSymbol(parentSymbol)) {
return;
}
// Fix up parent pointers since we're going to use these nodes before we bind into them
@@ -2515,8 +2524,8 @@ namespace ts {
: propertyAccess.parent.parent.kind === SyntaxKind.SourceFile;
if (!isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & SymbolFlags.Namespace)) && isToplevel) {
// make symbols or add declarations for intermediate containers
const flags = SymbolFlags.Module | SymbolFlags.JSContainer;
const excludeFlags = SymbolFlags.ValueModuleExcludes & ~SymbolFlags.JSContainer;
const flags = SymbolFlags.Module | SymbolFlags.Assignment;
const excludeFlags = SymbolFlags.ValueModuleExcludes & ~SymbolFlags.Assignment;
namespaceSymbol = forEachIdentifierInEntityName(propertyAccess.expression, namespaceSymbol, (id, symbol, parent) => {
if (symbol) {
addDeclarationToSymbol(symbol, id, flags);
@@ -2527,7 +2536,7 @@ namespace ts {
}
});
}
if (!namespaceSymbol || !isJavascriptContainer(namespaceSymbol)) {
if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) {
return;
}
@@ -2536,14 +2545,14 @@ namespace ts {
(namespaceSymbol.members || (namespaceSymbol.members = createSymbolTable())) :
(namespaceSymbol.exports || (namespaceSymbol.exports = createSymbolTable()));
const isMethod = isFunctionLikeDeclaration(getAssignedJavascriptInitializer(propertyAccess)!);
const isMethod = isFunctionLikeDeclaration(getAssignedExpandoInitializer(propertyAccess)!);
const includes = isMethod ? SymbolFlags.Method : SymbolFlags.Property;
const excludes = isMethod ? SymbolFlags.MethodExcludes : SymbolFlags.PropertyExcludes;
declareSymbol(symbolTable, namespaceSymbol, propertyAccess, includes | SymbolFlags.JSContainer, excludes & ~SymbolFlags.JSContainer);
declareSymbol(symbolTable, namespaceSymbol, propertyAccess, includes | SymbolFlags.Assignment, excludes & ~SymbolFlags.Assignment);
}
/**
* Javascript containers are:
* Javascript expando values are:
* - Functions
* - classes
* - namespaces
@@ -2552,7 +2561,7 @@ namespace ts {
* - with empty object literals
* - with non-empty object literals if assigned to the prototype property
*/
function isJavascriptContainer(symbol: Symbol): boolean {
function isExpandoSymbol(symbol: Symbol): boolean {
if (symbol.flags & (SymbolFlags.Function | SymbolFlags.Class | SymbolFlags.NamespaceModule)) {
return true;
}
@@ -2565,7 +2574,7 @@ namespace ts {
init = init && getRightMostAssignedExpression(init);
if (init) {
const isPrototypeAssignment = isPrototypeAccess(isVariableDeclaration(node) ? node.name : isBinaryExpression(node) ? node.left : node);
return !!getJavascriptInitializer(isBinaryExpression(init) && init.operatorToken.kind === SyntaxKind.BarBarToken ? init.right : init, isPrototypeAssignment);
return !!getExpandoInitializer(isBinaryExpression(init) && init.operatorToken.kind === SyntaxKind.BarBarToken ? init.right : init, isPrototypeAssignment);
}
return false;
}
@@ -2657,7 +2666,7 @@ namespace ts {
}
if (!isBindingPattern(node.name)) {
const isEnum = !!getJSDocEnumTag(node);
const isEnum = isInJSFile(node) && !!getJSDocEnumTag(node);
const enumFlags = (isEnum ? SymbolFlags.RegularEnum : SymbolFlags.None);
const enumExcludes = (isEnum ? SymbolFlags.RegularEnumExcludes : SymbolFlags.None);
if (isBlockOrCatchScoped(node)) {
+306 -212
View File
File diff suppressed because it is too large Load Diff
+36
View File
@@ -2088,6 +2088,30 @@
"category": "Error",
"code": 2577
},
"Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`.": {
"category": "Error",
"code": 2580
},
"Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`.": {
"category": "Error",
"code": 2581
},
"Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`.": {
"category": "Error",
"code": 2582
},
"Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.": {
"category": "Error",
"code": 2583
},
"Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'.": {
"category": "Error",
"code": 2584
},
"'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.": {
"category": "Error",
"code": 2585
},
"JSX element attributes type '{0}' may not be a union type.": {
"category": "Error",
"code": 2600
@@ -2457,6 +2481,10 @@
"category": "Error",
"code": 2733
},
"It is highly likely that you are missing a semicolon.": {
"category": "Error",
"code": 2734
},
"Import declaration '{0}' is using private name '{1}'.": {
"category": "Error",
@@ -3719,6 +3747,14 @@
"category": "Message",
"code": 6211
},
"Did you mean to call this expression?": {
"category": "Message",
"code": 6212
},
"Did you mean to use `new` with this expression?": {
"category": "Message",
"code": 6213
},
"Projects to reference": {
"category": "Message",
+6 -6
View File
@@ -52,7 +52,7 @@ namespace ts {
const jsFilePath = getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options));
const sourceMapFilePath = isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options);
// For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error
const isJs = isSourceFileJavaScript(sourceFile);
const isJs = isSourceFileJS(sourceFile);
const declarationFilePath = ((forceDtsPaths || getEmitDeclarations(options)) && !isJs) ? getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined;
const declarationMapPath = getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
return { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, bundleInfoPath: undefined };
@@ -80,7 +80,7 @@ namespace ts {
}
if (options.jsx === JsxEmit.Preserve) {
if (isSourceFileJavaScript(sourceFile)) {
if (isSourceFileJS(sourceFile)) {
if (fileExtensionIs(sourceFile.fileName, Extension.Jsx)) {
return Extension.Jsx;
}
@@ -187,12 +187,12 @@ namespace ts {
}
function emitDeclarationFileOrBundle(sourceFileOrBundle: SourceFile | Bundle, declarationFilePath: string | undefined, declarationMapPath: string | undefined) {
if (!(declarationFilePath && !isInJavaScriptFile(sourceFileOrBundle))) {
if (!(declarationFilePath && !isInJSFile(sourceFileOrBundle))) {
return;
}
const sourceFiles = isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
// Setup and perform the transformation to retrieve declarations from the input files
const nonJsFiles = filter(sourceFiles, isSourceFileNotJavaScript);
const nonJsFiles = filter(sourceFiles, isSourceFileNotJS);
const inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [createBundle(nonJsFiles, !isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles;
if (emitOnlyDtsFiles && !getEmitDeclarations(compilerOptions)) {
// Checker wont collect the linked aliases since thats only done when declaration is enabled.
@@ -1015,7 +1015,7 @@ namespace ts {
writeLines(helper.text);
}
else {
writeLines(helper.text(makeFileLevelOptmiisticUniqueName));
writeLines(helper.text(makeFileLevelOptimisticUniqueName));
}
helpersEmitted = true;
}
@@ -3588,7 +3588,7 @@ namespace ts {
}
}
function makeFileLevelOptmiisticUniqueName(name: string) {
function makeFileLevelOptimisticUniqueName(name: string) {
return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true);
}
+4 -4
View File
@@ -74,7 +74,7 @@ namespace ts {
if (!resolved) {
return undefined;
}
Debug.assert(extensionIsTypeScript(resolved.extension));
Debug.assert(extensionIsTS(resolved.extension));
return { fileName: resolved.path, packageId: resolved.packageId };
}
@@ -778,7 +778,7 @@ namespace ts {
* Throws an error if the module can't be resolved.
*/
/* @internal */
export function resolveJavaScriptModule(moduleName: string, initialDir: string, host: ModuleResolutionHost): string {
export function resolveJSModule(moduleName: string, initialDir: string, host: ModuleResolutionHost): string {
const { resolvedModule, failedLookupLocations } =
nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true);
if (!resolvedModule) {
@@ -958,7 +958,7 @@ namespace ts {
// If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one;
// e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts"
if (hasJavaScriptFileExtension(candidate)) {
if (hasJSFileExtension(candidate)) {
const extensionless = removeFileExtension(candidate);
if (state.traceEnabled) {
const extension = candidate.substring(extensionless.length);
@@ -1052,7 +1052,7 @@ namespace ts {
const jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state);
if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) {
const potentialSubModule = jsPath.substring(packageDirectory.length + 1);
subModuleName = (forEach(supportedJavascriptExtensions, extension =>
subModuleName = (forEach(supportedJSExtensions, extension =>
tryRemoveExtension(potentialSubModule, extension)) || potentialSubModule) + Extension.Dts;
}
else {
+4 -4
View File
@@ -30,7 +30,7 @@ namespace ts.moduleSpecifiers {
function getPreferencesForUpdate(compilerOptions: CompilerOptions, oldImportSpecifier: string): Preferences {
return {
relativePreference: isExternalModuleNameRelative(oldImportSpecifier) ? RelativePreference.Relative : RelativePreference.NonRelative,
ending: hasJavaScriptOrJsonFileExtension(oldImportSpecifier) ? Ending.JsExtension
ending: hasJSOrJsonFileExtension(oldImportSpecifier) ? Ending.JsExtension
: getEmitModuleResolutionKind(compilerOptions) !== ModuleResolutionKind.NodeJs || endsWith(oldImportSpecifier, "index") ? Ending.Index : Ending.Minimal,
};
}
@@ -148,7 +148,7 @@ namespace ts.moduleSpecifiers {
}
function usesJsExtensionOnImports({ imports }: SourceFile): boolean {
return firstDefined(imports, ({ text }) => pathIsRelative(text) ? hasJavaScriptOrJsonFileExtension(text) : undefined) || false;
return firstDefined(imports, ({ text }) => pathIsRelative(text) ? hasJSOrJsonFileExtension(text) : undefined) || false;
}
function stringsEqual(a: string, b: string, getCanonicalFileName: GetCanonicalFileName): boolean {
@@ -415,13 +415,13 @@ namespace ts.moduleSpecifiers {
case Ending.Index:
return noExtension;
case Ending.JsExtension:
return noExtension + getJavaScriptExtensionForFile(fileName, options);
return noExtension + getJSExtensionForFile(fileName, options);
default:
return Debug.assertNever(ending);
}
}
function getJavaScriptExtensionForFile(fileName: string, options: CompilerOptions): Extension {
function getJSExtensionForFile(fileName: string, options: CompilerOptions): Extension {
const ext = extensionFromPath(fileName);
switch (ext) {
case Extension.Ts:
+23 -25
View File
@@ -6517,7 +6517,7 @@ namespace ts {
}
}
function skipWhitespaceOrAsterisk(): void {
function skipWhitespaceOrAsterisk(next: () => void): void {
if (token() === SyntaxKind.WhitespaceTrivia || token() === SyntaxKind.NewLineTrivia) {
if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
@@ -6532,7 +6532,7 @@ namespace ts {
else if (token() === SyntaxKind.AsteriskToken) {
precedingLineBreak = false;
}
nextJSDocToken();
next();
}
}
@@ -6542,8 +6542,9 @@ namespace ts {
atToken.end = scanner.getTextPos();
nextJSDocToken();
const tagName = parseJSDocIdentifierName();
skipWhitespaceOrAsterisk();
// Use 'nextToken' instead of 'nextJsDocToken' so we can parse a type like 'number' in `@enum number`
const tagName = parseJSDocIdentifierName(/*message*/ undefined, nextToken);
skipWhitespaceOrAsterisk(nextToken);
let tag: JSDocTag | undefined;
switch (tagName.escapedText) {
@@ -6687,7 +6688,7 @@ namespace ts {
}
function tryParseTypeExpression(): JSDocTypeExpression | undefined {
skipWhitespaceOrAsterisk();
skipWhitespaceOrAsterisk(nextJSDocToken);
return token() === SyntaxKind.OpenBraceToken ? parseJSDocTypeExpression() : undefined;
}
@@ -6724,10 +6725,10 @@ namespace ts {
}
}
function parseParameterOrPropertyTag(atToken: AtToken, tagName: Identifier, target: PropertyLikeParse, indent: number | undefined): JSDocParameterTag | JSDocPropertyTag {
function parseParameterOrPropertyTag(atToken: AtToken, tagName: Identifier, target: PropertyLikeParse, indent: number): JSDocParameterTag | JSDocPropertyTag {
let typeExpression = tryParseTypeExpression();
let isNameFirst = !typeExpression;
skipWhitespaceOrAsterisk();
skipWhitespaceOrAsterisk(nextJSDocToken);
const { name, isBracketed } = parseBracketNameInPropertyAndParamTag();
skipWhitespace();
@@ -6739,9 +6740,8 @@ namespace ts {
const result = target === PropertyLikeParse.Property ?
<JSDocPropertyTag>createNode(SyntaxKind.JSDocPropertyTag, atToken.pos) :
<JSDocParameterTag>createNode(SyntaxKind.JSDocParameterTag, atToken.pos);
let comment: string | undefined;
if (indent !== undefined) comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos);
const nestedTypeLiteral = target !== PropertyLikeParse.CallbackParameter && parseNestedTypeLiteral(typeExpression, name, target);
const comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos);
const nestedTypeLiteral = target !== PropertyLikeParse.CallbackParameter && parseNestedTypeLiteral(typeExpression, name, target, indent);
if (nestedTypeLiteral) {
typeExpression = nestedTypeLiteral;
isNameFirst = true;
@@ -6756,14 +6756,14 @@ namespace ts {
return finishNode(result);
}
function parseNestedTypeLiteral(typeExpression: JSDocTypeExpression | undefined, name: EntityName, target: PropertyLikeParse) {
function parseNestedTypeLiteral(typeExpression: JSDocTypeExpression | undefined, name: EntityName, target: PropertyLikeParse, indent: number) {
if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
const typeLiteralExpression = <JSDocTypeExpression>createNode(SyntaxKind.JSDocTypeExpression, scanner.getTokenPos());
let child: JSDocPropertyLikeTag | JSDocTypeTag | false;
let jsdocTypeLiteral: JSDocTypeLiteral;
const start = scanner.getStartPos();
let children: JSDocPropertyLikeTag[] | undefined;
while (child = tryParse(() => parseChildParameterOrPropertyTag(target, name))) {
while (child = tryParse(() => parseChildParameterOrPropertyTag(target, indent, name))) {
if (child.kind === SyntaxKind.JSDocParameterTag || child.kind === SyntaxKind.JSDocPropertyTag) {
children = append(children, child);
}
@@ -6862,7 +6862,7 @@ namespace ts {
function parseTypedefTag(atToken: AtToken, tagName: Identifier, indent: number): JSDocTypedefTag {
const typeExpression = tryParseTypeExpression();
skipWhitespaceOrAsterisk();
skipWhitespaceOrAsterisk(nextJSDocToken);
const typedefTag = <JSDocTypedefTag>createNode(SyntaxKind.JSDocTypedefTag, atToken.pos);
typedefTag.atToken = atToken;
@@ -6879,7 +6879,7 @@ namespace ts {
let jsdocTypeLiteral: JSDocTypeLiteral | undefined;
let childTypeTag: JSDocTypeTag | undefined;
const start = atToken.pos;
while (child = tryParse(() => parseChildPropertyTag())) {
while (child = tryParse(() => parseChildPropertyTag(indent))) {
if (!jsdocTypeLiteral) {
jsdocTypeLiteral = <JSDocTypeLiteral>createNode(SyntaxKind.JSDocTypeLiteral, start);
}
@@ -6945,7 +6945,7 @@ namespace ts {
const start = scanner.getStartPos();
const jsdocSignature = createNode(SyntaxKind.JSDocSignature, start) as JSDocSignature;
jsdocSignature.parameters = [];
while (child = tryParse(() => parseChildParameterOrPropertyTag(PropertyLikeParse.CallbackParameter) as JSDocParameterTag)) {
while (child = tryParse(() => parseChildParameterOrPropertyTag(PropertyLikeParse.CallbackParameter, indent) as JSDocParameterTag)) {
jsdocSignature.parameters = append(jsdocSignature.parameters as MutableNodeArray<JSDocParameterTag>, child);
}
const returnTag = tryParse(() => {
@@ -6988,18 +6988,18 @@ namespace ts {
return a.escapedText === b.escapedText;
}
function parseChildPropertyTag() {
return parseChildParameterOrPropertyTag(PropertyLikeParse.Property) as JSDocTypeTag | JSDocPropertyTag | false;
function parseChildPropertyTag(indent: number) {
return parseChildParameterOrPropertyTag(PropertyLikeParse.Property, indent) as JSDocTypeTag | JSDocPropertyTag | false;
}
function parseChildParameterOrPropertyTag(target: PropertyLikeParse, name?: EntityName): JSDocTypeTag | JSDocPropertyTag | JSDocParameterTag | false {
function parseChildParameterOrPropertyTag(target: PropertyLikeParse, indent: number, name?: EntityName): JSDocTypeTag | JSDocPropertyTag | JSDocParameterTag | false {
let canParseTag = true;
let seenAsterisk = false;
while (true) {
switch (nextJSDocToken()) {
case SyntaxKind.AtToken:
if (canParseTag) {
const child = tryParseChildTag(target);
const child = tryParseChildTag(target, indent);
if (child && (child.kind === SyntaxKind.JSDocParameterTag || child.kind === SyntaxKind.JSDocPropertyTag) &&
target !== PropertyLikeParse.CallbackParameter &&
name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
@@ -7028,7 +7028,7 @@ namespace ts {
}
}
function tryParseChildTag(target: PropertyLikeParse): JSDocTypeTag | JSDocPropertyTag | JSDocParameterTag | false {
function tryParseChildTag(target: PropertyLikeParse, indent: number): JSDocTypeTag | JSDocPropertyTag | JSDocParameterTag | false {
Debug.assert(token() === SyntaxKind.AtToken);
const atToken = <AtToken>createNode(SyntaxKind.AtToken);
atToken.end = scanner.getTextPos();
@@ -7055,9 +7055,7 @@ namespace ts {
if (!(target & t)) {
return false;
}
const tag = parseParameterOrPropertyTag(atToken, tagName, target, /*indent*/ undefined);
tag.comment = parseTagComments(tag.end - tag.pos);
return tag;
return parseParameterOrPropertyTag(atToken, tagName, target, indent);
}
function parseTemplateTag(atToken: AtToken, tagName: Identifier): JSDocTemplateTag {
@@ -7117,7 +7115,7 @@ namespace ts {
return entity;
}
function parseJSDocIdentifierName(message?: DiagnosticMessage): Identifier {
function parseJSDocIdentifierName(message?: DiagnosticMessage, next: () => void = nextJSDocToken): Identifier {
if (!tokenIsIdentifierOrKeyword(token())) {
return createMissingNode<Identifier>(SyntaxKind.Identifier, /*reportAtCurrentPosition*/ !message, message || Diagnostics.Identifier_expected);
}
@@ -7128,7 +7126,7 @@ namespace ts {
result.escapedText = escapeLeadingUnderscores(scanner.getTokenText());
finishNode(result, end);
nextJSDocToken();
next();
return result;
}
}
+7 -7
View File
@@ -1438,9 +1438,9 @@ namespace ts {
function getSyntacticDiagnosticsForFile(sourceFile: SourceFile): ReadonlyArray<DiagnosticWithLocation> {
// For JavaScript files, we report semantic errors for using TypeScript-only
// constructs from within a JavaScript file as syntactic errors.
if (isSourceFileJavaScript(sourceFile)) {
if (isSourceFileJS(sourceFile)) {
if (!sourceFile.additionalSyntacticDiagnostics) {
sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile);
sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile);
}
return concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics);
}
@@ -1538,7 +1538,7 @@ namespace ts {
return true;
}
function getJavaScriptSyntacticDiagnosticsForFile(sourceFile: SourceFile): DiagnosticWithLocation[] {
function getJSSyntacticDiagnosticsForFile(sourceFile: SourceFile): DiagnosticWithLocation[] {
return runWithCancellationToken(() => {
const diagnostics: DiagnosticWithLocation[] = [];
let parent: Node = sourceFile;
@@ -1801,7 +1801,7 @@ namespace ts {
return;
}
const isJavaScriptFile = isSourceFileJavaScript(file);
const isJavaScriptFile = isSourceFileJS(file);
const isExternalModuleFile = isExternalModule(file);
// file.imports may not be undefined if there exists dynamic import
@@ -2273,7 +2273,7 @@ namespace ts {
}
const isFromNodeModulesSearch = resolution.isExternalLibraryImport;
const isJsFile = !resolutionExtensionIsTypeScriptOrJson(resolution.extension);
const isJsFile = !resolutionExtensionIsTSOrJson(resolution.extension);
const isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile;
const resolvedFileName = resolution.resolvedFileName;
@@ -2295,7 +2295,7 @@ namespace ts {
&& i < file.imports.length
&& !elideImport
&& !(isJsFile && !options.allowJs)
&& (isInJavaScriptFile(file.imports[i]) || !(file.imports[i].flags & NodeFlags.JSDoc));
&& (isInJSFile(file.imports[i]) || !(file.imports[i].flags & NodeFlags.JSDoc));
if (elideImport) {
modulesWithElidedImports.set(file.path, true);
@@ -2794,7 +2794,7 @@ namespace ts {
return containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames());
}
if (fileExtensionIsOneOf(filePath, supportedJavascriptExtensions) || fileExtensionIs(filePath, Extension.Dts)) {
if (fileExtensionIsOneOf(filePath, supportedJSExtensions) || fileExtensionIs(filePath, Extension.Dts)) {
// Otherwise just check if sourceFile with the name exists
const filePathWithoutExtension = removeFileExtension(filePath);
return !!getSourceFileByPath((filePathWithoutExtension + Extension.Ts) as Path) ||
+1 -1
View File
@@ -226,7 +226,7 @@ namespace ts {
// otherwise try to load typings from @types
const globalCache = resolutionHost.getGlobalCache();
if (globalCache !== undefined && !isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && extensionIsTypeScript(primaryResult.resolvedModule.extension))) {
if (globalCache !== undefined && !isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && extensionIsTS(primaryResult.resolvedModule.extension))) {
// create different collection of failed lookup locations for second pass
// if it will fail and we've already found something during the first pass - we don't want to pollute its results
const { resolvedModule, failedLookupLocations } = loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache);
+10 -6
View File
@@ -317,18 +317,22 @@ namespace ts {
const newTime = modifiedTime.getTime();
if (oldTime !== newTime) {
watchedFile.mtime = modifiedTime;
const eventKind = oldTime === 0
? FileWatcherEventKind.Created
: newTime === 0
? FileWatcherEventKind.Deleted
: FileWatcherEventKind.Changed;
watchedFile.callback(watchedFile.fileName, eventKind);
watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime));
return true;
}
return false;
}
/*@internal*/
export function getFileWatcherEventKind(oldTime: number, newTime: number) {
return oldTime === 0
? FileWatcherEventKind.Created
: newTime === 0
? FileWatcherEventKind.Deleted
: FileWatcherEventKind.Changed;
}
/*@internal*/
export interface RecursiveDirectoryWatcherHost {
watchDirectory: HostWatchDirectory;
+6 -6
View File
@@ -1,11 +1,11 @@
/*@internal*/
namespace ts {
export function getDeclarationDiagnostics(host: EmitHost, resolver: EmitResolver, file: SourceFile | undefined): DiagnosticWithLocation[] | undefined {
if (file && isSourceFileJavaScript(file)) {
if (file && isSourceFileJS(file)) {
return []; // No declaration diagnostics for js for now
}
const compilerOptions = host.getCompilerOptions();
const result = transformNodes(resolver, host, compilerOptions, file ? [file] : filter(host.getSourceFiles(), isSourceFileNotJavaScript), [transformDeclarations], /*allowDtsFiles*/ false);
const result = transformNodes(resolver, host, compilerOptions, file ? [file] : filter(host.getSourceFiles(), isSourceFileNotJS), [transformDeclarations], /*allowDtsFiles*/ false);
return result.diagnostics;
}
@@ -157,7 +157,7 @@ namespace ts {
function transformRoot(node: SourceFile): SourceFile;
function transformRoot(node: SourceFile | Bundle): SourceFile | Bundle;
function transformRoot(node: SourceFile | Bundle) {
if (node.kind === SyntaxKind.SourceFile && (node.isDeclarationFile || isSourceFileJavaScript(node))) {
if (node.kind === SyntaxKind.SourceFile && (node.isDeclarationFile || isSourceFileJS(node))) {
return node;
}
@@ -168,7 +168,7 @@ namespace ts {
let hasNoDefaultLib = false;
const bundle = createBundle(map(node.sourceFiles,
sourceFile => {
if (sourceFile.isDeclarationFile || isSourceFileJavaScript(sourceFile)) return undefined!; // Omit declaration files from bundle results, too // TODO: GH#18217
if (sourceFile.isDeclarationFile || isSourceFileJS(sourceFile)) return undefined!; // Omit declaration files from bundle results, too // TODO: GH#18217
hasNoDefaultLib = hasNoDefaultLib || sourceFile.hasNoDefaultLib;
currentSourceFile = sourceFile;
enclosingDeclaration = sourceFile;
@@ -303,7 +303,7 @@ namespace ts {
}
function collectReferences(sourceFile: SourceFile, ret: Map<SourceFile>) {
if (noResolve || isSourceFileJavaScript(sourceFile)) return ret;
if (noResolve || isSourceFileJS(sourceFile)) return ret;
forEach(sourceFile.referencedFiles, f => {
const elem = tryResolveScriptReference(host, sourceFile, f);
if (elem) {
@@ -989,7 +989,7 @@ namespace ts {
ensureType(input, input.type),
/*body*/ undefined
));
if (clean && resolver.isJSContainerFunctionDeclaration(input)) {
if (clean && resolver.isExpandoFunctionDeclaration(input)) {
const declarations = mapDefined(resolver.getPropertiesOfContainerFunction(input), p => {
if (!isPropertyAccessExpression(p.valueDeclaration)) {
return undefined;
+2 -2
View File
@@ -254,7 +254,7 @@ namespace ts {
return changeExtension(outputPath, Extension.Dts);
}
function getOutputJavaScriptFileName(inputFileName: string, configFile: ParsedCommandLine) {
function getOutputJSFileName(inputFileName: string, configFile: ParsedCommandLine) {
const relativePath = getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath!), inputFileName, /*ignoreCase*/ true);
const outputPath = resolvePath(configFile.options.outDir || getDirectoryPath(configFile.options.configFilePath!), relativePath);
const newExtension = fileExtensionIs(inputFileName, Extension.Json) ? Extension.Json :
@@ -269,7 +269,7 @@ namespace ts {
}
const outputs: string[] = [];
const js = getOutputJavaScriptFileName(inputFileName, configFile);
const js = getOutputJSFileName(inputFileName, configFile);
outputs.push(js);
if (configFile.options.sourceMap) {
outputs.push(`${js}.map`);
+6 -6
View File
@@ -3383,7 +3383,7 @@ namespace ts {
isImplementationOfOverload(node: FunctionLike): boolean | undefined;
isRequiredInitializedParameter(node: ParameterDeclaration): boolean;
isOptionalUninitializedParameterProperty(node: ParameterDeclaration): boolean;
isJSContainerFunctionDeclaration(node: FunctionDeclaration): boolean;
isExpandoFunctionDeclaration(node: FunctionDeclaration): boolean;
getPropertiesOfContainerFunction(node: Declaration): Symbol[];
createTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration | PropertyAccessExpression, enclosingDeclaration: Node, flags: NodeBuilderFlags, tracker: SymbolTracker, addUndefined?: boolean): TypeNode | undefined;
createReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: NodeBuilderFlags, tracker: SymbolTracker): TypeNode | undefined;
@@ -3435,7 +3435,7 @@ namespace ts {
ExportStar = 1 << 23, // Export * declaration
Optional = 1 << 24, // Optional property
Transient = 1 << 25, // Transient symbol (created during type check)
JSContainer = 1 << 26, // Contains Javascript special declarations
Assignment = 1 << 26, // Assignment treated as declaration (eg `this.prop = 1`)
ModuleExports = 1 << 27, // Symbol for CommonJS `module` of `module.exports`
/* @internal */
@@ -3444,8 +3444,8 @@ namespace ts {
Enum = RegularEnum | ConstEnum,
Variable = FunctionScopedVariable | BlockScopedVariable,
Value = Variable | Property | EnumMember | ObjectLiteral | Function | Class | Enum | ValueModule | Method | GetAccessor | SetAccessor | JSContainer,
Type = Class | Interface | Enum | EnumMember | TypeLiteral | TypeParameter | TypeAlias | JSContainer,
Value = Variable | Property | EnumMember | ObjectLiteral | Function | Class | Enum | ValueModule | Method | GetAccessor | SetAccessor | Assignment,
Type = Class | Interface | Enum | EnumMember | TypeLiteral | TypeParameter | TypeAlias | Assignment,
Namespace = ValueModule | NamespaceModule | Enum,
Module = ValueModule | NamespaceModule,
Accessor = GetAccessor | SetAccessor,
@@ -3466,7 +3466,7 @@ namespace ts {
InterfaceExcludes = Type & ~(Interface | Class),
RegularEnumExcludes = (Value | Type) & ~(RegularEnum | ValueModule), // regular enums merge only with regular enums and modules
ConstEnumExcludes = (Value | Type) & ~ConstEnum, // const enums merge only with const enums
ValueModuleExcludes = Value & ~(Function | Class | RegularEnum | ValueModule | JSContainer),
ValueModuleExcludes = Value & ~(Function | Class | RegularEnum | ValueModule | Assignment),
NamespaceModuleExcludes = 0,
MethodExcludes = Value & ~Method,
GetAccessorExcludes = Value & ~SetAccessor,
@@ -4219,7 +4219,7 @@ namespace ts {
}
/* @internal */
export const enum SpecialPropertyAssignmentKind {
export const enum AssignmentDeclarationKind {
None,
/// exports.name = expr
ExportsProperty,
+86 -77
View File
@@ -1678,15 +1678,15 @@ namespace ts {
return node.kind === SyntaxKind.ImportEqualsDeclaration && (<ImportEqualsDeclaration>node).moduleReference.kind !== SyntaxKind.ExternalModuleReference;
}
export function isSourceFileJavaScript(file: SourceFile): boolean {
return isInJavaScriptFile(file);
export function isSourceFileJS(file: SourceFile): boolean {
return isInJSFile(file);
}
export function isSourceFileNotJavaScript(file: SourceFile): boolean {
return !isInJavaScriptFile(file);
export function isSourceFileNotJS(file: SourceFile): boolean {
return !isInJSFile(file);
}
export function isInJavaScriptFile(node: Node | undefined): boolean {
export function isInJSFile(node: Node | undefined): boolean {
return !!node && !!(node.flags & NodeFlags.JavaScriptFile);
}
@@ -1738,14 +1738,14 @@ namespace ts {
return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === CharacterCodes.doubleQuote;
}
export function getDeclarationOfJSInitializer(node: Node): Node | undefined {
export function getDeclarationOfExpando(node: Node): Node | undefined {
if (!node.parent) {
return undefined;
}
let name: Expression | BindingName | undefined;
let decl: Node | undefined;
if (isVariableDeclaration(node.parent) && node.parent.initializer === node) {
if (!isInJavaScriptFile(node) && !isVarConst(node.parent)) {
if (!isInJSFile(node) && !isVarConst(node.parent)) {
return undefined;
}
name = node.parent.name;
@@ -1770,7 +1770,7 @@ namespace ts {
}
}
if (!name || !getJavascriptInitializer(node, isPrototypeAccess(name))) {
if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) {
return undefined;
}
return decl;
@@ -1782,7 +1782,7 @@ namespace ts {
/** Get the initializer, taking into account defaulted Javascript initializers */
export function getEffectiveInitializer(node: HasExpressionInitializer) {
if (isInJavaScriptFile(node) && node.initializer &&
if (isInJSFile(node) && node.initializer &&
isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === SyntaxKind.BarBarToken &&
node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) {
return node.initializer.right;
@@ -1790,26 +1790,26 @@ namespace ts {
return node.initializer;
}
/** Get the declaration initializer when it is container-like (See getJavascriptInitializer). */
export function getDeclaredJavascriptInitializer(node: HasExpressionInitializer) {
/** Get the declaration initializer when it is container-like (See getExpandoInitializer). */
export function getDeclaredExpandoInitializer(node: HasExpressionInitializer) {
const init = getEffectiveInitializer(node);
return init && getJavascriptInitializer(init, isPrototypeAccess(node.name));
return init && getExpandoInitializer(init, isPrototypeAccess(node.name));
}
/**
* Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getJavascriptInitializer).
* Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer).
* We treat the right hand side of assignments with container-like initalizers as declarations.
*/
export function getAssignedJavascriptInitializer(node: Node) {
export function getAssignedExpandoInitializer(node: Node) {
if (node && node.parent && isBinaryExpression(node.parent) && node.parent.operatorToken.kind === SyntaxKind.EqualsToken) {
const isPrototypeAssignment = isPrototypeAccess(node.parent.left);
return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) ||
getDefaultedJavascriptInitializer(node.parent.left as EntityNameExpression, node.parent.right, isPrototypeAssignment);
return getExpandoInitializer(node.parent.right, isPrototypeAssignment) ||
getDefaultedExpandoInitializer(node.parent.left as EntityNameExpression, node.parent.right, isPrototypeAssignment);
}
}
/**
* Recognized Javascript container-like initializers are:
* Recognized expando initializers are:
* 1. (function() {})() -- IIFEs
* 2. function() { } -- Function expressions
* 3. class { } -- Class expressions
@@ -1818,7 +1818,7 @@ namespace ts {
*
* This function returns the provided initializer, or undefined if it is not valid.
*/
export function getJavascriptInitializer(initializer: Node, isPrototypeAssignment: boolean): Expression | undefined {
export function getExpandoInitializer(initializer: Node, isPrototypeAssignment: boolean): Expression | undefined {
if (isCallExpression(initializer)) {
const e = skipParentheses(initializer.expression);
return e.kind === SyntaxKind.FunctionExpression || e.kind === SyntaxKind.ArrowFunction ? initializer : undefined;
@@ -1834,29 +1834,29 @@ namespace ts {
}
/**
* A defaulted Javascript initializer matches the pattern
* `Lhs = Lhs || JavascriptInitializer`
* or `var Lhs = Lhs || JavascriptInitializer`
* A defaulted expando initializer matches the pattern
* `Lhs = Lhs || ExpandoInitializer`
* or `var Lhs = Lhs || ExpandoInitializer`
*
* The second Lhs is required to be the same as the first except that it may be prefixed with
* 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker.
*/
function getDefaultedJavascriptInitializer(name: EntityNameExpression, initializer: Expression, isPrototypeAssignment: boolean) {
const e = isBinaryExpression(initializer) && initializer.operatorToken.kind === SyntaxKind.BarBarToken && getJavascriptInitializer(initializer.right, isPrototypeAssignment);
function getDefaultedExpandoInitializer(name: EntityNameExpression, initializer: Expression, isPrototypeAssignment: boolean) {
const e = isBinaryExpression(initializer) && initializer.operatorToken.kind === SyntaxKind.BarBarToken && getExpandoInitializer(initializer.right, isPrototypeAssignment);
if (e && isSameEntityName(name, (initializer as BinaryExpression).left as EntityNameExpression)) {
return e;
}
}
export function isDefaultedJavascriptInitializer(node: BinaryExpression) {
export function isDefaultedExpandoInitializer(node: BinaryExpression) {
const name = isVariableDeclaration(node.parent) ? node.parent.name :
isBinaryExpression(node.parent) && node.parent.operatorToken.kind === SyntaxKind.EqualsToken ? node.parent.left :
undefined;
return name && getJavascriptInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left);
return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left);
}
/** Given a Javascript initializer, return the outer name. That is, the lhs of the assignment or the declaration name. */
export function getOuterNameOfJsInitializer(node: Declaration): DeclarationName | undefined {
/** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */
export function getNameOfExpando(node: Declaration): DeclarationName | undefined {
if (isBinaryExpression(node.parent)) {
const parent = (node.parent.operatorToken.kind === SyntaxKind.BarBarToken && isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent;
if (parent.operatorToken.kind === SyntaxKind.EqualsToken && isIdentifier(parent.left)) {
@@ -1912,36 +1912,36 @@ namespace ts {
/// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property
/// assignments we treat as special in the binder
export function getSpecialPropertyAssignmentKind(expr: BinaryExpression): SpecialPropertyAssignmentKind {
const special = getSpecialPropertyAssignmentKindWorker(expr);
return special === SpecialPropertyAssignmentKind.Property || isInJavaScriptFile(expr) ? special : SpecialPropertyAssignmentKind.None;
export function getAssignmentDeclarationKind(expr: BinaryExpression): AssignmentDeclarationKind {
const special = getAssignmentDeclarationKindWorker(expr);
return special === AssignmentDeclarationKind.Property || isInJSFile(expr) ? special : AssignmentDeclarationKind.None;
}
function getSpecialPropertyAssignmentKindWorker(expr: BinaryExpression): SpecialPropertyAssignmentKind {
function getAssignmentDeclarationKindWorker(expr: BinaryExpression): AssignmentDeclarationKind {
if (expr.operatorToken.kind !== SyntaxKind.EqualsToken ||
!isPropertyAccessExpression(expr.left)) {
return SpecialPropertyAssignmentKind.None;
return AssignmentDeclarationKind.None;
}
const lhs = expr.left;
if (isEntityNameExpression(lhs.expression) && lhs.name.escapedText === "prototype" && isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) {
// F.prototype = { ... }
return SpecialPropertyAssignmentKind.Prototype;
return AssignmentDeclarationKind.Prototype;
}
return getSpecialPropertyAccessKind(lhs);
return getAssignmentDeclarationPropertyAccessKind(lhs);
}
export function getSpecialPropertyAccessKind(lhs: PropertyAccessExpression): SpecialPropertyAssignmentKind {
export function getAssignmentDeclarationPropertyAccessKind(lhs: PropertyAccessExpression): AssignmentDeclarationKind {
if (lhs.expression.kind === SyntaxKind.ThisKeyword) {
return SpecialPropertyAssignmentKind.ThisProperty;
return AssignmentDeclarationKind.ThisProperty;
}
else if (isIdentifier(lhs.expression) && lhs.expression.escapedText === "module" && lhs.name.escapedText === "exports") {
// module.exports = expr
return SpecialPropertyAssignmentKind.ModuleExports;
return AssignmentDeclarationKind.ModuleExports;
}
else if (isEntityNameExpression(lhs.expression)) {
if (isPrototypeAccess(lhs.expression)) {
// F.G....prototype.x = expr
return SpecialPropertyAssignmentKind.PrototypeProperty;
return AssignmentDeclarationKind.PrototypeProperty;
}
let nextToLast = lhs;
@@ -1953,13 +1953,13 @@ namespace ts {
if (id.escapedText === "exports" ||
id.escapedText === "module" && nextToLast.name.escapedText === "exports") {
// exports.name = expr OR module.exports.name = expr
return SpecialPropertyAssignmentKind.ExportsProperty;
return AssignmentDeclarationKind.ExportsProperty;
}
// F.G...x = expr
return SpecialPropertyAssignmentKind.Property;
return AssignmentDeclarationKind.Property;
}
return SpecialPropertyAssignmentKind.None;
return AssignmentDeclarationKind.None;
}
export function getInitializerOfBinaryExpression(expr: BinaryExpression) {
@@ -1970,11 +1970,11 @@ namespace ts {
}
export function isPrototypePropertyAssignment(node: Node): boolean {
return isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === SpecialPropertyAssignmentKind.PrototypeProperty;
return isBinaryExpression(node) && getAssignmentDeclarationKind(node) === AssignmentDeclarationKind.PrototypeProperty;
}
export function isSpecialPropertyDeclaration(expr: PropertyAccessExpression): boolean {
return isInJavaScriptFile(expr) &&
return isInJSFile(expr) &&
expr.parent && expr.parent.kind === SyntaxKind.ExpressionStatement &&
!!getJSDocTypeTag(expr.parent);
}
@@ -2082,7 +2082,7 @@ namespace ts {
function getSourceOfDefaultedAssignment(node: Node): Node | undefined {
return isExpressionStatement(node) &&
isBinaryExpression(node.expression) &&
getSpecialPropertyAssignmentKind(node.expression) !== SpecialPropertyAssignmentKind.None &&
getAssignmentDeclarationKind(node.expression) !== AssignmentDeclarationKind.None &&
isBinaryExpression(node.expression.right) &&
node.expression.right.operatorToken.kind === SyntaxKind.BarBarToken
? node.expression.right.right
@@ -2402,7 +2402,7 @@ namespace ts {
else {
const binExp = parent.parent;
return isBinaryExpression(binExp) &&
getSpecialPropertyAssignmentKind(binExp) !== SpecialPropertyAssignmentKind.None &&
getAssignmentDeclarationKind(binExp) !== AssignmentDeclarationKind.None &&
(binExp.left.symbol || binExp.symbol) &&
getNameOfDeclaration(binExp) === name
? binExp
@@ -2471,7 +2471,7 @@ namespace ts {
node.kind === SyntaxKind.ImportSpecifier ||
node.kind === SyntaxKind.ExportSpecifier ||
node.kind === SyntaxKind.ExportAssignment && exportAssignmentIsAlias(<ExportAssignment>node) ||
isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === SpecialPropertyAssignmentKind.ModuleExports;
isBinaryExpression(node) && getAssignmentDeclarationKind(node) === AssignmentDeclarationKind.ModuleExports;
}
export function exportAssignmentIsAlias(node: ExportAssignment | BinaryExpression): boolean {
@@ -2480,7 +2480,7 @@ namespace ts {
}
export function getEffectiveBaseTypeNode(node: ClassLikeDeclaration | InterfaceDeclaration) {
if (isInJavaScriptFile(node)) {
if (isInJSFile(node)) {
// Prefer an @augments tag because it may have type parameters.
const tag = getJSDocAugmentsTag(node);
if (tag) {
@@ -3286,7 +3286,7 @@ namespace ts {
/** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */
export function sourceFileMayBeEmitted(sourceFile: SourceFile, options: CompilerOptions, isSourceFileFromExternalLibrary: (file: SourceFile) => boolean) {
return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile);
return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile);
}
export function getSourceFilePathInNewDir(fileName: string, host: EmitHost, newDirPath: string): string {
@@ -3410,7 +3410,7 @@ namespace ts {
*/
export function getEffectiveTypeAnnotationNode(node: Node): TypeNode | undefined {
const type = (node as HasType).type;
if (type || !isInJavaScriptFile(node)) return type;
if (type || !isInJSFile(node)) return type;
return isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : getJSDocType(node);
}
@@ -3425,7 +3425,7 @@ namespace ts {
export function getEffectiveReturnTypeNode(node: SignatureDeclaration | JSDocSignature): TypeNode | undefined {
return isJSDocSignature(node) ?
node.type && node.type.typeExpression && node.type.typeExpression.type :
node.type || (isInJavaScriptFile(node) ? getJSDocReturnType(node) : undefined);
node.type || (isInJSFile(node) ? getJSDocReturnType(node) : undefined);
}
export function getJSDocTypeParameterDeclarations(node: DeclarationWithTypeParameters): ReadonlyArray<TypeParameterDeclaration> {
@@ -3818,8 +3818,8 @@ namespace ts {
}
/** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */
export function tryExtractTypeScriptExtension(fileName: string): string | undefined {
return find(supportedTypescriptExtensionsForExtractExtension, extension => fileExtensionIs(fileName, extension));
export function tryExtractTSExtension(fileName: string): string | undefined {
return find(supportedTSExtensionsForExtractExtension, extension => fileExtensionIs(fileName, extension));
}
/**
* Replace each instance of non-ascii characters by one, two, three, or four escape sequences
@@ -4986,11 +4986,11 @@ namespace ts {
}
case SyntaxKind.BinaryExpression: {
const expr = declaration as BinaryExpression;
switch (getSpecialPropertyAssignmentKind(expr)) {
case SpecialPropertyAssignmentKind.ExportsProperty:
case SpecialPropertyAssignmentKind.ThisProperty:
case SpecialPropertyAssignmentKind.Property:
case SpecialPropertyAssignmentKind.PrototypeProperty:
switch (getAssignmentDeclarationKind(expr)) {
case AssignmentDeclarationKind.ExportsProperty:
case AssignmentDeclarationKind.ThisProperty:
case AssignmentDeclarationKind.Property:
case AssignmentDeclarationKind.PrototypeProperty:
return (expr.left as PropertyAccessExpression).name;
default:
return undefined;
@@ -5207,7 +5207,7 @@ namespace ts {
if (node.typeParameters) {
return node.typeParameters;
}
if (isInJavaScriptFile(node)) {
if (isInJSFile(node)) {
const decls = getJSDocTypeParameterDeclarations(node);
if (decls.length) {
return decls;
@@ -6613,7 +6613,7 @@ namespace ts {
/* @internal */
export function isDeclaration(node: Node): node is NamedDeclaration {
if (node.kind === SyntaxKind.TypeParameter) {
return node.parent.kind !== SyntaxKind.JSDocTemplateTag || isInJavaScriptFile(node);
return node.parent.kind !== SyntaxKind.JSDocTemplateTag || isInJSFile(node);
}
return isDeclarationKind(node.kind);
@@ -7671,6 +7671,15 @@ namespace ts {
// It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future
// proof.
const reservedCharacterPattern = /[^\w\s\/]/g;
export function regExpEscape(text: string) {
return text.replace(reservedCharacterPattern, escapeRegExpCharacter);
}
function escapeRegExpCharacter(match: string) {
return "\\" + match;
}
const wildcardCharCodes = [CharacterCodes.asterisk, CharacterCodes.question];
export function hasExtension(fileName: string): boolean {
@@ -8001,42 +8010,42 @@ namespace ts {
/**
* List of supported extensions in order of file resolution precedence.
*/
export const supportedTypeScriptExtensions: ReadonlyArray<Extension> = [Extension.Ts, Extension.Tsx, Extension.Dts];
export const supportedTSExtensions: ReadonlyArray<Extension> = [Extension.Ts, Extension.Tsx, Extension.Dts];
/** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */
export const supportedTypescriptExtensionsForExtractExtension: ReadonlyArray<Extension> = [Extension.Dts, Extension.Ts, Extension.Tsx];
export const supportedJavascriptExtensions: ReadonlyArray<Extension> = [Extension.Js, Extension.Jsx];
export const supportedJavaScriptAndJsonExtensions: ReadonlyArray<Extension> = [Extension.Js, Extension.Jsx, Extension.Json];
const allSupportedExtensions: ReadonlyArray<Extension> = [...supportedTypeScriptExtensions, ...supportedJavascriptExtensions];
export const supportedTSExtensionsForExtractExtension: ReadonlyArray<Extension> = [Extension.Dts, Extension.Ts, Extension.Tsx];
export const supportedJSExtensions: ReadonlyArray<Extension> = [Extension.Js, Extension.Jsx];
export const supportedJSAndJsonExtensions: ReadonlyArray<Extension> = [Extension.Js, Extension.Jsx, Extension.Json];
const allSupportedExtensions: ReadonlyArray<Extension> = [...supportedTSExtensions, ...supportedJSExtensions];
export function getSupportedExtensions(options?: CompilerOptions, extraFileExtensions?: ReadonlyArray<FileExtensionInfo>): ReadonlyArray<string> {
const needJsExtensions = options && options.allowJs;
if (!extraFileExtensions || extraFileExtensions.length === 0) {
return needJsExtensions ? allSupportedExtensions : supportedTypeScriptExtensions;
return needJsExtensions ? allSupportedExtensions : supportedTSExtensions;
}
const extensions = [
...needJsExtensions ? allSupportedExtensions : supportedTypeScriptExtensions,
...mapDefined(extraFileExtensions, x => x.scriptKind === ScriptKind.Deferred || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined)
...needJsExtensions ? allSupportedExtensions : supportedTSExtensions,
...mapDefined(extraFileExtensions, x => x.scriptKind === ScriptKind.Deferred || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined)
];
return deduplicate<string>(extensions, equateStringsCaseSensitive, compareStringsCaseSensitive);
}
function isJavaScriptLike(scriptKind: ScriptKind | undefined): boolean {
function isJSLike(scriptKind: ScriptKind | undefined): boolean {
return scriptKind === ScriptKind.JS || scriptKind === ScriptKind.JSX;
}
export function hasJavaScriptFileExtension(fileName: string): boolean {
return some(supportedJavascriptExtensions, extension => fileExtensionIs(fileName, extension));
export function hasJSFileExtension(fileName: string): boolean {
return some(supportedJSExtensions, extension => fileExtensionIs(fileName, extension));
}
export function hasJavaScriptOrJsonFileExtension(fileName: string): boolean {
return supportedJavaScriptAndJsonExtensions.some(ext => fileExtensionIs(fileName, ext));
export function hasJSOrJsonFileExtension(fileName: string): boolean {
return supportedJSAndJsonExtensions.some(ext => fileExtensionIs(fileName, ext));
}
export function hasTypeScriptFileExtension(fileName: string): boolean {
return some(supportedTypeScriptExtensions, extension => fileExtensionIs(fileName, extension));
export function hasTSFileExtension(fileName: string): boolean {
return some(supportedTSExtensions, extension => fileExtensionIs(fileName, extension));
}
export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions, extraFileExtensions?: ReadonlyArray<FileExtensionInfo>) {
@@ -8172,12 +8181,12 @@ namespace ts {
}
/** True if an extension is one of the supported TypeScript extensions. */
export function extensionIsTypeScript(ext: Extension): boolean {
export function extensionIsTS(ext: Extension): boolean {
return ext === Extension.Ts || ext === Extension.Tsx || ext === Extension.Dts;
}
export function resolutionExtensionIsTypeScriptOrJson(ext: Extension) {
return extensionIsTypeScript(ext) || ext === Extension.Json;
export function resolutionExtensionIsTSOrJson(ext: Extension) {
return extensionIsTS(ext) || ext === Extension.Json;
}
/**
+18 -11
View File
@@ -593,7 +593,7 @@ namespace FourSlash {
public verifyNoErrors() {
ts.forEachKey(this.inputFiles, fileName => {
if (!ts.isAnySupportedFileExtension(fileName)
|| !this.getProgram().getCompilerOptions().allowJs && !ts.extensionIsTypeScript(ts.extensionFromPath(fileName))) return;
|| !this.getProgram().getCompilerOptions().allowJs && !ts.extensionIsTS(ts.extensionFromPath(fileName))) return;
const errors = this.getDiagnostics(fileName).filter(e => e.category !== ts.DiagnosticCategory.Suggestion);
if (errors.length) {
this.printErrorLog(/*expectErrors*/ false, errors);
@@ -908,8 +908,8 @@ namespace FourSlash {
}
private verifyCompletionEntry(actual: ts.CompletionEntry, expected: FourSlashInterface.ExpectedCompletionEntry) {
const { insertText, replacementSpan, hasAction, isRecommended, kind, text, documentation, source, sourceDisplay } = typeof expected === "string"
? { insertText: undefined, replacementSpan: undefined, hasAction: undefined, isRecommended: undefined, kind: undefined, text: undefined, documentation: undefined, source: undefined, sourceDisplay: undefined }
const { insertText, replacementSpan, hasAction, isRecommended, kind, text, documentation, tags, source, sourceDisplay } = typeof expected === "string"
? { insertText: undefined, replacementSpan: undefined, hasAction: undefined, isRecommended: undefined, kind: undefined, text: undefined, documentation: undefined, tags: undefined, source: undefined, sourceDisplay: undefined }
: expected;
if (actual.insertText !== insertText) {
@@ -929,7 +929,7 @@ namespace FourSlash {
assert.equal(actual.isRecommended, isRecommended);
assert.equal(actual.source, source);
if (text) {
if (text !== undefined) {
const actualDetails = this.getCompletionEntryDetails(actual.name, actual.source)!;
assert.equal(ts.displayPartsToString(actualDetails.displayParts), text);
assert.equal(ts.displayPartsToString(actualDetails.documentation), documentation || "");
@@ -937,9 +937,10 @@ namespace FourSlash {
// assert.equal(actualDetails.kind, actual.kind);
assert.equal(actualDetails.kindModifiers, actual.kindModifiers);
assert.equal(actualDetails.source && ts.displayPartsToString(actualDetails.source), sourceDisplay);
assert.deepEqual(actualDetails.tags, tags);
}
else {
assert(documentation === undefined && sourceDisplay === undefined, "If specifying completion details, should specify 'text'");
assert(documentation === undefined && tags === undefined && sourceDisplay === undefined, "If specifying completion details, should specify 'text'");
}
}
@@ -1363,7 +1364,7 @@ Actual: ${stringify(fullActual)}`);
public verifyQuickInfoDisplayParts(kind: string, kindModifiers: string, textSpan: TextSpan,
displayParts: ts.SymbolDisplayPart[],
documentation: ts.SymbolDisplayPart[],
tags: ts.JSDocTagInfo[]
tags: ts.JSDocTagInfo[] | undefined
) {
const actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition)!;
@@ -1372,11 +1373,16 @@ Actual: ${stringify(fullActual)}`);
assert.equal(JSON.stringify(actualQuickInfo.textSpan), JSON.stringify(textSpan), this.messageAtLastKnownMarker("QuickInfo textSpan"));
assert.equal(TestState.getDisplayPartsJson(actualQuickInfo.displayParts), TestState.getDisplayPartsJson(displayParts), this.messageAtLastKnownMarker("QuickInfo displayParts"));
assert.equal(TestState.getDisplayPartsJson(actualQuickInfo.documentation), TestState.getDisplayPartsJson(documentation), this.messageAtLastKnownMarker("QuickInfo documentation"));
assert.equal(actualQuickInfo.tags!.length, tags.length, this.messageAtLastKnownMarker("QuickInfo tags"));
ts.zipWith(tags, actualQuickInfo.tags!, (expectedTag, actualTag) => {
assert.equal(expectedTag.name, actualTag.name);
assert.equal(expectedTag.text, actualTag.text, this.messageAtLastKnownMarker("QuickInfo tag " + actualTag.name));
});
if (!actualQuickInfo.tags || !tags) {
assert.equal(actualQuickInfo.tags, tags, this.messageAtLastKnownMarker("QuickInfo tags"));
}
else {
assert.equal(actualQuickInfo.tags.length, tags.length, this.messageAtLastKnownMarker("QuickInfo tags"));
ts.zipWith(tags, actualQuickInfo.tags, (expectedTag, actualTag) => {
assert.equal(expectedTag.name, actualTag.name);
assert.equal(expectedTag.text, actualTag.text, this.messageAtLastKnownMarker("QuickInfo tag " + actualTag.name));
});
}
}
public verifyRangesAreRenameLocations(options?: Range[] | { findInStrings?: boolean, findInComments?: boolean, ranges?: Range[] }) {
@@ -4802,6 +4808,7 @@ namespace FourSlashInterface {
readonly text: string;
readonly documentation: string;
readonly sourceDisplay?: string;
readonly tags?: ReadonlyArray<ts.JSDocTagInfo>;
};
export interface CompletionsAtOptions extends Partial<ts.UserPreferences> {
triggerCharacter?: ts.CompletionsTriggerCharacter;
+1 -1
View File
@@ -268,7 +268,7 @@ namespace Harness.LanguageService {
getHost(): LanguageServiceAdapterHost { return this.host; }
getLanguageService(): ts.LanguageService { return ts.createLanguageService(this.host); }
getClassifier(): ts.Classifier { return ts.createClassifier(); }
getPreProcessedFileInfo(fileName: string, fileContents: string): ts.PreProcessedFileInfo { return ts.preProcessFile(fileContents, /* readImportFiles */ true, ts.hasJavaScriptFileExtension(fileName)); }
getPreProcessedFileInfo(fileName: string, fileContents: string): ts.PreProcessedFileInfo { return ts.preProcessFile(fileContents, /* readImportFiles */ true, ts.hasJSFileExtension(fileName)); }
}
/// Shim adapter
+15
View File
@@ -7,6 +7,21 @@ namespace utils {
return text !== undefined ? text.replace(testPathPrefixRegExp, (_, scheme) => scheme || (retainTrailingDirectorySeparator ? "/" : "")) : undefined!; // TODO: GH#18217
}
function createDiagnosticMessageReplacer<R extends (messageArgs: string[], ...args: string[]) => string[]>(diagnosticMessage: ts.DiagnosticMessage, replacer: R) {
const messageParts = diagnosticMessage.message.split(/{\d+}/g);
const regExp = new RegExp(`^(?:${messageParts.map(ts.regExpEscape).join("(.*?)")})$`);
type Args<R> = R extends (messageArgs: string[], ...args: infer A) => string[] ? A : [];
return (text: string, ...args: Args<R>) => text.replace(regExp, (_, ...fixedArgs) => ts.formatStringFromArgs(diagnosticMessage.message, replacer(fixedArgs, ...args)));
}
const replaceTypesVersionsMessage = createDiagnosticMessageReplacer(
ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2,
([entry, , moduleName], compilerVersion) => [entry, compilerVersion, moduleName]);
export function sanitizeTraceResolutionLogEntry(text: string) {
return text && removeTestPathPrefixes(replaceTypesVersionsMessage(text, "3.1.0-dev"));
}
/**
* Removes leading indentation from a template literal string.
*/
+3 -3
View File
@@ -21,8 +21,8 @@ namespace vpath {
export import relative = ts.getRelativePathFromDirectory;
export import beneath = ts.containsPath;
export import changeExtension = ts.changeAnyExtension;
export import isTypeScript = ts.hasTypeScriptFileExtension;
export import isJavaScript = ts.hasJavaScriptFileExtension;
export import isTypeScript = ts.hasTSFileExtension;
export import isJavaScript = ts.hasJSFileExtension;
const invalidRootComponentRegExp = /^(?!(\/|\/\/\w+\/|[a-zA-Z]:\/?|)$)/;
const invalidNavigableComponentRegExp = /[:*?"<>|]/;
@@ -133,4 +133,4 @@ namespace vpath {
export function isTsConfigFile(path: string): boolean {
return path.indexOf("tsconfig") !== -1 && path.indexOf("json") !== -1;
}
}
}
+2 -2
View File
@@ -122,7 +122,7 @@ namespace ts.JsTyping {
// Only infer typings for .js and .jsx files
fileNames = mapDefined(fileNames, fileName => {
const path = normalizePath(fileName);
if (hasJavaScriptFileExtension(path)) {
if (hasJSFileExtension(path)) {
return path;
}
});
@@ -218,7 +218,7 @@ namespace ts.JsTyping {
*/
function getTypingNamesFromSourceFileNames(fileNames: string[]) {
const fromFileNames = mapDefined(fileNames, j => {
if (!hasJavaScriptFileExtension(j)) return undefined;
if (!hasJSFileExtension(j)) return undefined;
const inferredTypingName = removeFileExtension(getBaseFileName(j.toLowerCase()));
const cleanedTypingName = removeMinAndVersionNumbers(inferredTypingName);
+2 -2
View File
@@ -7,7 +7,7 @@ interface PromiseConstructor {
/**
* Creates a new Promise.
* @param executor A callback used to initialize the promise. This callback is passed two arguments:
* a resolve callback used resolve the promise with a value or the result of another promise,
* a resolve callback used to resolve the promise with a value or the result of another promise,
* and a reject callback used to reject the promise with a provided reason or error.
*/
new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Promise<T>;
@@ -193,4 +193,4 @@ interface PromiseConstructor {
resolve(): Promise<void>;
}
declare var Promise: PromiseConstructor;
declare var Promise: PromiseConstructor;
+104 -15
View File
@@ -291,7 +291,8 @@ namespace ts.server {
ClosedScriptInfo = "Closed Script info",
ConfigFileForInferredRoot = "Config file for the inferred project root",
FailedLookupLocation = "Directory of Failed lookup locations in module resolution",
TypeRoots = "Type root directory"
TypeRoots = "Type root directory",
NodeModulesForClosedScriptInfo = "node_modules for closed script infos in them",
}
const enum ConfigFileWatcherStatus {
@@ -353,10 +354,18 @@ namespace ts.server {
return !!(infoOrFileName as ScriptInfo).containingProjects;
}
interface ScriptInfoInNodeModulesWatcher extends FileWatcher {
refCount: number;
}
function getDetailWatchInfo(watchType: WatchType, project: Project | undefined) {
return `Project: ${project ? project.getProjectName() : ""} WatchType: ${watchType}`;
}
function isScriptInfoWatchedFromNodeModules(info: ScriptInfo) {
return !info.isScriptOpen() && info.mTime !== undefined;
}
/*@internal*/
export function updateProjectIfDirty(project: Project) {
return project.dirty && project.updateGraph();
@@ -380,6 +389,7 @@ namespace ts.server {
* Container of all known scripts
*/
private readonly filenameToScriptInfo = createMap<ScriptInfo>();
private readonly scriptInfoInNodeModulesWatchers = createMap <ScriptInfoInNodeModulesWatcher>();
/**
* Contains all the deleted script info's version information so that
* it does not reset when creating script info again
@@ -1447,14 +1457,14 @@ namespace ts.server {
for (const f of fileNames) {
const fileName = propertyReader.getFileName(f);
if (hasTypeScriptFileExtension(fileName)) {
if (hasTSFileExtension(fileName)) {
continue;
}
totalNonTsFileSize += this.host.getFileSize(fileName);
if (totalNonTsFileSize > maxProgramSizeForNonTsFiles || totalNonTsFileSize > availableSpace) {
this.logger.info(getExceedLimitMessage({ propertyReader, hasTypeScriptFileExtension, host: this.host }, totalNonTsFileSize));
this.logger.info(getExceedLimitMessage({ propertyReader, hasTSFileExtension, host: this.host }, totalNonTsFileSize));
// Keep the size as zero since it's disabled
return fileName;
}
@@ -1464,14 +1474,14 @@ namespace ts.server {
return;
function getExceedLimitMessage(context: { propertyReader: FilePropertyReader<any>, hasTypeScriptFileExtension: (filename: string) => boolean, host: ServerHost }, totalNonTsFileSize: number) {
function getExceedLimitMessage(context: { propertyReader: FilePropertyReader<any>, hasTSFileExtension: (filename: string) => boolean, host: ServerHost }, totalNonTsFileSize: number) {
const files = getTop5LargestFiles(context);
return `Non TS file size exceeded limit (${totalNonTsFileSize}). Largest files: ${files.map(file => `${file.name}:${file.size}`).join(", ")}`;
}
function getTop5LargestFiles({ propertyReader, hasTypeScriptFileExtension, host }: { propertyReader: FilePropertyReader<any>, hasTypeScriptFileExtension: (filename: string) => boolean, host: ServerHost }) {
function getTop5LargestFiles({ propertyReader, hasTSFileExtension, host }: { propertyReader: FilePropertyReader<any>, hasTSFileExtension: (filename: string) => boolean, host: ServerHost }) {
return fileNames.map(f => propertyReader.getFileName(f))
.filter(name => hasTypeScriptFileExtension(name))
.filter(name => hasTSFileExtension(name))
.map(name => ({ name, size: host.getFileSize!(name) })) // TODO: GH#18217
.sort((a, b) => b.size - a.size)
.slice(0, 5);
@@ -1923,18 +1933,97 @@ namespace ts.server {
if (!info.isDynamicOrHasMixedContent() &&
(!this.globalCacheLocationDirectoryPath ||
!startsWith(info.path, this.globalCacheLocationDirectoryPath))) {
const { fileName } = info;
info.fileWatcher = this.watchFactory.watchFilePath(
this.host,
fileName,
(fileName, eventKind, path) => this.onSourceFileChanged(fileName, eventKind, path),
PollingInterval.Medium,
info.path,
WatchType.ClosedScriptInfo
);
const indexOfNodeModules = info.path.indexOf("/node_modules/");
if (!this.host.getModifiedTime || indexOfNodeModules === -1) {
info.fileWatcher = this.watchFactory.watchFilePath(
this.host,
info.fileName,
(fileName, eventKind, path) => this.onSourceFileChanged(fileName, eventKind, path),
PollingInterval.Medium,
info.path,
WatchType.ClosedScriptInfo
);
}
else {
info.mTime = this.getModifiedTime(info);
info.fileWatcher = this.watchClosedScriptInfoInNodeModules(info.path.substr(0, indexOfNodeModules) as Path);
}
}
}
private watchClosedScriptInfoInNodeModules(dir: Path): ScriptInfoInNodeModulesWatcher {
// Watch only directory
const existing = this.scriptInfoInNodeModulesWatchers.get(dir);
if (existing) {
existing.refCount++;
return existing;
}
const watchDir = dir + "/node_modules" as Path;
const watcher = this.watchFactory.watchDirectory(
this.host,
watchDir,
(fileOrDirectory) => {
const fileOrDirectoryPath = this.toPath(fileOrDirectory);
// Has extension
Debug.assert(result.refCount > 0);
if (watchDir === fileOrDirectoryPath) {
this.refreshScriptInfosInDirectory(watchDir);
}
else {
const info = this.getScriptInfoForPath(fileOrDirectoryPath);
if (info) {
if (isScriptInfoWatchedFromNodeModules(info)) {
this.refreshScriptInfo(info);
}
}
// Folder
else if (!hasExtension(fileOrDirectoryPath)) {
this.refreshScriptInfosInDirectory(fileOrDirectoryPath);
}
}
},
WatchDirectoryFlags.Recursive,
WatchType.NodeModulesForClosedScriptInfo
);
const result: ScriptInfoInNodeModulesWatcher = {
close: () => {
if (result.refCount === 1) {
watcher.close();
this.scriptInfoInNodeModulesWatchers.delete(dir);
}
else {
result.refCount--;
}
},
refCount: 1
};
this.scriptInfoInNodeModulesWatchers.set(dir, result);
return result;
}
private getModifiedTime(info: ScriptInfo) {
return (this.host.getModifiedTime!(info.path) || missingFileModifiedTime).getTime();
}
private refreshScriptInfo(info: ScriptInfo) {
const mTime = this.getModifiedTime(info);
if (mTime !== info.mTime) {
const eventKind = getFileWatcherEventKind(info.mTime!, mTime);
info.mTime = mTime;
this.onSourceFileChanged(info.fileName, eventKind, info.path);
}
}
private refreshScriptInfosInDirectory(dir: Path) {
dir = dir + directorySeparator as Path;
this.filenameToScriptInfo.forEach(info => {
if (isScriptInfoWatchedFromNodeModules(info) && startsWith(info.path, dir)) {
this.refreshScriptInfo(info);
}
});
}
private stopWatchingScriptInfo(info: ScriptInfo) {
if (info.fileWatcher) {
info.fileWatcher.close();
+4 -1
View File
@@ -167,7 +167,7 @@ namespace ts.server {
const fileName = tempFileName || this.fileName;
const getText = () => text === undefined ? (text = this.host.readFile(fileName) || "") : text;
// Only non typescript files have size limitation
if (!hasTypeScriptFileExtension(this.fileName)) {
if (!hasTSFileExtension(this.fileName)) {
const fileSize = this.host.getFileSize ? this.host.getFileSize(fileName) : getText().length;
if (fileSize > maxFileSize) {
Debug.assert(!!this.info.containingProjects.length);
@@ -250,6 +250,9 @@ namespace ts.server {
/*@internal*/
cacheSourceFile: DocumentRegistrySourceFileCache;
/*@internal*/
mTime?: number;
constructor(
private readonly host: ServerHost,
readonly fileName: NormalizedPath,
@@ -138,7 +138,7 @@ namespace ts.codefix {
default: {
// Don't try to declare members in JavaScript files
if (isSourceFileJavaScript(sourceFile)) {
if (isSourceFileJS(sourceFile)) {
return;
}
const prop = createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined,
@@ -2,11 +2,13 @@
namespace ts.codefix {
const fixId = "convertToAsyncFunction";
const errorCodes = [Diagnostics.This_may_be_converted_to_an_async_function.code];
let codeActionSucceeded = true;
registerCodeFix({
errorCodes,
getCodeActions(context: CodeFixContext) {
codeActionSucceeded = true;
const changes = textChanges.ChangeTracker.with(context, (t) => convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context));
return [createCodeFixAction(fixId, changes, Diagnostics.Convert_to_async_function, fixId, Diagnostics.Convert_all_to_async_functions)];
return codeActionSucceeded ? [createCodeFixAction(fixId, changes, Diagnostics.Convert_to_async_function, fixId, Diagnostics.Convert_all_to_async_functions)] : [];
},
fixIds: [fixId],
getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, err) => convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker(), context)),
@@ -61,12 +63,12 @@ namespace ts.codefix {
const synthNamesMap: Map<SynthIdentifier> = createMap();
const originalTypeMap: Map<Type> = createMap();
const allVarNames: SymbolAndIdentifier[] = [];
const isInJSFile = isInJavaScriptFile(functionToConvert);
const isInJavascript = isInJSFile(functionToConvert);
const setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker);
const functionToConvertRenamed: FunctionLikeDeclaration = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context, setOfExpressionsToReturn, originalTypeMap, allVarNames);
const constIdentifiers = getConstIdentifiers(synthNamesMap);
const returnStatements = getReturnStatementsWithPromiseHandlers(functionToConvertRenamed);
const transformer = { checker, synthNamesMap, allVarNames, setOfExpressionsToReturn, constIdentifiers, originalTypeMap, isInJSFile };
const transformer = { checker, synthNamesMap, allVarNames, setOfExpressionsToReturn, constIdentifiers, originalTypeMap, isInJSFile: isInJavascript };
if (!returnStatements.length) {
return;
@@ -252,6 +254,7 @@ namespace ts.codefix {
}
// dispatch function to recursively build the refactoring
// should be kept up to date with isFixablePromiseHandler in suggestionDiagnostics.ts
function transformExpression(node: Expression, transformer: Transformer, outermostParent: CallExpression, prevArgName?: SynthIdentifier): Statement[] {
if (!node) {
return [];
@@ -273,6 +276,7 @@ namespace ts.codefix {
return transformPromiseCall(node, transformer, prevArgName);
}
codeActionSucceeded = false;
return [];
}
@@ -381,13 +385,18 @@ namespace ts.codefix {
(createVariableDeclarationList([createVariableDeclaration(getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]);
}
// should be kept up to date with isFixablePromiseArgument in suggestionDiagnostics.ts
function getTransformationBody(func: Node, prevArgName: SynthIdentifier | undefined, argName: SynthIdentifier, parent: CallExpression, transformer: Transformer): NodeArray<Statement> {
const hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0;
const hasArgName = argName && argName.identifier.text.length > 0;
const shouldReturn = transformer.setOfExpressionsToReturn.get(getNodeId(parent).toString());
switch (func.kind) {
case SyntaxKind.NullKeyword:
// do not produce a transformed statement for a null argument
break;
case SyntaxKind.Identifier:
// identifier includes undefined
if (!hasArgName) break;
const synthCall = createCall(getSynthesizedDeepClone(func) as Identifier, /*typeArguments*/ undefined, [argName.identifier]);
@@ -443,6 +452,9 @@ namespace ts.codefix {
return createNodeArray([createReturn(getSynthesizedDeepClone(funcBody) as Expression)]);
}
}
default:
// We've found a transformation body we don't know how to handle, so the refactoring should no-op to avoid deleting code.
codeActionSucceeded = false;
break;
}
return createNodeArray([]);
@@ -492,14 +504,6 @@ namespace ts.codefix {
return innerCbBody;
}
function hasPropertyAccessExpressionWithName(node: CallExpression, funcName: string): boolean {
if (!isPropertyAccessExpression(node.expression)) {
return false;
}
return node.expression.name.text === funcName;
}
function getArgName(funcNode: Node, transformer: Transformer): SynthIdentifier {
const numberOfAssignmentsOriginal = 0;
@@ -546,4 +550,4 @@ namespace ts.codefix {
return node.original ? node.original : node;
}
}
}
}
@@ -12,7 +12,7 @@ namespace ts.codefix {
getCodeActions(context) {
const { sourceFile, program, span, host, formatContext } = context;
if (!isInJavaScriptFile(sourceFile) || !isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) {
if (!isInJSFile(sourceFile) || !isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) {
return undefined;
}
@@ -20,7 +20,7 @@ namespace ts.codefix {
const { parentDeclaration, declSourceFile, inJs, makeStatic, token, call } = info;
const methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences);
const addMember = inJs && !isInterfaceDeclaration(parentDeclaration) ?
singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) :
singleElementArray(getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) :
getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic);
return concatenate(singleElementArray(methodCodeAction), addMember);
},
@@ -131,7 +131,7 @@ namespace ts.codefix {
if (classOrInterface) {
const makeStatic = ((leftExpressionType as TypeReference).target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol);
const declSourceFile = classOrInterface.getSourceFile();
const inJs = isSourceFileJavaScript(declSourceFile);
const inJs = isSourceFileJS(declSourceFile);
const call = tryCast(parent.parent, isCallExpression);
return { kind: InfoKind.ClassOrInterface, token, parentDeclaration: classOrInterface, makeStatic, declSourceFile, inJs, call };
}
@@ -142,7 +142,7 @@ namespace ts.codefix {
return undefined;
}
function getActionsForAddMissingMemberInJavaScriptFile(context: CodeFixContext, declSourceFile: SourceFile, classDeclaration: ClassLikeDeclaration, tokenName: string, makeStatic: boolean): CodeFixAction | undefined {
function getActionsForAddMissingMemberInJavascriptFile(context: CodeFixContext, declSourceFile: SourceFile, classDeclaration: ClassLikeDeclaration, tokenName: string, makeStatic: boolean): CodeFixAction | undefined {
const changes = textChanges.ChangeTracker.with(context, t => addMissingMemberInJs(t, declSourceFile, classDeclaration, tokenName, makeStatic));
return changes.length === 0 ? undefined
: createCodeFixAction(fixName, changes, [makeStatic ? Diagnostics.Initialize_static_property_0 : Diagnostics.Initialize_property_0_in_the_constructor, tokenName], fixId, Diagnostics.Add_all_missing_members);
+2 -2
View File
@@ -267,7 +267,7 @@ namespace ts.codefix {
function getExistingImportDeclarations({ moduleSymbol, importKind, exportedSymbolIsTypeOnly }: SymbolExportInfo, checker: TypeChecker, sourceFile: SourceFile): ReadonlyArray<FixAddToExistingImportInfo> {
// Can't use an es6 import for a type in JS.
return exportedSymbolIsTypeOnly && isSourceFileJavaScript(sourceFile) ? emptyArray : mapDefined<StringLiteralLike, FixAddToExistingImportInfo>(sourceFile.imports, moduleSpecifier => {
return exportedSymbolIsTypeOnly && isSourceFileJS(sourceFile) ? emptyArray : mapDefined<StringLiteralLike, FixAddToExistingImportInfo>(sourceFile.imports, moduleSpecifier => {
const i = importFromModuleSpecifier(moduleSpecifier);
return (i.kind === SyntaxKind.ImportDeclaration || i.kind === SyntaxKind.ImportEqualsDeclaration)
&& checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind } : undefined;
@@ -282,7 +282,7 @@ namespace ts.codefix {
host: LanguageServiceHost,
preferences: UserPreferences,
): ReadonlyArray<FixAddNewImport | FixUseImportType> {
const isJs = isSourceFileJavaScript(sourceFile);
const isJs = isSourceFileJS(sourceFile);
const choicesForEachExportingModule = flatMap(moduleSymbols, ({ moduleSymbol, importKind, exportedSymbolIsTypeOnly }) =>
moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap)
.map((moduleSpecifier): FixAddNewImport | FixUseImportType =>
+1 -1
View File
@@ -26,7 +26,7 @@ namespace ts.codefix {
errorCodes,
getCodeActions(context) {
const { sourceFile, program, span: { start }, errorCode, cancellationToken } = context;
if (isSourceFileJavaScript(sourceFile)) {
if (isSourceFileJS(sourceFile)) {
return undefined; // TODO: GH#20113
}
+25 -15
View File
@@ -134,7 +134,7 @@ namespace ts.Completions {
if (isUncheckedFile(sourceFile, compilerOptions)) {
const uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target!, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap);
getJavaScriptCompletionEntries(sourceFile, location!.pos, uniqueNames, compilerOptions.target!, entries); // TODO: GH#18217
getJSCompletionEntries(sourceFile, location!.pos, uniqueNames, compilerOptions.target!, entries); // TODO: GH#18217
}
else {
if ((!symbols || symbols.length === 0) && keywordFilters === KeywordCompletionFilters.None) {
@@ -161,7 +161,7 @@ namespace ts.Completions {
}
function isUncheckedFile(sourceFile: SourceFile, compilerOptions: CompilerOptions): boolean {
return isSourceFileJavaScript(sourceFile) && !isCheckJsEnabledForFile(sourceFile, compilerOptions);
return isSourceFileJS(sourceFile) && !isCheckJsEnabledForFile(sourceFile, compilerOptions);
}
function isMemberCompletionKind(kind: CompletionKind): boolean {
@@ -175,7 +175,7 @@ namespace ts.Completions {
}
}
function getJavaScriptCompletionEntries(
function getJSCompletionEntries(
sourceFile: SourceFile,
position: number,
uniqueNames: Map<true>,
@@ -390,11 +390,12 @@ namespace ts.Completions {
}
type StringLiteralCompletion = { readonly kind: StringLiteralCompletionKind.Paths, readonly paths: ReadonlyArray<PathCompletions.PathCompletion> } | StringLiteralCompletionsFromProperties | StringLiteralCompletionsFromTypes;
function getStringLiteralCompletionEntries(sourceFile: SourceFile, node: StringLiteralLike, position: number, typeChecker: TypeChecker, compilerOptions: CompilerOptions, host: LanguageServiceHost): StringLiteralCompletion | undefined {
switch (node.parent.kind) {
const { parent } = node;
switch (parent.kind) {
case SyntaxKind.LiteralType:
switch (node.parent.parent.kind) {
switch (parent.parent.kind) {
case SyntaxKind.TypeReference:
return { kind: StringLiteralCompletionKind.Types, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent as LiteralTypeNode)), isNewIdentifier: false };
return { kind: StringLiteralCompletionKind.Types, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent as LiteralTypeNode)), isNewIdentifier: false };
case SyntaxKind.IndexedAccessType:
// Get all apparent property names
// i.e. interface Foo {
@@ -402,17 +403,21 @@ namespace ts.Completions {
// bar: string;
// }
// let x: Foo["/*completion position*/"]
return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode((node.parent.parent as IndexedAccessTypeNode).objectType));
return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode((parent.parent as IndexedAccessTypeNode).objectType));
case SyntaxKind.ImportType:
return { kind: StringLiteralCompletionKind.Paths, paths: PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) };
case SyntaxKind.UnionType:
return isTypeReferenceNode(node.parent.parent.parent) ? { kind: StringLiteralCompletionKind.Types, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent.parent as UnionTypeNode)), isNewIdentifier: false } : undefined;
case SyntaxKind.UnionType: {
if (!isTypeReferenceNode(parent.parent.parent)) return undefined;
const alreadyUsedTypes = getAlreadyUsedTypesInStringLiteralUnion(parent.parent as UnionTypeNode, parent as LiteralTypeNode);
const types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent.parent as UnionTypeNode)).filter(t => !contains(alreadyUsedTypes, t.value));
return { kind: StringLiteralCompletionKind.Types, types, isNewIdentifier: false };
}
default:
return undefined;
}
case SyntaxKind.PropertyAssignment:
if (isObjectLiteralExpression(node.parent.parent) && (<PropertyAssignment>node.parent).name === node) {
if (isObjectLiteralExpression(parent.parent) && (<PropertyAssignment>parent).name === node) {
// Get quoted name of properties of the object literal expression
// i.e. interface ConfigFiles {
// 'jspm:dev': string
@@ -425,12 +430,12 @@ namespace ts.Completions {
// foo({
// '/*completion position*/'
// });
return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(node.parent.parent));
return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(parent.parent));
}
return fromContextualType();
case SyntaxKind.ElementAccessExpression: {
const { expression, argumentExpression } = node.parent as ElementAccessExpression;
const { expression, argumentExpression } = parent as ElementAccessExpression;
if (node === argumentExpression) {
// Get all names of properties on the expression
// i.e. interface A {
@@ -445,7 +450,7 @@ namespace ts.Completions {
case SyntaxKind.CallExpression:
case SyntaxKind.NewExpression:
if (!isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) && !isImportCall(node.parent)) {
if (!isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ false) && !isImportCall(parent)) {
const argumentInfo = SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile);
// Get string literal completions from specialized signatures of the target
// i.e. declare function f(a: 'A');
@@ -476,6 +481,11 @@ namespace ts.Completions {
}
}
function getAlreadyUsedTypesInStringLiteralUnion(union: UnionTypeNode, current: LiteralTypeNode): ReadonlyArray<string> {
return mapDefined(union.types, type =>
type !== current && isLiteralTypeNode(type) && isStringLiteral(type.literal) ? type.literal.text : undefined);
}
function getStringLiteralCompletionsFromSignature(argumentInfo: SignatureHelp.ArgumentInfoForCompletions, checker: TypeChecker): StringLiteralCompletionsFromTypes {
let isNewIdentifier = false;
@@ -1268,10 +1278,10 @@ namespace ts.Completions {
if (sourceFile.externalModuleIndicator) return true;
// If already using commonjs, don't introduce ES6.
if (sourceFile.commonJsModuleIndicator) return false;
// If some file is using ES6 modules, assume that it's OK to add more.
if (programContainsEs6Modules(program)) return true;
// For JS, stay on the safe side.
if (isUncheckedFile) return false;
// If some file is using ES6 modules, assume that it's OK to add more.
if (programContainsEs6Modules(program)) return true;
// If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK.
return compilerOptionsIndicateEs6Modules(program.getCompilerOptions());
}
+15 -7
View File
@@ -196,15 +196,23 @@ namespace ts {
}
function getSourceFileToImportFromResolved(resolved: ResolvedModuleWithFailedLookupLocations | undefined, oldToNew: PathUpdater, host: LanguageServiceHost): ToImport | undefined {
return resolved && (
(resolved.resolvedModule && getIfExists(resolved.resolvedModule.resolvedFileName)) || firstDefined(resolved.failedLookupLocations, getIfExists));
// Search through all locations looking for a moved file, and only then test already existing files.
// This is because if `a.ts` is compiled to `a.js` and `a.ts` is moved, we don't want to resolve anything to `a.js`, but to `a.ts`'s new location.
return tryEach(tryGetNewFile) || tryEach(tryGetOldFile);
function getIfExists(oldLocation: string): ToImport | undefined {
const newLocation = oldToNew(oldLocation);
function tryEach(cb: (oldFileName: string) => ToImport | undefined): ToImport | undefined {
return resolved && (
(resolved.resolvedModule && cb(resolved.resolvedModule.resolvedFileName)) || firstDefined(resolved.failedLookupLocations, cb));
}
return host.fileExists!(oldLocation) || newLocation !== undefined && host.fileExists!(newLocation) // TODO: GH#18217
? newLocation !== undefined ? { newFileName: newLocation, updated: true } : { newFileName: oldLocation, updated: false }
: undefined;
function tryGetNewFile(oldFileName: string): ToImport | undefined {
const newFileName = oldToNew(oldFileName);
return newFileName !== undefined && host.fileExists!(newFileName) ? { newFileName, updated: true } : undefined; // TODO: GH#18217
}
function tryGetOldFile(oldFileName: string): ToImport | undefined {
const newFileName = oldToNew(oldFileName);
return host.fileExists!(oldFileName) ? newFileName !== undefined ? { newFileName, updated: true } : { newFileName: oldFileName, updated: false } : undefined; // TODO: GH#18217
}
}
+3 -3
View File
@@ -502,11 +502,11 @@ namespace ts.FindAllReferences {
function getSpecialPropertyExport(node: BinaryExpression, useLhsSymbol: boolean): ExportedSymbol | undefined {
let kind: ExportKind;
switch (getSpecialPropertyAssignmentKind(node)) {
case SpecialPropertyAssignmentKind.ExportsProperty:
switch (getAssignmentDeclarationKind(node)) {
case AssignmentDeclarationKind.ExportsProperty:
kind = ExportKind.Named;
break;
case SpecialPropertyAssignmentKind.ModuleExports:
case AssignmentDeclarationKind.ModuleExports:
kind = ExportKind.ExportEquals;
break;
default:
+4 -4
View File
@@ -208,7 +208,7 @@ namespace ts.JsDoc {
kindModifiers: "",
displayParts: [textPart(name)],
documentation: emptyArray,
tags: emptyArray,
tags: undefined,
codeActions: undefined,
};
}
@@ -242,7 +242,7 @@ namespace ts.JsDoc {
kindModifiers: "",
displayParts: [textPart(name)],
documentation: emptyArray,
tags: emptyArray,
tags: undefined,
codeActions: undefined,
};
}
@@ -312,7 +312,7 @@ namespace ts.JsDoc {
const preamble = "/**" + newLine + indentationStr + " * ";
const result =
preamble + newLine +
parameterDocComments(parameters, hasJavaScriptFileExtension(sourceFile.fileName), indentationStr, newLine) +
parameterDocComments(parameters, hasJSFileExtension(sourceFile.fileName), indentationStr, newLine) +
indentationStr + " */" +
(tokenStart === position ? newLine + indentationStr : "");
@@ -383,7 +383,7 @@ namespace ts.JsDoc {
case SyntaxKind.BinaryExpression: {
const be = commentOwner as BinaryExpression;
if (getSpecialPropertyAssignmentKind(be) === SpecialPropertyAssignmentKind.None) {
if (getAssignmentDeclarationKind(be) === AssignmentDeclarationKind.None) {
return "quit";
}
const parameters = isFunctionLike(be.right) ? be.right.parameters : emptyArray;
+8 -8
View File
@@ -270,17 +270,17 @@ namespace ts.NavigationBar {
break;
case SyntaxKind.BinaryExpression: {
const special = getSpecialPropertyAssignmentKind(node as BinaryExpression);
const special = getAssignmentDeclarationKind(node as BinaryExpression);
switch (special) {
case SpecialPropertyAssignmentKind.ExportsProperty:
case SpecialPropertyAssignmentKind.ModuleExports:
case SpecialPropertyAssignmentKind.PrototypeProperty:
case SpecialPropertyAssignmentKind.Prototype:
case AssignmentDeclarationKind.ExportsProperty:
case AssignmentDeclarationKind.ModuleExports:
case AssignmentDeclarationKind.PrototypeProperty:
case AssignmentDeclarationKind.Prototype:
addNodeWithRecursiveChild(node, (node as BinaryExpression).right);
return;
case SpecialPropertyAssignmentKind.ThisProperty:
case SpecialPropertyAssignmentKind.Property:
case SpecialPropertyAssignmentKind.None:
case AssignmentDeclarationKind.ThisProperty:
case AssignmentDeclarationKind.Property:
case AssignmentDeclarationKind.None:
break;
default:
Debug.assertNever(special);
+3 -3
View File
@@ -719,7 +719,7 @@ namespace ts.refactor.extractSymbol {
// Make a unique name for the extracted function
const file = scope.getSourceFile();
const functionNameText = getUniqueName(isClassLike(scope) ? "newMethod" : "newFunction", file);
const isJS = isInJavaScriptFile(scope);
const isJS = isInJSFile(scope);
const functionName = createIdentifier(functionNameText);
@@ -1006,7 +1006,7 @@ namespace ts.refactor.extractSymbol {
// Make a unique name for the extracted variable
const file = scope.getSourceFile();
const localNameText = getUniqueName(isClassLike(scope) ? "newProperty" : "newLocal", file);
const isJS = isInJavaScriptFile(scope);
const isJS = isInJSFile(scope);
const variableType = isJS || !checker.isContextSensitive(node)
? undefined
@@ -1424,7 +1424,7 @@ namespace ts.refactor.extractSymbol {
if (expressionDiagnostic) {
constantErrors.push(expressionDiagnostic);
}
if (isClassLike(scope) && isInJavaScriptFile(scope)) {
if (isClassLike(scope) && isInJSFile(scope)) {
constantErrors.push(createDiagnosticForNode(scope, Messages.cannotExtractToJSClass));
}
if (isArrowFunction(scope) && !isBlock(scope.body)) {
@@ -41,7 +41,7 @@ namespace ts.refactor.generateGetAccessorAndSetAccessor {
const fieldInfo = getConvertibleFieldAtPosition(context);
if (!fieldInfo) return undefined;
const isJS = isSourceFileJavaScript(file);
const isJS = isSourceFileJS(file);
const changeTracker = textChanges.ChangeTracker.fromContext(context);
const { isStatic, isReadonly, fieldName, accessorName, originalName, type, container, declaration, renameAccessor } = fieldInfo;
+1 -1
View File
@@ -657,7 +657,7 @@ namespace ts.refactor {
case SyntaxKind.ExpressionStatement: {
const { expression } = statement as ExpressionStatement;
return isBinaryExpression(expression) && getSpecialPropertyAssignmentKind(expression) === SpecialPropertyAssignmentKind.ExportsProperty
return isBinaryExpression(expression) && getAssignmentDeclarationKind(expression) === AssignmentDeclarationKind.ExportsProperty
? cb(statement as TopLevelExpressionStatement)
: undefined;
}
+1 -1
View File
@@ -760,7 +760,7 @@ namespace ts {
break;
case SyntaxKind.BinaryExpression:
if (getSpecialPropertyAssignmentKind(node as BinaryExpression) !== SpecialPropertyAssignmentKind.None) {
if (getAssignmentDeclarationKind(node as BinaryExpression) !== AssignmentDeclarationKind.None) {
addDeclaration(node as BinaryExpression);
}
// falls through
+2 -2
View File
@@ -50,7 +50,7 @@ namespace ts.SignatureHelp {
if (!candidateInfo) {
// We didn't have any sig help items produced by the TS compiler. If this is a JS
// file, then see if we can figure out anything better.
return isSourceFileJavaScript(sourceFile) ? createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined;
return isSourceFileJS(sourceFile) ? createJSSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined;
}
return typeChecker.runWithCancellationToken(cancellationToken, typeChecker =>
@@ -115,7 +115,7 @@ namespace ts.SignatureHelp {
}
}
function createJavaScriptSignatureHelpItems(argumentInfo: ArgumentListInfo, program: Program, cancellationToken: CancellationToken): SignatureHelpItems | undefined {
function createJSSignatureHelpItems(argumentInfo: ArgumentListInfo, program: Program, cancellationToken: CancellationToken): SignatureHelpItems | undefined {
if (argumentInfo.invocation.kind === InvocationKind.Contextual) return undefined;
// See if we can find some symbol with the call expression name that has call signatures.
const expression = getExpressionFromInvocation(argumentInfo.invocation);
+39 -8
View File
@@ -11,7 +11,7 @@ namespace ts {
diags.push(createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module));
}
const isJsFile = isSourceFileJavaScript(sourceFile);
const isJsFile = isSourceFileJS(sourceFile);
check(sourceFile);
@@ -36,7 +36,7 @@ namespace ts {
if (isJsFile) {
switch (node.kind) {
case SyntaxKind.FunctionExpression:
const decl = getDeclarationOfJSInitializer(node);
const decl = getDeclarationOfExpando(node);
if (decl) {
const symbol = decl.symbol;
if (symbol && (symbol.exports && symbol.exports.size || symbol.members && symbol.members.size)) {
@@ -86,8 +86,8 @@ namespace ts {
case SyntaxKind.ExpressionStatement: {
const { expression } = statement as ExpressionStatement;
if (!isBinaryExpression(expression)) return isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true);
const kind = getSpecialPropertyAssignmentKind(expression);
return kind === SpecialPropertyAssignmentKind.ExportsProperty || kind === SpecialPropertyAssignmentKind.ModuleExports;
const kind = getAssignmentDeclarationKind(expression);
return kind === AssignmentDeclarationKind.ExportsProperty || kind === AssignmentDeclarationKind.ModuleExports;
}
default:
return false;
@@ -160,7 +160,7 @@ namespace ts {
}
function addHandlers(returnChild: Node) {
if (isPromiseHandler(returnChild)) {
if (isFixablePromiseHandler(returnChild)) {
returnStatements.push(child as ReturnStatement);
}
}
@@ -170,8 +170,39 @@ namespace ts {
return returnStatements;
}
function isPromiseHandler(node: Node): boolean {
return (isCallExpression(node) && isPropertyAccessExpression(node.expression) &&
(node.expression.name.text === "then" || node.expression.name.text === "catch"));
// Should be kept up to date with transformExpression in convertToAsyncFunction.ts
function isFixablePromiseHandler(node: Node): boolean {
// ensure outermost call exists and is a promise handler
if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) {
return false;
}
// ensure all chained calls are valid
let currentNode = node.expression;
while (isPromiseHandler(currentNode) || isPropertyAccessExpression(currentNode)) {
if (isCallExpression(currentNode) && !currentNode.arguments.every(isFixablePromiseArgument)) {
return false;
}
currentNode = currentNode.expression;
}
return true;
}
function isPromiseHandler(node: Node): node is CallExpression {
return isCallExpression(node) && (hasPropertyAccessExpressionWithName(node, "then") || hasPropertyAccessExpressionWithName(node, "catch"));
}
// should be kept up to date with getTransformationBody in convertToAsyncFunction.ts
function isFixablePromiseArgument(arg: Expression): boolean {
switch (arg.kind) {
case SyntaxKind.NullKeyword:
case SyntaxKind.Identifier: // identifier includes undefined
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionExpression:
case SyntaxKind.ArrowFunction:
return true;
default:
return false;
}
}
}
+1 -1
View File
@@ -534,7 +534,7 @@ namespace ts.SymbolDisplay {
tags = tagsFromAlias;
}
return { displayParts, documentation, symbolKind, tags: tags! };
return { displayParts, documentation, symbolKind, tags: tags!.length === 0 ? undefined : tags };
function getPrinter() {
if (!printer) {
+19 -9
View File
@@ -23,8 +23,10 @@ namespace ts {
export function getMeaningFromDeclaration(node: Node): SemanticMeaning {
switch (node.kind) {
case SyntaxKind.Parameter:
case SyntaxKind.VariableDeclaration:
return isInJSFile(node) && getJSDocEnumTag(node) ? SemanticMeaning.All : SemanticMeaning.Value;
case SyntaxKind.Parameter:
case SyntaxKind.BindingElement:
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.PropertySignature:
@@ -224,6 +226,14 @@ namespace ts {
return undefined;
}
export function hasPropertyAccessExpressionWithName(node: CallExpression, funcName: string): boolean {
if (!isPropertyAccessExpression(node.expression)) {
return false;
}
return node.expression.name.text === funcName;
}
export function isJumpStatementTarget(node: Node): node is Identifier & { parent: BreakOrContinueStatement } {
return node.kind === SyntaxKind.Identifier && isBreakOrContinueStatement(node.parent) && node.parent.label === node;
}
@@ -355,23 +365,23 @@ namespace ts {
case SyntaxKind.NamespaceImport:
return ScriptElementKind.alias;
case SyntaxKind.BinaryExpression:
const kind = getSpecialPropertyAssignmentKind(node as BinaryExpression);
const kind = getAssignmentDeclarationKind(node as BinaryExpression);
const { right } = node as BinaryExpression;
switch (kind) {
case SpecialPropertyAssignmentKind.None:
case AssignmentDeclarationKind.None:
return ScriptElementKind.unknown;
case SpecialPropertyAssignmentKind.ExportsProperty:
case SpecialPropertyAssignmentKind.ModuleExports:
case AssignmentDeclarationKind.ExportsProperty:
case AssignmentDeclarationKind.ModuleExports:
const rightKind = getNodeKind(right);
return rightKind === ScriptElementKind.unknown ? ScriptElementKind.constElement : rightKind;
case SpecialPropertyAssignmentKind.PrototypeProperty:
case AssignmentDeclarationKind.PrototypeProperty:
return isFunctionExpression(right) ? ScriptElementKind.memberFunctionElement : ScriptElementKind.memberVariableElement;
case SpecialPropertyAssignmentKind.ThisProperty:
case AssignmentDeclarationKind.ThisProperty:
return ScriptElementKind.memberVariableElement; // property
case SpecialPropertyAssignmentKind.Property:
case AssignmentDeclarationKind.Property:
// static method / property
return isFunctionExpression(right) ? ScriptElementKind.memberFunctionElement : ScriptElementKind.memberVariableElement;
case SpecialPropertyAssignmentKind.Prototype:
case AssignmentDeclarationKind.Prototype:
return ScriptElementKind.localClassElement;
default: {
assertType<never>(kind);
+1 -1
View File
@@ -208,7 +208,7 @@ class CompilerTest {
public verifyModuleResolution() {
if (this.options.traceResolution) {
Harness.Baseline.runBaseline(this.justName.replace(/\.tsx?$/, ".trace.json"),
utils.removeTestPathPrefixes(JSON.stringify(this.result.traces, undefined, 4)));
JSON.stringify(this.result.traces.map(utils.sanitizeTraceResolutionLogEntry), undefined, 4));
}
}
@@ -1,68 +1,4 @@
namespace ts {
interface Range {
pos: number;
end: number;
name: string;
}
interface Test {
source: string;
ranges: Map<Range>;
}
function getTest(source: string): Test {
const activeRanges: Range[] = [];
let text = "";
let lastPos = 0;
let pos = 0;
const ranges = createMap<Range>();
while (pos < source.length) {
if (source.charCodeAt(pos) === CharacterCodes.openBracket &&
(source.charCodeAt(pos + 1) === CharacterCodes.hash || source.charCodeAt(pos + 1) === CharacterCodes.$)) {
const saved = pos;
pos += 2;
const s = pos;
consumeIdentifier();
const e = pos;
if (source.charCodeAt(pos) === CharacterCodes.bar) {
pos++;
text += source.substring(lastPos, saved);
const name = s === e
? source.charCodeAt(saved + 1) === CharacterCodes.hash ? "selection" : "extracted"
: source.substring(s, e);
activeRanges.push({ name, pos: text.length, end: undefined! });
lastPos = pos;
continue;
}
else {
pos = saved;
}
}
else if (source.charCodeAt(pos) === CharacterCodes.bar && source.charCodeAt(pos + 1) === CharacterCodes.closeBracket) {
text += source.substring(lastPos, pos);
activeRanges[activeRanges.length - 1].end = text.length;
const range = activeRanges.pop()!;
if (range.name in ranges) {
throw new Error(`Duplicate name of range ${range.name}`);
}
ranges.set(range.name, range);
pos += 2;
lastPos = pos;
continue;
}
pos++;
}
text += source.substring(lastPos, pos);
function consumeIdentifier() {
while (isIdentifierPart(source.charCodeAt(pos), ScriptTarget.Latest)) {
pos++;
}
}
return { source: text, ranges };
}
const libFile: TestFSWithWatch.File = {
path: "/a/lib/lib.d.ts",
content: `/// <reference no-default-lib="true"/>
@@ -319,19 +255,22 @@ interface String { charAt: any; }
interface Array<T> {}`
};
function testConvertToAsyncFunction(caption: string, text: string, baselineFolder: string, diagnosticDescription: DiagnosticMessage, codeFixDescription: DiagnosticMessage, includeLib?: boolean) {
const t = getTest(text);
function testConvertToAsyncFunction(caption: string, text: string, baselineFolder: string, includeLib?: boolean, expectFailure = false) {
const t = extractTest(text);
const selectionRange = t.ranges.get("selection")!;
if (!selectionRange) {
throw new Error(`Test ${caption} does not specify selection range`);
}
[Extension.Ts, Extension.Js].forEach(extension =>
const extensions = expectFailure ? [Extension.Ts] : [Extension.Ts, Extension.Js];
extensions.forEach(extension =>
it(`${caption} [${extension}]`, () => runBaseline(extension)));
function runBaseline(extension: Extension) {
const path = "/a" + extension;
const program = makeProgram({ path, content: t.source }, includeLib)!;
const languageService = makeLanguageService({ path, content: t.source }, includeLib);
const program = languageService.getProgram()!;
if (hasSyntacticDiagnostics(program)) {
// Don't bother generating JS baselines for inputs that aren't valid JS.
@@ -345,10 +284,6 @@ interface Array<T> {}`
};
const sourceFile = program.getSourceFile(path)!;
const host = projectSystem.createServerHost([f, libFile]);
const projectService = projectSystem.createProjectService(host);
projectService.openClientFile(f.path);
const languageService = projectService.inferredProjects[0].getLanguageService();
const context: CodeFixContext = {
errorCode: 80006,
span: { start: selectionRange.pos, length: selectionRange.end - selectionRange.pos },
@@ -361,37 +296,45 @@ interface Array<T> {}`
};
const diagnostics = languageService.getSuggestionDiagnostics(f.path);
const diagnostic = find(diagnostics, diagnostic => diagnostic.messageText === diagnosticDescription.message);
assert.exists(diagnostic);
assert.equal(diagnostic!.start, context.span.start);
assert.equal(diagnostic!.length, context.span.length);
const diagnostic = find(diagnostics, diagnostic => diagnostic.messageText === Diagnostics.This_may_be_converted_to_an_async_function.message &&
diagnostic.start === context.span.start && diagnostic.length === context.span.length);
if (expectFailure) {
assert.isUndefined(diagnostic);
}
else {
assert.exists(diagnostic);
}
const actions = codefix.getFixes(context);
const action = find(actions, action => action.description === codeFixDescription.message)!;
assert.exists(action);
const action = find(actions, action => action.description === Diagnostics.Convert_to_async_function.message);
if (expectFailure) {
assert.isNotTrue(action && action.changes.length > 0);
return;
}
assert.isTrue(action && action.changes.length > 0);
const data: string[] = [];
data.push(`// ==ORIGINAL==`);
data.push(text.replace("[#|", "/*[#|*/").replace("|]", "/*|]*/"));
const changes = action.changes;
const changes = action!.changes;
assert.lengthOf(changes, 1);
data.push(`// ==ASYNC FUNCTION::${action.description}==`);
data.push(`// ==ASYNC FUNCTION::${action!.description}==`);
const newText = textChanges.applyChanges(sourceFile.text, changes[0].textChanges);
data.push(newText);
const diagProgram = makeProgram({ path, content: newText }, includeLib)!;
const diagProgram = makeLanguageService({ path, content: newText }, includeLib).getProgram()!;
assert.isFalse(hasSyntacticDiagnostics(diagProgram));
Harness.Baseline.runBaseline(`${baselineFolder}/${caption}${extension}`, data.join(newLineCharacter));
}
function makeProgram(f: { path: string, content: string }, includeLib?: boolean) {
function makeLanguageService(f: { path: string, content: string }, includeLib?: boolean) {
const host = projectSystem.createServerHost(includeLib ? [f, libFile] : [f]); // libFile is expensive to parse repeatedly - only test when required
const projectService = projectSystem.createProjectService(host);
projectService.openClientFile(f.path);
const program = projectService.inferredProjects[0].getLanguageService().getProgram();
return program;
return projectService.inferredProjects[0].getLanguageService();
}
function hasSyntacticDiagnostics(program: Program) {
@@ -400,27 +343,6 @@ interface Array<T> {}`
}
}
function testConvertToAsyncFunctionFailed(caption: string, text: string, description: DiagnosticMessage) {
it(caption, () => {
const t = extractTest(text);
const selectionRange = t.ranges.get("selection");
if (!selectionRange) {
throw new Error(`Test ${caption} does not specify selection range`);
}
const f = {
path: "/a.ts",
content: t.source
};
const host = projectSystem.createServerHost([f, libFile]);
const projectService = projectSystem.createProjectService(host);
projectService.openClientFile(f.path);
const languageService = projectService.inferredProjects[0].getLanguageService();
const actions = languageService.getSuggestionDiagnostics(f.path);
assert.isUndefined(find(actions, action => action.messageText === description.message));
});
}
describe("convertToAsyncFunctions", () => {
_testConvertToAsyncFunction("convertToAsyncFunction_basic", `
function [#|f|](): Promise<void>{
@@ -545,6 +467,12 @@ function [#|f|]():Promise<void | Response> {
function [#|f|]():Promise<void | Response> {
return fetch('https://typescriptlang.org').catch(rej => console.log(rej));
}
`
);
_testConvertToAsyncFunction("convertToAsyncFunction_NoRes4", `
function [#|f|]() {
return fetch('https://typescriptlang.org').then(undefined, rejection => console.log("rejected:", rejection));
}
`
);
_testConvertToAsyncFunctionFailed("convertToAsyncFunction_NoSuggestion", `
@@ -1157,7 +1085,7 @@ function [#|f|]() {
`
);
_testConvertToAsyncFunctionFailed("convertToAsyncFunction_NestedFunction", `
_testConvertToAsyncFunctionFailed("convertToAsyncFunction_NestedFunctionWrongLocation", `
function [#|f|]() {
function fn2(){
function fn3(){
@@ -1167,6 +1095,18 @@ function [#|f|]() {
}
return fn2();
}
`);
_testConvertToAsyncFunction("convertToAsyncFunction_NestedFunctionRightLocation", `
function f() {
function fn2(){
function [#|fn3|](){
return fetch("https://typescriptlang.org").then(res => console.log(res));
}
return fn3();
}
return fn2();
}
`);
_testConvertToAsyncFunction("convertToAsyncFunction_UntypedFunction", `
@@ -1194,14 +1134,26 @@ const [#|foo|] = function () {
}
`);
_testConvertToAsyncFunctionFailed("convertToAsyncFunction_thenArgumentNotFunction", `
function [#|f|]() {
return Promise.resolve().then(f ? (x => x) : (y => y));
}
`);
_testConvertToAsyncFunctionFailed("convertToAsyncFunction_thenArgumentNotFunctionNotLastInChain", `
function [#|f|]() {
return Promise.resolve().then(f ? (x => x) : (y => y)).then(q => q);
}
`);
});
function _testConvertToAsyncFunction(caption: string, text: string) {
testConvertToAsyncFunction(caption, text, "convertToAsyncFunction", Diagnostics.This_may_be_converted_to_an_async_function, Diagnostics.Convert_to_async_function, /*includeLib*/ true);
testConvertToAsyncFunction(caption, text, "convertToAsyncFunction", /*includeLib*/ true);
}
function _testConvertToAsyncFunctionFailed(caption: string, text: string) {
testConvertToAsyncFunctionFailed(caption, text, Diagnostics.Convert_to_async_function);
testConvertToAsyncFunction(caption, text, "convertToAsyncFunction", /*includeLib*/ true, /*expectFailure*/ true);
}
}
+3 -3
View File
@@ -83,7 +83,7 @@ namespace ts {
describe("Node module resolution - relative paths", () => {
function testLoadAsFile(containingFileName: string, moduleFileNameNoExt: string, moduleName: string): void {
for (const ext of supportedTypeScriptExtensions) {
for (const ext of supportedTSExtensions) {
test(ext, /*hasDirectoryExists*/ false);
test(ext, /*hasDirectoryExists*/ true);
}
@@ -96,7 +96,7 @@ namespace ts {
const failedLookupLocations: string[] = [];
const dir = getDirectoryPath(containingFileName);
for (const e of supportedTypeScriptExtensions) {
for (const e of supportedTSExtensions) {
if (e === ext) {
break;
}
@@ -137,7 +137,7 @@ namespace ts {
const resolution = nodeModuleNameResolver(moduleName, containingFile.name, {}, createModuleResolutionHost(hasDirectoryExists, containingFile, packageJson, moduleFile));
checkResolvedModule(resolution.resolvedModule, createResolvedModule(moduleFile.name));
// expect three failed lookup location - attempt to load module as file with all supported extensions
assert.equal(resolution.failedLookupLocations.length, supportedTypeScriptExtensions.length);
assert.equal(resolution.failedLookupLocations.length, supportedTSExtensions.length);
}
}
@@ -3136,7 +3136,7 @@ namespace ts.projectSystem {
const project = projectService.configuredProjects.get(configFile.path)!;
assert.isDefined(project);
checkProjectActualFiles(project, [file1.path, libFile.path, module1.path, module2.path, configFile.path]);
checkWatchedFiles(host, [libFile.path, module1.path, module2.path, configFile.path]);
checkWatchedFiles(host, [libFile.path, configFile.path]);
checkWatchedDirectories(host, [], /*recursive*/ false);
const watchedRecursiveDirectories = getTypeRootsFromLocation(root + "/a/b/src");
watchedRecursiveDirectories.push(`${root}/a/b/src/node_modules`, `${root}/a/b/node_modules`);
@@ -3204,7 +3204,7 @@ namespace ts.projectSystem {
{ text: "number", kind: "keyword" }
],
documentation: [],
tags: []
tags: undefined,
});
});
@@ -7435,7 +7435,7 @@ namespace ts.projectSystem {
const projectFilePaths = map(projectFiles, f => f.path);
checkProjectActualFiles(project, projectFilePaths);
const filesWatched = filter(projectFilePaths, p => p !== app.path);
const filesWatched = filter(projectFilePaths, p => p !== app.path && p.indexOf("/a/b/node_modules") === -1);
checkWatchedFiles(host, filesWatched);
checkWatchedDirectories(host, typeRootDirectories.concat(recursiveWatchedDirectories), /*recursive*/ true);
checkWatchedDirectories(host, [], /*recursive*/ false);
@@ -8658,10 +8658,21 @@ new C();`
}
function verifyWatchesWithConfigFile(host: TestServerHost, files: File[], openFile: File, extraExpectedDirectories?: ReadonlyArray<string>) {
checkWatchedFiles(host, mapDefined(files, f => f === openFile ? undefined : f.path));
const expectedRecursiveDirectories = arrayToSet([projectLocation, `${projectLocation}/${nodeModulesAtTypes}`, ...(extraExpectedDirectories || emptyArray)]);
checkWatchedFiles(host, mapDefined(files, f => {
if (f === openFile) {
return undefined;
}
const indexOfNodeModules = f.path.indexOf("/node_modules/");
if (indexOfNodeModules === -1) {
return f.path;
}
expectedRecursiveDirectories.set(f.path.substr(0, indexOfNodeModules + "/node_modules".length), true);
return undefined;
}));
checkWatchedDirectories(host, [], /*recursive*/ false);
checkWatchedDirectories(host, [projectLocation, `${projectLocation}/${nodeModulesAtTypes}`, ...(extraExpectedDirectories || emptyArray)], /*recursive*/ true);
}
checkWatchedDirectories(host, arrayFrom(expectedRecursiveDirectories.keys()), /*recursive*/ true);
}
describe("from files in same folder", () => {
function getFiles(fileContent: string) {
@@ -8862,7 +8873,7 @@ new C();`
verifyTrace(resolutionTrace, expectedTrace);
const currentDirectory = getDirectoryPath(file1.path);
const watchedFiles = mapDefined(files, f => f === file1 ? undefined : f.path);
const watchedFiles = mapDefined(files, f => f === file1 || f.path.indexOf("/node_modules/") !== -1 ? undefined : f.path);
forEachAncestorDirectory(currentDirectory, d => {
watchedFiles.push(combinePaths(d, "tsconfig.json"), combinePaths(d, "jsconfig.json"));
});
@@ -9501,7 +9512,7 @@ export function Test2() {
kindModifiers: ScriptElementKindModifier.exportedModifier,
name: "foo",
source: [{ text: "./a", kind: "text" }],
tags: emptyArray,
tags: undefined,
};
assert.deepEqual<ReadonlyArray<protocol.CompletionEntryDetails> | undefined>(detailsResponse, [
{
@@ -9583,7 +9594,7 @@ declare class TestLib {
constructor() {
var l = new TestLib();
}
public test2() {
+1 -1
View File
@@ -891,7 +891,7 @@ namespace ts.server {
sys.require = (initialDir: string, moduleName: string): RequireResult => {
try {
return { module: require(resolveJavaScriptModule(moduleName, initialDir, sys)), error: undefined };
return { module: require(resolveJSModule(moduleName, initialDir, sys)), error: undefined };
}
catch (error) {
return { module: undefined, error };
@@ -1,4 +1,4 @@
tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck10.ts(9,6): error TS2693: 'Symbol' only refers to a type, but is being used as a value here.
tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck10.ts(9,6): error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.
tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck10.ts(14,15): error TS2569: Type 'StringIterator' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators.
@@ -13,7 +13,7 @@ tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck10.ts(14,1
}
[Symbol.iterator]() {
~~~~~~
!!! error TS2693: 'Symbol' only refers to a type, but is being used as a value here.
!!! error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.
return this;
}
}
@@ -1,5 +1,5 @@
tests/cases/conformance/Symbols/ES5SymbolProperty2.ts(5,10): error TS2471: A computed property name of the form 'Symbol.iterator' must be of type 'symbol'.
tests/cases/conformance/Symbols/ES5SymbolProperty2.ts(10,11): error TS2693: 'Symbol' only refers to a type, but is being used as a value here.
tests/cases/conformance/Symbols/ES5SymbolProperty2.ts(10,11): error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.
==== tests/cases/conformance/Symbols/ES5SymbolProperty2.ts (2 errors) ====
@@ -16,4 +16,4 @@ tests/cases/conformance/Symbols/ES5SymbolProperty2.ts(10,11): error TS2693: 'Sym
(new M.C)[Symbol.iterator];
~~~~~~
!!! error TS2693: 'Symbol' only refers to a type, but is being used as a value here.
!!! error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.
@@ -1,14 +1,14 @@
tests/cases/conformance/Symbols/ES5SymbolProperty6.ts(2,6): error TS2693: 'Symbol' only refers to a type, but is being used as a value here.
tests/cases/conformance/Symbols/ES5SymbolProperty6.ts(5,9): error TS2693: 'Symbol' only refers to a type, but is being used as a value here.
tests/cases/conformance/Symbols/ES5SymbolProperty6.ts(2,6): error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.
tests/cases/conformance/Symbols/ES5SymbolProperty6.ts(5,9): error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.
==== tests/cases/conformance/Symbols/ES5SymbolProperty6.ts (2 errors) ====
class C {
[Symbol.iterator]() { }
~~~~~~
!!! error TS2693: 'Symbol' only refers to a type, but is being used as a value here.
!!! error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.
}
(new C)[Symbol.iterator]
~~~~~~
!!! error TS2693: 'Symbol' only refers to a type, but is being used as a value here.
!!! error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.
@@ -6,7 +6,7 @@
"0": {
"kind": "JSDocTag",
"pos": 63,
"end": 68,
"end": 67,
"atToken": {
"kind": "AtToken",
"pos": 63,
@@ -22,7 +22,7 @@
},
"length": 1,
"pos": 63,
"end": 68
"end": 67
},
"comment": "{@link first link}\nInside {@link link text} thing"
}
@@ -30,7 +30,7 @@
{
"kind": "JSDocParameterTag",
"pos": 34,
"end": 54,
"end": 64,
"atToken": {
"kind": "AtToken",
"pos": 34,
@@ -21,7 +21,7 @@
"typeParameters": {
"0": {
"kind": "TypeParameter",
"pos": 18,
"pos": 17,
"end": 19,
"name": {
"kind": "Identifier",
@@ -31,7 +31,7 @@
}
},
"length": 1,
"pos": 18,
"pos": 17,
"end": 19
}
},
@@ -21,7 +21,7 @@
"typeParameters": {
"0": {
"kind": "TypeParameter",
"pos": 18,
"pos": 17,
"end": 19,
"name": {
"kind": "Identifier",
@@ -42,7 +42,7 @@
}
},
"length": 2,
"pos": 18,
"pos": 17,
"end": 21
}
},
@@ -21,7 +21,7 @@
"typeParameters": {
"0": {
"kind": "TypeParameter",
"pos": 18,
"pos": 17,
"end": 19,
"name": {
"kind": "Identifier",
@@ -42,7 +42,7 @@
}
},
"length": 2,
"pos": 18,
"pos": 17,
"end": 22
}
},
@@ -21,7 +21,7 @@
"typeParameters": {
"0": {
"kind": "TypeParameter",
"pos": 18,
"pos": 17,
"end": 19,
"name": {
"kind": "Identifier",
@@ -42,7 +42,7 @@
}
},
"length": 2,
"pos": 18,
"pos": 17,
"end": 22
}
},
@@ -21,7 +21,7 @@
"typeParameters": {
"0": {
"kind": "TypeParameter",
"pos": 18,
"pos": 17,
"end": 19,
"name": {
"kind": "Identifier",
@@ -42,7 +42,7 @@
}
},
"length": 2,
"pos": 18,
"pos": 17,
"end": 23
}
},
@@ -21,7 +21,7 @@
"typeParameters": {
"0": {
"kind": "TypeParameter",
"pos": 18,
"pos": 17,
"end": 19,
"name": {
"kind": "Identifier",
@@ -42,7 +42,7 @@
}
},
"length": 2,
"pos": 18,
"pos": 17,
"end": 24
},
"comment": "Description of type parameters."
@@ -38,7 +38,7 @@
{
"kind": "JSDocPropertyTag",
"pos": 47,
"end": 72,
"end": 74,
"atToken": {
"kind": "AtToken",
"pos": 47,
@@ -72,7 +72,7 @@
{
"kind": "JSDocPropertyTag",
"pos": 74,
"end": 97,
"end": 100,
"atToken": {
"kind": "AtToken",
"pos": 74,
@@ -1,22 +1,22 @@
tests/cases/compiler/anonymousModules.ts(1,1): error TS2304: Cannot find name 'module'.
tests/cases/compiler/anonymousModules.ts(1,1): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`.
tests/cases/compiler/anonymousModules.ts(1,8): error TS1005: ';' expected.
tests/cases/compiler/anonymousModules.ts(4,2): error TS2304: Cannot find name 'module'.
tests/cases/compiler/anonymousModules.ts(4,2): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`.
tests/cases/compiler/anonymousModules.ts(4,9): error TS1005: ';' expected.
tests/cases/compiler/anonymousModules.ts(10,2): error TS2304: Cannot find name 'module'.
tests/cases/compiler/anonymousModules.ts(10,2): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`.
tests/cases/compiler/anonymousModules.ts(10,9): error TS1005: ';' expected.
==== tests/cases/compiler/anonymousModules.ts (6 errors) ====
module {
~~~~~~
!!! error TS2304: Cannot find name 'module'.
!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`.
~
!!! error TS1005: ';' expected.
export var foo = 1;
module {
~~~~~~
!!! error TS2304: Cannot find name 'module'.
!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`.
~
!!! error TS1005: ';' expected.
export var bar = 1;
@@ -26,7 +26,7 @@ tests/cases/compiler/anonymousModules.ts(10,9): error TS1005: ';' expected.
module {
~~~~~~
!!! error TS2304: Cannot find name 'module'.
!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`.
~
!!! error TS1005: ';' expected.
var x = bar;
+6 -1
View File
@@ -2059,7 +2059,7 @@ declare namespace ts {
ExportStar = 8388608,
Optional = 16777216,
Transient = 33554432,
JSContainer = 67108864,
Assignment = 67108864,
ModuleExports = 134217728,
Enum = 384,
Variable = 3,
@@ -8378,6 +8378,7 @@ declare namespace ts.server {
* Container of all known scripts
*/
private readonly filenameToScriptInfo;
private readonly scriptInfoInNodeModulesWatchers;
/**
* Contains all the deleted script info's version information so that
* it does not reset when creating script info again
@@ -8548,6 +8549,10 @@ declare namespace ts.server {
private createInferredProject;
getScriptInfo(uncheckedFileName: string): ScriptInfo | undefined;
private watchClosedScriptInfo;
private watchClosedScriptInfoInNodeModules;
private getModifiedTime;
private refreshScriptInfo;
private refreshScriptInfosInDirectory;
private stopWatchingScriptInfo;
private getOrCreateScriptInfoNotOpenedByClientForNormalizedPath;
private getOrCreateScriptInfoOpenedByClientForNormalizedPath;
+1 -1
View File
@@ -2059,7 +2059,7 @@ declare namespace ts {
ExportStar = 8388608,
Optional = 16777216,
Transient = 33554432,
JSContainer = 67108864,
Assignment = 67108864,
ModuleExports = 134217728,
Enum = 384,
Variable = 3,
@@ -1,11 +1,11 @@
tests/cases/compiler/argumentsObjectIterator02_ES5.ts(2,26): error TS2693: 'Symbol' only refers to a type, but is being used as a value here.
tests/cases/compiler/argumentsObjectIterator02_ES5.ts(2,26): error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.
==== tests/cases/compiler/argumentsObjectIterator02_ES5.ts (1 errors) ====
function doubleAndReturnAsArray(x: number, y: number, z: number): [number, number, number] {
let blah = arguments[Symbol.iterator];
~~~~~~
!!! error TS2693: 'Symbol' only refers to a type, but is being used as a value here.
!!! error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.
let result = [];
for (let arg of blah()) {
@@ -0,0 +1,39 @@
tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts(3,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures.
tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts(5,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures.
tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts(7,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures.
tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts(10,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures.
tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts(13,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures.
==== tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts (5 errors) ====
declare function foo(): string;
foo()(1 as number).toString();
~~~~~~~~~~~~~~~~~~
!!! error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures.
foo() (1 as number).toString();
~~~~~~~~~~~~~~~~~~~~~
!!! error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures.
foo()
~~~~~
(1 as number).toString();
~~~~~~~~~~~~~
!!! error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures.
!!! related TS2734 tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts:7:1: It is highly likely that you are missing a semicolon.
foo()
~~~~~~~~
(1 as number).toString();
~~~~~~~~~~~~~~~~~
!!! error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures.
!!! related TS2734 tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts:10:1: It is highly likely that you are missing a semicolon.
foo()
~~~~~~~~
(<number>1).toString();
~~~~~~~~~~~~~~~
!!! error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures.
!!! related TS2734 tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts:13:1: It is highly likely that you are missing a semicolon.
@@ -0,0 +1,23 @@
//// [betterErrorForAccidentallyCallingTypeAssertionExpressions.ts]
declare function foo(): string;
foo()(1 as number).toString();
foo() (1 as number).toString();
foo()
(1 as number).toString();
foo()
(1 as number).toString();
foo()
(<number>1).toString();
//// [betterErrorForAccidentallyCallingTypeAssertionExpressions.js]
foo()(1).toString();
foo()(1).toString();
foo()(1).toString();
foo()(1).toString();
foo()(1).toString();
@@ -0,0 +1,25 @@
=== tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts ===
declare function foo(): string;
>foo : Symbol(foo, Decl(betterErrorForAccidentallyCallingTypeAssertionExpressions.ts, 0, 0))
foo()(1 as number).toString();
>foo : Symbol(foo, Decl(betterErrorForAccidentallyCallingTypeAssertionExpressions.ts, 0, 0))
foo() (1 as number).toString();
>foo : Symbol(foo, Decl(betterErrorForAccidentallyCallingTypeAssertionExpressions.ts, 0, 0))
foo()
>foo : Symbol(foo, Decl(betterErrorForAccidentallyCallingTypeAssertionExpressions.ts, 0, 0))
(1 as number).toString();
foo()
>foo : Symbol(foo, Decl(betterErrorForAccidentallyCallingTypeAssertionExpressions.ts, 0, 0))
(1 as number).toString();
foo()
>foo : Symbol(foo, Decl(betterErrorForAccidentallyCallingTypeAssertionExpressions.ts, 0, 0))
(<number>1).toString();
@@ -0,0 +1,60 @@
=== tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts ===
declare function foo(): string;
>foo : () => string
foo()(1 as number).toString();
>foo()(1 as number).toString() : any
>foo()(1 as number).toString : any
>foo()(1 as number) : any
>foo() : string
>foo : () => string
>1 as number : number
>1 : 1
>toString : any
foo() (1 as number).toString();
>foo() (1 as number).toString() : any
>foo() (1 as number).toString : any
>foo() (1 as number) : any
>foo() : string
>foo : () => string
>1 as number : number
>1 : 1
>toString : any
foo()
>foo()(1 as number).toString() : any
>foo()(1 as number).toString : any
>foo()(1 as number) : any
>foo() : string
>foo : () => string
(1 as number).toString();
>1 as number : number
>1 : 1
>toString : any
foo()
>foo() (1 as number).toString() : any
>foo() (1 as number).toString : any
>foo() (1 as number) : any
>foo() : string
>foo : () => string
(1 as number).toString();
>1 as number : number
>1 : 1
>toString : any
foo()
>foo() (<number>1).toString() : any
>foo() (<number>1).toString : any
>foo() (<number>1) : any
>foo() : string
>foo : () => string
(<number>1).toString();
><number>1 : number
>1 : 1
>toString : any
@@ -1,11 +1,11 @@
tests/cases/conformance/salsa/bug24934.js(2,1): error TS2304: Cannot find name 'module'.
tests/cases/conformance/salsa/bug24934.js(2,1): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`.
==== tests/cases/conformance/salsa/bug24934.js (1 errors) ====
export function abc(a, b, c) { return 5; }
module.exports = { abc };
~~~~~~
!!! error TS2304: Cannot find name 'module'.
!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`.
==== tests/cases/conformance/salsa/use.js (0 errors) ====
import { abc } from './bug24934';
abc(1, 2, 3);
@@ -1,5 +1,5 @@
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(11,13): error TS2304: Cannot find name 'module'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(11,13): error TS2503: Cannot find namespace 'module'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(11,13): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(11,19): error TS1005: ';' expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(22,35): error TS1005: ')' expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(22,39): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.
@@ -21,8 +21,8 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(40,41): error TS
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(40,45): error TS1002: Unterminated string literal.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(41,21): error TS2304: Cannot find name 'retValue'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(46,13): error TS1005: 'try' expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(47,17): error TS2304: Cannot find name 'console'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(53,13): error TS2304: Cannot find name 'console'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(47,17): error TS2584: Cannot find name 'console'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(53,13): error TS2584: Cannot find name 'console'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(58,5): error TS1128: Declaration or statement expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(69,13): error TS1109: Expression expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(72,37): error TS1127: Invalid character.
@@ -103,9 +103,9 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS
import fs = module("fs");
~~~~~~
!!! error TS2304: Cannot find name 'module'.
~~~~~~
!!! error TS2503: Cannot find namespace 'module'.
~~~~~~
!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`.
~
!!! error TS1005: ';' expected.
@@ -188,7 +188,7 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS
!!! error TS1005: 'try' expected.
console.log(e);
~~~~~~~
!!! error TS2304: Cannot find name 'console'.
!!! error TS2584: Cannot find name 'console'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'.
}
finally {
@@ -196,7 +196,7 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS
console.log('Done');
~~~~~~~
!!! error TS2304: Cannot find name 'console'.
!!! error TS2584: Cannot find name 'console'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'.
return 0;
@@ -0,0 +1,24 @@
// ==ORIGINAL==
function f() {
function fn2(){
function /*[#|*/fn3/*|]*/(){
return fetch("https://typescriptlang.org").then(res => console.log(res));
}
return fn3();
}
return fn2();
}
// ==ASYNC FUNCTION::Convert to async function==
function f() {
function fn2(){
async function fn3(){
const res = await fetch("https://typescriptlang.org");
return console.log(res);
}
return fn3();
}
return fn2();
}
@@ -0,0 +1,24 @@
// ==ORIGINAL==
function f() {
function fn2(){
function /*[#|*/fn3/*|]*/(){
return fetch("https://typescriptlang.org").then(res => console.log(res));
}
return fn3();
}
return fn2();
}
// ==ASYNC FUNCTION::Convert to async function==
function f() {
function fn2(){
async function fn3(){
const res = await fetch("https://typescriptlang.org");
return console.log(res);
}
return fn3();
}
return fn2();
}
@@ -0,0 +1,16 @@
// ==ORIGINAL==
function /*[#|*/f/*|]*/() {
return fetch('https://typescriptlang.org').then(undefined, rejection => console.log("rejected:", rejection));
}
// ==ASYNC FUNCTION::Convert to async function==
async function f() {
try {
await fetch('https://typescriptlang.org');
}
catch (rejection) {
return console.log("rejected:", rejection);
}
}
@@ -0,0 +1,16 @@
// ==ORIGINAL==
function /*[#|*/f/*|]*/() {
return fetch('https://typescriptlang.org').then(undefined, rejection => console.log("rejected:", rejection));
}
// ==ASYNC FUNCTION::Convert to async function==
async function f() {
try {
await fetch('https://typescriptlang.org');
}
catch (rejection) {
return console.log("rejected:", rejection);
}
}
@@ -0,0 +1,23 @@
//// [expando.ts]
// #27032
function ExpandoMerge(n: number) {
return n;
}
namespace ExpandoMerge {
export interface I { }
}
//// [expando.js]
// #27032
function ExpandoMerge(n) {
return n;
}
//// [expando.d.ts]
declare function ExpandoMerge(n: number): number;
declare namespace ExpandoMerge {
interface I {
}
}
@@ -0,0 +1,16 @@
=== tests/cases/compiler/expando.ts ===
// #27032
function ExpandoMerge(n: number) {
>ExpandoMerge : Symbol(ExpandoMerge, Decl(expando.ts, 0, 0), Decl(expando.ts, 3, 1))
>n : Symbol(n, Decl(expando.ts, 1, 22))
return n;
>n : Symbol(n, Decl(expando.ts, 1, 22))
}
namespace ExpandoMerge {
>ExpandoMerge : Symbol(ExpandoMerge, Decl(expando.ts, 0, 0), Decl(expando.ts, 3, 1))
export interface I { }
>I : Symbol(I, Decl(expando.ts, 4, 24))
}
@@ -0,0 +1,13 @@
=== tests/cases/compiler/expando.ts ===
// #27032
function ExpandoMerge(n: number) {
>ExpandoMerge : (n: number) => number
>n : number
return n;
>n : number
}
namespace ExpandoMerge {
export interface I { }
}
@@ -0,0 +1,14 @@
=== tests/cases/compiler/index.d.ts ===
export class C extends Object {
>C : Symbol(C, Decl(index.d.ts, 0, 0))
>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
static readonly p: unique symbol;
>p : Symbol(C.p, Decl(index.d.ts, 0, 31))
[C.p](): void;
>[C.p] : Symbol(C[C.p], Decl(index.d.ts, 1, 37))
>C.p : Symbol(C.p, Decl(index.d.ts, 0, 31))
>C : Symbol(C, Decl(index.d.ts, 0, 0))
>p : Symbol(C.p, Decl(index.d.ts, 0, 31))
}
@@ -0,0 +1,14 @@
=== tests/cases/compiler/index.d.ts ===
export class C extends Object {
>C : C
>Object : Object
static readonly p: unique symbol;
>p : unique symbol
[C.p](): void;
>[C.p] : () => void
>C.p : unique symbol
>C : typeof C
>p : unique symbol
}
@@ -7,7 +7,7 @@ error TS2318: Cannot find global type 'Object'.
error TS2318: Cannot find global type 'RegExp'.
error TS2318: Cannot find global type 'String'.
tests/cases/compiler/decoratorMetadataNoLibIsolatedModulesTypes.ts(2,6): error TS2304: Cannot find name 'Decorate'.
tests/cases/compiler/decoratorMetadataNoLibIsolatedModulesTypes.ts(3,13): error TS2304: Cannot find name 'Map'.
tests/cases/compiler/decoratorMetadataNoLibIsolatedModulesTypes.ts(3,13): error TS2583: Cannot find name 'Map'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.
!!! error TS2318: Cannot find global type 'Array'.
@@ -25,6 +25,6 @@ tests/cases/compiler/decoratorMetadataNoLibIsolatedModulesTypes.ts(3,13): error
!!! error TS2304: Cannot find name 'Decorate'.
member: Map<string, number>;
~~~
!!! error TS2304: Cannot find name 'Map'.
!!! error TS2583: Cannot find name 'Map'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.
}
@@ -0,0 +1,51 @@
tests/cases/compiler/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts(10,8): error TS2322: Type 'typeof Bar' is not assignable to type 'Bar'.
Property 'x' is missing in type 'typeof Bar'.
tests/cases/compiler/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts(11,8): error TS2322: Type 'DateConstructor' is not assignable to type 'Date'.
Property 'toDateString' is missing in type 'DateConstructor'.
tests/cases/compiler/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts(17,4): error TS2322: Type '() => number' is not assignable to type 'number'.
tests/cases/compiler/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts(26,5): error TS2322: Type '() => number' is not assignable to type 'number'.
==== tests/cases/compiler/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts (4 errors) ====
class Bar {
x!: string;
}
declare function getNum(): number;
declare function foo(arg: { x: Bar, y: Date }, item: number, items?: [number, number, number]): void;
foo({
x: Bar,
~~~
!!! error TS2322: Type 'typeof Bar' is not assignable to type 'Bar'.
!!! error TS2322: Property 'x' is missing in type 'typeof Bar'.
!!! related TS6213 tests/cases/compiler/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts:10:8: Did you mean to use `new` with this expression?
y: Date
~~~~
!!! error TS2322: Type 'DateConstructor' is not assignable to type 'Date'.
!!! error TS2322: Property 'toDateString' is missing in type 'DateConstructor'.
!!! related TS6213 tests/cases/compiler/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts:11:8: Did you mean to use `new` with this expression?
}, getNum());
foo({
x: new Bar(),
y: new Date()
}, getNum);
~~~~~~
!!! error TS2322: Type '() => number' is not assignable to type 'number'.
!!! related TS6212 tests/cases/compiler/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts:17:4: Did you mean to call this expression?
foo({
x: new Bar(),
y: new Date()
}, getNum(), [
1,
2,
getNum
~~~~~~
!!! error TS2322: Type '() => number' is not assignable to type 'number'.
!!! related TS6212 tests/cases/compiler/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts:26:5: Did you mean to call this expression?
]);
@@ -0,0 +1,52 @@
//// [didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts]
class Bar {
x!: string;
}
declare function getNum(): number;
declare function foo(arg: { x: Bar, y: Date }, item: number, items?: [number, number, number]): void;
foo({
x: Bar,
y: Date
}, getNum());
foo({
x: new Bar(),
y: new Date()
}, getNum);
foo({
x: new Bar(),
y: new Date()
}, getNum(), [
1,
2,
getNum
]);
//// [didYouMeanElaborationsForExpressionsWhichCouldBeCalled.js]
var Bar = /** @class */ (function () {
function Bar() {
}
return Bar;
}());
foo({
x: Bar,
y: Date
}, getNum());
foo({
x: new Bar(),
y: new Date()
}, getNum);
foo({
x: new Bar(),
y: new Date()
}, getNum(), [
1,
2,
getNum
]);
@@ -0,0 +1,71 @@
=== tests/cases/compiler/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts ===
class Bar {
>Bar : Symbol(Bar, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 0, 0))
x!: string;
>x : Symbol(Bar.x, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 0, 11))
}
declare function getNum(): number;
>getNum : Symbol(getNum, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 2, 1))
declare function foo(arg: { x: Bar, y: Date }, item: number, items?: [number, number, number]): void;
>foo : Symbol(foo, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 4, 34))
>arg : Symbol(arg, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 6, 21))
>x : Symbol(x, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 6, 27))
>Bar : Symbol(Bar, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 0, 0))
>y : Symbol(y, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 6, 35))
>Date : Symbol(Date, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.scripthost.d.ts, --, --))
>item : Symbol(item, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 6, 46))
>items : Symbol(items, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 6, 60))
foo({
>foo : Symbol(foo, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 4, 34))
x: Bar,
>x : Symbol(x, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 8, 5))
>Bar : Symbol(Bar, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 0, 0))
y: Date
>y : Symbol(y, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 9, 11))
>Date : Symbol(Date, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.scripthost.d.ts, --, --))
}, getNum());
>getNum : Symbol(getNum, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 2, 1))
foo({
>foo : Symbol(foo, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 4, 34))
x: new Bar(),
>x : Symbol(x, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 13, 5))
>Bar : Symbol(Bar, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 0, 0))
y: new Date()
>y : Symbol(y, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 14, 17))
>Date : Symbol(Date, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.scripthost.d.ts, --, --))
}, getNum);
>getNum : Symbol(getNum, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 2, 1))
foo({
>foo : Symbol(foo, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 4, 34))
x: new Bar(),
>x : Symbol(x, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 19, 5))
>Bar : Symbol(Bar, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 0, 0))
y: new Date()
>y : Symbol(y, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 20, 17))
>Date : Symbol(Date, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.scripthost.d.ts, --, --))
}, getNum(), [
>getNum : Symbol(getNum, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 2, 1))
1,
2,
getNum
>getNum : Symbol(getNum, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 2, 1))
]);
@@ -0,0 +1,86 @@
=== tests/cases/compiler/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts ===
class Bar {
>Bar : Bar
x!: string;
>x : string
}
declare function getNum(): number;
>getNum : () => number
declare function foo(arg: { x: Bar, y: Date }, item: number, items?: [number, number, number]): void;
>foo : (arg: { x: Bar; y: Date; }, item: number, items?: [number, number, number]) => void
>arg : { x: Bar; y: Date; }
>x : Bar
>y : Date
>item : number
>items : [number, number, number]
foo({
>foo({ x: Bar, y: Date}, getNum()) : void
>foo : (arg: { x: Bar; y: Date; }, item: number, items?: [number, number, number]) => void
>{ x: Bar, y: Date} : { x: typeof Bar; y: DateConstructor; }
x: Bar,
>x : typeof Bar
>Bar : typeof Bar
y: Date
>y : DateConstructor
>Date : DateConstructor
}, getNum());
>getNum() : number
>getNum : () => number
foo({
>foo({ x: new Bar(), y: new Date()}, getNum) : void
>foo : (arg: { x: Bar; y: Date; }, item: number, items?: [number, number, number]) => void
>{ x: new Bar(), y: new Date()} : { x: Bar; y: Date; }
x: new Bar(),
>x : Bar
>new Bar() : Bar
>Bar : typeof Bar
y: new Date()
>y : Date
>new Date() : Date
>Date : DateConstructor
}, getNum);
>getNum : () => number
foo({
>foo({ x: new Bar(), y: new Date()}, getNum(), [ 1, 2, getNum]) : void
>foo : (arg: { x: Bar; y: Date; }, item: number, items?: [number, number, number]) => void
>{ x: new Bar(), y: new Date()} : { x: Bar; y: Date; }
x: new Bar(),
>x : Bar
>new Bar() : Bar
>Bar : typeof Bar
y: new Date()
>y : Date
>new Date() : Date
>Date : DateConstructor
}, getNum(), [
>getNum() : number
>getNum : () => number
>[ 1, 2, getNum] : (number | (() => number))[]
1,
>1 : 1
2,
>2 : 2
getNum
>getNum : () => number
]);
@@ -0,0 +1,88 @@
tests/cases/compiler/didYouMeanSuggestionErrors.ts(1,1): error TS2582: Cannot find name 'describe'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`.
tests/cases/compiler/didYouMeanSuggestionErrors.ts(2,5): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`.
tests/cases/compiler/didYouMeanSuggestionErrors.ts(3,19): error TS2581: Cannot find name '$'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`.
tests/cases/compiler/didYouMeanSuggestionErrors.ts(7,1): error TS2582: Cannot find name 'suite'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`.
tests/cases/compiler/didYouMeanSuggestionErrors.ts(8,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`.
tests/cases/compiler/didYouMeanSuggestionErrors.ts(9,9): error TS2584: Cannot find name 'console'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'.
tests/cases/compiler/didYouMeanSuggestionErrors.ts(9,21): error TS2580: Cannot find name 'process'. Do you need to install type definitions for node? Try `npm i @types/node`.
tests/cases/compiler/didYouMeanSuggestionErrors.ts(10,9): error TS2584: Cannot find name 'document'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'.
tests/cases/compiler/didYouMeanSuggestionErrors.ts(12,19): error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node`.
tests/cases/compiler/didYouMeanSuggestionErrors.ts(13,19): error TS2580: Cannot find name 'Buffer'. Do you need to install type definitions for node? Try `npm i @types/node`.
tests/cases/compiler/didYouMeanSuggestionErrors.ts(14,19): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`.
tests/cases/compiler/didYouMeanSuggestionErrors.ts(16,23): error TS2583: Cannot find name 'Map'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.
tests/cases/compiler/didYouMeanSuggestionErrors.ts(17,23): error TS2583: Cannot find name 'Set'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.
tests/cases/compiler/didYouMeanSuggestionErrors.ts(18,23): error TS2583: Cannot find name 'WeakMap'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.
tests/cases/compiler/didYouMeanSuggestionErrors.ts(19,23): error TS2583: Cannot find name 'WeakSet'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.
tests/cases/compiler/didYouMeanSuggestionErrors.ts(20,19): error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.
tests/cases/compiler/didYouMeanSuggestionErrors.ts(21,19): error TS2585: 'Promise' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.
tests/cases/compiler/didYouMeanSuggestionErrors.ts(23,18): error TS2583: Cannot find name 'Iterator'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.
tests/cases/compiler/didYouMeanSuggestionErrors.ts(24,18): error TS2583: Cannot find name 'AsyncIterator'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.
==== tests/cases/compiler/didYouMeanSuggestionErrors.ts (19 errors) ====
describe("my test suite", () => {
~~~~~~~~
!!! error TS2582: Cannot find name 'describe'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`.
it("should run", () => {
~~
!!! error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`.
const a = $(".thing");
~
!!! error TS2581: Cannot find name '$'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`.
});
});
suite("another suite", () => {
~~~~~
!!! error TS2582: Cannot find name 'suite'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`.
test("everything else", () => {
~~~~
!!! error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`.
console.log(process.env);
~~~~~~~
!!! error TS2584: Cannot find name 'console'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'.
~~~~~~~
!!! error TS2580: Cannot find name 'process'. Do you need to install type definitions for node? Try `npm i @types/node`.
document.createElement("div");
~~~~~~~~
!!! error TS2584: Cannot find name 'document'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'.
const x = require("fs");
~~~~~~~
!!! error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node`.
const y = Buffer.from([]);
~~~~~~
!!! error TS2580: Cannot find name 'Buffer'. Do you need to install type definitions for node? Try `npm i @types/node`.
const z = module.exports;
~~~~~~
!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`.
const a = new Map();
~~~
!!! error TS2583: Cannot find name 'Map'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.
const b = new Set();
~~~
!!! error TS2583: Cannot find name 'Set'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.
const c = new WeakMap();
~~~~~~~
!!! error TS2583: Cannot find name 'WeakMap'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.
const d = new WeakSet();
~~~~~~~
!!! error TS2583: Cannot find name 'WeakSet'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.
const e = Symbol();
~~~~~~
!!! error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.
const f = Promise.resolve(0);
~~~~~~~
!!! error TS2585: 'Promise' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.
const i: Iterator<any> = null as any;
~~~~~~~~
!!! error TS2583: Cannot find name 'Iterator'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.
const j: AsyncIterator<any> = null as any;
~~~~~~~~~~~~~
!!! error TS2583: Cannot find name 'AsyncIterator'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.
const k: Symbol = null as any;
const l: Promise<any> = null as any;
});
});
@@ -0,0 +1,55 @@
//// [didYouMeanSuggestionErrors.ts]
describe("my test suite", () => {
it("should run", () => {
const a = $(".thing");
});
});
suite("another suite", () => {
test("everything else", () => {
console.log(process.env);
document.createElement("div");
const x = require("fs");
const y = Buffer.from([]);
const z = module.exports;
const a = new Map();
const b = new Set();
const c = new WeakMap();
const d = new WeakSet();
const e = Symbol();
const f = Promise.resolve(0);
const i: Iterator<any> = null as any;
const j: AsyncIterator<any> = null as any;
const k: Symbol = null as any;
const l: Promise<any> = null as any;
});
});
//// [didYouMeanSuggestionErrors.js]
describe("my test suite", function () {
it("should run", function () {
var a = $(".thing");
});
});
suite("another suite", function () {
test("everything else", function () {
console.log(process.env);
document.createElement("div");
var x = require("fs");
var y = Buffer.from([]);
var z = module.exports;
var a = new Map();
var b = new Set();
var c = new WeakMap();
var d = new WeakSet();
var e = Symbol();
var f = Promise.resolve(0);
var i = null;
var j = null;
var k = null;
var l = null;
});
});
@@ -0,0 +1,57 @@
=== tests/cases/compiler/didYouMeanSuggestionErrors.ts ===
describe("my test suite", () => {
it("should run", () => {
const a = $(".thing");
>a : Symbol(a, Decl(didYouMeanSuggestionErrors.ts, 2, 13))
});
});
suite("another suite", () => {
test("everything else", () => {
console.log(process.env);
document.createElement("div");
const x = require("fs");
>x : Symbol(x, Decl(didYouMeanSuggestionErrors.ts, 11, 13))
const y = Buffer.from([]);
>y : Symbol(y, Decl(didYouMeanSuggestionErrors.ts, 12, 13))
const z = module.exports;
>z : Symbol(z, Decl(didYouMeanSuggestionErrors.ts, 13, 13))
const a = new Map();
>a : Symbol(a, Decl(didYouMeanSuggestionErrors.ts, 15, 13))
const b = new Set();
>b : Symbol(b, Decl(didYouMeanSuggestionErrors.ts, 16, 13))
const c = new WeakMap();
>c : Symbol(c, Decl(didYouMeanSuggestionErrors.ts, 17, 13))
const d = new WeakSet();
>d : Symbol(d, Decl(didYouMeanSuggestionErrors.ts, 18, 13))
const e = Symbol();
>e : Symbol(e, Decl(didYouMeanSuggestionErrors.ts, 19, 13))
const f = Promise.resolve(0);
>f : Symbol(f, Decl(didYouMeanSuggestionErrors.ts, 20, 13))
const i: Iterator<any> = null as any;
>i : Symbol(i, Decl(didYouMeanSuggestionErrors.ts, 22, 13))
const j: AsyncIterator<any> = null as any;
>j : Symbol(j, Decl(didYouMeanSuggestionErrors.ts, 23, 13))
const k: Symbol = null as any;
>k : Symbol(k, Decl(didYouMeanSuggestionErrors.ts, 24, 13))
>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --))
const l: Promise<any> = null as any;
>l : Symbol(l, Decl(didYouMeanSuggestionErrors.ts, 25, 13))
>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --))
});
});
@@ -0,0 +1,125 @@
=== tests/cases/compiler/didYouMeanSuggestionErrors.ts ===
describe("my test suite", () => {
>describe("my test suite", () => { it("should run", () => { const a = $(".thing"); });}) : any
>describe : any
>"my test suite" : "my test suite"
>() => { it("should run", () => { const a = $(".thing"); });} : () => void
it("should run", () => {
>it("should run", () => { const a = $(".thing"); }) : any
>it : any
>"should run" : "should run"
>() => { const a = $(".thing"); } : () => void
const a = $(".thing");
>a : any
>$(".thing") : any
>$ : any
>".thing" : ".thing"
});
});
suite("another suite", () => {
>suite("another suite", () => { test("everything else", () => { console.log(process.env); document.createElement("div"); const x = require("fs"); const y = Buffer.from([]); const z = module.exports; const a = new Map(); const b = new Set(); const c = new WeakMap(); const d = new WeakSet(); const e = Symbol(); const f = Promise.resolve(0); const i: Iterator<any> = null as any; const j: AsyncIterator<any> = null as any; const k: Symbol = null as any; const l: Promise<any> = null as any; });}) : any
>suite : any
>"another suite" : "another suite"
>() => { test("everything else", () => { console.log(process.env); document.createElement("div"); const x = require("fs"); const y = Buffer.from([]); const z = module.exports; const a = new Map(); const b = new Set(); const c = new WeakMap(); const d = new WeakSet(); const e = Symbol(); const f = Promise.resolve(0); const i: Iterator<any> = null as any; const j: AsyncIterator<any> = null as any; const k: Symbol = null as any; const l: Promise<any> = null as any; });} : () => void
test("everything else", () => {
>test("everything else", () => { console.log(process.env); document.createElement("div"); const x = require("fs"); const y = Buffer.from([]); const z = module.exports; const a = new Map(); const b = new Set(); const c = new WeakMap(); const d = new WeakSet(); const e = Symbol(); const f = Promise.resolve(0); const i: Iterator<any> = null as any; const j: AsyncIterator<any> = null as any; const k: Symbol = null as any; const l: Promise<any> = null as any; }) : any
>test : any
>"everything else" : "everything else"
>() => { console.log(process.env); document.createElement("div"); const x = require("fs"); const y = Buffer.from([]); const z = module.exports; const a = new Map(); const b = new Set(); const c = new WeakMap(); const d = new WeakSet(); const e = Symbol(); const f = Promise.resolve(0); const i: Iterator<any> = null as any; const j: AsyncIterator<any> = null as any; const k: Symbol = null as any; const l: Promise<any> = null as any; } : () => void
console.log(process.env);
>console.log(process.env) : any
>console.log : any
>console : any
>log : any
>process.env : any
>process : any
>env : any
document.createElement("div");
>document.createElement("div") : any
>document.createElement : any
>document : any
>createElement : any
>"div" : "div"
const x = require("fs");
>x : any
>require("fs") : any
>require : any
>"fs" : "fs"
const y = Buffer.from([]);
>y : any
>Buffer.from([]) : any
>Buffer.from : any
>Buffer : any
>from : any
>[] : undefined[]
const z = module.exports;
>z : any
>module.exports : any
>module : any
>exports : any
const a = new Map();
>a : any
>new Map() : any
>Map : any
const b = new Set();
>b : any
>new Set() : any
>Set : any
const c = new WeakMap();
>c : any
>new WeakMap() : any
>WeakMap : any
const d = new WeakSet();
>d : any
>new WeakSet() : any
>WeakSet : any
const e = Symbol();
>e : any
>Symbol() : any
>Symbol : any
const f = Promise.resolve(0);
>f : any
>Promise.resolve(0) : any
>Promise.resolve : any
>Promise : any
>resolve : any
>0 : 0
const i: Iterator<any> = null as any;
>i : any
>null as any : any
>null : null
const j: AsyncIterator<any> = null as any;
>j : any
>null as any : any
>null : null
const k: Symbol = null as any;
>k : Symbol
>null as any : any
>null : null
const l: Promise<any> = null as any;
>l : Promise<any>
>null as any : any
>null : null
});
});
+1 -1
View File
@@ -15,7 +15,7 @@ tests/cases/conformance/jsdoc/a.js(37,16): error TS2339: Property 'UNKNOWN' does
/** @type {number} */
OK_I_GUESS: 2
}
/** @enum {number} */
/** @enum number */
const Second = {
MISTAKE: "end",
~~~~~~~~~~~~~~
+1 -1
View File
@@ -19,7 +19,7 @@ const Target = {
OK_I_GUESS: 2
>OK_I_GUESS : Symbol(OK_I_GUESS, Decl(a.js, 5, 15))
}
/** @enum {number} */
/** @enum number */
const Second = {
>Second : Symbol(Second, Decl(a.js, 10, 5))
+1 -1
View File
@@ -25,7 +25,7 @@ const Target = {
>OK_I_GUESS : number
>2 : 2
}
/** @enum {number} */
/** @enum number */
const Second = {
>Second : { MISTAKE: string; OK: number; FINE: number; }
>{ MISTAKE: "end", OK: 1, /** @type {number} */ FINE: 2,} : { MISTAKE: string; OK: number; FINE: number; }
@@ -1,9 +1,10 @@
tests/cases/compiler/errorForConflictingExportEqualsValue.ts(2,1): error TS2309: An export assignment cannot be used in a module with other exported elements.
/a.ts(2,1): error TS2309: An export assignment cannot be used in a module with other exported elements.
==== tests/cases/compiler/errorForConflictingExportEqualsValue.ts (1 errors) ====
==== /a.ts (1 errors) ====
export var x;
export = {};
~~~~~~~~~~~~
export = x;
~~~~~~~~~~~
!!! error TS2309: An export assignment cannot be used in a module with other exported elements.
import("./a");
@@ -1,8 +1,10 @@
//// [errorForConflictingExportEqualsValue.ts]
//// [a.ts]
export var x;
export = {};
export = x;
import("./a");
//// [errorForConflictingExportEqualsValue.js]
//// [a.js]
"use strict";
module.exports = {};
Promise.resolve().then(function () { return require("./a"); });
module.exports = exports.x;
@@ -1,6 +1,10 @@
=== tests/cases/compiler/errorForConflictingExportEqualsValue.ts ===
=== /a.ts ===
export var x;
>x : Symbol(x, Decl(errorForConflictingExportEqualsValue.ts, 0, 10))
>x : Symbol(x, Decl(a.ts, 0, 10))
export = {};
export = x;
>x : Symbol(x, Decl(a.ts, 0, 10))
import("./a");
>"./a" : Symbol("/a", Decl(a.ts, 0, 0))
@@ -1,7 +1,11 @@
=== tests/cases/compiler/errorForConflictingExportEqualsValue.ts ===
=== /a.ts ===
export var x;
>x : any
export = {};
>{} : {}
export = x;
>x : any
import("./a");
>import("./a") : Promise<typeof import("/a").x>
>"./a" : "./a"
@@ -1,6 +1,6 @@
tests/cases/compiler/externModule.ts(1,1): error TS2304: Cannot find name 'declare'.
tests/cases/compiler/externModule.ts(1,9): error TS1005: ';' expected.
tests/cases/compiler/externModule.ts(1,9): error TS2304: Cannot find name 'module'.
tests/cases/compiler/externModule.ts(1,9): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`.
tests/cases/compiler/externModule.ts(1,16): error TS1005: ';' expected.
tests/cases/compiler/externModule.ts(3,10): error TS2391: Function implementation is missing or not immediately following the declaration.
tests/cases/compiler/externModule.ts(4,10): error TS2391: Function implementation is missing or not immediately following the declaration.
@@ -21,7 +21,7 @@ tests/cases/compiler/externModule.ts(37,3): error TS2552: Cannot find name 'XDat
~~~~~~
!!! error TS1005: ';' expected.
~~~~~~
!!! error TS2304: Cannot find name 'module'.
!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`.
~
!!! error TS1005: ';' expected.
export class XDate {
@@ -50,9 +50,9 @@ tests/cases/conformance/fixSignatureCaching.ts(915,36): error TS2339: Property '
tests/cases/conformance/fixSignatureCaching.ts(915,53): error TS2339: Property 'mobileDetectRules' does not exist on type '{}'.
tests/cases/conformance/fixSignatureCaching.ts(955,42): error TS2339: Property 'mobileGrade' does not exist on type '{}'.
tests/cases/conformance/fixSignatureCaching.ts(964,57): error TS2339: Property 'getDeviceSmallerSide' does not exist on type '{}'.
tests/cases/conformance/fixSignatureCaching.ts(978,16): error TS2304: Cannot find name 'module'.
tests/cases/conformance/fixSignatureCaching.ts(978,42): error TS2304: Cannot find name 'module'.
tests/cases/conformance/fixSignatureCaching.ts(979,37): error TS2304: Cannot find name 'module'.
tests/cases/conformance/fixSignatureCaching.ts(978,16): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`.
tests/cases/conformance/fixSignatureCaching.ts(978,42): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`.
tests/cases/conformance/fixSignatureCaching.ts(979,37): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`.
tests/cases/conformance/fixSignatureCaching.ts(980,23): error TS2304: Cannot find name 'define'.
tests/cases/conformance/fixSignatureCaching.ts(980,48): error TS2304: Cannot find name 'define'.
tests/cases/conformance/fixSignatureCaching.ts(981,16): error TS2304: Cannot find name 'define'.
@@ -1143,12 +1143,12 @@ tests/cases/conformance/fixSignatureCaching.ts(983,44): error TS2339: Property '
})((function (undefined) {
if (typeof module !== 'undefined' && module.exports) {
~~~~~~
!!! error TS2304: Cannot find name 'module'.
!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`.
~~~~~~
!!! error TS2304: Cannot find name 'module'.
!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`.
return function (factory) { module.exports = factory(); };
~~~~~~
!!! error TS2304: Cannot find name 'module'.
!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`.
} else if (typeof define === 'function' && define.amd) {
~~~~~~
!!! error TS2304: Cannot find name 'define'.
@@ -1,4 +1,4 @@
tests/cases/compiler/functionSignatureAssignmentCompat1.ts(10,5): error TS2322: Type '(delimiter?: string) => ParserFunc' is not assignable to type 'ParserFunc'.
tests/cases/compiler/functionSignatureAssignmentCompat1.ts(10,21): error TS2322: Type '(delimiter?: string) => ParserFunc' is not assignable to type 'ParserFunc'.
Types of parameters 'delimiter' and 'eventEmitter' are incompatible.
Type 'number' is not assignable to type 'string'.
@@ -14,8 +14,9 @@ tests/cases/compiler/functionSignatureAssignmentCompat1.ts(10,5): error TS2322:
var parsers: Parsers;
var c: ParserFunc = parsers.raw; // ok!
var d: ParserFunc = parsers.readline; // not ok
~
~~~~~~~~~~~~~~~~
!!! error TS2322: Type '(delimiter?: string) => ParserFunc' is not assignable to type 'ParserFunc'.
!!! error TS2322: Types of parameters 'delimiter' and 'eventEmitter' are incompatible.
!!! error TS2322: Type 'number' is not assignable to type 'string'.
!!! related TS6212 tests/cases/compiler/functionSignatureAssignmentCompat1.ts:10:21: Did you mean to call this expression?
var e: ParserFunc = parsers.readline(); // ok
@@ -1,4 +1,4 @@
tests/cases/compiler/innerModExport1.ts(5,5): error TS2304: Cannot find name 'module'.
tests/cases/compiler/innerModExport1.ts(5,5): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`.
tests/cases/compiler/innerModExport1.ts(5,12): error TS1005: ';' expected.
@@ -9,7 +9,7 @@ tests/cases/compiler/innerModExport1.ts(5,12): error TS1005: ';' expected.
var non_export_var: number;
module {
~~~~~~
!!! error TS2304: Cannot find name 'module'.
!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`.
~
!!! error TS1005: ';' expected.
var non_export_var = 0;
@@ -1,4 +1,4 @@
tests/cases/compiler/innerModExport2.ts(5,5): error TS2304: Cannot find name 'module'.
tests/cases/compiler/innerModExport2.ts(5,5): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`.
tests/cases/compiler/innerModExport2.ts(5,12): error TS1005: ';' expected.
tests/cases/compiler/innerModExport2.ts(7,20): error TS2395: Individual declarations in merged declaration 'export_var' must be all exported or all local.
tests/cases/compiler/innerModExport2.ts(13,9): error TS2395: Individual declarations in merged declaration 'export_var' must be all exported or all local.
@@ -12,7 +12,7 @@ tests/cases/compiler/innerModExport2.ts(20,7): error TS2339: Property 'NonExport
var non_export_var: number;
module {
~~~~~~
!!! error TS2304: Cannot find name 'module'.
!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`.
~
!!! error TS1005: ';' expected.
var non_export_var = 0;
@@ -7,7 +7,7 @@ tests/cases/conformance/types/primitives/void/invalidAssignmentsToVoid.ts(10,1):
tests/cases/conformance/types/primitives/void/invalidAssignmentsToVoid.ts(14,1): error TS2322: Type 'I' is not assignable to type 'void'.
tests/cases/conformance/types/primitives/void/invalidAssignmentsToVoid.ts(17,1): error TS2322: Type 'typeof M' is not assignable to type 'void'.
tests/cases/conformance/types/primitives/void/invalidAssignmentsToVoid.ts(20,5): error TS2322: Type 'T' is not assignable to type 'void'.
tests/cases/conformance/types/primitives/void/invalidAssignmentsToVoid.ts(22,1): error TS2322: Type '<T>(a: T) => void' is not assignable to type 'void'.
tests/cases/conformance/types/primitives/void/invalidAssignmentsToVoid.ts(22,5): error TS2322: Type '<T>(a: T) => void' is not assignable to type 'void'.
==== tests/cases/conformance/types/primitives/void/invalidAssignmentsToVoid.ts (10 errors) ====
@@ -51,5 +51,6 @@ tests/cases/conformance/types/primitives/void/invalidAssignmentsToVoid.ts(22,1):
!!! error TS2322: Type 'T' is not assignable to type 'void'.
}
x = f;
~
!!! error TS2322: Type '<T>(a: T) => void' is not assignable to type 'void'.
~
!!! error TS2322: Type '<T>(a: T) => void' is not assignable to type 'void'.
!!! related TS6212 tests/cases/conformance/types/primitives/void/invalidAssignmentsToVoid.ts:22:5: Did you mean to call this expression?
@@ -8,7 +8,7 @@ tests/cases/conformance/types/primitives/void/invalidVoidValues.ts(16,1): error
tests/cases/conformance/types/primitives/void/invalidVoidValues.ts(18,1): error TS2322: Type '{ f(): void; }' is not assignable to type 'void'.
tests/cases/conformance/types/primitives/void/invalidVoidValues.ts(21,1): error TS2322: Type 'typeof M' is not assignable to type 'void'.
tests/cases/conformance/types/primitives/void/invalidVoidValues.ts(24,5): error TS2322: Type 'T' is not assignable to type 'void'.
tests/cases/conformance/types/primitives/void/invalidVoidValues.ts(26,1): error TS2322: Type '<T>(a: T) => void' is not assignable to type 'void'.
tests/cases/conformance/types/primitives/void/invalidVoidValues.ts(26,5): error TS2322: Type '<T>(a: T) => void' is not assignable to type 'void'.
==== tests/cases/conformance/types/primitives/void/invalidVoidValues.ts (11 errors) ====
@@ -58,5 +58,6 @@ tests/cases/conformance/types/primitives/void/invalidVoidValues.ts(26,1): error
!!! error TS2322: Type 'T' is not assignable to type 'void'.
}
x = f;
~
!!! error TS2322: Type '<T>(a: T) => void' is not assignable to type 'void'.
~
!!! error TS2322: Type '<T>(a: T) => void' is not assignable to type 'void'.
!!! related TS6212 tests/cases/conformance/types/primitives/void/invalidVoidValues.ts:26:5: Did you mean to call this expression?

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