diff --git a/packages/typescript/test/async/api.test.ts b/packages/typescript/test/async/api.test.ts index 3f303868a73cc..12ce92357c254 100644 --- a/packages/typescript/test/async/api.test.ts +++ b/packages/typescript/test/async/api.test.ts @@ -93,6 +93,7 @@ import { ModuleKind, ModuleResolutionKind, type ModuleResolver, + NodeBuilderFlags, type NumberLiteralType, ObjectFlags, type Program, @@ -4217,6 +4218,69 @@ export class Cache { assert.ok(target, "getTarget() should return the generic signature"); assert.ok(target.typeParameters && target.typeParameters.length > 0, "target should have type parameters"); }); + + test("instantiated signature declarations do not expose type arguments as type parameters", async () => { + await using api = spawnAPI({ + "/tsconfig.json": "{}", + "/src/main.ts": `function identity(value: T): T { return value; } +identity("hello");`, + }); + const snapshot = await api.createSnapshot({ openProjects: ["/tsconfig.json"] }); + const project = snapshot.getConfiguredProject("/tsconfig.json")!; + const source = await project.program.getSourceFile("/src/main.ts"); + assert.ok(source); + const statement = source.statements[1]; + assert.ok(isExpressionStatement(statement)); + const call = statement.expression; + assert.ok(isCallExpression(call)); + const signature = await project.checker.getResolvedSignature(call); + const declaration = await project.checker.signatureToSignatureDeclaration( + signature, + SyntaxKind.FunctionDeclaration, + undefined, + NodeBuilderFlags.WriteTypeArgumentsOfSignature, + ); + assert.ok(declaration && isFunctionDeclaration(declaration)); + assert.strictEqual(declaration.typeParameters, undefined); + assert.strictEqual(declaration.parameters[0].type?.kind, SyntaxKind.StringKeyword); + assert.strictEqual(declaration.type?.kind, SyntaxKind.StringKeyword); + const target = await signature.getTarget(); + assert.ok(target); + const generic = await project.checker.signatureToSignatureDeclaration(target, SyntaxKind.FunctionDeclaration); + assert.ok(generic && isFunctionDeclaration(generic)); + assert.strictEqual(generic.typeParameters?.[0].kind, SyntaxKind.TypeParameter); + }); + + test("instantiated generic signature declarations retain their type parameter constraints", async () => { + await using api = spawnAPI({ + "/tsconfig.json": "{}", + "/src/main.ts": `class C { + method(value: U): U { return value; } +} +new C().method;`, + }); + const snapshot = await api.createSnapshot({ openProjects: ["/tsconfig.json"] }); + const project = snapshot.getConfiguredProject("/tsconfig.json")!; + const source = await project.program.getSourceFile("/src/main.ts"); + assert.ok(source); + const statement = source.statements[1]; + assert.ok(isExpressionStatement(statement)); + const type = await project.checker.getTypeAtLocation(statement.expression); + const signatures = await type.getCallSignatures(); + assert.strictEqual(signatures.length, 1); + const declaration = await project.checker.signatureToSignatureDeclaration( + signatures[0], + SyntaxKind.FunctionDeclaration, + undefined, + NodeBuilderFlags.WriteTypeArgumentsOfSignature, + ); + assert.ok(declaration && isFunctionDeclaration(declaration)); + assert.ok(declaration.typeParameters); + assert.strictEqual(declaration.typeParameters.length, 1); + const parameter = declaration.typeParameters[0]; + assert.strictEqual(parameter.name.text, "U"); + assert.strictEqual(parameter.constraint?.kind, SyntaxKind.StringKeyword); + }); }); describe("Symbol - parent, members, exports", { concurrency }, () => { diff --git a/packages/typescript/test/sync/api.test.ts b/packages/typescript/test/sync/api.test.ts index c57ca53e905bc..fb757d6bccd6b 100644 --- a/packages/typescript/test/sync/api.test.ts +++ b/packages/typescript/test/sync/api.test.ts @@ -115,6 +115,7 @@ import { ModuleKind, ModuleResolutionKind, type ModuleResolver, + NodeBuilderFlags, type NumberLiteralType, ObjectFlags, type Program, @@ -4000,6 +4001,69 @@ export class Cache { assert.ok(target, "getTarget() should return the generic signature"); assert.ok(target.typeParameters && target.typeParameters.length > 0, "target should have type parameters"); }); + + test("instantiated signature declarations do not expose type arguments as type parameters", () => { + using api = spawnAPI({ + "/tsconfig.json": "{}", + "/src/main.ts": `function identity(value: T): T { return value; } +identity("hello");`, + }); + const snapshot = api.createSnapshot({ openProjects: ["/tsconfig.json"] }); + const project = snapshot.getConfiguredProject("/tsconfig.json")!; + const source = project.program.getSourceFile("/src/main.ts"); + assert.ok(source); + const statement = source.statements[1]; + assert.ok(isExpressionStatement(statement)); + const call = statement.expression; + assert.ok(isCallExpression(call)); + const signature = project.checker.getResolvedSignature(call); + const declaration = project.checker.signatureToSignatureDeclaration( + signature, + SyntaxKind.FunctionDeclaration, + undefined, + NodeBuilderFlags.WriteTypeArgumentsOfSignature, + ); + assert.ok(declaration && isFunctionDeclaration(declaration)); + assert.strictEqual(declaration.typeParameters, undefined); + assert.strictEqual(declaration.parameters[0].type?.kind, SyntaxKind.StringKeyword); + assert.strictEqual(declaration.type?.kind, SyntaxKind.StringKeyword); + const target = signature.getTarget(); + assert.ok(target); + const generic = project.checker.signatureToSignatureDeclaration(target, SyntaxKind.FunctionDeclaration); + assert.ok(generic && isFunctionDeclaration(generic)); + assert.strictEqual(generic.typeParameters?.[0].kind, SyntaxKind.TypeParameter); + }); + + test("instantiated generic signature declarations retain their type parameter constraints", () => { + using api = spawnAPI({ + "/tsconfig.json": "{}", + "/src/main.ts": `class C { + method(value: U): U { return value; } +} +new C().method;`, + }); + const snapshot = api.createSnapshot({ openProjects: ["/tsconfig.json"] }); + const project = snapshot.getConfiguredProject("/tsconfig.json")!; + const source = project.program.getSourceFile("/src/main.ts"); + assert.ok(source); + const statement = source.statements[1]; + assert.ok(isExpressionStatement(statement)); + const type = project.checker.getTypeAtLocation(statement.expression); + const signatures = type.getCallSignatures(); + assert.strictEqual(signatures.length, 1); + const declaration = project.checker.signatureToSignatureDeclaration( + signatures[0], + SyntaxKind.FunctionDeclaration, + undefined, + NodeBuilderFlags.WriteTypeArgumentsOfSignature, + ); + assert.ok(declaration && isFunctionDeclaration(declaration)); + assert.ok(declaration.typeParameters); + assert.strictEqual(declaration.typeParameters.length, 1); + const parameter = declaration.typeParameters[0]; + assert.strictEqual(parameter.name.text, "U"); + assert.strictEqual(parameter.constraint?.kind, SyntaxKind.StringKeyword); + }); }); describe("Symbol - parent, members, exports", { concurrency }, () => { diff --git a/tsc/internal/checker/checker_test.go b/tsc/internal/checker/checker_test.go index f5b766607c5f7..94c8a05360c26 100644 --- a/tsc/internal/checker/checker_test.go +++ b/tsc/internal/checker/checker_test.go @@ -11,6 +11,8 @@ import ( "github.com/microsoft/TypeScript/tsc/internal/checker" "github.com/microsoft/TypeScript/tsc/internal/compiler" "github.com/microsoft/TypeScript/tsc/internal/core" + "github.com/microsoft/TypeScript/tsc/internal/nodebuilder" + "github.com/microsoft/TypeScript/tsc/internal/printer" "github.com/microsoft/TypeScript/tsc/internal/repo" "github.com/microsoft/TypeScript/tsc/internal/tsoptions" "github.com/microsoft/TypeScript/tsc/internal/tspath" @@ -19,6 +21,141 @@ import ( "gotest.tools/v3/assert" ) +func TestInstantiatedSignatureDeclarationTypeParameters(t *testing.T) { + t.Parallel() + newSignature := func(t *testing.T) (*checker.Checker, *checker.Signature) { + t.Helper() + fs := bundled.WrapFS(vfstest.FromMap(map[string]string{ + "/main.ts": `function identity(value: T): T { return value; } +identity("hello");`, + }, tspath.CaseSensitive)) + program, err := compiler.NewProgram(t.Context(), compiler.ProgramOptions{ + Config: tsoptions.NewParsedCommandLine(&core.CompilerOptions{NoLib: core.TSTrue}, []tspath.RootedFilePath{"/main.ts"}, nil, "/", fs.CaseSensitivity()), + Host: compiler.NewCompilerHost(fs, bundled.LibPath(), nil, nil, nil), + }) + assert.NilError(t, err) + program.BindSourceFiles() + c, done := program.GetTypeChecker(t.Context()) + t.Cleanup(done) + call := program.GetSourceFile("/main.ts").Statements.Nodes[1].Expression() + return c, c.GetResolvedSignature(call) + } + for _, kind := range []ast.Kind{ + ast.KindCallSignature, ast.KindConstructSignature, ast.KindMethodSignature, + ast.KindMethodDeclaration, ast.KindFunctionType, ast.KindConstructorType, + ast.KindFunctionDeclaration, ast.KindFunctionExpression, ast.KindArrowFunction, + } { + t.Run(kind.String(), func(t *testing.T) { + t.Parallel() + c, signature := newSignature(t) + declaration := c.SignatureToSignatureDeclaration(signature, kind, nil, nodebuilder.FlagsWriteTypeArgumentsOfSignature) + assert.Assert(t, declaration.TypeParameters() == nil, "type parameters must contain declarations, not instantiated argument types") + assert.Equal(t, declaration.Parameters()[0].Type().Kind, ast.KindStringKeyword) + assert.Equal(t, declaration.Type().Kind, ast.KindStringKeyword) + }) + } + t.Run("rendering", func(t *testing.T) { + t.Parallel() + c, signature := newSignature(t) + assert.Equal(t, c.SignatureToStringEx(signature, nil, checker.TypeFormatFlagsWriteTypeArgumentsOfSignature, nil), "(value: string): string") + assert.Equal(t, c.SignatureToStringEx(signature, nil, checker.TypeFormatFlagsWriteTypeArgumentsOfSignature|checker.TypeFormatFlagsWriteArrowStyleSignature, nil), "(value: string) => string") + + emitContext := printer.NewEmitContext() + defer emitContext.Factory.ReleaseArenas() + builder := checker.NewNodeBuilderEx(c, emitContext, nil) + declaration := builder.SignatureToSignatureDeclaration(signature, ast.KindFunctionType, nil, nodebuilder.FlagsWriteTypeArgumentsOfSignature, nodebuilder.InternalFlagsNone, nil) + printNode := func(node *ast.Node) string { + writer := printer.NewTextWriter("\n", 4) + p := printer.NewPrinter(printer.PrinterOptions{}, printer.PrintHandlers{}, emitContext) + p.Write(node, nil, writer, nil) + return writer.String() + } + assert.Equal(t, printNode(declaration), "(value: string) => string") + clone := declaration.Clone(emitContext.Factory.AsNodeFactory()) + assert.Equal(t, printNode(clone), "(value: string) => string") + updated := emitContext.Factory.UpdateFunctionTypeNode( + clone.AsFunctionTypeNode(), + clone.TypeParameterList(), + clone.ParameterList(), + emitContext.Factory.NewKeywordTypeNode(ast.KindNumberKeyword), + ) + assert.Equal(t, printNode(updated), "(value: string) => number") + }) +} + +func TestInstantiatedGenericSignatureDeclarationTypeParameters(t *testing.T) { + t.Parallel() + fs := bundled.WrapFS(vfstest.FromMap(map[string]string{ + "/main.ts": `class C { + method(value: U): U { return value; } +} +new C().method;`, + }, tspath.CaseSensitive)) + program, err := compiler.NewProgram(t.Context(), compiler.ProgramOptions{ + Config: tsoptions.NewParsedCommandLine(&core.CompilerOptions{NoLib: core.TSTrue}, []tspath.RootedFilePath{"/main.ts"}, nil, "/", fs.CaseSensitivity()), + Host: compiler.NewCompilerHost(fs, bundled.LibPath(), nil, nil, nil), + }) + assert.NilError(t, err) + program.BindSourceFiles() + c, done := program.GetTypeChecker(t.Context()) + defer done() + expression := program.GetSourceFile("/main.ts").Statements.Nodes[1].Expression() + signatures := c.GetSignaturesOfType(c.GetTypeAtLocation(expression), checker.SignatureKindCall) + assert.Equal(t, len(signatures), 1) + emitContext := printer.NewEmitContext() + defer emitContext.Factory.ReleaseArenas() + builder := checker.NewNodeBuilderEx(c, emitContext, nil) + for _, declaration := range []*ast.Node{ + c.SignatureToSignatureDeclaration(signatures[0], ast.KindFunctionType, nil, nodebuilder.FlagsWriteTypeArgumentsOfSignature), + builder.SignatureToSignatureDeclaration(signatures[0], ast.KindFunctionType, nil, nodebuilder.FlagsWriteTypeArgumentsOfSignature, nodebuilder.InternalFlagsNone, nil), + } { + parameters := declaration.TypeParameters() + assert.Equal(t, len(parameters), 1) + assert.Equal(t, parameters[0].Kind, ast.KindTypeParameter) + assert.Equal(t, parameters[0].Name().Text(), "U") + assert.Equal(t, parameters[0].AsTypeParameterDeclaration().Constraint.Kind, ast.KindStringKeyword) + } +} + +func TestInstantiatedSignatureHiddenTypeParameterTruncation(t *testing.T) { + t.Parallel() + longLiteral := `"` + strings.Repeat("x", 200) + `"` + for _, test := range []struct { + name string + declaration string + }{ + {"default", "= " + longLiteral}, + {"constraint", "extends { hidden: " + longLiteral + "; nested: { value: number } }"}, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + fs := bundled.WrapFS(vfstest.FromMap(map[string]string{ + "/main.ts": "class C {\nmethod() { return { value: null as T }; }\n}\nnew C().method;", + }, tspath.CaseSensitive)) + program, err := compiler.NewProgram(t.Context(), compiler.ProgramOptions{ + Config: tsoptions.NewParsedCommandLine(&core.CompilerOptions{NoLib: core.TSTrue}, []tspath.RootedFilePath{"/main.ts"}, nil, "/", fs.CaseSensitivity()), + Host: compiler.NewCompilerHost(fs, bundled.LibPath(), nil, nil, nil), + }) + assert.NilError(t, err) + program.BindSourceFiles() + c, done := program.GetTypeChecker(t.Context()) + defer done() + expression := program.GetSourceFile("/main.ts").Statements.Nodes[1].Expression() + signatures := c.GetSignaturesOfType(c.GetTypeAtLocation(expression), checker.SignatureKindCall) + assert.Equal(t, len(signatures), 1) + for _, verbosity := range []*checker.VerbosityContext{nil, {}} { + text := c.SignatureToStringEx(signatures[0], nil, checker.TypeFormatFlagsWriteTypeArgumentsOfSignature, verbosity) + assert.Equal(t, text, "(): { value: string; }") + if verbosity != nil { + assert.Assert(t, !verbosity.Truncated) + } + } + visible := c.SignatureToStringEx(signatures[0], nil, checker.TypeFormatFlagsNone, nil) + assert.Assert(t, strings.HasSuffix(visible, "(): ..."), visible) + }) + } +} + func TestGetSymbolAtLocation(t *testing.T) { t.Parallel() diff --git a/tsc/internal/checker/nodebuilder.go b/tsc/internal/checker/nodebuilder.go index a4fb793b334bf..a4a61f2c2c71c 100644 --- a/tsc/internal/checker/nodebuilder.go +++ b/tsc/internal/checker/nodebuilder.go @@ -296,6 +296,15 @@ func (c *Checker) getNodeBuilder() (*NodeBuilder, func()) { return c.typeToStringNodebuilder, releaseNodes } +func (c *Checker) getNodeBuilderForTypeFormat(flags TypeFormatFlags) (*NodeBuilder, func()) { + if flags&TypeFormatFlagsWriteTypeArgumentsOfSignature == 0 { + return c.getNodeBuilder() + } + // Instantiated signature display metadata must not retain nodes in the cached builder. + builder := c.getNodeBuilderEx(nil) + return builder, builder.EmitContext().Factory.ReleaseArenas +} + func (c *Checker) getNodeBuilderEx(idToSymbol map[*ast.IdentifierNode]*ast.Symbol) *NodeBuilder { b := NewNodeBuilderEx(c, printer.NewEmitContext(), idToSymbol) return b diff --git a/tsc/internal/checker/nodebuilderimpl.go b/tsc/internal/checker/nodebuilderimpl.go index 2d2d01e83affa..b213109c3456f 100644 --- a/tsc/internal/checker/nodebuilderimpl.go +++ b/tsc/internal/checker/nodebuilderimpl.go @@ -1911,6 +1911,7 @@ type SignatureToSignatureDeclarationOptions struct { func (b *NodeBuilderImpl) signatureToSignatureDeclarationHelper(signature *Signature, kind ast.Kind, options *SignatureToSignatureDeclarationOptions) *ast.Node { var typeParameters []*ast.Node + var typeArguments []*ast.Node expandedParams, cleanup := b.enterSignatureScope(signature) b.ctx.approximateLength += 3 @@ -1918,13 +1919,19 @@ func (b *NodeBuilderImpl) signatureToSignatureDeclarationHelper(signature *Signa if b.ctx.flags&nodebuilder.FlagsWriteTypeArgumentsOfSignature != 0 && signature.target != nil && signature.mapper != nil && len(signature.target.TypeParameters()) != 0 { for _, parameter := range signature.target.TypeParameters() { - typeParameters = append(typeParameters, b.typeToTypeNode(b.ch.instantiateType(parameter, signature.mapper))) - } - } else { - for _, parameter := range signature.TypeParameters() { - typeParameters = append(typeParameters, b.typeParameterToDeclaration(parameter)) + typeArguments = append(typeArguments, b.typeToTypeNode(b.ch.instantiateType(parameter, signature.mapper))) } } + displayLength, displayTruncating := b.ctx.approximateLength, b.ctx.truncating + canIncreaseExpansionDepth, expansionTruncated := b.ctx.canIncreaseExpansionDepth, b.ctx.expansionTruncated + for _, parameter := range signature.TypeParameters() { + typeParameters = append(typeParameters, b.typeParameterToDeclaration(parameter)) + } + if len(typeArguments) != 0 { + // These declarations remain in the AST but are hidden behind display arguments. + b.ctx.approximateLength, b.ctx.truncating = displayLength, displayTruncating + b.ctx.canIncreaseExpansionDepth, b.ctx.expansionTruncated = canIncreaseExpansionDepth, expansionTruncated + } restoreFlags := b.saveRestoreFlags() b.ctx.flags &^= nodebuilder.FlagsSuppressAnyReturnType @@ -2020,10 +2027,10 @@ func (b *NodeBuilderImpl) signatureToSignatureDeclarationHelper(signature *Signa panic("Unhandled kind in signatureToSignatureDeclarationHelper") } - // !!! TODO: Smuggle type arguments of signatures out for quickinfo - // if typeArguments != nil { - // node.TypeArguments = b.f.NewNodeList(typeArguments) - // } + // Instantiated arguments are display metadata, not type parameter declarations. + if len(typeArguments) != 0 { + b.e.SetSignatureTypeArguments(node, b.f.NewNodeList(typeArguments)) + } cleanup() return node diff --git a/tsc/internal/checker/printer.go b/tsc/internal/checker/printer.go index b84c967883d88..5a3a49b2620e7 100644 --- a/tsc/internal/checker/printer.go +++ b/tsc/internal/checker/printer.go @@ -73,7 +73,7 @@ func (c *Checker) typeToStringEx(t *Type, enclosingDeclaration *ast.Node, flags if noTruncation { combinedFlags = combinedFlags | nodebuilder.FlagsNoTruncation } - nodeBuilder, release := c.getNodeBuilder() + nodeBuilder, release := c.getNodeBuilderForTypeFormat(flags) defer release() oldVerbosity := nodeBuilder.verbosity nodeBuilder.verbosity = vc @@ -201,7 +201,7 @@ func (c *Checker) signatureToStringEx(signature *Signature, enclosingDeclaration } } - nodeBuilder, release := c.getNodeBuilder() + nodeBuilder, release := c.getNodeBuilderForTypeFormat(flags) defer release() oldVerbosity := nodeBuilder.verbosity nodeBuilder.verbosity = vc @@ -233,7 +233,7 @@ func (c *Checker) typePredicateToString(typePredicate *TypePredicate) string { func (c *Checker) typePredicateToStringEx(typePredicate *TypePredicate, enclosingDeclaration *ast.Node, flags TypeFormatFlags) string { writer, putWriter := printer.GetSingleLineStringWriter() defer putWriter() - nodeBuilder, release := c.getNodeBuilder() + nodeBuilder, release := c.getNodeBuilderForTypeFormat(flags) defer release() combinedFlags := toNodeBuilderFlags(flags) | nodebuilder.FlagsIgnoreErrors | nodebuilder.FlagsWriteTypeParametersInQualifiedName predicate := nodeBuilder.TypePredicateToTypePredicateNode(typePredicate, enclosingDeclaration, combinedFlags, nodebuilder.InternalFlagsNone, nil) // TODO: GH#18217 @@ -291,6 +291,8 @@ func (c *Checker) TypeToTypeNode(t *Type, enclosingDeclaration *ast.Node, flags } func (c *Checker) SignatureToSignatureDeclaration(signature *Signature, kind ast.Kind, enclosingDeclaration *ast.Node, flags nodebuilder.Flags) *ast.Node { + // Declaration ASTs do not carry hover-only instantiation metadata. + flags &^= nodebuilder.FlagsWriteTypeArgumentsOfSignature nodeBuilder, release := c.getNodeBuilder() defer release() return nodeBuilder.SignatureToSignatureDeclaration(signature, kind, enclosingDeclaration, flags, nodebuilder.InternalFlagsNone, nil) diff --git a/tsc/internal/printer/emitcontext.go b/tsc/internal/printer/emitcontext.go index 7953212bd40e7..c06e1467e3811 100644 --- a/tsc/internal/printer/emitcontext.go +++ b/tsc/internal/printer/emitcontext.go @@ -14,16 +14,17 @@ import ( // // NOTE: EmitContext is not guaranteed to be thread-safe. type EmitContext struct { - Factory *NodeFactory // Required. The NodeFactory to use to create new nodes - autoGenerate map[*ast.MemberName]*AutoGenerateInfo - textSource map[*ast.StringLiteralNode]*ast.Node - original map[*ast.Node]*ast.Node - emitNodes core.LinkStore[*ast.Node, emitNode] - assignedName map[*ast.Node]*ast.Expression - classThis map[*ast.Node]*ast.IdentifierNode - varScopeStack core.Stack[*varScope] - letScopeStack core.Stack[*varScope] - emitHelpers collections.OrderedSet[*EmitHelper] + Factory *NodeFactory // Required. The NodeFactory to use to create new nodes + autoGenerate map[*ast.MemberName]*AutoGenerateInfo + textSource map[*ast.StringLiteralNode]*ast.Node + original map[*ast.Node]*ast.Node + emitNodes core.LinkStore[*ast.Node, emitNode] + signatureTypeArguments map[*ast.Node]*ast.TypeArgumentList + assignedName map[*ast.Node]*ast.Expression + classThis map[*ast.Node]*ast.IdentifierNode + varScopeStack core.Stack[*varScope] + letScopeStack core.Stack[*varScope] + emitHelpers collections.OrderedSet[*EmitHelper] } type environmentFlags int @@ -445,6 +446,9 @@ func (c *EmitContext) SetOriginalEx(node *ast.Node, original *ast.Node, allowOve if emitNode := c.emitNodes.TryGet(original); emitNode != nil { c.emitNodes.Get(node).copyFrom(emitNode) } + if arguments := c.signatureTypeArguments[original]; arguments != nil { + c.signatureTypeArguments[node] = arguments + } } else if !allowOverwrite && existing != original { panic("Original node already set.") } else if allowOverwrite { @@ -452,6 +456,21 @@ func (c *EmitContext) SetOriginalEx(node *ast.Node, original *ast.Node, allowOve } } +func (c *EmitContext) SignatureTypeArguments(node *ast.Node) *ast.TypeArgumentList { + return c.signatureTypeArguments[node] +} + +func (c *EmitContext) SetSignatureTypeArguments(node *ast.Node, arguments *ast.TypeArgumentList) { + if arguments == nil { + delete(c.signatureTypeArguments, node) + return + } + if c.signatureTypeArguments == nil { + c.signatureTypeArguments = make(map[*ast.Node]*ast.TypeArgumentList) + } + c.signatureTypeArguments[node] = arguments +} + // Gets the original node for a given node. // // NOTE: This is the equivalent to reading `node.original` in Strada. diff --git a/tsc/internal/printer/printer.go b/tsc/internal/printer/printer.go index a4cb6e3591cba..803d7a974d0e9 100644 --- a/tsc/internal/printer/printer.go +++ b/tsc/internal/printer/printer.go @@ -1461,8 +1461,7 @@ func (p *Printer) emitTypeParameter(node *ast.TypeParameterDeclaration) { } func (p *Printer) emitTypeParameterDeclarationNode(node *ast.TypeParameterDeclarationNode) { - // NOTE: QuickInfo uses TypeFormatFlagsWriteTypeArgumentsOfSignature to instruct the NodeBuilder to store type arguments - // (i.e. type nodes) instead of type parameter declarations in the type parameter list. + // Synthesized display argument lists may also contain type parameter declarations. if ast.IsTypeParameterDeclaration(node) { p.emitTypeParameter(node.AsTypeParameterDeclaration()) } else { @@ -1521,6 +1520,14 @@ func (p *Printer) emitTypeParameters(parentNode *ast.Node, nodes *ast.TypeParame p.emitList((*Printer).emitTypeParameterDeclarationNode, parentNode, nodes, LFTypeParameters|core.IfElse(ast.IsArrowFunction(parentNode) /*p.shouldAllowTrailingComma(parentNode, nodes)*/, LFAllowTrailingComma, LFNone)) // TODO: preserve trailing comma after Strada migration } +func (p *Printer) emitSignatureTypeArgumentsOrParameters(node *ast.Node) { + if arguments := p.emitContext.SignatureTypeArguments(node); arguments != nil { + p.emitTypeArguments(node, arguments) + } else { + p.emitTypeParameters(node, node.FunctionLikeData().TypeParameters) + } +} + func (p *Printer) emitTypeAnnotation(node *ast.TypeNode) { if node == nil { return @@ -1586,12 +1593,7 @@ func (p *Printer) emitParametersForIndexSignature(parentNode *ast.Node, paramete func (p *Printer) emitSignature(node *ast.Node) { n := node.FunctionLikeData() - // !!! In old emitter, quickinfo used type arguments in place of type parameters on instantiated signatures - ////if n.TypeArguments != nil { - //// p.emitTypeArguments(node, n.TypeArguments) - ////} else { - p.emitTypeParameters(node, n.TypeParameters) - ////} + p.emitSignatureTypeArgumentsOrParameters(node) p.emitParameters(node, n.Parameters) p.emitTypeAnnotation(n.Type) @@ -1939,8 +1941,7 @@ func (p *Printer) emitFunctionType(node *ast.FunctionTypeNode) { indented := p.shouldEmitIndented(node.AsNode()) p.increaseIndentIf(indented) p.pushNameGenerationScope(node.AsNode()) - // !!! in the old emitter, quickinfo uses type arguments in place of type parameters for instantiated signatures - p.emitTypeParameters(node.AsNode(), node.TypeParameters) + p.emitSignatureTypeArgumentsOrParameters(node.AsNode()) p.emitParameters(node.AsNode(), node.Parameters) p.writeSpace() p.emitReturnType(node.Type) @@ -1957,8 +1958,7 @@ func (p *Printer) emitConstructorType(node *ast.ConstructorTypeNode) { indented := p.shouldEmitIndented(node.AsNode()) p.increaseIndentIf(indented) p.pushNameGenerationScope(node.AsNode()) - // !!! in the old emitter, quickinfo uses type arguments in place of type parameters for instantiated signatures - p.emitTypeParameters(node.AsNode(), node.TypeParameters) + p.emitSignatureTypeArgumentsOrParameters(node.AsNode()) p.emitParameters(node.AsNode(), node.Parameters) p.writeSpace() p.emitReturnType(node.Type) @@ -2691,7 +2691,7 @@ func (p *Printer) emitArrowFunction(node *ast.ArrowFunction) { indented := p.shouldEmitIndented(node.AsNode()) p.increaseIndentIf(indented) p.pushNameGenerationScope(node.AsNode()) - p.emitTypeParameters(node.AsNode(), node.TypeParameters) + p.emitSignatureTypeArgumentsOrParameters(node.AsNode()) p.emitParametersForArrow(node.AsNode(), node.Parameters) p.emitTypeAnnotation(node.Type) p.writeSpace()