Merge branch 'master' into kind

This commit is contained in:
Andy Hanson 2017-05-23 07:02:30 -07:00
commit b1e100e494
59 changed files with 5289 additions and 4829 deletions

View File

@ -260,18 +260,9 @@ namespace ts {
case SyntaxKind.ExportAssignment:
return (<ExportAssignment>node).isExportEquals ? "export=" : "default";
case SyntaxKind.BinaryExpression:
switch (getSpecialPropertyAssignmentKind(node as BinaryExpression)) {
case SpecialPropertyAssignmentKind.ModuleExports:
// module.exports = ...
return "export=";
case SpecialPropertyAssignmentKind.ExportsProperty:
case SpecialPropertyAssignmentKind.ThisProperty:
case SpecialPropertyAssignmentKind.Property:
// exports.x = ... or this.y = ...
return ((node as BinaryExpression).left as PropertyAccessExpression).name.text;
case SpecialPropertyAssignmentKind.PrototypeProperty:
// className.prototype.methodName = ...
return (((node as BinaryExpression).left as PropertyAccessExpression).expression as PropertyAccessExpression).name.text;
if (getSpecialPropertyAssignmentKind(node as BinaryExpression) === SpecialPropertyAssignmentKind.ModuleExports) {
// module.exports = ...
return "export=";
}
Debug.fail("Unknown binary declaration kind");
break;
@ -439,6 +430,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 (node.kind === SyntaxKind.JSDocTypedefTag) Debug.assert(isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file.
const isJSDocTypedefInJSDocNamespace = node.kind === SyntaxKind.JSDocTypedefTag &&
(node as JSDocTypedefTag).name &&
(node as JSDocTypedefTag).name.kind === SyntaxKind.Identifier &&
@ -603,9 +595,7 @@ namespace ts {
// Binding of JsDocComment should be done before the current block scope container changes.
// because the scope of JsDocComment should not be affected by whether the current node is a
// container or not.
if (isInJavaScriptFile(node) && node.jsDoc) {
forEach(node.jsDoc, bind);
}
forEach(node.jsDoc, bind);
if (checkUnreachable(node)) {
bindEachChild(node);
return;
@ -1913,9 +1903,7 @@ namespace ts {
// Here the current node is "foo", which is a container, but the scope of "MyType" should
// not be inside "foo". Therefore we always bind @typedef before bind the parent node,
// and skip binding this tag later when binding all the other jsdoc tags.
if (isInJavaScriptFile(node)) {
bindJSDocTypedefTagIfAny(node);
}
bindJSDocTypedefTagIfAny(node);
// First we bind declaration nodes to a symbol if possible. We'll both create a symbol
// and then potentially add the symbol to an appropriate symbol table. Possible
@ -2003,7 +1991,7 @@ namespace ts {
// for typedef type names with namespaces, bind the new jsdoc type symbol here
// because it requires all containing namespaces to be in effect, namely the
// current "blockScopeContainer" needs to be set to its immediate namespace parent.
if ((<Identifier>node).isInJSDocNamespace) {
if (isInJavaScriptFile(node) && (<Identifier>node).isInJSDocNamespace) {
let parentNode = node.parent;
while (parentNode && parentNode.kind !== SyntaxKind.JSDocTypedefTag) {
parentNode = parentNode.parent;
@ -2073,10 +2061,7 @@ namespace ts {
return bindVariableDeclarationOrBindingElement(<VariableDeclaration | BindingElement>node);
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.PropertySignature:
case SyntaxKind.JSDocRecordMember:
return bindPropertyOrMethodOrAccessor(<Declaration>node, SymbolFlags.Property | ((<PropertyDeclaration>node).questionToken ? SymbolFlags.Optional : SymbolFlags.None), SymbolFlags.PropertyExcludes);
case SyntaxKind.JSDocPropertyTag:
return bindJSDocProperty(<JSDocPropertyTag>node);
return bindPropertyWorker(node as PropertyDeclaration | PropertySignature);
case SyntaxKind.PropertyAssignment:
case SyntaxKind.ShorthandPropertyAssignment:
return bindPropertyOrMethodOrAccessor(<Declaration>node, SymbolFlags.Property, SymbolFlags.PropertyExcludes);
@ -2121,13 +2106,10 @@ namespace ts {
return bindPropertyOrMethodOrAccessor(<Declaration>node, SymbolFlags.SetAccessor, SymbolFlags.SetAccessorExcludes);
case SyntaxKind.FunctionType:
case SyntaxKind.ConstructorType:
case SyntaxKind.JSDocFunctionType:
return bindFunctionOrConstructorType(<SignatureDeclaration>node);
case SyntaxKind.TypeLiteral:
case SyntaxKind.MappedType:
case SyntaxKind.JSDocTypeLiteral:
case SyntaxKind.JSDocRecordType:
return bindAnonymousDeclaration(<Declaration>node, SymbolFlags.TypeLiteral, "__type");
return bindAnonymousTypeWorker(node as TypeLiteralNode | MappedTypeNode);
case SyntaxKind.ObjectLiteralExpression:
return bindObjectLiteralExpression(<ObjectLiteralExpression>node);
case SyntaxKind.FunctionExpression:
@ -2148,11 +2130,6 @@ namespace ts {
return bindClassLikeDeclaration(<ClassLikeDeclaration>node);
case SyntaxKind.InterfaceDeclaration:
return bindBlockScopedDeclaration(<Declaration>node, SymbolFlags.Interface, SymbolFlags.InterfaceExcludes);
case SyntaxKind.JSDocTypedefTag:
if (!(<JSDocTypedefTag>node).fullName || (<JSDocTypedefTag>node).fullName.kind === SyntaxKind.Identifier) {
return bindBlockScopedDeclaration(<Declaration>node, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes);
}
break;
case SyntaxKind.TypeAliasDeclaration:
return bindBlockScopedDeclaration(<Declaration>node, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes);
case SyntaxKind.EnumDeclaration:
@ -2190,9 +2167,41 @@ namespace ts {
// falls through
case SyntaxKind.ModuleBlock:
return updateStrictModeStatementList((<Block | ModuleBlock>node).statements);
default:
if (isInJavaScriptFile(node)) return bindJSDocWorker(node);
}
}
function bindJSDocWorker(node: Node) {
switch (node.kind) {
case SyntaxKind.JSDocRecordMember:
return bindPropertyWorker(node as JSDocRecordMember);
case SyntaxKind.JSDocPropertyTag:
return declareSymbolAndAddToSymbolTable(node as JSDocPropertyTag, SymbolFlags.Property, SymbolFlags.PropertyExcludes);
case SyntaxKind.JSDocFunctionType:
return bindFunctionOrConstructorType(<SignatureDeclaration>node);
case SyntaxKind.JSDocTypeLiteral:
case SyntaxKind.JSDocRecordType:
return bindAnonymousTypeWorker(node as JSDocTypeLiteral | JSDocRecordType);
case SyntaxKind.JSDocTypedefTag: {
const { fullName } = node as JSDocTypedefTag;
if (!fullName || fullName.kind === SyntaxKind.Identifier) {
return bindBlockScopedDeclaration(<Declaration>node, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes);
}
break;
}
}
}
function bindPropertyWorker(node: PropertyDeclaration | PropertySignature) {
return bindPropertyOrMethodOrAccessor(node, SymbolFlags.Property | (node.questionToken ? SymbolFlags.Optional : SymbolFlags.None), SymbolFlags.PropertyExcludes);
}
function bindAnonymousTypeWorker(node: TypeLiteralNode | MappedTypeNode | JSDocTypeLiteral | JSDocRecordType) {
return bindAnonymousDeclaration(<Declaration>node, SymbolFlags.TypeLiteral, "__type");
}
function checkTypePredicate(node: TypePredicateNode) {
const { parameterName, type } = node;
if (parameterName && parameterName.kind === SyntaxKind.Identifier) {
@ -2558,10 +2567,8 @@ namespace ts {
}
function bindPropertyOrMethodOrAccessor(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags) {
if (!file.isDeclarationFile && !isInAmbientContext(node)) {
if (isAsyncFunction(node)) {
emitFlags |= NodeFlags.HasAsyncFunctions;
}
if (!file.isDeclarationFile && !isInAmbientContext(node) && isAsyncFunction(node)) {
emitFlags |= NodeFlags.HasAsyncFunctions;
}
if (currentFlow && isObjectLiteralOrClassExpressionMethod(node)) {
@ -2573,10 +2580,6 @@ namespace ts {
: declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
}
function bindJSDocProperty(node: JSDocPropertyTag) {
return declareSymbolAndAddToSymbolTable(node, SymbolFlags.Property, SymbolFlags.PropertyExcludes);
}
// reachability checks
function shouldReportErrorOnModuleDeclaration(node: ModuleDeclaration): boolean {

View File

@ -3161,7 +3161,7 @@ namespace ts {
}
function buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]) {
const globalFlagsToPass = globalFlags & TypeFormatFlags.WriteOwnNameForAnyLike;
const globalFlagsToPass = globalFlags & (TypeFormatFlags.WriteOwnNameForAnyLike | TypeFormatFlags.WriteClassExpressionAsTypeLiteral);
let inObjectTypeLiteral = false;
return writeType(type, globalFlags);
@ -3278,6 +3278,11 @@ namespace ts {
writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), SyntaxKind.CommaToken);
writePunctuation(writer, SyntaxKind.CloseBracketToken);
}
else if (flags & TypeFormatFlags.WriteClassExpressionAsTypeLiteral &&
type.symbol.valueDeclaration &&
type.symbol.valueDeclaration.kind === SyntaxKind.ClassExpression) {
writeAnonymousType(getDeclaredTypeOfClassOrInterface(type.symbol), flags);
}
else {
// Write the type reference in the format f<A>.g<B>.C<X, Y> where A and B are type arguments
// for outer type parameters, and f and g are the respective declaring containers of those
@ -3325,7 +3330,9 @@ namespace ts {
const symbol = type.symbol;
if (symbol) {
// Always use 'typeof T' for type of class, enum, and module objects
if (symbol.flags & SymbolFlags.Class && !getBaseTypeVariableOfClass(symbol) ||
if (symbol.flags & SymbolFlags.Class &&
!getBaseTypeVariableOfClass(symbol) &&
!(symbol.valueDeclaration.kind === SyntaxKind.ClassExpression && flags & TypeFormatFlags.WriteClassExpressionAsTypeLiteral) ||
symbol.flags & (SymbolFlags.Enum | SymbolFlags.ValueModule)) {
writeTypeOfSymbol(type, flags);
}
@ -3347,12 +3354,23 @@ namespace ts {
else {
// Since instantiations of the same anonymous type have the same symbol, tracking symbols instead
// of types allows us to catch circular references to instantiations of the same anonymous type
// However, in case of class expressions, we want to write both the static side and the instance side.
// We skip adding the static side so that the instance side has a chance to be written
// before checking for circular references.
if (!symbolStack) {
symbolStack = [];
}
symbolStack.push(symbol);
writeLiteralType(type, flags);
symbolStack.pop();
const isConstructorObject = type.flags & TypeFlags.Object &&
getObjectFlags(type) & ObjectFlags.Anonymous &&
type.symbol && type.symbol.flags & SymbolFlags.Class;
if (isConstructorObject) {
writeLiteralType(type, flags);
}
else {
symbolStack.push(symbol);
writeLiteralType(type, flags);
symbolStack.pop();
}
}
}
else {
@ -3471,6 +3489,14 @@ namespace ts {
buildIndexSignatureDisplay(resolved.stringIndexInfo, writer, IndexKind.String, enclosingDeclaration, globalFlags, symbolStack);
buildIndexSignatureDisplay(resolved.numberIndexInfo, writer, IndexKind.Number, enclosingDeclaration, globalFlags, symbolStack);
for (const p of resolved.properties) {
if (globalFlags & TypeFormatFlags.WriteClassExpressionAsTypeLiteral) {
if (p.flags & SymbolFlags.Prototype) {
continue;
}
if (getDeclarationModifierFlagsFromSymbol(p) & (ModifierFlags.Private | ModifierFlags.Protected)) {
writer.reportPrivateInBaseOfClassExpression(p.name);
}
}
const t = getTypeOfSymbol(p);
if (p.flags & (SymbolFlags.Function | SymbolFlags.Method) && !getPropertiesOfObjectType(t).length) {
const signatures = getSignaturesOfType(t, SignatureKind.Call);
@ -3485,7 +3511,7 @@ namespace ts {
writePropertyWithModifiers(p);
writePunctuation(writer, SyntaxKind.ColonToken);
writeSpace(writer);
writeType(t, TypeFormatFlags.None);
writeType(t, globalFlags & TypeFormatFlags.WriteClassExpressionAsTypeLiteral);
writePunctuation(writer, SyntaxKind.SemicolonToken);
writer.writeLine();
}
@ -22327,6 +22353,11 @@ namespace ts {
}
}
if (entityName.parent!.kind === SyntaxKind.JSDocParameterTag) {
const parameter = ts.getParameterFromJSDoc(entityName.parent as JSDocParameterTag);
return parameter && parameter.symbol;
}
if (isPartOfExpression(entityName)) {
if (nodeIsMissing(entityName)) {
// Missing entity name.

View File

@ -1783,7 +1783,8 @@ namespace ts {
return path.length > extension.length && endsWith(path, extension);
}
export function fileExtensionIsAny(path: string, extensions: string[]): boolean {
/* @internal */
export function fileExtensionIsOneOf(path: string, extensions: string[]): boolean {
for (const extension of extensions) {
if (fileExtensionIs(path, extension)) {
return true;
@ -1983,7 +1984,7 @@ namespace ts {
for (const current of files) {
const name = combinePaths(path, current);
const absoluteName = combinePaths(absolutePath, current);
if (extensions && !fileExtensionIsAny(name, extensions)) continue;
if (extensions && !fileExtensionIsOneOf(name, extensions)) continue;
if (excludeRegex && excludeRegex.test(absoluteName)) continue;
if (!includeFileRegexes) {
results[0].push(name);

View File

@ -190,7 +190,7 @@ namespace ts {
const writer = <EmitTextWriterWithSymbolWriter>createTextWriter(newLine);
writer.trackSymbol = trackSymbol;
writer.reportInaccessibleThisError = reportInaccessibleThisError;
writer.reportIllegalExtends = reportIllegalExtends;
writer.reportPrivateInBaseOfClassExpression = reportPrivateInBaseOfClassExpression;
writer.writeKeyword = writer.write;
writer.writeOperator = writer.write;
writer.writePunctuation = writer.write;
@ -314,11 +314,11 @@ namespace ts {
recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning));
}
function reportIllegalExtends() {
function reportPrivateInBaseOfClassExpression(propertyName: string) {
if (errorNameNode) {
reportedDeclarationError = true;
emitterDiagnostics.add(createDiagnosticForNode(errorNameNode, Diagnostics.extends_clause_of_exported_class_0_refers_to_a_type_whose_name_cannot_be_referenced,
declarationNameToString(errorNameNode)));
emitterDiagnostics.add(
createDiagnosticForNode(errorNameNode, Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName));
}
}
@ -344,7 +344,9 @@ namespace ts {
}
else {
errorNameNode = declaration.name;
const format = TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue |
const format = TypeFormatFlags.UseTypeOfFunction |
TypeFormatFlags.WriteClassExpressionAsTypeLiteral |
TypeFormatFlags.UseTypeAliasValue |
(shouldUseResolverType ? TypeFormatFlags.AddUndefined : 0);
resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer);
errorNameNode = undefined;
@ -360,7 +362,11 @@ namespace ts {
}
else {
errorNameNode = signature.name;
resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue, writer);
resolver.writeReturnTypeOfSignatureDeclaration(
signature,
enclosingDeclaration,
TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue | TypeFormatFlags.WriteClassExpressionAsTypeLiteral,
writer);
errorNameNode = undefined;
}
}
@ -621,7 +627,11 @@ namespace ts {
write(tempVarName);
write(": ");
writer.getSymbolAccessibilityDiagnostic = () => diagnostic;
resolver.writeTypeOfExpression(expr, enclosingDeclaration, TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue, writer);
resolver.writeTypeOfExpression(
expr,
enclosingDeclaration,
TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue | TypeFormatFlags.WriteClassExpressionAsTypeLiteral,
writer);
write(";");
writeLine();
return tempVarName;

View File

@ -2456,9 +2456,9 @@
"category": "Error",
"code": 4092
},
"'extends' clause of exported class '{0}' refers to a type whose name cannot be referenced.": {
"Property '{0}' of exported class expression may not be private or protected.": {
"category": "Error",
"code": 4093
"code": 4094
},
"The current host does not support the '{0}' option.": {

View File

@ -1631,14 +1631,14 @@ namespace ts {
: node;
}
export function createImportClause(name: Identifier, namedBindings: NamedImportBindings): ImportClause {
export function createImportClause(name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause {
const node = <ImportClause>createSynthesizedNode(SyntaxKind.ImportClause);
node.name = name;
node.namedBindings = namedBindings;
return node;
}
export function updateImportClause(node: ImportClause, name: Identifier, namedBindings: NamedImportBindings) {
export function updateImportClause(node: ImportClause, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined) {
return node.name !== name
|| node.namedBindings !== namedBindings
? updateNode(createImportClause(name, namedBindings), node)

View File

@ -971,10 +971,13 @@ namespace ts {
}
}
/** Double underscores are used in DefinitelyTyped to delimit scoped packages. */
const mangledScopedPackageSeparator = "__";
/** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */
function mangleScopedPackage(moduleName: string, state: ModuleResolutionState): string {
if (startsWith(moduleName, "@")) {
const replaceSlash = moduleName.replace(ts.directorySeparator, "__");
const replaceSlash = moduleName.replace(ts.directorySeparator, mangledScopedPackageSeparator);
if (replaceSlash !== moduleName) {
const mangled = replaceSlash.slice(1); // Take off the "@"
if (state.traceEnabled) {
@ -986,6 +989,17 @@ namespace ts {
return moduleName;
}
/* @internal */
export function getPackageNameFromAtTypesDirectory(mangledName: string): string {
const withoutAtTypePrefix = removePrefix(mangledName, "@types/");
if (withoutAtTypePrefix !== mangledName) {
return withoutAtTypePrefix.indexOf("__") !== -1 ?
"@" + withoutAtTypePrefix.replace(mangledScopedPackageSeparator, ts.directorySeparator) :
withoutAtTypePrefix;
}
return mangledName;
}
function tryFindNonRelativeModuleNameInCache(cache: PerModuleNameCache | undefined, moduleName: string, containingDirectory: string, traceEnabled: boolean, host: ModuleResolutionHost): SearchResult<Resolved> {
const result = cache && cache.get(containingDirectory);
if (result) {

View File

@ -50,7 +50,7 @@ namespace ts {
// stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise,
// embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns
// a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
export function forEachChild<T>(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T | undefined {
export function forEachChild<T>(node: Node, cbNode: (node: Node) => T | undefined, cbNodeArray?: (nodes: NodeArray<Node>) => T | undefined): T | undefined {
if (!node) {
return;
}

View File

@ -2651,24 +2651,25 @@ namespace ts {
// with import statements it previously saw (but chose not to emit).
trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void;
reportInaccessibleThisError(): void;
reportIllegalExtends(): void;
reportPrivateInBaseOfClassExpression(propertyName: string): void;
}
export const enum TypeFormatFlags {
None = 0x00000000,
WriteArrayAsGenericType = 0x00000001, // Write Array<T> instead T[]
UseTypeOfFunction = 0x00000002, // Write typeof instead of function type literal
NoTruncation = 0x00000004, // Don't truncate typeToString result
WriteArrowStyleSignature = 0x00000008, // Write arrow style signature
WriteOwnNameForAnyLike = 0x00000010, // Write symbol's own name instead of 'any' for any like types (eg. unknown, __resolving__ etc)
WriteTypeArgumentsOfSignature = 0x00000020, // Write the type arguments instead of type parameters of the signature
InElementType = 0x00000040, // Writing an array or union element type
UseFullyQualifiedType = 0x00000080, // Write out the fully qualified type name (eg. Module.Type, instead of Type)
InFirstTypeArgument = 0x00000100, // Writing first type argument of the instantiated type
InTypeAlias = 0x00000200, // Writing type in type alias declaration
UseTypeAliasValue = 0x00000400, // Serialize the type instead of using type-alias. This is needed when we emit declaration file.
SuppressAnyReturnType = 0x00000800, // If the return type is any-like, don't offer a return type.
AddUndefined = 0x00001000, // Add undefined to types of initialized, non-optional parameters
None = 0,
WriteArrayAsGenericType = 1 << 0, // Write Array<T> instead T[]
UseTypeOfFunction = 1 << 2, // Write typeof instead of function type literal
NoTruncation = 1 << 3, // Don't truncate typeToString result
WriteArrowStyleSignature = 1 << 4, // Write arrow style signature
WriteOwnNameForAnyLike = 1 << 5, // Write symbol's own name instead of 'any' for any like types (eg. unknown, __resolving__ etc)
WriteTypeArgumentsOfSignature = 1 << 6, // Write the type arguments instead of type parameters of the signature
InElementType = 1 << 7, // Writing an array or union element type
UseFullyQualifiedType = 1 << 8, // Write out the fully qualified type name (eg. Module.Type, instead of Type)
InFirstTypeArgument = 1 << 9, // Writing first type argument of the instantiated type
InTypeAlias = 1 << 10, // Writing type in type alias declaration
UseTypeAliasValue = 1 << 11, // Serialize the type instead of using type-alias. This is needed when we emit declaration file.
SuppressAnyReturnType = 1 << 12, // If the return type is any-like, don't offer a return type.
AddUndefined = 1 << 13, // Add undefined to types of initialized, non-optional parameters
WriteClassExpressionAsTypeLiteral = 1 << 14, // Write a type literal instead of (Anonymous class)
}
export const enum SymbolFormatFlags {

View File

@ -68,7 +68,7 @@ namespace ts {
clear: () => str = "",
trackSymbol: noop,
reportInaccessibleThisError: noop,
reportIllegalExtends: noop
reportPrivateInBaseOfClassExpression: noop,
};
}
@ -1599,7 +1599,7 @@ namespace ts {
// Pull parameter comments from declaring function as well
if (node.kind === SyntaxKind.Parameter) {
cache = concatenate(cache, getJSDocParameterTags(node));
cache = concatenate(cache, getJSDocParameterTags(node as ParameterDeclaration));
}
if (isVariableLike(node) && node.initializer) {
@ -1610,11 +1610,8 @@ namespace ts {
}
}
export function getJSDocParameterTags(param: Node): JSDocParameterTag[] {
if (!isParameter(param)) {
return undefined;
}
const func = param.parent as FunctionLikeDeclaration;
export function getJSDocParameterTags(param: ParameterDeclaration): JSDocParameterTag[] {
const func = param.parent;
const tags = getJSDocTags(func, SyntaxKind.JSDocParameterTag) as JSDocParameterTag[];
if (!param.name) {
// this is an anonymous jsdoc param from a `function(type1, type2): type3` specification
@ -1635,10 +1632,22 @@ namespace ts {
}
}
/** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */
export function getParameterFromJSDoc(node: JSDocParameterTag): ParameterDeclaration | undefined {
const name = node.parameterName.text;
const grandParent = node.parent!.parent!;
Debug.assert(node.parent!.kind === SyntaxKind.JSDocComment);
if (!isFunctionLike(grandParent)) {
return undefined;
}
return find(grandParent.parameters, p =>
p.name.kind === SyntaxKind.Identifier && p.name.text === name);
}
export function getJSDocType(node: Node): JSDocType {
let tag: JSDocTypeTag | JSDocParameterTag = getFirstJSDocTag(node, SyntaxKind.JSDocTypeTag) as JSDocTypeTag;
if (!tag && node.kind === SyntaxKind.Parameter) {
const paramTags = getJSDocParameterTags(node);
const paramTags = getJSDocParameterTags(node as ParameterDeclaration);
if (paramTags) {
tag = find(paramTags, tag => !!tag.typeExpression);
}
@ -1776,36 +1785,6 @@ namespace ts {
}
}
export function getNameOfDeclaration(declaration: Declaration): DeclarationName {
if (!declaration) {
return undefined;
}
if (declaration.kind === SyntaxKind.BinaryExpression) {
const kind = getSpecialPropertyAssignmentKind(declaration as BinaryExpression);
const lhs = (declaration as BinaryExpression).left;
switch (kind) {
case SpecialPropertyAssignmentKind.None:
case SpecialPropertyAssignmentKind.ModuleExports:
return undefined;
case SpecialPropertyAssignmentKind.ExportsProperty:
if (lhs.kind === SyntaxKind.Identifier) {
return (lhs as PropertyAccessExpression).name;
}
else {
return ((lhs as PropertyAccessExpression).expression as PropertyAccessExpression).name;
}
case SpecialPropertyAssignmentKind.ThisProperty:
case SpecialPropertyAssignmentKind.Property:
return (lhs as PropertyAccessExpression).name;
case SpecialPropertyAssignmentKind.PrototypeProperty:
return ((lhs as PropertyAccessExpression).expression as PropertyAccessExpression).name;
}
}
else {
return (declaration as NamedDeclaration).name;
}
}
export function isLiteralComputedPropertyDeclarationName(node: Node) {
return (node.kind === SyntaxKind.StringLiteral || node.kind === SyntaxKind.NumericLiteral) &&
node.parent.kind === SyntaxKind.ComputedPropertyName &&
@ -4729,4 +4708,25 @@ namespace ts {
export function unescapeIdentifier(identifier: string): string {
return identifier.length >= 3 && identifier.charCodeAt(0) === CharacterCodes._ && identifier.charCodeAt(1) === CharacterCodes._ && identifier.charCodeAt(2) === CharacterCodes._ ? identifier.substr(1) : identifier;
}
export function getNameOfDeclaration(declaration: Declaration): DeclarationName | undefined {
if (!declaration) {
return undefined;
}
if (declaration.kind === SyntaxKind.BinaryExpression) {
const expr = declaration as BinaryExpression;
switch (getSpecialPropertyAssignmentKind(expr)) {
case SpecialPropertyAssignmentKind.ExportsProperty:
case SpecialPropertyAssignmentKind.ThisProperty:
case SpecialPropertyAssignmentKind.Property:
case SpecialPropertyAssignmentKind.PrototypeProperty:
return (expr.left as PropertyAccessExpression).name;
default:
return undefined;
}
}
else {
return (declaration as NamedDeclaration).name;
}
}
}

View File

@ -916,7 +916,7 @@ namespace FourSlash {
}
private getNode(): ts.Node {
return ts.getTouchingPropertyName(this.getSourceFile(), this.currentCaretPosition);
return ts.getTouchingPropertyName(this.getSourceFile(), this.currentCaretPosition, /*includeJsDocComment*/ false);
}
private goToAndGetNode(range: Range): ts.Node {
@ -994,12 +994,11 @@ namespace FourSlash {
}
public verifyReferenceGroups(startRanges: Range | Range[], parts: Array<{ definition: string, ranges: Range[] }>): void {
interface ReferenceJson { definition: string; ranges: ts.ReferenceEntry[]; }
const fullExpected = ts.map(parts, ({ definition, ranges }) => ({ definition, ranges: ranges.map(rangeToReferenceEntry) }));
for (const startRange of toArray(startRanges)) {
this.goToRangeStart(startRange);
const fullActual = ts.map<ts.ReferencedSymbol, ReferenceJson>(this.findReferencesAtCaret(), ({ definition, references }) => ({
const fullActual = ts.map(this.findReferencesAtCaret(), ({ definition, references }) => ({
definition: definition.displayParts.map(d => d.text).join(""),
ranges: references
}));
@ -1046,6 +1045,10 @@ namespace FourSlash {
this.raiseError(`${msgPrefix}At ${path}: ${msg}`);
};
if ((actual === undefined) !== (expected === undefined)) {
fail(`Expected ${expected}, got ${actual}`);
}
for (const key in actual) if (ts.hasProperty(actual as any, key)) {
const ak = actual[key], ek = expected[key];
if (typeof ak === "object" && typeof ek === "object") {

View File

@ -172,7 +172,7 @@ namespace Utils {
assert.isFalse(child.pos < currentPos, "child.pos < currentPos");
currentPos = child.end;
},
(array: ts.NodeArray<ts.Node>) => {
array => {
assert.isFalse(array.pos < node.pos, "array.pos < node.pos");
assert.isFalse(array.end > node.end, "array.end > node.end");
assert.isFalse(array.pos < currentPos, "array.pos < currentPos");
@ -383,7 +383,7 @@ namespace Utils {
assertStructuralEquals(child1, child2);
},
(array1: ts.NodeArray<ts.Node>) => {
array1 => {
const childName = findChildName(node1, array1);
const array2: ts.NodeArray<ts.Node> = (<any>node2)[childName];

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
/////////////////////////////
/// IE Worker APIs
/// Worker APIs
/////////////////////////////
interface Algorithm {
@ -8,16 +8,16 @@ interface Algorithm {
}
interface CacheQueryOptions {
ignoreSearch?: boolean;
ignoreMethod?: boolean;
ignoreVary?: boolean;
cacheName?: string;
ignoreMethod?: boolean;
ignoreSearch?: boolean;
ignoreVary?: boolean;
}
interface CloseEventInit extends EventInit {
wasClean?: boolean;
code?: number;
reason?: string;
wasClean?: boolean;
}
interface EventInit {
@ -49,16 +49,16 @@ interface MessageEventInit extends EventInit {
channel?: string;
data?: any;
origin?: string;
source?: any;
ports?: MessagePort[];
source?: any;
}
interface NotificationOptions {
dir?: NotificationDirection;
lang?: string;
body?: string;
tag?: string;
dir?: NotificationDirection;
icon?: string;
lang?: string;
tag?: string;
}
interface ObjectURLOptions {
@ -66,29 +66,29 @@ interface ObjectURLOptions {
}
interface PushSubscriptionOptionsInit {
userVisibleOnly?: boolean;
applicationServerKey?: any;
userVisibleOnly?: boolean;
}
interface RequestInit {
method?: string;
headers?: any;
body?: any;
referrer?: string;
referrerPolicy?: ReferrerPolicy;
mode?: RequestMode;
credentials?: RequestCredentials;
cache?: RequestCache;
redirect?: RequestRedirect;
credentials?: RequestCredentials;
headers?: any;
integrity?: string;
keepalive?: boolean;
method?: string;
mode?: RequestMode;
redirect?: RequestRedirect;
referrer?: string;
referrerPolicy?: ReferrerPolicy;
window?: any;
}
interface ResponseInit {
headers?: any;
status?: number;
statusText?: string;
headers?: any;
}
interface ClientQueryOptions {
@ -156,7 +156,7 @@ interface AudioBuffer {
declare var AudioBuffer: {
prototype: AudioBuffer;
new(): AudioBuffer;
}
};
interface Blob {
readonly size: number;
@ -169,7 +169,7 @@ interface Blob {
declare var Blob: {
prototype: Blob;
new (blobParts?: any[], options?: BlobPropertyBag): Blob;
}
};
interface Cache {
add(request: RequestInfo): Promise<void>;
@ -184,7 +184,7 @@ interface Cache {
declare var Cache: {
prototype: Cache;
new(): Cache;
}
};
interface CacheStorage {
delete(cacheName: string): Promise<boolean>;
@ -197,7 +197,7 @@ interface CacheStorage {
declare var CacheStorage: {
prototype: CacheStorage;
new(): CacheStorage;
}
};
interface CloseEvent extends Event {
readonly code: number;
@ -209,7 +209,7 @@ interface CloseEvent extends Event {
declare var CloseEvent: {
prototype: CloseEvent;
new(typeArg: string, eventInitDict?: CloseEventInit): CloseEvent;
}
};
interface Console {
assert(test?: boolean, message?: string, ...optionalParams: any[]): void;
@ -220,8 +220,8 @@ interface Console {
dirxml(value: any): void;
error(message?: any, ...optionalParams: any[]): void;
exception(message?: string, ...optionalParams: any[]): void;
group(groupTitle?: string): void;
groupCollapsed(groupTitle?: string): void;
group(groupTitle?: string, ...optionalParams: any[]): void;
groupCollapsed(groupTitle?: string, ...optionalParams: any[]): void;
groupEnd(): void;
info(message?: any, ...optionalParams: any[]): void;
log(message?: any, ...optionalParams: any[]): void;
@ -239,7 +239,7 @@ interface Console {
declare var Console: {
prototype: Console;
new(): Console;
}
};
interface Coordinates {
readonly accuracy: number;
@ -254,7 +254,7 @@ interface Coordinates {
declare var Coordinates: {
prototype: Coordinates;
new(): Coordinates;
}
};
interface CryptoKey {
readonly algorithm: KeyAlgorithm;
@ -266,7 +266,7 @@ interface CryptoKey {
declare var CryptoKey: {
prototype: CryptoKey;
new(): CryptoKey;
}
};
interface DOMError {
readonly name: string;
@ -276,7 +276,7 @@ interface DOMError {
declare var DOMError: {
prototype: DOMError;
new(): DOMError;
}
};
interface DOMException {
readonly code: number;
@ -296,10 +296,10 @@ interface DOMException {
readonly INVALID_STATE_ERR: number;
readonly NAMESPACE_ERR: number;
readonly NETWORK_ERR: number;
readonly NOT_FOUND_ERR: number;
readonly NOT_SUPPORTED_ERR: number;
readonly NO_DATA_ALLOWED_ERR: number;
readonly NO_MODIFICATION_ALLOWED_ERR: number;
readonly NOT_FOUND_ERR: number;
readonly NOT_SUPPORTED_ERR: number;
readonly PARSE_ERR: number;
readonly QUOTA_EXCEEDED_ERR: number;
readonly SECURITY_ERR: number;
@ -328,10 +328,10 @@ declare var DOMException: {
readonly INVALID_STATE_ERR: number;
readonly NAMESPACE_ERR: number;
readonly NETWORK_ERR: number;
readonly NOT_FOUND_ERR: number;
readonly NOT_SUPPORTED_ERR: number;
readonly NO_DATA_ALLOWED_ERR: number;
readonly NO_MODIFICATION_ALLOWED_ERR: number;
readonly NOT_FOUND_ERR: number;
readonly NOT_SUPPORTED_ERR: number;
readonly PARSE_ERR: number;
readonly QUOTA_EXCEEDED_ERR: number;
readonly SECURITY_ERR: number;
@ -342,7 +342,7 @@ declare var DOMException: {
readonly URL_MISMATCH_ERR: number;
readonly VALIDATION_ERR: number;
readonly WRONG_DOCUMENT_ERR: number;
}
};
interface DOMStringList {
readonly length: number;
@ -354,7 +354,7 @@ interface DOMStringList {
declare var DOMStringList: {
prototype: DOMStringList;
new(): DOMStringList;
}
};
interface ErrorEvent extends Event {
readonly colno: number;
@ -368,12 +368,12 @@ interface ErrorEvent extends Event {
declare var ErrorEvent: {
prototype: ErrorEvent;
new(type: string, errorEventInitDict?: ErrorEventInit): ErrorEvent;
}
};
interface Event {
readonly bubbles: boolean;
cancelBubble: boolean;
readonly cancelable: boolean;
cancelBubble: boolean;
readonly currentTarget: EventTarget;
readonly defaultPrevented: boolean;
readonly eventPhase: number;
@ -400,7 +400,7 @@ declare var Event: {
readonly AT_TARGET: number;
readonly BUBBLING_PHASE: number;
readonly CAPTURING_PHASE: number;
}
};
interface EventTarget {
addEventListener(type: string, listener?: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
@ -411,7 +411,7 @@ interface EventTarget {
declare var EventTarget: {
prototype: EventTarget;
new(): EventTarget;
}
};
interface File extends Blob {
readonly lastModifiedDate: any;
@ -422,7 +422,7 @@ interface File extends Blob {
declare var File: {
prototype: File;
new (parts: (ArrayBuffer | ArrayBufferView | Blob | string)[], filename: string, properties?: FilePropertyBag): File;
}
};
interface FileList {
readonly length: number;
@ -433,7 +433,7 @@ interface FileList {
declare var FileList: {
prototype: FileList;
new(): FileList;
}
};
interface FileReader extends EventTarget, MSBaseReader {
readonly error: DOMError;
@ -448,8 +448,17 @@ interface FileReader extends EventTarget, MSBaseReader {
declare var FileReader: {
prototype: FileReader;
new(): FileReader;
};
interface FormData {
append(name: string, value: string | Blob, fileName?: string): void;
}
declare var FormData: {
prototype: FormData;
new(): FormData;
};
interface Headers {
append(name: string, value: string): void;
delete(name: string): void;
@ -462,7 +471,7 @@ interface Headers {
declare var Headers: {
prototype: Headers;
new(init?: any): Headers;
}
};
interface IDBCursor {
readonly direction: IDBCursorDirection;
@ -486,7 +495,7 @@ declare var IDBCursor: {
readonly NEXT_NO_DUPLICATE: string;
readonly PREV: string;
readonly PREV_NO_DUPLICATE: string;
}
};
interface IDBCursorWithValue extends IDBCursor {
readonly value: any;
@ -495,7 +504,7 @@ interface IDBCursorWithValue extends IDBCursor {
declare var IDBCursorWithValue: {
prototype: IDBCursorWithValue;
new(): IDBCursorWithValue;
}
};
interface IDBDatabaseEventMap {
"abort": Event;
@ -512,7 +521,7 @@ interface IDBDatabase extends EventTarget {
close(): void;
createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore;
deleteObjectStore(name: string): void;
transaction(storeNames: string | string[], mode?: string): IDBTransaction;
transaction(storeNames: string | string[], mode?: IDBTransactionMode): IDBTransaction;
addEventListener(type: "versionchange", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void;
addEventListener<K extends keyof IDBDatabaseEventMap>(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
@ -521,7 +530,7 @@ interface IDBDatabase extends EventTarget {
declare var IDBDatabase: {
prototype: IDBDatabase;
new(): IDBDatabase;
}
};
interface IDBFactory {
cmp(first: any, second: any): number;
@ -532,7 +541,7 @@ interface IDBFactory {
declare var IDBFactory: {
prototype: IDBFactory;
new(): IDBFactory;
}
};
interface IDBIndex {
keyPath: string | string[];
@ -543,14 +552,14 @@ interface IDBIndex {
count(key?: IDBKeyRange | IDBValidKey): IDBRequest;
get(key: IDBKeyRange | IDBValidKey): IDBRequest;
getKey(key: IDBKeyRange | IDBValidKey): IDBRequest;
openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest;
openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest;
openCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest;
openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest;
}
declare var IDBIndex: {
prototype: IDBIndex;
new(): IDBIndex;
}
};
interface IDBKeyRange {
readonly lower: any;
@ -566,7 +575,7 @@ declare var IDBKeyRange: {
lowerBound(lower: any, open?: boolean): IDBKeyRange;
only(value: any): IDBKeyRange;
upperBound(upper: any, open?: boolean): IDBKeyRange;
}
};
interface IDBObjectStore {
readonly indexNames: DOMStringList;
@ -582,14 +591,14 @@ interface IDBObjectStore {
deleteIndex(indexName: string): void;
get(key: any): IDBRequest;
index(name: string): IDBIndex;
openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest;
openCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest;
put(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest;
}
declare var IDBObjectStore: {
prototype: IDBObjectStore;
new(): IDBObjectStore;
}
};
interface IDBOpenDBRequestEventMap extends IDBRequestEventMap {
"blocked": Event;
@ -606,7 +615,7 @@ interface IDBOpenDBRequest extends IDBRequest {
declare var IDBOpenDBRequest: {
prototype: IDBOpenDBRequest;
new(): IDBOpenDBRequest;
}
};
interface IDBRequestEventMap {
"error": Event;
@ -614,7 +623,7 @@ interface IDBRequestEventMap {
}
interface IDBRequest extends EventTarget {
readonly error: DOMError;
readonly error: DOMException;
onerror: (this: IDBRequest, ev: Event) => any;
onsuccess: (this: IDBRequest, ev: Event) => any;
readonly readyState: IDBRequestReadyState;
@ -628,7 +637,7 @@ interface IDBRequest extends EventTarget {
declare var IDBRequest: {
prototype: IDBRequest;
new(): IDBRequest;
}
};
interface IDBTransactionEventMap {
"abort": Event;
@ -638,7 +647,7 @@ interface IDBTransactionEventMap {
interface IDBTransaction extends EventTarget {
readonly db: IDBDatabase;
readonly error: DOMError;
readonly error: DOMException;
readonly mode: IDBTransactionMode;
onabort: (this: IDBTransaction, ev: Event) => any;
oncomplete: (this: IDBTransaction, ev: Event) => any;
@ -658,7 +667,7 @@ declare var IDBTransaction: {
readonly READ_ONLY: string;
readonly READ_WRITE: string;
readonly VERSION_CHANGE: string;
}
};
interface IDBVersionChangeEvent extends Event {
readonly newVersion: number | null;
@ -668,7 +677,7 @@ interface IDBVersionChangeEvent extends Event {
declare var IDBVersionChangeEvent: {
prototype: IDBVersionChangeEvent;
new(): IDBVersionChangeEvent;
}
};
interface ImageData {
data: Uint8ClampedArray;
@ -680,7 +689,7 @@ declare var ImageData: {
prototype: ImageData;
new(width: number, height: number): ImageData;
new(array: Uint8ClampedArray, width: number, height: number): ImageData;
}
};
interface MessageChannel {
readonly port1: MessagePort;
@ -690,7 +699,7 @@ interface MessageChannel {
declare var MessageChannel: {
prototype: MessageChannel;
new(): MessageChannel;
}
};
interface MessageEvent extends Event {
readonly data: any;
@ -703,7 +712,7 @@ interface MessageEvent extends Event {
declare var MessageEvent: {
prototype: MessageEvent;
new(type: string, eventInitDict?: MessageEventInit): MessageEvent;
}
};
interface MessagePortEventMap {
"message": MessageEvent;
@ -721,7 +730,7 @@ interface MessagePort extends EventTarget {
declare var MessagePort: {
prototype: MessagePort;
new(): MessagePort;
}
};
interface NotificationEventMap {
"click": Event;
@ -751,7 +760,7 @@ declare var Notification: {
prototype: Notification;
new(title: string, options?: NotificationOptions): Notification;
requestPermission(callback?: NotificationPermissionCallback): Promise<NotificationPermission>;
}
};
interface Performance {
readonly navigation: PerformanceNavigation;
@ -774,7 +783,7 @@ interface Performance {
declare var Performance: {
prototype: Performance;
new(): Performance;
}
};
interface PerformanceNavigation {
readonly redirectCount: number;
@ -793,18 +802,18 @@ declare var PerformanceNavigation: {
readonly TYPE_NAVIGATE: number;
readonly TYPE_RELOAD: number;
readonly TYPE_RESERVED: number;
}
};
interface PerformanceTiming {
readonly connectEnd: number;
readonly connectStart: number;
readonly domainLookupEnd: number;
readonly domainLookupStart: number;
readonly domComplete: number;
readonly domContentLoadedEventEnd: number;
readonly domContentLoadedEventStart: number;
readonly domInteractive: number;
readonly domLoading: number;
readonly domainLookupEnd: number;
readonly domainLookupStart: number;
readonly fetchStart: number;
readonly loadEventEnd: number;
readonly loadEventStart: number;
@ -824,7 +833,7 @@ interface PerformanceTiming {
declare var PerformanceTiming: {
prototype: PerformanceTiming;
new(): PerformanceTiming;
}
};
interface Position {
readonly coords: Coordinates;
@ -834,7 +843,7 @@ interface Position {
declare var Position: {
prototype: Position;
new(): Position;
}
};
interface PositionError {
readonly code: number;
@ -851,7 +860,7 @@ declare var PositionError: {
readonly PERMISSION_DENIED: number;
readonly POSITION_UNAVAILABLE: number;
readonly TIMEOUT: number;
}
};
interface ProgressEvent extends Event {
readonly lengthComputable: boolean;
@ -863,7 +872,7 @@ interface ProgressEvent extends Event {
declare var ProgressEvent: {
prototype: ProgressEvent;
new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent;
}
};
interface PushManager {
getSubscription(): Promise<PushSubscription>;
@ -874,7 +883,7 @@ interface PushManager {
declare var PushManager: {
prototype: PushManager;
new(): PushManager;
}
};
interface PushSubscription {
readonly endpoint: USVString;
@ -887,7 +896,7 @@ interface PushSubscription {
declare var PushSubscription: {
prototype: PushSubscription;
new(): PushSubscription;
}
};
interface PushSubscriptionOptions {
readonly applicationServerKey: ArrayBuffer | null;
@ -897,7 +906,7 @@ interface PushSubscriptionOptions {
declare var PushSubscriptionOptions: {
prototype: PushSubscriptionOptions;
new(): PushSubscriptionOptions;
}
};
interface ReadableStream {
readonly locked: boolean;
@ -908,7 +917,7 @@ interface ReadableStream {
declare var ReadableStream: {
prototype: ReadableStream;
new(): ReadableStream;
}
};
interface ReadableStreamReader {
cancel(): Promise<void>;
@ -919,7 +928,7 @@ interface ReadableStreamReader {
declare var ReadableStreamReader: {
prototype: ReadableStreamReader;
new(): ReadableStreamReader;
}
};
interface Request extends Object, Body {
readonly cache: RequestCache;
@ -941,7 +950,7 @@ interface Request extends Object, Body {
declare var Request: {
prototype: Request;
new(input: Request | string, init?: RequestInit): Request;
}
};
interface Response extends Object, Body {
readonly body: ReadableStream | null;
@ -957,7 +966,9 @@ interface Response extends Object, Body {
declare var Response: {
prototype: Response;
new(body?: any, init?: ResponseInit): Response;
}
error: () => Response;
redirect: (url: string, status?: number) => Response;
};
interface ServiceWorkerEventMap extends AbstractWorkerEventMap {
"statechange": Event;
@ -975,7 +986,7 @@ interface ServiceWorker extends EventTarget, AbstractWorker {
declare var ServiceWorker: {
prototype: ServiceWorker;
new(): ServiceWorker;
}
};
interface ServiceWorkerRegistrationEventMap {
"updatefound": Event;
@ -1000,7 +1011,7 @@ interface ServiceWorkerRegistration extends EventTarget {
declare var ServiceWorkerRegistration: {
prototype: ServiceWorkerRegistration;
new(): ServiceWorkerRegistration;
}
};
interface SyncManager {
getTags(): any;
@ -1010,7 +1021,7 @@ interface SyncManager {
declare var SyncManager: {
prototype: SyncManager;
new(): SyncManager;
}
};
interface URL {
hash: string;
@ -1033,7 +1044,7 @@ declare var URL: {
new(url: string, base?: string): URL;
createObjectURL(object: any, options?: ObjectURLOptions): string;
revokeObjectURL(url: string): void;
}
};
interface WebSocketEventMap {
"close": CloseEvent;
@ -1070,7 +1081,7 @@ declare var WebSocket: {
readonly CLOSING: number;
readonly CONNECTING: number;
readonly OPEN: number;
}
};
interface WorkerEventMap extends AbstractWorkerEventMap {
"message": MessageEvent;
@ -1087,7 +1098,7 @@ interface Worker extends EventTarget, AbstractWorker {
declare var Worker: {
prototype: Worker;
new(stringUrl: string): Worker;
}
};
interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap {
"readystatechange": Event;
@ -1133,7 +1144,7 @@ declare var XMLHttpRequest: {
readonly LOADING: number;
readonly OPENED: number;
readonly UNSENT: number;
}
};
interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget {
addEventListener<K extends keyof XMLHttpRequestEventTargetEventMap>(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void;
@ -1143,7 +1154,7 @@ interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget {
declare var XMLHttpRequestUpload: {
prototype: XMLHttpRequestUpload;
new(): XMLHttpRequestUpload;
}
};
interface AbstractWorkerEventMap {
"error": ErrorEvent;
@ -1258,7 +1269,7 @@ interface Client {
declare var Client: {
prototype: Client;
new(): Client;
}
};
interface Clients {
claim(): Promise<void>;
@ -1270,7 +1281,7 @@ interface Clients {
declare var Clients: {
prototype: Clients;
new(): Clients;
}
};
interface DedicatedWorkerGlobalScopeEventMap extends WorkerGlobalScopeEventMap {
"message": MessageEvent;
@ -1287,7 +1298,7 @@ interface DedicatedWorkerGlobalScope extends WorkerGlobalScope {
declare var DedicatedWorkerGlobalScope: {
prototype: DedicatedWorkerGlobalScope;
new(): DedicatedWorkerGlobalScope;
}
};
interface ExtendableEvent extends Event {
waitUntil(f: Promise<any>): void;
@ -1296,7 +1307,7 @@ interface ExtendableEvent extends Event {
declare var ExtendableEvent: {
prototype: ExtendableEvent;
new(type: string, eventInitDict?: ExtendableEventInit): ExtendableEvent;
}
};
interface ExtendableMessageEvent extends ExtendableEvent {
readonly data: any;
@ -1309,7 +1320,7 @@ interface ExtendableMessageEvent extends ExtendableEvent {
declare var ExtendableMessageEvent: {
prototype: ExtendableMessageEvent;
new(type: string, eventInitDict?: ExtendableMessageEventInit): ExtendableMessageEvent;
}
};
interface FetchEvent extends ExtendableEvent {
readonly clientId: string | null;
@ -1321,7 +1332,7 @@ interface FetchEvent extends ExtendableEvent {
declare var FetchEvent: {
prototype: FetchEvent;
new(type: string, eventInitDict: FetchEventInit): FetchEvent;
}
};
interface FileReaderSync {
readAsArrayBuffer(blob: Blob): any;
@ -1333,7 +1344,7 @@ interface FileReaderSync {
declare var FileReaderSync: {
prototype: FileReaderSync;
new(): FileReaderSync;
}
};
interface NotificationEvent extends ExtendableEvent {
readonly action: string;
@ -1343,7 +1354,7 @@ interface NotificationEvent extends ExtendableEvent {
declare var NotificationEvent: {
prototype: NotificationEvent;
new(type: string, eventInitDict: NotificationEventInit): NotificationEvent;
}
};
interface PushEvent extends ExtendableEvent {
readonly data: PushMessageData | null;
@ -1352,7 +1363,7 @@ interface PushEvent extends ExtendableEvent {
declare var PushEvent: {
prototype: PushEvent;
new(type: string, eventInitDict?: PushEventInit): PushEvent;
}
};
interface PushMessageData {
arrayBuffer(): ArrayBuffer;
@ -1364,7 +1375,7 @@ interface PushMessageData {
declare var PushMessageData: {
prototype: PushMessageData;
new(): PushMessageData;
}
};
interface ServiceWorkerGlobalScopeEventMap extends WorkerGlobalScopeEventMap {
"activate": ExtendableEvent;
@ -1398,7 +1409,7 @@ interface ServiceWorkerGlobalScope extends WorkerGlobalScope {
declare var ServiceWorkerGlobalScope: {
prototype: ServiceWorkerGlobalScope;
new(): ServiceWorkerGlobalScope;
}
};
interface SyncEvent extends ExtendableEvent {
readonly lastChance: boolean;
@ -1408,7 +1419,7 @@ interface SyncEvent extends ExtendableEvent {
declare var SyncEvent: {
prototype: SyncEvent;
new(type: string, init: SyncEventInit): SyncEvent;
}
};
interface WindowClient extends Client {
readonly focused: boolean;
@ -1420,7 +1431,7 @@ interface WindowClient extends Client {
declare var WindowClient: {
prototype: WindowClient;
new(): WindowClient;
}
};
interface WorkerGlobalScopeEventMap {
"error": ErrorEvent;
@ -1443,7 +1454,7 @@ interface WorkerGlobalScope extends EventTarget, WorkerUtils, WindowConsole, Glo
declare var WorkerGlobalScope: {
prototype: WorkerGlobalScope;
new(): WorkerGlobalScope;
}
};
interface WorkerLocation {
readonly hash: string;
@ -1461,7 +1472,7 @@ interface WorkerLocation {
declare var WorkerLocation: {
prototype: WorkerLocation;
new(): WorkerLocation;
}
};
interface WorkerNavigator extends Object, NavigatorID, NavigatorOnLine, NavigatorBeacon, NavigatorConcurrentHardware {
readonly hardwareConcurrency: number;
@ -1470,7 +1481,7 @@ interface WorkerNavigator extends Object, NavigatorID, NavigatorOnLine, Navigato
declare var WorkerNavigator: {
prototype: WorkerNavigator;
new(): WorkerNavigator;
}
};
interface WorkerUtils extends Object, WindowBase64 {
readonly indexedDB: IDBFactory;
@ -1513,38 +1524,38 @@ interface ImageBitmap {
interface URLSearchParams {
/**
* Appends a specified key/value pair as a new search parameter.
*/
* Appends a specified key/value pair as a new search parameter.
*/
append(name: string, value: string): void;
/**
* Deletes the given search parameter, and its associated value, from the list of all search parameters.
*/
* Deletes the given search parameter, and its associated value, from the list of all search parameters.
*/
delete(name: string): void;
/**
* Returns the first value associated to the given search parameter.
*/
* Returns the first value associated to the given search parameter.
*/
get(name: string): string | null;
/**
* Returns all the values association with a given search parameter.
*/
* Returns all the values association with a given search parameter.
*/
getAll(name: string): string[];
/**
* Returns a Boolean indicating if such a search parameter exists.
*/
* Returns a Boolean indicating if such a search parameter exists.
*/
has(name: string): boolean;
/**
* Sets the value associated to a given search parameter to the given value. If there were several values, delete the others.
*/
* Sets the value associated to a given search parameter to the given value. If there were several values, delete the others.
*/
set(name: string, value: string): void;
}
declare var URLSearchParams: {
prototype: URLSearchParams;
/**
* Constructor returning a URLSearchParams object.
*/
* Constructor returning a URLSearchParams object.
*/
new (init?: string | URLSearchParams): URLSearchParams;
}
};
interface BlobPropertyBag {
type?: string;
@ -1751,8 +1762,23 @@ interface AddEventListenerOptions extends EventListenerOptions {
declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject;
interface DecodeErrorCallback {
(error: DOMException): void;
}
interface DecodeSuccessCallback {
(decodedData: AudioBuffer): void;
}
interface ErrorEventHandler {
(message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void;
(message: string, filename?: string, lineno?: number, colno?: number, error?: Error): void;
}
interface ForEachCallback {
(keyId: any, status: MediaKeyStatus): void;
}
interface FunctionStringCallback {
(data: string): void;
}
interface NotificationPermissionCallback {
(permission: NotificationPermission): void;
}
interface PositionCallback {
(position: Position): void;
@ -1760,21 +1786,6 @@ interface PositionCallback {
interface PositionErrorCallback {
(error: PositionError): void;
}
interface DecodeSuccessCallback {
(decodedData: AudioBuffer): void;
}
interface DecodeErrorCallback {
(error: DOMException): void;
}
interface FunctionStringCallback {
(data: string): void;
}
interface ForEachCallback {
(keyId: any, status: MediaKeyStatus): void;
}
interface NotificationPermissionCallback {
(permission: NotificationPermission): void;
}
declare var onmessage: (this: DedicatedWorkerGlobalScope, ev: MessageEvent) => any;
declare function close(): void;
declare function postMessage(message: any, transfer?: any[]): void;

View File

@ -14,7 +14,7 @@ namespace ts.BreakpointResolver {
return undefined;
}
let tokenAtLocation = getTokenAtPosition(sourceFile, position);
let tokenAtLocation = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false);
const lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line;
if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) {
// Get previous token if the token is returned starts on new line

View File

@ -22,7 +22,7 @@ namespace ts.codefix {
// We also want to check if the previous line holds a comment for a node on the next line
// if so, we do not want to separate the node from its comment if we can.
if (!isInComment(sourceFile, startPosition) && !isInString(sourceFile, startPosition) && !isInTemplateString(sourceFile, startPosition)) {
const token = getTouchingToken(sourceFile, startPosition);
const token = getTouchingToken(sourceFile, startPosition, /*includeJsDocComment*/ false);
const tokenLeadingCommnets = getLeadingCommentRangesOfNode(token, sourceFile);
if (!tokenLeadingCommnets || !tokenLeadingCommnets.length || tokenLeadingCommnets[0].pos >= startPosition) {
return {

View File

@ -13,7 +13,7 @@ namespace ts.codefix {
// This is the identifier of the missing property. eg:
// this.missing = 1;
// ^^^^^^^
const token = getTokenAtPosition(sourceFile, start);
const token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false);
if (token.kind !== SyntaxKind.Identifier) {
return undefined;

View File

@ -15,7 +15,7 @@ namespace ts.codefix {
const start = context.span.start;
// This is the identifier in the case of a class declaration
// or the class keyword token in the case of a class expression.
const token = getTokenAtPosition(sourceFile, start);
const token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false);
const checker = context.program.getTypeChecker();
if (isClassLike(token.parent)) {

View File

@ -8,7 +8,7 @@ namespace ts.codefix {
function getActionForClassLikeIncorrectImplementsInterface(context: CodeFixContext): CodeAction[] | undefined {
const sourceFile = context.sourceFile;
const start = context.span.start;
const token = getTokenAtPosition(sourceFile, start);
const token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false);
const checker = context.program.getTypeChecker();
const classDeclaration = getContainingClass(token);

View File

@ -5,7 +5,7 @@ namespace ts.codefix {
getCodeActions: (context: CodeFixContext) => {
const sourceFile = context.sourceFile;
const token = getTokenAtPosition(sourceFile, context.span.start);
const token = getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false);
if (token.kind !== SyntaxKind.ThisKeyword) {
return undefined;
}

View File

@ -4,7 +4,7 @@ namespace ts.codefix {
errorCodes: [Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code],
getCodeActions: (context: CodeFixContext) => {
const sourceFile = context.sourceFile;
const token = getTokenAtPosition(sourceFile, context.span.start);
const token = getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false);
if (token.kind !== SyntaxKind.ConstructorKeyword) {
return undefined;

View File

@ -5,7 +5,7 @@ namespace ts.codefix {
getCodeActions: (context: CodeFixContext) => {
const sourceFile = context.sourceFile;
const start = context.span.start;
const token = getTokenAtPosition(sourceFile, start);
const token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false);
const classDeclNode = getContainingClass(token);
if (!(token.kind === SyntaxKind.Identifier && isClassLike(classDeclNode))) {
return undefined;

View File

@ -4,7 +4,7 @@ namespace ts.codefix {
errorCodes: [Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code],
getCodeActions: (context: CodeFixContext) => {
const sourceFile = context.sourceFile;
const token = getTokenAtPosition(sourceFile, context.span.start);
const token = getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false);
if (token.kind !== SyntaxKind.Identifier) {
return undefined;
}

View File

@ -12,7 +12,7 @@ namespace ts.codefix {
// This is the identifier of the misspelled word. eg:
// this.speling = 1;
// ^^^^^^^
const node = getTokenAtPosition(sourceFile, context.span.start);
const node = getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); // TODO: GH#15852
const checker = context.program.getTypeChecker();
let suggestion: string;
if (node.kind === SyntaxKind.Identifier && isPropertyAccessExpression(node.parent)) {

View File

@ -128,7 +128,7 @@ namespace ts.codefix {
const allSourceFiles = context.program.getSourceFiles();
const useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false;
const token = getTokenAtPosition(sourceFile, context.span.start);
const token = getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false);
const name = token.getText();
const symbolIdActionMap = new ImportCodeActionMap();
@ -523,7 +523,7 @@ namespace ts.codefix {
catch (e) { }
}
return relativeFileName;
return getPackageNameFromAtTypesDirectory(relativeFileName);
}
}

View File

@ -9,11 +9,11 @@ namespace ts.codefix {
const sourceFile = context.sourceFile;
const start = context.span.start;
let token = getTokenAtPosition(sourceFile, start);
let token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false);
// this handles var ["computed"] = 12;
if (token.kind === SyntaxKind.OpenBracketToken) {
token = getTokenAtPosition(sourceFile, start + 1);
token = getTokenAtPosition(sourceFile, start + 1, /*includeJsDocComment*/ false);
}
switch (token.kind) {
@ -48,11 +48,11 @@ namespace ts.codefix {
case SyntaxKind.TypeParameter:
const typeParameters = (<DeclarationWithTypeParameters>token.parent.parent).typeParameters;
if (typeParameters.length === 1) {
const previousToken = getTokenAtPosition(sourceFile, typeParameters.pos - 1);
const previousToken = getTokenAtPosition(sourceFile, typeParameters.pos - 1, /*includeJsDocComment*/ false);
if (!previousToken || previousToken.kind !== SyntaxKind.LessThanToken) {
return deleteRange(typeParameters);
}
const nextToken = getTokenAtPosition(sourceFile, typeParameters.end);
const nextToken = getTokenAtPosition(sourceFile, typeParameters.end, /*includeJsDocComment*/ false);
if (!nextToken || nextToken.kind !== SyntaxKind.GreaterThanToken) {
return deleteRange(typeParameters);
}
@ -99,7 +99,7 @@ namespace ts.codefix {
else {
// import |d,| * as ns from './file'
const start = importClause.name.getStart(sourceFile);
const nextToken = getTokenAtPosition(sourceFile, importClause.name.end);
const nextToken = getTokenAtPosition(sourceFile, importClause.name.end, /*includeJsDocComment*/ false);
if (nextToken && nextToken.kind === SyntaxKind.CommaToken) {
// shift first non-whitespace position after comma to the start position of the node
return deleteRange({ pos: start, end: skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true) });
@ -116,7 +116,7 @@ namespace ts.codefix {
return deleteNode(importDecl);
}
else {
const previousToken = getTokenAtPosition(sourceFile, namespaceImport.pos - 1);
const previousToken = getTokenAtPosition(sourceFile, namespaceImport.pos - 1, /*includeJsDocComment*/ false);
if (previousToken && previousToken.kind === SyntaxKind.CommaToken) {
const startPosition = textChanges.getAdjustedStartPosition(sourceFile, previousToken, {}, textChanges.Position.FullStart);
return deleteRange({ pos: startPosition, end: namespaceImport.end });

View File

@ -354,7 +354,7 @@ namespace ts.Completions {
let requestJsDocTag = false;
let start = timestamp();
const currentToken = getTokenAtPosition(sourceFile, position);
const currentToken = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); // TODO: GH#15853
log("getCompletionData: Get current token: " + (timestamp() - start));
start = timestamp();
@ -449,7 +449,7 @@ namespace ts.Completions {
let isRightOfOpenTag = false;
let isStartingCloseTag = false;
let location = getTouchingPropertyName(sourceFile, position);
let location = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ false); // TODO: GH#15853
if (contextToken) {
// Bail out if this is a known invalid completion location
if (isCompletionListBlocker(contextToken)) {

View File

@ -1,7 +1,7 @@
/* @internal */
namespace ts.DocumentHighlights {
export function getDocumentHighlights(program: Program, cancellationToken: CancellationToken, sourceFile: SourceFile, position: number, sourceFilesToSearch: SourceFile[]): DocumentHighlights[] {
const node = getTouchingWord(sourceFile, position);
const node = getTouchingWord(sourceFile, position, /*includeJsDocComment*/ true);
return node && (getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile));
}

View File

@ -61,13 +61,18 @@ namespace ts.FindAllReferences {
}
export function getImplementationsAtPosition(program: Program, cancellationToken: CancellationToken, sourceFiles: SourceFile[], sourceFile: SourceFile, position: number): ImplementationLocation[] {
const node = getTouchingPropertyName(sourceFile, position);
// A node in a JSDoc comment can't have an implementation anyway.
const node = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ false);
const referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node);
const checker = program.getTypeChecker();
return map(referenceEntries, entry => toImplementationLocation(entry, checker));
}
function getImplementationReferenceEntries(program: Program, cancellationToken: CancellationToken, sourceFiles: SourceFile[], node: Node): Entry[] | undefined {
if (node.kind === SyntaxKind.SourceFile) {
return undefined;
}
const checker = program.getTypeChecker();
// If invoked directly on a shorthand property assignment, then return
// the declaration of the symbol being assigned (not the symbol being assigned to).
@ -740,7 +745,7 @@ namespace ts.FindAllReferences.Core {
const labelName = targetLabel.text;
const possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container);
for (const position of possiblePositions) {
const node = getTouchingWord(sourceFile, position);
const node = getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false);
// Only pick labels that are either the target label, or have a target that is the target label
if (node && (node === targetLabel || (isJumpStatementTarget(node) && getTargetLabel(node, labelName) === targetLabel))) {
references.push(nodeEntry(node));
@ -778,9 +783,10 @@ namespace ts.FindAllReferences.Core {
}
function addReferencesForKeywordInFile(sourceFile: SourceFile, kind: SyntaxKind, searchText: string, references: Push<NodeEntry>): void {
const possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText);
// Want fullStart so we can find the symbol in JSDoc comments
const possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, sourceFile, /*fullStart*/ true);
for (const position of possiblePositions) {
const referenceLocation = getTouchingPropertyName(sourceFile, position);
const referenceLocation = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
if (referenceLocation.kind === kind) {
references.push(nodeEntry(referenceLocation));
}
@ -802,13 +808,13 @@ namespace ts.FindAllReferences.Core {
return;
}
for (const position of getPossibleSymbolReferencePositions(sourceFile, search.text, container, /*fullStart*/ state.findInComments)) {
for (const position of getPossibleSymbolReferencePositions(sourceFile, search.text, container, /*fullStart*/ state.findInComments || container.jsDoc !== undefined)) {
getReferencesAtLocation(sourceFile, position, search, state);
}
}
function getReferencesAtLocation(sourceFile: SourceFile, position: number, search: Search, state: State): void {
const referenceLocation = getTouchingPropertyName(sourceFile, position);
const referenceLocation = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
if (!isValidReferencePosition(referenceLocation, search.text)) {
// This wasn't the start of a token. Check to see if it might be a
@ -1248,7 +1254,7 @@ namespace ts.FindAllReferences.Core {
const sourceFile = searchSpaceNode.getSourceFile();
const possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode);
for (const position of possiblePositions) {
const node = getTouchingWord(sourceFile, position);
const node = getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false);
if (!node || node.kind !== SyntaxKind.SuperKeyword) {
continue;
@ -1325,7 +1331,7 @@ namespace ts.FindAllReferences.Core {
function getThisReferencesInFile(sourceFile: SourceFile, searchSpaceNode: Node, possiblePositions: number[], result: Entry[]): void {
forEach(possiblePositions, position => {
const node = getTouchingWord(sourceFile, position);
const node = getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false);
if (!node || !isThis(node)) {
return;
}
@ -1379,7 +1385,7 @@ namespace ts.FindAllReferences.Core {
function getReferencesForStringLiteralInFile(sourceFile: SourceFile, searchText: string, possiblePositions: number[], references: Push<NodeEntry>): void {
for (const position of possiblePositions) {
const node = getTouchingWord(sourceFile, position);
const node = getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false);
if (node && node.kind === SyntaxKind.StringLiteral && (node as StringLiteral).text === searchText) {
references.push(nodeEntry(node, /*isInString*/ true));
}

View File

@ -599,7 +599,7 @@ namespace ts.formatting {
child => {
processChildNode(child, /*inheritedIndentation*/ Constants.Unknown, node, nodeDynamicIndentation, nodeStartLine, undecoratedNodeStartLine, /*isListItem*/ false);
},
(nodes: NodeArray<Node>) => {
nodes => {
processChildNodes(nodes, node, nodeStartLine, nodeDynamicIndentation);
});

View File

@ -19,7 +19,7 @@ namespace ts.GoToDefinition {
[getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)];
}
const node = getTouchingPropertyName(sourceFile, position);
const node = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
if (node === sourceFile) {
return undefined;
}
@ -95,7 +95,7 @@ namespace ts.GoToDefinition {
/// Goto type
export function getTypeDefinitionAtPosition(typeChecker: TypeChecker, sourceFile: SourceFile, position: number): DefinitionInfo[] {
const node = getTouchingPropertyName(sourceFile, position);
const node = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
if (node === sourceFile) {
return undefined;
}

View File

@ -300,7 +300,7 @@ namespace ts.FindAllReferences {
});
}
type ModuleReference =
export type ModuleReference =
/** "import" also includes require() calls. */
| { kind: "import", literal: StringLiteral }
/** <reference path> or <reference types> */

View File

@ -158,7 +158,7 @@ namespace ts.JsDoc {
return undefined;
}
const tokenAtPos = getTokenAtPosition(sourceFile, position);
const tokenAtPos = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false);
const tokenStart = tokenAtPos.getStart();
if (!tokenAtPos || tokenStart < position) {
return undefined;

View File

@ -245,18 +245,15 @@ namespace ts.Completions.PathCompletions {
// Get modules that the type checker picked up
const ambientModules = map(typeChecker.getAmbientModules(), sym => stripQuotes(sym.name));
let nonRelativeModules = filter(ambientModules, moduleName => startsWith(moduleName, fragment));
let nonRelativeModuleNames = filter(ambientModules, moduleName => startsWith(moduleName, fragment));
// Nested modules of the form "module-name/sub" need to be adjusted to only return the string
// after the last '/' that appears in the fragment because that's where the replacement span
// starts
if (isNestedModule) {
const moduleNameWithSeperator = ensureTrailingDirectorySeparator(moduleNameFragment);
nonRelativeModules = map(nonRelativeModules, moduleName => {
if (startsWith(fragment, moduleNameWithSeperator)) {
return moduleName.substr(moduleNameWithSeperator.length);
}
return moduleName;
nonRelativeModuleNames = map(nonRelativeModuleNames, nonRelativeModuleName => {
return removePrefix(nonRelativeModuleName, moduleNameWithSeperator);
});
}
@ -264,7 +261,7 @@ namespace ts.Completions.PathCompletions {
if (!options.moduleResolution || options.moduleResolution === ModuleResolutionKind.NodeJs) {
for (const visibleModule of enumerateNodeModulesVisibleToScript(host, scriptPath)) {
if (!isNestedModule) {
nonRelativeModules.push(visibleModule.moduleName);
nonRelativeModuleNames.push(visibleModule.moduleName);
}
else if (startsWith(visibleModule.moduleName, moduleNameFragment)) {
const nestedFiles = tryReadDirectory(host, visibleModule.moduleDir, supportedTypeScriptExtensions, /*exclude*/ undefined, /*include*/ ["./*"]);
@ -272,18 +269,18 @@ namespace ts.Completions.PathCompletions {
for (let f of nestedFiles) {
f = normalizePath(f);
const nestedModule = removeFileExtension(getBaseFileName(f));
nonRelativeModules.push(nestedModule);
nonRelativeModuleNames.push(nestedModule);
}
}
}
}
}
return deduplicate(nonRelativeModules);
return deduplicate(nonRelativeModuleNames);
}
export function getTripleSlashReferenceCompletion(sourceFile: SourceFile, position: number, compilerOptions: CompilerOptions, host: LanguageServiceHost): CompletionInfo {
const token = getTokenAtPosition(sourceFile, position);
const token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false);
if (!token) {
return undefined;
}

View File

@ -12,7 +12,7 @@ namespace ts.refactor {
function isApplicable(context: RefactorContext): boolean {
const start = context.startPosition;
const node = getTokenAtPosition(context.file, start);
const node = getTokenAtPosition(context.file, start, /*includeJsDocComment*/ false);
const checker = context.program.getTypeChecker();
let symbol = checker.getSymbolAtLocation(node);
@ -27,7 +27,7 @@ namespace ts.refactor {
const start = context.startPosition;
const sourceFile = context.file;
const checker = context.program.getTypeChecker();
const token = getTokenAtPosition(sourceFile, start);
const token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false);
const ctorSymbol = checker.getSymbolAtLocation(token);
const newLine = context.rulesProvider.getFormatOptions().newLineCharacter;

View File

@ -107,6 +107,7 @@ namespace ts {
scanner.setTextPos(pos);
while (pos < end) {
const token = useJSDocScanner ? scanner.scanJSDocToken() : scanner.scan();
Debug.assert(token !== SyntaxKind.EndOfFileToken); // Else it would infinitely loop
const textPos = scanner.getTextPos();
if (textPos <= end) {
nodes.push(createNode(token, pos, textPos, this));
@ -135,10 +136,15 @@ namespace ts {
}
private createChildren(sourceFile?: SourceFileLike) {
let children: Node[];
if (this.kind >= SyntaxKind.FirstNode) {
if (isJSDocTag(this)) {
/** Don't add trivia for "tokens" since this is in a comment. */
const children: Node[] = [];
this.forEachChild(child => { children.push(child); });
this._children = children;
}
else if (this.kind >= SyntaxKind.FirstNode) {
const children: Node[] = [];
scanner.setText((sourceFile || this.getSourceFile()).text);
children = [];
let pos = this.pos;
const useJSDocScanner = this.kind >= SyntaxKind.FirstJSDocTagNode && this.kind <= SyntaxKind.LastJSDocTagNode;
const processNode = (node: Node) => {
@ -155,7 +161,7 @@ namespace ts {
if (pos < nodes.pos) {
pos = this.addSyntheticNodes(children, pos, nodes.pos, useJSDocScanner);
}
children.push(this.createSyntaxList(<NodeArray<Node>>nodes));
children.push(this.createSyntaxList(nodes));
pos = nodes.end;
};
// jsDocComments need to be the first children
@ -173,8 +179,11 @@ namespace ts {
this.addSyntheticNodes(children, pos, this.end);
}
scanner.setText(undefined);
this._children = children;
}
else {
this._children = emptyArray;
}
this._children = children || emptyArray;
}
public getChildCount(sourceFile?: SourceFile): number {
@ -215,7 +224,7 @@ namespace ts {
return child.kind < SyntaxKind.FirstNode ? child : child.getLastToken(sourceFile);
}
public forEachChild<T>(cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T {
public forEachChild<T>(cbNode: (node: Node) => T, cbNodeArray?: (nodes: NodeArray<Node>) => T): T {
return forEachChild(this, cbNode, cbNodeArray);
}
}
@ -1356,7 +1365,7 @@ namespace ts {
synchronizeHostData();
const sourceFile = getValidSourceFile(fileName);
const node = getTouchingPropertyName(sourceFile, position);
const node = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
if (node === sourceFile) {
return undefined;
}
@ -1543,7 +1552,7 @@ namespace ts {
const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
// Get node at the location
const node = getTouchingPropertyName(sourceFile, startPos);
const node = getTouchingPropertyName(sourceFile, startPos, /*includeJsDocComment*/ false);
if (node === sourceFile) {
return;
@ -1654,7 +1663,7 @@ namespace ts {
const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
const result: TextSpan[] = [];
const token = getTouchingToken(sourceFile, position);
const token = getTouchingToken(sourceFile, position, /*includeJsDocComment*/ false);
if (token.getStart(sourceFile) === position) {
const matchKind = getMatchingTokenKind(token);
@ -1856,7 +1865,6 @@ namespace ts {
// OK, we have found a match in the file. This is only an acceptable match if
// it is contained within a comment.
if (!isInComment(sourceFile, matchPosition)) {
continue;
}

View File

@ -202,7 +202,7 @@ namespace ts.textChanges {
return this;
}
if (index !== containingList.length - 1) {
const nextToken = getTokenAtPosition(sourceFile, node.end);
const nextToken = getTokenAtPosition(sourceFile, node.end, /*includeJsDocComment*/ false);
if (nextToken && isSeparator(node, nextToken)) {
// find first non-whitespace position in the leading trivia of the node
const startPosition = skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
@ -214,7 +214,7 @@ namespace ts.textChanges {
}
}
else {
const previousToken = getTokenAtPosition(sourceFile, containingList[index - 1].end);
const previousToken = getTokenAtPosition(sourceFile, containingList[index - 1].end, /*includeJsDocComment*/ false);
if (previousToken && isSeparator(node, previousToken)) {
this.deleteNodeRange(sourceFile, previousToken, node);
}
@ -292,7 +292,7 @@ namespace ts.textChanges {
if (index !== containingList.length - 1) {
// any element except the last one
// use next sibling as an anchor
const nextToken = getTokenAtPosition(sourceFile, after.end);
const nextToken = getTokenAtPosition(sourceFile, after.end, /*includeJsDocComment*/ false);
if (nextToken && isSeparator(after, nextToken)) {
// for list
// a, b, c

View File

@ -590,29 +590,29 @@ namespace ts {
/* Gets the token whose text has range [start, end) and
* position >= start and (position < end or (position === end && token is keyword or identifier))
*/
export function getTouchingWord(sourceFile: SourceFile, position: number, includeJsDocComment = false): Node {
return getTouchingToken(sourceFile, position, n => isWord(n.kind), includeJsDocComment);
export function getTouchingWord(sourceFile: SourceFile, position: number, includeJsDocComment: boolean): Node {
return getTouchingToken(sourceFile, position, includeJsDocComment, n => isWord(n.kind));
}
/* Gets the token whose text has range [start, end) and position >= start
* and (position < end or (position === end && token is keyword or identifier or numeric/string literal))
*/
export function getTouchingPropertyName(sourceFile: SourceFile, position: number, includeJsDocComment = false): Node {
return getTouchingToken(sourceFile, position, n => isPropertyName(n.kind), includeJsDocComment);
export function getTouchingPropertyName(sourceFile: SourceFile, position: number, includeJsDocComment: boolean): Node {
return getTouchingToken(sourceFile, position, includeJsDocComment, n => isPropertyName(n.kind));
}
/** Returns the token if position is in [start, end) or if position === end and includeItemAtEndPosition(token) === true */
export function getTouchingToken(sourceFile: SourceFile, position: number, includeItemAtEndPosition?: (n: Node) => boolean, includeJsDocComment = false): Node {
export function getTouchingToken(sourceFile: SourceFile, position: number, includeJsDocComment: boolean, includeItemAtEndPosition?: (n: Node) => boolean): Node {
return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ false, includeItemAtEndPosition, includeJsDocComment);
}
/** Returns a token if position is in [start-of-leading-trivia, end) */
export function getTokenAtPosition(sourceFile: SourceFile, position: number, includeJsDocComment = false): Node {
export function getTokenAtPosition(sourceFile: SourceFile, position: number, includeJsDocComment: boolean): Node {
return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includeItemAtEndPosition*/ undefined, includeJsDocComment);
}
/** Get the token whose text contains the position */
function getTokenAtPositionWorker(sourceFile: SourceFile, position: number, allowPositionInLeadingTrivia: boolean, includeItemAtEndPosition: (n: Node) => boolean, includeJsDocComment = false): Node {
function getTokenAtPositionWorker(sourceFile: SourceFile, position: number, allowPositionInLeadingTrivia: boolean, includeItemAtEndPosition: (n: Node) => boolean, includeJsDocComment: boolean): Node {
let current: Node = sourceFile;
outer: while (true) {
if (isToken(current)) {
@ -659,7 +659,7 @@ namespace ts {
export function findTokenOnLeftOfPosition(file: SourceFile, position: number): Node {
// Ideally, getTokenAtPosition should return a token. However, it is currently
// broken, so we do a check to make sure the result was indeed a token.
const tokenAtPosition = getTokenAtPosition(file, position);
const tokenAtPosition = getTokenAtPosition(file, position, /*includeJsDocComment*/ false);
if (isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) {
return tokenAtPosition;
}
@ -789,7 +789,7 @@ namespace ts {
* returns true if the position is in between the open and close elements of an JSX expression.
*/
export function isInsideJsxElementOrAttribute(sourceFile: SourceFile, position: number) {
const token = getTokenAtPosition(sourceFile, position);
const token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false);
if (!token) {
return false;
@ -825,7 +825,7 @@ namespace ts {
}
export function isInTemplateString(sourceFile: SourceFile, position: number) {
const token = getTokenAtPosition(sourceFile, position);
const token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false);
return isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile);
}
@ -835,7 +835,11 @@ namespace ts {
* @param tokenAtPosition Must equal `getTokenAtPosition(sourceFile, position)
* @param predicate Additional predicate to test on the comment range.
*/
export function isInComment(sourceFile: SourceFile, position: number, tokenAtPosition = getTokenAtPosition(sourceFile, position), predicate?: (c: CommentRange) => boolean): boolean {
export function isInComment(
sourceFile: SourceFile,
position: number,
tokenAtPosition = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false),
predicate?: (c: CommentRange) => boolean): boolean {
return position <= tokenAtPosition.getStart(sourceFile) &&
(isInCommentRange(getLeadingCommentRanges(sourceFile.text, tokenAtPosition.pos)) ||
isInCommentRange(getTrailingCommentRanges(sourceFile.text, tokenAtPosition.pos)));
@ -870,7 +874,7 @@ namespace ts {
}
export function hasDocComment(sourceFile: SourceFile, position: number) {
const token = getTokenAtPosition(sourceFile, position);
const token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false);
// First, we have to see if this position actually landed in a comment.
const commentRanges = getLeadingCommentRanges(sourceFile.text, token.pos);
@ -887,7 +891,7 @@ namespace ts {
* Get the corresponding JSDocTag node if the position is in a jsDoc comment
*/
export function getJsDocTagAtPosition(sourceFile: SourceFile, position: number): JSDocTag {
let node = ts.getTokenAtPosition(sourceFile, position);
let node = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false);
if (isToken(node)) {
switch (node.kind) {
case SyntaxKind.VarKeyword:
@ -1132,7 +1136,7 @@ namespace ts {
clear: resetWriter,
trackSymbol: noop,
reportInaccessibleThisError: noop,
reportIllegalExtends: noop
reportPrivateInBaseOfClassExpression: noop,
};
function writeIndent() {
@ -1354,6 +1358,6 @@ namespace ts {
}
export function getOpenBraceOfClassLike(declaration: ClassLikeDeclaration, sourceFile: SourceFile) {
return getTokenAtPosition(sourceFile, declaration.members.pos - 1);
return getTokenAtPosition(sourceFile, declaration.members.pos - 1, /*includeJsDocComment*/ false);
}
}

View File

@ -1,23 +1,17 @@
tests/cases/compiler/declarationEmitExpressionInExtends4.ts(1,10): error TS4060: Return type of exported function has or is using private name 'D'.
tests/cases/compiler/declarationEmitExpressionInExtends4.ts(5,17): error TS2315: Type 'D' is not generic.
tests/cases/compiler/declarationEmitExpressionInExtends4.ts(5,17): error TS4020: 'extends' clause of exported class 'C' has or is using private name 'D'.
tests/cases/compiler/declarationEmitExpressionInExtends4.ts(9,18): error TS2304: Cannot find name 'SomeUndefinedFunction'.
tests/cases/compiler/declarationEmitExpressionInExtends4.ts(14,18): error TS2304: Cannot find name 'SomeUndefinedFunction'.
tests/cases/compiler/declarationEmitExpressionInExtends4.ts(14,18): error TS4020: 'extends' clause of exported class 'C3' has or is using private name 'SomeUndefinedFunction'.
==== tests/cases/compiler/declarationEmitExpressionInExtends4.ts (6 errors) ====
==== tests/cases/compiler/declarationEmitExpressionInExtends4.ts (4 errors) ====
function getSomething() {
~~~~~~~~~~~~
!!! error TS4060: Return type of exported function has or is using private name 'D'.
return class D { }
}
class C extends getSomething()<number, string> {
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
!!! error TS2315: Type 'D' is not generic.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
!!! error TS4020: 'extends' clause of exported class 'C' has or is using private name 'D'.
}

View File

@ -0,0 +1,132 @@
//// [emitClassExpressionInDeclarationFile.ts]
export var simpleExample = class {
static getTags() { }
tags() { }
}
export var circularReference = class C {
static getTags(c: C): C { return c }
tags(c: C): C { return c }
}
// repro from #15066
export class FooItem {
foo(): void { }
name?: string;
}
export type Constructor<T> = new(...args: any[]) => T;
export function WithTags<T extends Constructor<FooItem>>(Base: T) {
return class extends Base {
static getTags(): void { }
tags(): void { }
}
}
export class Test extends WithTags(FooItem) {}
const test = new Test();
Test.getTags()
test.tags();
//// [emitClassExpressionInDeclarationFile.js]
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
exports.__esModule = true;
exports.simpleExample = (function () {
function class_1() {
}
class_1.getTags = function () { };
class_1.prototype.tags = function () { };
return class_1;
}());
exports.circularReference = (function () {
function C() {
}
C.getTags = function (c) { return c; };
C.prototype.tags = function (c) { return c; };
return C;
}());
// repro from #15066
var FooItem = (function () {
function FooItem() {
}
FooItem.prototype.foo = function () { };
return FooItem;
}());
exports.FooItem = FooItem;
function WithTags(Base) {
return (function (_super) {
__extends(class_2, _super);
function class_2() {
return _super !== null && _super.apply(this, arguments) || this;
}
class_2.getTags = function () { };
class_2.prototype.tags = function () { };
return class_2;
}(Base));
}
exports.WithTags = WithTags;
var Test = (function (_super) {
__extends(Test, _super);
function Test() {
return _super !== null && _super.apply(this, arguments) || this;
}
return Test;
}(WithTags(FooItem)));
exports.Test = Test;
var test = new Test();
Test.getTags();
test.tags();
//// [emitClassExpressionInDeclarationFile.d.ts]
export declare var simpleExample: {
new (): {
tags(): void;
};
getTags(): void;
};
export declare var circularReference: {
new (): {
tags(c: any): any;
};
getTags(c: {
tags(c: any): any;
}): {
tags(c: any): any;
};
};
export declare class FooItem {
foo(): void;
name?: string;
}
export declare type Constructor<T> = new (...args: any[]) => T;
export declare function WithTags<T extends Constructor<FooItem>>(Base: T): {
new (...args: any[]): {
tags(): void;
foo(): void;
name?: string;
};
getTags(): void;
} & T;
declare const Test_base: {
new (...args: any[]): {
tags(): void;
foo(): void;
name?: string;
};
getTags(): void;
} & typeof FooItem;
export declare class Test extends Test_base {
}

View File

@ -0,0 +1,84 @@
=== tests/cases/compiler/emitClassExpressionInDeclarationFile.ts ===
export var simpleExample = class {
>simpleExample : Symbol(simpleExample, Decl(emitClassExpressionInDeclarationFile.ts, 0, 10))
static getTags() { }
>getTags : Symbol(simpleExample.getTags, Decl(emitClassExpressionInDeclarationFile.ts, 0, 34))
tags() { }
>tags : Symbol(simpleExample.tags, Decl(emitClassExpressionInDeclarationFile.ts, 1, 24))
}
export var circularReference = class C {
>circularReference : Symbol(circularReference, Decl(emitClassExpressionInDeclarationFile.ts, 4, 10))
>C : Symbol(C, Decl(emitClassExpressionInDeclarationFile.ts, 4, 30))
static getTags(c: C): C { return c }
>getTags : Symbol(C.getTags, Decl(emitClassExpressionInDeclarationFile.ts, 4, 40))
>c : Symbol(c, Decl(emitClassExpressionInDeclarationFile.ts, 5, 19))
>C : Symbol(C, Decl(emitClassExpressionInDeclarationFile.ts, 4, 30))
>C : Symbol(C, Decl(emitClassExpressionInDeclarationFile.ts, 4, 30))
>c : Symbol(c, Decl(emitClassExpressionInDeclarationFile.ts, 5, 19))
tags(c: C): C { return c }
>tags : Symbol(C.tags, Decl(emitClassExpressionInDeclarationFile.ts, 5, 40))
>c : Symbol(c, Decl(emitClassExpressionInDeclarationFile.ts, 6, 9))
>C : Symbol(C, Decl(emitClassExpressionInDeclarationFile.ts, 4, 30))
>C : Symbol(C, Decl(emitClassExpressionInDeclarationFile.ts, 4, 30))
>c : Symbol(c, Decl(emitClassExpressionInDeclarationFile.ts, 6, 9))
}
// repro from #15066
export class FooItem {
>FooItem : Symbol(FooItem, Decl(emitClassExpressionInDeclarationFile.ts, 7, 1))
foo(): void { }
>foo : Symbol(FooItem.foo, Decl(emitClassExpressionInDeclarationFile.ts, 10, 22))
name?: string;
>name : Symbol(FooItem.name, Decl(emitClassExpressionInDeclarationFile.ts, 11, 19))
}
export type Constructor<T> = new(...args: any[]) => T;
>Constructor : Symbol(Constructor, Decl(emitClassExpressionInDeclarationFile.ts, 13, 1))
>T : Symbol(T, Decl(emitClassExpressionInDeclarationFile.ts, 15, 24))
>args : Symbol(args, Decl(emitClassExpressionInDeclarationFile.ts, 15, 33))
>T : Symbol(T, Decl(emitClassExpressionInDeclarationFile.ts, 15, 24))
export function WithTags<T extends Constructor<FooItem>>(Base: T) {
>WithTags : Symbol(WithTags, Decl(emitClassExpressionInDeclarationFile.ts, 15, 54))
>T : Symbol(T, Decl(emitClassExpressionInDeclarationFile.ts, 16, 25))
>Constructor : Symbol(Constructor, Decl(emitClassExpressionInDeclarationFile.ts, 13, 1))
>FooItem : Symbol(FooItem, Decl(emitClassExpressionInDeclarationFile.ts, 7, 1))
>Base : Symbol(Base, Decl(emitClassExpressionInDeclarationFile.ts, 16, 57))
>T : Symbol(T, Decl(emitClassExpressionInDeclarationFile.ts, 16, 25))
return class extends Base {
>Base : Symbol(Base, Decl(emitClassExpressionInDeclarationFile.ts, 16, 57))
static getTags(): void { }
>getTags : Symbol((Anonymous class).getTags, Decl(emitClassExpressionInDeclarationFile.ts, 17, 31))
tags(): void { }
>tags : Symbol((Anonymous class).tags, Decl(emitClassExpressionInDeclarationFile.ts, 18, 34))
}
}
export class Test extends WithTags(FooItem) {}
>Test : Symbol(Test, Decl(emitClassExpressionInDeclarationFile.ts, 21, 1))
>WithTags : Symbol(WithTags, Decl(emitClassExpressionInDeclarationFile.ts, 15, 54))
>FooItem : Symbol(FooItem, Decl(emitClassExpressionInDeclarationFile.ts, 7, 1))
const test = new Test();
>test : Symbol(test, Decl(emitClassExpressionInDeclarationFile.ts, 25, 5))
>Test : Symbol(Test, Decl(emitClassExpressionInDeclarationFile.ts, 21, 1))
Test.getTags()
>Test.getTags : Symbol((Anonymous class).getTags, Decl(emitClassExpressionInDeclarationFile.ts, 17, 31))
>Test : Symbol(Test, Decl(emitClassExpressionInDeclarationFile.ts, 21, 1))
>getTags : Symbol((Anonymous class).getTags, Decl(emitClassExpressionInDeclarationFile.ts, 17, 31))
test.tags();
>test.tags : Symbol((Anonymous class).tags, Decl(emitClassExpressionInDeclarationFile.ts, 18, 34))
>test : Symbol(test, Decl(emitClassExpressionInDeclarationFile.ts, 25, 5))
>tags : Symbol((Anonymous class).tags, Decl(emitClassExpressionInDeclarationFile.ts, 18, 34))

View File

@ -0,0 +1,91 @@
=== tests/cases/compiler/emitClassExpressionInDeclarationFile.ts ===
export var simpleExample = class {
>simpleExample : typeof simpleExample
>class { static getTags() { } tags() { }} : typeof simpleExample
static getTags() { }
>getTags : () => void
tags() { }
>tags : () => void
}
export var circularReference = class C {
>circularReference : typeof C
>class C { static getTags(c: C): C { return c } tags(c: C): C { return c }} : typeof C
>C : typeof C
static getTags(c: C): C { return c }
>getTags : (c: C) => C
>c : C
>C : C
>C : C
>c : C
tags(c: C): C { return c }
>tags : (c: C) => C
>c : C
>C : C
>C : C
>c : C
}
// repro from #15066
export class FooItem {
>FooItem : FooItem
foo(): void { }
>foo : () => void
name?: string;
>name : string
}
export type Constructor<T> = new(...args: any[]) => T;
>Constructor : Constructor<T>
>T : T
>args : any[]
>T : T
export function WithTags<T extends Constructor<FooItem>>(Base: T) {
>WithTags : <T extends Constructor<FooItem>>(Base: T) => { new (...args: any[]): (Anonymous class); prototype: WithTags<any>.(Anonymous class); getTags(): void; } & T
>T : T
>Constructor : Constructor<T>
>FooItem : FooItem
>Base : T
>T : T
return class extends Base {
>class extends Base { static getTags(): void { } tags(): void { } } : { new (...args: any[]): (Anonymous class); prototype: WithTags<any>.(Anonymous class); getTags(): void; } & T
>Base : FooItem
static getTags(): void { }
>getTags : () => void
tags(): void { }
>tags : () => void
}
}
export class Test extends WithTags(FooItem) {}
>Test : Test
>WithTags(FooItem) : WithTags<typeof FooItem>.(Anonymous class) & FooItem
>WithTags : <T extends Constructor<FooItem>>(Base: T) => { new (...args: any[]): (Anonymous class); prototype: WithTags<any>.(Anonymous class); getTags(): void; } & T
>FooItem : typeof FooItem
const test = new Test();
>test : Test
>new Test() : Test
>Test : typeof Test
Test.getTags()
>Test.getTags() : void
>Test.getTags : () => void
>Test : typeof Test
>getTags : () => void
test.tags();
>test.tags() : void
>test.tags : () => void
>test : Test
>tags : () => void

View File

@ -0,0 +1,41 @@
tests/cases/compiler/emitClassExpressionInDeclarationFile2.ts(1,12): error TS4094: Property 'p' of exported class expression may not be private or protected.
tests/cases/compiler/emitClassExpressionInDeclarationFile2.ts(1,12): error TS4094: Property 'ps' of exported class expression may not be private or protected.
tests/cases/compiler/emitClassExpressionInDeclarationFile2.ts(16,17): error TS4094: Property 'property' of exported class expression may not be private or protected.
==== tests/cases/compiler/emitClassExpressionInDeclarationFile2.ts (3 errors) ====
export var noPrivates = class {
~~~~~~~~~~
!!! error TS4094: Property 'p' of exported class expression may not be private or protected.
~~~~~~~~~~
!!! error TS4094: Property 'ps' of exported class expression may not be private or protected.
static getTags() { }
tags() { }
private static ps = -1
private p = 12
}
// altered repro from #15066 to add private property
export class FooItem {
foo(): void { }
name?: string;
private property = "capitalism"
}
export type Constructor<T> = new(...args: any[]) => T;
export function WithTags<T extends Constructor<FooItem>>(Base: T) {
~~~~~~~~
!!! error TS4094: Property 'property' of exported class expression may not be private or protected.
return class extends Base {
static getTags(): void { }
tags(): void { }
}
}
export class Test extends WithTags(FooItem) {}
const test = new Test();
Test.getTags()
test.tags();

View File

@ -0,0 +1,87 @@
//// [emitClassExpressionInDeclarationFile2.ts]
export var noPrivates = class {
static getTags() { }
tags() { }
private static ps = -1
private p = 12
}
// altered repro from #15066 to add private property
export class FooItem {
foo(): void { }
name?: string;
private property = "capitalism"
}
export type Constructor<T> = new(...args: any[]) => T;
export function WithTags<T extends Constructor<FooItem>>(Base: T) {
return class extends Base {
static getTags(): void { }
tags(): void { }
}
}
export class Test extends WithTags(FooItem) {}
const test = new Test();
Test.getTags()
test.tags();
//// [emitClassExpressionInDeclarationFile2.js]
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
exports.__esModule = true;
exports.noPrivates = (_a = (function () {
function class_1() {
this.p = 12;
}
class_1.getTags = function () { };
class_1.prototype.tags = function () { };
return class_1;
}()),
_a.ps = -1,
_a);
// altered repro from #15066 to add private property
var FooItem = (function () {
function FooItem() {
this.property = "capitalism";
}
FooItem.prototype.foo = function () { };
return FooItem;
}());
exports.FooItem = FooItem;
function WithTags(Base) {
return (function (_super) {
__extends(class_2, _super);
function class_2() {
return _super !== null && _super.apply(this, arguments) || this;
}
class_2.getTags = function () { };
class_2.prototype.tags = function () { };
return class_2;
}(Base));
}
exports.WithTags = WithTags;
var Test = (function (_super) {
__extends(Test, _super);
function Test() {
return _super !== null && _super.apply(this, arguments) || this;
}
return Test;
}(WithTags(FooItem)));
exports.Test = Test;
var test = new Test();
Test.getTags();
test.tags();
var _a;

View File

@ -1,4 +1,4 @@
tests/cases/compiler/a.ts(1,21): error TS6137: Cannot import type declaration files. Consider importing 'foo-bar' instead of '@types/foo-bar'.
/a.ts(1,21): error TS6137: Cannot import type declaration files. Consider importing 'foo-bar' instead of '@types/foo-bar'.
==== /node_modules/@types/foo-bar/index.d.ts (0 errors) ====
@ -7,7 +7,7 @@ tests/cases/compiler/a.ts(1,21): error TS6137: Cannot import type declaration fi
}
// This should error
==== tests/cases/compiler/a.ts (1 errors) ====
==== /a.ts (1 errors) ====
import { Foo } from "@types/foo-bar";
~~~~~~~~~~~~~~~~
!!! error TS6137: Cannot import type declaration files. Consider importing 'foo-bar' instead of '@types/foo-bar'.

View File

@ -0,0 +1,49 @@
tests/cases/compiler/jsdocInTypeScript.ts(16,23): error TS2304: Cannot find name 'MyType'.
tests/cases/compiler/jsdocInTypeScript.ts(23,33): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.
tests/cases/compiler/jsdocInTypeScript.ts(25,3): error TS2345: Argument of type '1' is not assignable to parameter of type 'boolean'.
tests/cases/compiler/jsdocInTypeScript.ts(25,15): error TS2339: Property 'length' does not exist on type 'number'.
tests/cases/compiler/jsdocInTypeScript.ts(30,3): error TS2339: Property 'x' does not exist on type '{}'.
==== tests/cases/compiler/jsdocInTypeScript.ts (5 errors) ====
// JSDoc typedef tags are not bound TypeScript files.
/** @typedef {function} T */
declare const x: T;
class T {
prop: number;
}
x.prop;
// Just to be sure that @property has no impact either.
/**
* @typedef {Object} MyType
* @property {string} yes
*/
declare const myType: MyType; // should error, no such type
~~~~~~
!!! error TS2304: Cannot find name 'MyType'.
// @param type has no effect.
/**
* @param {number} x
* @returns string
*/
function f(x: boolean) { return x * 2; } // Should error
~
!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.
// Should fail, because it takes a boolean and returns a number
f(1); f(true).length;
~
!!! error TS2345: Argument of type '1' is not assignable to parameter of type 'boolean'.
~~~~~~
!!! error TS2339: Property 'length' does not exist on type 'number'.
// @type has no effect either.
/** @type {{ x?: number }} */
const z = {};
z.x = 1;
~
!!! error TS2339: Property 'x' does not exist on type '{}'.

View File

@ -8,6 +8,27 @@ class T {
}
x.prop;
// Just to be sure that @property has no impact either.
/**
* @typedef {Object} MyType
* @property {string} yes
*/
declare const myType: MyType; // should error, no such type
// @param type has no effect.
/**
* @param {number} x
* @returns string
*/
function f(x: boolean) { return x * 2; } // Should error
// Should fail, because it takes a boolean and returns a number
f(1); f(true).length;
// @type has no effect either.
/** @type {{ x?: number }} */
const z = {};
z.x = 1;
//// [jsdocInTypeScript.js]
@ -17,3 +38,16 @@ var T = (function () {
return T;
}());
x.prop;
// @param type has no effect.
/**
* @param {number} x
* @returns string
*/
function f(x) { return x * 2; } // Should error
// Should fail, because it takes a boolean and returns a number
f(1);
f(true).length;
// @type has no effect either.
/** @type {{ x?: number }} */
var z = {};
z.x = 1;

View File

@ -1,19 +0,0 @@
=== tests/cases/compiler/jsdocInTypeScript.ts ===
// JSDoc typedef tags are not bound TypeScript files.
/** @typedef {function} T */
declare const x: T;
>x : Symbol(x, Decl(jsdocInTypeScript.ts, 2, 13))
>T : Symbol(T, Decl(jsdocInTypeScript.ts, 2, 19))
class T {
>T : Symbol(T, Decl(jsdocInTypeScript.ts, 2, 19))
prop: number;
>prop : Symbol(T.prop, Decl(jsdocInTypeScript.ts, 4, 9))
}
x.prop;
>x.prop : Symbol(T.prop, Decl(jsdocInTypeScript.ts, 4, 9))
>x : Symbol(x, Decl(jsdocInTypeScript.ts, 2, 13))
>prop : Symbol(T.prop, Decl(jsdocInTypeScript.ts, 4, 9))

View File

@ -1,19 +0,0 @@
=== tests/cases/compiler/jsdocInTypeScript.ts ===
// JSDoc typedef tags are not bound TypeScript files.
/** @typedef {function} T */
declare const x: T;
>x : T
>T : T
class T {
>T : T
prop: number;
>prop : number
}
x.prop;
>x.prop : number
>x : T
>prop : number

View File

@ -2,9 +2,9 @@
for (const element of document.getElementsByTagName("a")) {
>element : HTMLAnchorElement
>document.getElementsByTagName("a") : NodeListOf<HTMLAnchorElement>
>document.getElementsByTagName : { <K extends "symbol" | "object" | "a" | "abbr" | "acronym" | "address" | "applet" | "area" | "article" | "aside" | "audio" | "b" | "base" | "basefont" | "bdo" | "big" | "blockquote" | "body" | "br" | "button" | "canvas" | "caption" | "center" | "circle" | "cite" | "clippath" | "code" | "col" | "colgroup" | "data" | "datalist" | "dd" | "defs" | "del" | "desc" | "dfn" | "dir" | "div" | "dl" | "dt" | "ellipse" | "em" | "embed" | "feblend" | "fecolormatrix" | "fecomponenttransfer" | "fecomposite" | "feconvolvematrix" | "fediffuselighting" | "fedisplacementmap" | "fedistantlight" | "feflood" | "fefunca" | "fefuncb" | "fefuncg" | "fefuncr" | "fegaussianblur" | "feimage" | "femerge" | "femergenode" | "femorphology" | "feoffset" | "fepointlight" | "fespecularlighting" | "fespotlight" | "fetile" | "feturbulence" | "fieldset" | "figcaption" | "figure" | "filter" | "font" | "footer" | "foreignobject" | "form" | "frame" | "frameset" | "g" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "head" | "header" | "hgroup" | "hr" | "html" | "i" | "iframe" | "image" | "img" | "input" | "ins" | "isindex" | "kbd" | "keygen" | "label" | "legend" | "li" | "line" | "lineargradient" | "link" | "listing" | "map" | "mark" | "marker" | "marquee" | "mask" | "menu" | "meta" | "metadata" | "meter" | "nav" | "nextid" | "nobr" | "noframes" | "noscript" | "ol" | "optgroup" | "option" | "output" | "p" | "param" | "path" | "pattern" | "picture" | "plaintext" | "polygon" | "polyline" | "pre" | "progress" | "q" | "radialgradient" | "rect" | "rt" | "ruby" | "s" | "samp" | "script" | "section" | "select" | "small" | "source" | "span" | "stop" | "strike" | "strong" | "style" | "sub" | "sup" | "svg" | "switch" | "table" | "tbody" | "td" | "template" | "text" | "textpath" | "textarea" | "tfoot" | "th" | "thead" | "time" | "title" | "tr" | "track" | "tspan" | "tt" | "u" | "ul" | "use" | "var" | "video" | "view" | "wbr" | "x-ms-webview" | "xmp">(tagname: K): ElementListTagNameMap[K]; (tagname: string): NodeListOf<Element>; }
>document.getElementsByTagName : { <K extends "symbol" | "object" | "abbr" | "acronym" | "address" | "article" | "aside" | "b" | "bdo" | "big" | "center" | "circle" | "cite" | "clippath" | "code" | "dd" | "defs" | "desc" | "dfn" | "dt" | "ellipse" | "em" | "feblend" | "fecolormatrix" | "fecomponenttransfer" | "fecomposite" | "feconvolvematrix" | "fediffuselighting" | "fedisplacementmap" | "fedistantlight" | "feflood" | "fefunca" | "fefuncb" | "fefuncg" | "fefuncr" | "fegaussianblur" | "feimage" | "femerge" | "femergenode" | "femorphology" | "feoffset" | "fepointlight" | "fespecularlighting" | "fespotlight" | "fetile" | "feturbulence" | "figcaption" | "figure" | "filter" | "footer" | "foreignobject" | "g" | "header" | "hgroup" | "i" | "image" | "kbd" | "keygen" | "line" | "lineargradient" | "mark" | "marker" | "mask" | "metadata" | "nav" | "nobr" | "noframes" | "noscript" | "path" | "pattern" | "plaintext" | "polygon" | "polyline" | "radialgradient" | "rect" | "rt" | "ruby" | "s" | "samp" | "section" | "small" | "stop" | "strike" | "strong" | "sub" | "sup" | "svg" | "switch" | "text" | "textpath" | "tspan" | "tt" | "u" | "use" | "var" | "view" | "wbr" | "a" | "applet" | "area" | "audio" | "base" | "basefont" | "blockquote" | "body" | "br" | "button" | "canvas" | "caption" | "col" | "colgroup" | "data" | "datalist" | "del" | "dir" | "div" | "dl" | "embed" | "fieldset" | "font" | "form" | "frame" | "frameset" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "head" | "hr" | "html" | "iframe" | "img" | "input" | "ins" | "isindex" | "label" | "legend" | "li" | "link" | "listing" | "map" | "marquee" | "menu" | "meta" | "meter" | "nextid" | "ol" | "optgroup" | "option" | "output" | "p" | "param" | "picture" | "pre" | "progress" | "q" | "script" | "select" | "source" | "span" | "style" | "table" | "tbody" | "td" | "template" | "textarea" | "tfoot" | "th" | "thead" | "time" | "title" | "tr" | "track" | "ul" | "video" | "x-ms-webview" | "xmp">(tagname: K): ElementListTagNameMap[K]; (tagname: string): NodeListOf<Element>; }
>document : Document
>getElementsByTagName : { <K extends "symbol" | "object" | "a" | "abbr" | "acronym" | "address" | "applet" | "area" | "article" | "aside" | "audio" | "b" | "base" | "basefont" | "bdo" | "big" | "blockquote" | "body" | "br" | "button" | "canvas" | "caption" | "center" | "circle" | "cite" | "clippath" | "code" | "col" | "colgroup" | "data" | "datalist" | "dd" | "defs" | "del" | "desc" | "dfn" | "dir" | "div" | "dl" | "dt" | "ellipse" | "em" | "embed" | "feblend" | "fecolormatrix" | "fecomponenttransfer" | "fecomposite" | "feconvolvematrix" | "fediffuselighting" | "fedisplacementmap" | "fedistantlight" | "feflood" | "fefunca" | "fefuncb" | "fefuncg" | "fefuncr" | "fegaussianblur" | "feimage" | "femerge" | "femergenode" | "femorphology" | "feoffset" | "fepointlight" | "fespecularlighting" | "fespotlight" | "fetile" | "feturbulence" | "fieldset" | "figcaption" | "figure" | "filter" | "font" | "footer" | "foreignobject" | "form" | "frame" | "frameset" | "g" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "head" | "header" | "hgroup" | "hr" | "html" | "i" | "iframe" | "image" | "img" | "input" | "ins" | "isindex" | "kbd" | "keygen" | "label" | "legend" | "li" | "line" | "lineargradient" | "link" | "listing" | "map" | "mark" | "marker" | "marquee" | "mask" | "menu" | "meta" | "metadata" | "meter" | "nav" | "nextid" | "nobr" | "noframes" | "noscript" | "ol" | "optgroup" | "option" | "output" | "p" | "param" | "path" | "pattern" | "picture" | "plaintext" | "polygon" | "polyline" | "pre" | "progress" | "q" | "radialgradient" | "rect" | "rt" | "ruby" | "s" | "samp" | "script" | "section" | "select" | "small" | "source" | "span" | "stop" | "strike" | "strong" | "style" | "sub" | "sup" | "svg" | "switch" | "table" | "tbody" | "td" | "template" | "text" | "textpath" | "textarea" | "tfoot" | "th" | "thead" | "time" | "title" | "tr" | "track" | "tspan" | "tt" | "u" | "ul" | "use" | "var" | "video" | "view" | "wbr" | "x-ms-webview" | "xmp">(tagname: K): ElementListTagNameMap[K]; (tagname: string): NodeListOf<Element>; }
>getElementsByTagName : { <K extends "symbol" | "object" | "abbr" | "acronym" | "address" | "article" | "aside" | "b" | "bdo" | "big" | "center" | "circle" | "cite" | "clippath" | "code" | "dd" | "defs" | "desc" | "dfn" | "dt" | "ellipse" | "em" | "feblend" | "fecolormatrix" | "fecomponenttransfer" | "fecomposite" | "feconvolvematrix" | "fediffuselighting" | "fedisplacementmap" | "fedistantlight" | "feflood" | "fefunca" | "fefuncb" | "fefuncg" | "fefuncr" | "fegaussianblur" | "feimage" | "femerge" | "femergenode" | "femorphology" | "feoffset" | "fepointlight" | "fespecularlighting" | "fespotlight" | "fetile" | "feturbulence" | "figcaption" | "figure" | "filter" | "footer" | "foreignobject" | "g" | "header" | "hgroup" | "i" | "image" | "kbd" | "keygen" | "line" | "lineargradient" | "mark" | "marker" | "mask" | "metadata" | "nav" | "nobr" | "noframes" | "noscript" | "path" | "pattern" | "plaintext" | "polygon" | "polyline" | "radialgradient" | "rect" | "rt" | "ruby" | "s" | "samp" | "section" | "small" | "stop" | "strike" | "strong" | "sub" | "sup" | "svg" | "switch" | "text" | "textpath" | "tspan" | "tt" | "u" | "use" | "var" | "view" | "wbr" | "a" | "applet" | "area" | "audio" | "base" | "basefont" | "blockquote" | "body" | "br" | "button" | "canvas" | "caption" | "col" | "colgroup" | "data" | "datalist" | "del" | "dir" | "div" | "dl" | "embed" | "fieldset" | "font" | "form" | "frame" | "frameset" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "head" | "hr" | "html" | "iframe" | "img" | "input" | "ins" | "isindex" | "label" | "legend" | "li" | "link" | "listing" | "map" | "marquee" | "menu" | "meta" | "meter" | "nextid" | "ol" | "optgroup" | "option" | "output" | "p" | "param" | "picture" | "pre" | "progress" | "q" | "script" | "select" | "source" | "span" | "style" | "table" | "tbody" | "td" | "template" | "textarea" | "tfoot" | "th" | "thead" | "time" | "title" | "tr" | "track" | "ul" | "video" | "x-ms-webview" | "xmp">(tagname: K): ElementListTagNameMap[K]; (tagname: string): NodeListOf<Element>; }
>"a" : "a"
element.href;

View File

@ -0,0 +1,30 @@
// @declaration: true
export var simpleExample = class {
static getTags() { }
tags() { }
}
export var circularReference = class C {
static getTags(c: C): C { return c }
tags(c: C): C { return c }
}
// repro from #15066
export class FooItem {
foo(): void { }
name?: string;
}
export type Constructor<T> = new(...args: any[]) => T;
export function WithTags<T extends Constructor<FooItem>>(Base: T) {
return class extends Base {
static getTags(): void { }
tags(): void { }
}
}
export class Test extends WithTags(FooItem) {}
const test = new Test();
Test.getTags()
test.tags();

View File

@ -0,0 +1,29 @@
// @declaration: true
export var noPrivates = class {
static getTags() { }
tags() { }
private static ps = -1
private p = 12
}
// altered repro from #15066 to add private property
export class FooItem {
foo(): void { }
name?: string;
private property = "capitalism"
}
export type Constructor<T> = new(...args: any[]) => T;
export function WithTags<T extends Constructor<FooItem>>(Base: T) {
return class extends Base {
static getTags(): void { }
tags(): void { }
}
}
export class Test extends WithTags(FooItem) {}
const test = new Test();
Test.getTags()
test.tags();

View File

@ -5,5 +5,5 @@ export interface Foo {
}
// This should error
// @filename: a.ts
// @filename: /a.ts
import { Foo } from "@types/foo-bar";

View File

@ -7,3 +7,24 @@ class T {
}
x.prop;
// Just to be sure that @property has no impact either.
/**
* @typedef {Object} MyType
* @property {string} yes
*/
declare const myType: MyType; // should error, no such type
// @param type has no effect.
/**
* @param {number} x
* @returns string
*/
function f(x: boolean) { return x * 2; } // Should error
// Should fail, because it takes a boolean and returns a number
f(1); f(true).length;
// @type has no effect either.
/** @type {{ x?: number }} */
const z = {};
z.x = 1;

View File

@ -0,0 +1,9 @@
/// <reference path='fourslash.ts' />
// Just testing that this doesn't cause an exception due to the @typedef contents not having '.parent' set.
// But it isn't bound to a Symbol so find-all-refs will return nothing.
/////** @typedef {Object} [|T|] */
////function foo() {}
verify.referenceGroups(test.ranges()[0], undefined);

View File

@ -0,0 +1,11 @@
// @noLib: true
/// <reference path='fourslash.ts'/>
/////**
//// * @param {[|number|]} n
//// * @returns {[|number|]}
//// */
////function f(n: [|number|]): [|number|] {}
verify.singleReferenceGroup("number");

View File

@ -0,0 +1,13 @@
/// <reference path="fourslash.ts" />
//// [|f1/*0*/();|]
// @Filename: node_modules/@types/myLib/index.d.ts
//// export function f1() {}
//// export var v1 = 5;
verify.importFixAtPosition([
`import { f1 } from "myLib";
f1();`
]);

View File

@ -0,0 +1,13 @@
/// <reference path="fourslash.ts" />
//// [|f1/*0*/();|]
// @Filename: node_modules/@types/myLib__scoped/index.d.ts
//// export function f1() {}
//// export var v1 = 5;
verify.importFixAtPosition([
`import { f1 } from "@myLib/scoped";
f1();`
]);

View File

@ -0,0 +1,24 @@
///<reference path="fourslash.ts" />
// Note: We include the word "foo" in the documentation to test for a bug where
// the `.getChildren()` of the JSDocParameterTag included an identifier at that position with no '.text'.
////interface /*I*/I {}
////
/////**
//// * @param /*use*/[|foo|] I pity the foo
//// */
////function f([|/*def*/{| "isWriteAccess": true, "isDefinition": true |}foo|]: I) {
//// return [|foo|];
////}
const ranges = test.ranges();
goTo.marker("use");
verify.goToDefinitionIs("def");
verify.goToType("use", "I");
goTo.marker("use");
verify.quickInfoIs("(parameter) foo: I", "I pity the foo");
verify.singleReferenceGroup("(parameter) foo: I");
verify.rangesAreDocumentHighlights();
verify.rangesAreRenameLocations();