Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions packages/typescript/test/async/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ import {
ModuleKind,
ModuleResolutionKind,
type ModuleResolver,
NodeBuilderFlags,
type NumberLiteralType,
ObjectFlags,
type Program,
Expand Down Expand Up @@ -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<T>(value: T): T { return value; }
identity<string>("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<T> {
method<U extends T>(value: U): U { return value; }
}
new C<string>().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 }, () => {
Expand Down
64 changes: 64 additions & 0 deletions packages/typescript/test/sync/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ import {
ModuleKind,
ModuleResolutionKind,
type ModuleResolver,
NodeBuilderFlags,
type NumberLiteralType,
ObjectFlags,
type Program,
Expand Down Expand Up @@ -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<T>(value: T): T { return value; }
identity<string>("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<T> {
method<U extends T>(value: U): U { return value; }
}
new C<string>().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 }, () => {
Expand Down
137 changes: 137 additions & 0 deletions tsc/internal/checker/checker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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<T>(value: T): T { return value; }
identity<string>("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), "<string>(value: string): string")
assert.Equal(t, c.SignatureToStringEx(signature, nil, checker.TypeFormatFlagsWriteTypeArgumentsOfSignature|checker.TypeFormatFlagsWriteArrowStyleSignature, nil), "<string>(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), "<string>(value: string) => string")
clone := declaration.Clone(emitContext.Factory.AsNodeFactory())
assert.Equal(t, printNode(clone), "<string>(value: string) => string")
updated := emitContext.Factory.UpdateFunctionTypeNode(
clone.AsFunctionTypeNode(),
clone.TypeParameterList(),
clone.ParameterList(),
emitContext.Factory.NewKeywordTypeNode(ast.KindNumberKeyword),
)
assert.Equal(t, printNode(updated), "<string>(value: string) => number")
})
}

func TestInstantiatedGenericSignatureDeclarationTypeParameters(t *testing.T) {
t.Parallel()
fs := bundled.WrapFS(vfstest.FromMap(map[string]string{
"/main.ts": `class C<T> {
method<U extends T>(value: U): U { return value; }
}
new C<string>().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<T> {\nmethod<U " + test.declaration + ">() { return { value: null as T }; }\n}\nnew C<string>().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, "<U>(): { 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()

Expand Down
9 changes: 9 additions & 0 deletions tsc/internal/checker/nodebuilder.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
25 changes: 16 additions & 9 deletions tsc/internal/checker/nodebuilderimpl.go
Original file line number Diff line number Diff line change
Expand Up @@ -1911,20 +1911,27 @@ 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
// Usually a signature contributes a few more characters than this, but 3 is the minimum

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)))
Comment thread
jakebailey marked this conversation as resolved.
Resolved
}
}
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))
Comment thread
jakebailey marked this conversation as resolved.
Resolved
}
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
Comment on lines +1932 to +1933
}

restoreFlags := b.saveRestoreFlags()
b.ctx.flags &^= nodebuilder.FlagsSuppressAnyReturnType
Expand Down Expand Up @@ -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))

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this really matter?

}

cleanup()
return node
Expand Down
Loading
Loading