Skip to content

Commit 90397fa

Browse files
committed
Keep instantiated signature arguments out of parameter lists
Signature type parameter lists contain declarations, not the types used to instantiate a call. Keeping concrete types there exposes invalid AST children through the public API. Store instantiated arguments in a lazy EmitContext side table used only for signature display instead of adding a pointer to every functionlike AST node. Copy this metadata through the normal clone and update hooks so regular and arrow-style signature printing retains its arguments. Cover declaration kinds, cloned and updated display nodes, and generic versus instantiated signatures through the sync and async public APIs.
1 parent 0064858 commit 90397fa

6 files changed

Lines changed: 178 additions & 28 deletions

File tree

‎packages/typescript/test/async/api.test.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@ import {
9393
ModuleKind,
9494
ModuleResolutionKind,
9595
type ModuleResolver,
96+
NodeBuilderFlags,
9697
type NumberLiteralType,
9798
ObjectFlags,
9899
type Program,
@@ -4217,6 +4218,38 @@ export class Cache {
42174218
assert.ok(target, "getTarget() should return the generic signature");
42184219
assert.ok(target.typeParameters && target.typeParameters.length > 0, "target should have type parameters");
42194220
});
4221+
4222+
test("instantiated signature declarations do not expose type arguments as type parameters", async () => {
4223+
await using api = spawnAPI({
4224+
"/tsconfig.json": "{}",
4225+
"/src/main.ts": `function identity<T>(value: T): T { return value; }
4226+
identity<string>("hello");`,
4227+
});
4228+
const snapshot = await api.createSnapshot({ openProjects: ["/tsconfig.json"] });
4229+
const project = snapshot.getConfiguredProject("/tsconfig.json")!;
4230+
const source = await project.program.getSourceFile("/src/main.ts");
4231+
assert.ok(source);
4232+
const statement = source.statements[1];
4233+
assert.ok(isExpressionStatement(statement));
4234+
const call = statement.expression;
4235+
assert.ok(isCallExpression(call));
4236+
const signature = await project.checker.getResolvedSignature(call);
4237+
const declaration = await project.checker.signatureToSignatureDeclaration(
4238+
signature,
4239+
SyntaxKind.FunctionDeclaration,
4240+
undefined,
4241+
NodeBuilderFlags.WriteTypeArgumentsOfSignature,
4242+
);
4243+
assert.ok(declaration && isFunctionDeclaration(declaration));
4244+
assert.strictEqual(declaration.typeParameters, undefined);
4245+
assert.strictEqual(declaration.parameters[0].type?.kind, SyntaxKind.StringKeyword);
4246+
assert.strictEqual(declaration.type?.kind, SyntaxKind.StringKeyword);
4247+
const target = await signature.getTarget();
4248+
assert.ok(target);
4249+
const generic = await project.checker.signatureToSignatureDeclaration(target, SyntaxKind.FunctionDeclaration);
4250+
assert.ok(generic && isFunctionDeclaration(generic));
4251+
assert.strictEqual(generic.typeParameters?.[0].kind, SyntaxKind.TypeParameter);
4252+
});
42204253
});
42214254

42224255
describe("Symbol - parent, members, exports", { concurrency }, () => {

‎packages/typescript/test/sync/api.test.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,7 @@ import {
115115
ModuleKind,
116116
ModuleResolutionKind,
117117
type ModuleResolver,
118+
NodeBuilderFlags,
118119
type NumberLiteralType,
119120
ObjectFlags,
120121
type Program,
@@ -4000,6 +4001,38 @@ export class Cache {
40004001
assert.ok(target, "getTarget() should return the generic signature");
40014002
assert.ok(target.typeParameters && target.typeParameters.length > 0, "target should have type parameters");
40024003
});
4004+
4005+
test("instantiated signature declarations do not expose type arguments as type parameters", () => {
4006+
using api = spawnAPI({
4007+
"/tsconfig.json": "{}",
4008+
"/src/main.ts": `function identity<T>(value: T): T { return value; }
4009+
identity<string>("hello");`,
4010+
});
4011+
const snapshot = api.createSnapshot({ openProjects: ["/tsconfig.json"] });
4012+
const project = snapshot.getConfiguredProject("/tsconfig.json")!;
4013+
const source = project.program.getSourceFile("/src/main.ts");
4014+
assert.ok(source);
4015+
const statement = source.statements[1];
4016+
assert.ok(isExpressionStatement(statement));
4017+
const call = statement.expression;
4018+
assert.ok(isCallExpression(call));
4019+
const signature = project.checker.getResolvedSignature(call);
4020+
const declaration = project.checker.signatureToSignatureDeclaration(
4021+
signature,
4022+
SyntaxKind.FunctionDeclaration,
4023+
undefined,
4024+
NodeBuilderFlags.WriteTypeArgumentsOfSignature,
4025+
);
4026+
assert.ok(declaration && isFunctionDeclaration(declaration));
4027+
assert.strictEqual(declaration.typeParameters, undefined);
4028+
assert.strictEqual(declaration.parameters[0].type?.kind, SyntaxKind.StringKeyword);
4029+
assert.strictEqual(declaration.type?.kind, SyntaxKind.StringKeyword);
4030+
const target = signature.getTarget();
4031+
assert.ok(target);
4032+
const generic = project.checker.signatureToSignatureDeclaration(target, SyntaxKind.FunctionDeclaration);
4033+
assert.ok(generic && isFunctionDeclaration(generic));
4034+
assert.strictEqual(generic.typeParameters?.[0].kind, SyntaxKind.TypeParameter);
4035+
});
40034036
});
40044037

40054038
describe("Symbol - parent, members, exports", { concurrency }, () => {

‎tsc/internal/checker/checker_test.go‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ import (
1111
"github.com/microsoft/TypeScript/tsc/internal/checker"
1212
"github.com/microsoft/TypeScript/tsc/internal/compiler"
1313
"github.com/microsoft/TypeScript/tsc/internal/core"
14+
"github.com/microsoft/TypeScript/tsc/internal/nodebuilder"
15+
"github.com/microsoft/TypeScript/tsc/internal/printer"
1416
"github.com/microsoft/TypeScript/tsc/internal/repo"
1517
"github.com/microsoft/TypeScript/tsc/internal/tsoptions"
1618
"github.com/microsoft/TypeScript/tsc/internal/tspath"
@@ -19,6 +21,68 @@ import (
1921
"gotest.tools/v3/assert"
2022
)
2123

24+
func TestInstantiatedSignatureDeclarationTypeParameters(t *testing.T) {
25+
t.Parallel()
26+
newSignature := func(t *testing.T) (*checker.Checker, *checker.Signature) {
27+
t.Helper()
28+
fs := bundled.WrapFS(vfstest.FromMap(map[string]string{
29+
"/main.ts": `function identity<T>(value: T): T { return value; }
30+
identity<string>("hello");`,
31+
}, tspath.CaseSensitive))
32+
program, err := compiler.NewProgram(t.Context(), compiler.ProgramOptions{
33+
Config: tsoptions.NewParsedCommandLine(&core.CompilerOptions{NoLib: core.TSTrue}, []tspath.RootedFilePath{"/main.ts"}, nil, "/", fs.CaseSensitivity()),
34+
Host: compiler.NewCompilerHost(fs, bundled.LibPath(), nil, nil, nil),
35+
})
36+
assert.NilError(t, err)
37+
program.BindSourceFiles()
38+
c, done := program.GetTypeChecker(t.Context())
39+
t.Cleanup(done)
40+
call := program.GetSourceFile("/main.ts").Statements.Nodes[1].Expression()
41+
return c, c.GetResolvedSignature(call)
42+
}
43+
for _, kind := range []ast.Kind{
44+
ast.KindCallSignature, ast.KindConstructSignature, ast.KindMethodSignature,
45+
ast.KindMethodDeclaration, ast.KindFunctionType, ast.KindConstructorType,
46+
ast.KindFunctionDeclaration, ast.KindFunctionExpression, ast.KindArrowFunction,
47+
} {
48+
t.Run(kind.String(), func(t *testing.T) {
49+
t.Parallel()
50+
c, signature := newSignature(t)
51+
declaration := c.SignatureToSignatureDeclaration(signature, kind, nil, nodebuilder.FlagsWriteTypeArgumentsOfSignature)
52+
assert.Assert(t, declaration.TypeParameters() == nil, "type parameters must contain declarations, not instantiated argument types")
53+
assert.Equal(t, declaration.Parameters()[0].Type().Kind, ast.KindStringKeyword)
54+
assert.Equal(t, declaration.Type().Kind, ast.KindStringKeyword)
55+
})
56+
}
57+
t.Run("rendering", func(t *testing.T) {
58+
t.Parallel()
59+
c, signature := newSignature(t)
60+
assert.Equal(t, c.SignatureToStringEx(signature, nil, checker.TypeFormatFlagsWriteTypeArgumentsOfSignature, nil), "<string>(value: string): string")
61+
assert.Equal(t, c.SignatureToStringEx(signature, nil, checker.TypeFormatFlagsWriteTypeArgumentsOfSignature|checker.TypeFormatFlagsWriteArrowStyleSignature, nil), "<string>(value: string) => string")
62+
63+
emitContext := printer.NewEmitContext()
64+
defer emitContext.Factory.ReleaseArenas()
65+
builder := checker.NewNodeBuilderEx(c, emitContext, nil)
66+
declaration := builder.SignatureToSignatureDeclaration(signature, ast.KindFunctionType, nil, nodebuilder.FlagsWriteTypeArgumentsOfSignature, nodebuilder.InternalFlagsNone, nil)
67+
printNode := func(node *ast.Node) string {
68+
writer := printer.NewTextWriter("\n", 4)
69+
p := printer.NewPrinter(printer.PrinterOptions{}, printer.PrintHandlers{}, emitContext)
70+
p.Write(node, nil, writer, nil)
71+
return writer.String()
72+
}
73+
assert.Equal(t, printNode(declaration), "<string>(value: string) => string")
74+
clone := declaration.Clone(emitContext.Factory.AsNodeFactory())
75+
assert.Equal(t, printNode(clone), "<string>(value: string) => string")
76+
updated := emitContext.Factory.UpdateFunctionTypeNode(
77+
clone.AsFunctionTypeNode(),
78+
clone.TypeParameterList(),
79+
clone.ParameterList(),
80+
emitContext.Factory.NewKeywordTypeNode(ast.KindNumberKeyword),
81+
)
82+
assert.Equal(t, printNode(updated), "<string>(value: string) => number")
83+
})
84+
}
85+
2286
func TestGetSymbolAtLocation(t *testing.T) {
2387
t.Parallel()
2488

‎tsc/internal/checker/nodebuilderimpl.go‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1911,14 +1911,15 @@ type SignatureToSignatureDeclarationOptions struct {
19111911

19121912
func (b *NodeBuilderImpl) signatureToSignatureDeclarationHelper(signature *Signature, kind ast.Kind, options *SignatureToSignatureDeclarationOptions) *ast.Node {
19131913
var typeParameters []*ast.Node
1914+
var typeArguments []*ast.Node
19141915

19151916
expandedParams, cleanup := b.enterSignatureScope(signature)
19161917
b.ctx.approximateLength += 3
19171918
// Usually a signature contributes a few more characters than this, but 3 is the minimum
19181919

19191920
if b.ctx.flags&nodebuilder.FlagsWriteTypeArgumentsOfSignature != 0 && signature.target != nil && signature.mapper != nil && len(signature.target.TypeParameters()) != 0 {
19201921
for _, parameter := range signature.target.TypeParameters() {
1921-
typeParameters = append(typeParameters, b.typeToTypeNode(b.ch.instantiateType(parameter, signature.mapper)))
1922+
typeArguments = append(typeArguments, b.typeToTypeNode(b.ch.instantiateType(parameter, signature.mapper)))
19221923
}
19231924
} else {
19241925
for _, parameter := range signature.TypeParameters() {
@@ -2020,10 +2021,10 @@ func (b *NodeBuilderImpl) signatureToSignatureDeclarationHelper(signature *Signa
20202021
panic("Unhandled kind in signatureToSignatureDeclarationHelper")
20212022
}
20222023

2023-
// !!! TODO: Smuggle type arguments of signatures out for quickinfo
2024-
// if typeArguments != nil {
2025-
// node.TypeArguments = b.f.NewNodeList(typeArguments)
2026-
// }
2024+
// Instantiated arguments are display metadata, not type parameter declarations.
2025+
if len(typeArguments) != 0 {
2026+
b.e.SetSignatureTypeArguments(node, b.f.NewNodeList(typeArguments))
2027+
}
20272028

20282029
cleanup()
20292030
return node

‎tsc/internal/printer/emitcontext.go‎

Lines changed: 29 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -14,16 +14,17 @@ import (
1414
//
1515
// NOTE: EmitContext is not guaranteed to be thread-safe.
1616
type EmitContext struct {
17-
Factory *NodeFactory // Required. The NodeFactory to use to create new nodes
18-
autoGenerate map[*ast.MemberName]*AutoGenerateInfo
19-
textSource map[*ast.StringLiteralNode]*ast.Node
20-
original map[*ast.Node]*ast.Node
21-
emitNodes core.LinkStore[*ast.Node, emitNode]
22-
assignedName map[*ast.Node]*ast.Expression
23-
classThis map[*ast.Node]*ast.IdentifierNode
24-
varScopeStack core.Stack[*varScope]
25-
letScopeStack core.Stack[*varScope]
26-
emitHelpers collections.OrderedSet[*EmitHelper]
17+
Factory *NodeFactory // Required. The NodeFactory to use to create new nodes
18+
autoGenerate map[*ast.MemberName]*AutoGenerateInfo
19+
textSource map[*ast.StringLiteralNode]*ast.Node
20+
original map[*ast.Node]*ast.Node
21+
emitNodes core.LinkStore[*ast.Node, emitNode]
22+
signatureTypeArguments map[*ast.Node]*ast.TypeArgumentList
23+
assignedName map[*ast.Node]*ast.Expression
24+
classThis map[*ast.Node]*ast.IdentifierNode
25+
varScopeStack core.Stack[*varScope]
26+
letScopeStack core.Stack[*varScope]
27+
emitHelpers collections.OrderedSet[*EmitHelper]
2728
}
2829

2930
type environmentFlags int
@@ -445,13 +446,31 @@ func (c *EmitContext) SetOriginalEx(node *ast.Node, original *ast.Node, allowOve
445446
if emitNode := c.emitNodes.TryGet(original); emitNode != nil {
446447
c.emitNodes.Get(node).copyFrom(emitNode)
447448
}
449+
if arguments := c.signatureTypeArguments[original]; arguments != nil {
450+
c.signatureTypeArguments[node] = arguments
451+
}
448452
} else if !allowOverwrite && existing != original {
449453
panic("Original node already set.")
450454
} else if allowOverwrite {
451455
c.original[node] = original
452456
}
453457
}
454458

459+
func (c *EmitContext) SignatureTypeArguments(node *ast.Node) *ast.TypeArgumentList {
460+
return c.signatureTypeArguments[node]
461+
}
462+
463+
func (c *EmitContext) SetSignatureTypeArguments(node *ast.Node, arguments *ast.TypeArgumentList) {
464+
if arguments == nil {
465+
delete(c.signatureTypeArguments, node)
466+
return
467+
}
468+
if c.signatureTypeArguments == nil {
469+
c.signatureTypeArguments = make(map[*ast.Node]*ast.TypeArgumentList)
470+
}
471+
c.signatureTypeArguments[node] = arguments
472+
}
473+
455474
// Gets the original node for a given node.
456475
//
457476
// NOTE: This is the equivalent to reading `node.original` in Strada.

‎tsc/internal/printer/printer.go‎

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1461,8 +1461,7 @@ func (p *Printer) emitTypeParameter(node *ast.TypeParameterDeclaration) {
14611461
}
14621462

14631463
func (p *Printer) emitTypeParameterDeclarationNode(node *ast.TypeParameterDeclarationNode) {
1464-
// NOTE: QuickInfo uses TypeFormatFlagsWriteTypeArgumentsOfSignature to instruct the NodeBuilder to store type arguments
1465-
// (i.e. type nodes) instead of type parameter declarations in the type parameter list.
1464+
// Synthesized display argument lists may also contain type parameter declarations.
14661465
if ast.IsTypeParameterDeclaration(node) {
14671466
p.emitTypeParameter(node.AsTypeParameterDeclaration())
14681467
} else {
@@ -1521,6 +1520,14 @@ func (p *Printer) emitTypeParameters(parentNode *ast.Node, nodes *ast.TypeParame
15211520
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
15221521
}
15231522

1523+
func (p *Printer) emitSignatureTypeArgumentsOrParameters(node *ast.Node) {
1524+
if arguments := p.emitContext.SignatureTypeArguments(node); arguments != nil {
1525+
p.emitTypeArguments(node, arguments)
1526+
} else {
1527+
p.emitTypeParameters(node, node.FunctionLikeData().TypeParameters)
1528+
}
1529+
}
1530+
15241531
func (p *Printer) emitTypeAnnotation(node *ast.TypeNode) {
15251532
if node == nil {
15261533
return
@@ -1586,12 +1593,7 @@ func (p *Printer) emitParametersForIndexSignature(parentNode *ast.Node, paramete
15861593
func (p *Printer) emitSignature(node *ast.Node) {
15871594
n := node.FunctionLikeData()
15881595

1589-
// !!! In old emitter, quickinfo used type arguments in place of type parameters on instantiated signatures
1590-
////if n.TypeArguments != nil {
1591-
//// p.emitTypeArguments(node, n.TypeArguments)
1592-
////} else {
1593-
p.emitTypeParameters(node, n.TypeParameters)
1594-
////}
1596+
p.emitSignatureTypeArgumentsOrParameters(node)
15951597

15961598
p.emitParameters(node, n.Parameters)
15971599
p.emitTypeAnnotation(n.Type)
@@ -1939,8 +1941,7 @@ func (p *Printer) emitFunctionType(node *ast.FunctionTypeNode) {
19391941
indented := p.shouldEmitIndented(node.AsNode())
19401942
p.increaseIndentIf(indented)
19411943
p.pushNameGenerationScope(node.AsNode())
1942-
// !!! in the old emitter, quickinfo uses type arguments in place of type parameters for instantiated signatures
1943-
p.emitTypeParameters(node.AsNode(), node.TypeParameters)
1944+
p.emitSignatureTypeArgumentsOrParameters(node.AsNode())
19441945
p.emitParameters(node.AsNode(), node.Parameters)
19451946
p.writeSpace()
19461947
p.emitReturnType(node.Type)
@@ -1957,8 +1958,7 @@ func (p *Printer) emitConstructorType(node *ast.ConstructorTypeNode) {
19571958
indented := p.shouldEmitIndented(node.AsNode())
19581959
p.increaseIndentIf(indented)
19591960
p.pushNameGenerationScope(node.AsNode())
1960-
// !!! in the old emitter, quickinfo uses type arguments in place of type parameters for instantiated signatures
1961-
p.emitTypeParameters(node.AsNode(), node.TypeParameters)
1961+
p.emitSignatureTypeArgumentsOrParameters(node.AsNode())
19621962
p.emitParameters(node.AsNode(), node.Parameters)
19631963
p.writeSpace()
19641964
p.emitReturnType(node.Type)
@@ -2691,7 +2691,7 @@ func (p *Printer) emitArrowFunction(node *ast.ArrowFunction) {
26912691
indented := p.shouldEmitIndented(node.AsNode())
26922692
p.increaseIndentIf(indented)
26932693
p.pushNameGenerationScope(node.AsNode())
2694-
p.emitTypeParameters(node.AsNode(), node.TypeParameters)
2694+
p.emitSignatureTypeArgumentsOrParameters(node.AsNode())
26952695
p.emitParametersForArrow(node.AsNode(), node.Parameters)
26962696
p.emitTypeAnnotation(node.Type)
26972697
p.writeSpace()

0 commit comments

Comments
 (0)