From 2c42297e21842b667391f8cfb0a801cadeb8d5a5 Mon Sep 17 00:00:00 2001 From: el-j Date: Fri, 30 Oct 2026 16:38:41 +0100 Subject: [PATCH 1/3] feat(printer): implement JSDoc node emission in AST printer Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- tsc/internal/printer/printer.go | 388 ++++++++++++++++++++++++++- tsc/internal/printer/printer_test.go | 116 ++++++++ 2 files changed, 502 insertions(+), 2 deletions(-) diff --git a/tsc/internal/printer/printer.go b/tsc/internal/printer/printer.go index a4cb6e3591cba..781e9fa8cbe52 100644 --- a/tsc/internal/printer/printer.go +++ b/tsc/internal/printer/printer.go @@ -2376,6 +2376,19 @@ func (p *Printer) emitTypeNode(node *ast.TypeNode, precedence ast.TypePrecedence case ast.KindJSDocAllType: p.emitJSDocAllType(node) + case ast.KindJSDocTypeExpression: + p.writePunctuation("{") + if typeNode := node.AsJSDocTypeExpression().Type; typeNode != nil { + p.emitTypeNode(typeNode, ast.TypePrecedenceJSDoc) + } + p.writePunctuation("}") + case ast.KindJSDocNameReference: + p.emitEntityName(node.AsJSDocNameReference().Name()) + case ast.KindJSDocTypeLiteral: + p.emitJSDocTypeLiteral(node.AsJSDocTypeLiteral()) + case ast.KindJSDocSignature: + p.write("function") + p.emitSignature(node) case ast.KindJSDocNonNullableType: p.emitJSDocNonNullableType(node.AsJSDocNonNullableType()) case ast.KindJSDocNullableType: @@ -4603,8 +4616,379 @@ func (p *Printer) emitEnumMemberNode(node *ast.EnumMemberNode) { // func (p *Printer) emitJSDocNode(node *ast.Node) { - // !!! - panic("not implemented") + switch node.Kind { + case ast.KindJSDoc: + p.emitJSDoc(node.AsJSDoc()) + case ast.KindJSDocTypeExpression: + p.writePunctuation("{") + if typeNode := node.AsJSDocTypeExpression().Type; typeNode != nil { + p.emitTypeNode(typeNode, ast.TypePrecedenceJSDoc) + } + p.writePunctuation("}") + case ast.KindJSDocNameReference: + p.emitEntityName(node.AsJSDocNameReference().Name()) + case ast.KindJSDocTypeLiteral: + p.emitJSDocTypeLiteral(node.AsJSDocTypeLiteral()) + case ast.KindJSDocSignature: + p.write("function") + p.emitSignature(node) + case ast.KindJSDocText: + p.write(node.Text()) + case ast.KindJSDocLink, ast.KindJSDocLinkCode, ast.KindJSDocLinkPlain: + var text strings.Builder + p.writeJSDocCommentNode(&text, node) + p.write(text.String()) + default: + if ast.IsJSDocTag(node) { + p.emitJSDocTag(node) + return + } + panic(fmt.Sprintf("unhandled JSDoc node: %v", node.Kind)) + } +} + +func (p *Printer) emitJSDoc(node *ast.JSDoc) { + hasComment := node.Comment != nil && len(node.Comment.Nodes) > 0 + hasTags := node.Tags != nil && len(node.Tags.Nodes) > 0 + var commentText strings.Builder + if hasComment { + for _, commentNode := range node.Comment.Nodes { + p.writeJSDocCommentNode(&commentText, commentNode) + } + } + text := commentText.String() + p.write("/**") + if hasComment && !hasTags && len(node.Comment.Nodes) == 1 && text != "" && + len(text) <= 80 && !strings.Contains(text, "\n") { + p.writeSpace() + p.write(strings.TrimSpace(text)) + p.writeSpace() + p.write("*/") + return + } + if !hasComment && !hasTags { + p.write(" */") + return + } + + p.writeLine() + if hasComment { + p.emitJSDocCommentLines(text) + p.writeLine() + } + if hasTags { + for _, tag := range node.Tags.Nodes { + p.write(" * ") + p.emitJSDocTag(tag) + p.writeLine() + } + } + p.write(" */") +} + +func (p *Printer) emitJSDocCommentLines(text string) { + for i, line := range strings.Split(text, "\n") { + if i > 0 { + p.writeLine() + } + p.write(" *") + if line = strings.TrimSpace(line); line != "" { + p.writeSpace() + p.write(line) + } + } +} + +func (p *Printer) writeJSDocCommentNode(text *strings.Builder, node *ast.Node) { + switch node.Kind { + case ast.KindJSDocText: + text.WriteString(node.Text()) + case ast.KindJSDocLink, ast.KindJSDocLinkCode, ast.KindJSDocLinkPlain: + kind := "link" + var name *ast.Node + switch node.Kind { + case ast.KindJSDocLink: + name = node.AsJSDocLink().Name() + case ast.KindJSDocLinkCode: + kind = "linkcode" + name = node.AsJSDocLinkCode().Name() + case ast.KindJSDocLinkPlain: + kind = "linkplain" + name = node.AsJSDocLinkPlain().Name() + } + linkText := node.Text() + text.WriteString("{@") + text.WriteString(kind) + text.WriteByte(' ') + if name != nil { + text.WriteString(jsDocEntityNameText(name)) + if linkText == "" || !strings.HasPrefix(linkText, "://") { + text.WriteByte(' ') + } + } + text.WriteString(linkText) + text.WriteByte('}') + default: + panic(fmt.Sprintf("unhandled JSDoc comment node: %v", node.Kind)) + } +} + +func jsDocEntityNameText(node *ast.Node) string { + switch node.Kind { + case ast.KindIdentifier, ast.KindPrivateIdentifier: + return node.Text() + case ast.KindQualifiedName: + name := node.AsQualifiedName() + return jsDocEntityNameText(name.Left) + "." + jsDocEntityNameText(name.Right) + case ast.KindThisKeyword: + return "this" + default: + panic(fmt.Sprintf("unhandled JSDoc entity name: %v", node.Kind)) + } +} + +func (p *Printer) emitJSDocType(node *ast.Node) { + if node == nil { + return + } + p.writeSpace() + p.writePunctuation("{") + if node.Kind == ast.KindJSDocTypeExpression { + if typeNode := node.AsJSDocTypeExpression().Type; typeNode != nil { + p.emitTypeNode(typeNode, ast.TypePrecedenceJSDoc) + } + } else { + p.emitTypeNode(node, ast.TypePrecedenceJSDoc) + } + p.writePunctuation("}") +} + +func (p *Printer) emitJSDocTag(node *ast.Node) { + tagName, comment := jsDocTagBase(node) + p.write("@") + if tagName != nil { + p.write(tagName.Text()) + } + + switch node.Kind { + case ast.KindJSDocParameterTag, ast.KindJSDocPropertyTag: + tag := node.AsJSDocParameterOrPropertyTag() + if !tag.IsNameFirst { + p.emitJSDocType(tag.TypeExpression) + } + if tag.Name() != nil { + p.writeSpace() + if tag.IsBracketed { + p.write("[") + } + p.emitEntityName(tag.Name()) + if tag.IsBracketed { + p.write("]") + } + } + if tag.IsNameFirst { + p.emitJSDocType(tag.TypeExpression) + } + case ast.KindJSDocReturnTag: + p.emitJSDocType(node.AsJSDocReturnTag().TypeExpression) + case ast.KindJSDocThisTag: + p.emitJSDocType(node.AsJSDocThisTag().TypeExpression) + case ast.KindJSDocThrowsTag: + p.emitJSDocType(node.AsJSDocThrowsTag().TypeExpression) + case ast.KindJSDocSatisfiesTag: + p.emitJSDocType(node.AsJSDocSatisfiesTag().TypeExpression) + case ast.KindJSDocTypeTag: + p.emitJSDocType(node.AsJSDocTypeTag().TypeExpression) + case ast.KindJSDocTemplateTag: + tag := node.AsJSDocTemplateTag() + if tag.Constraint != nil { + p.emitJSDocType(tag.Constraint) + } + if tag.TypeParameters != nil { + p.writeSpace() + for i, typeParameter := range tag.TypeParameters.Nodes { + if i > 0 { + p.writePunctuation(",") + p.writeSpace() + } + p.emitEntityName(typeParameter.AsTypeParameterDeclaration().Name()) + } + } + case ast.KindJSDocSeeTag: + tag := node.AsJSDocSeeTag() + if tag.NameExpression != nil { + p.writeSpace() + p.emitTypeNode(tag.NameExpression, ast.TypePrecedenceJSDoc) + } + case ast.KindJSDocImplementsTag: + tag := node.AsJSDocImplementsTag() + if tag.ClassName != nil { + p.writeSpace() + p.emitExpressionWithTypeArguments(tag.ClassName.AsExpressionWithTypeArguments()) + } + case ast.KindJSDocAugmentsTag: + tag := node.AsJSDocAugmentsTag() + if tag.ClassName != nil { + p.writeSpace() + p.emitExpressionWithTypeArguments(tag.ClassName.AsExpressionWithTypeArguments()) + } + case ast.KindJSDocCallbackTag: + tag := node.AsJSDocCallbackTag() + p.emitJSDocType(tag.TypeExpression) + if tag.Name() != nil { + p.writeSpace() + p.emitJSDocFullName(tag.Name()) + } + case ast.KindJSDocOverloadTag: + p.emitJSDocType(node.AsJSDocOverloadTag().TypeExpression) + case ast.KindJSDocTypedefTag: + tag := node.AsJSDocTypedefTag() + p.emitJSDocType(tag.TypeExpression) + if tag.Name() != nil { + p.writeSpace() + p.emitJSDocFullName(tag.Name()) + } + case ast.KindJSDocImportTag: + tag := node.AsJSDocImportTag() + if tag.ImportClause != nil { + p.writeSpace() + p.emitImportClause(tag.ImportClause.AsImportClause()) + } + if tag.ModuleSpecifier != nil { + p.writeSpace() + p.emitExpression(tag.ModuleSpecifier, ast.OperatorPrecedenceLowest) + } + if tag.Attributes != nil { + p.writeSpace() + p.emitImportAttributes(tag.Attributes.AsImportAttributes()) + } + } + + if comment != nil && len(comment.Nodes) > 0 { + var text strings.Builder + for _, commentNode := range comment.Nodes { + p.writeJSDocCommentNode(&text, commentNode) + } + lines := strings.Split(strings.TrimSpace(text.String()), "\n") + if len(lines) > 0 && lines[0] != "" { + p.writeSpace() + p.write(strings.TrimSpace(lines[0])) + for _, line := range lines[1:] { + p.writeLine() + p.write(" * ") + p.write(strings.TrimSpace(line)) + } + } + } +} + +func (p *Printer) emitJSDocTypeLiteral(node *ast.JSDocTypeLiteral) { + p.writePunctuation("{") + if len(node.JSDocPropertyTags) > 0 { + p.writeSpace() + for i, property := range node.JSDocPropertyTags { + if i > 0 { + p.writePunctuation(",") + p.writeSpace() + } + tag := property.AsJSDocParameterOrPropertyTag() + if tag.Name() != nil { + p.emitEntityName(tag.Name()) + } + if tag.TypeExpression != nil { + p.writePunctuation(":") + p.writeSpace() + p.emitTypeNode(tag.TypeExpression, ast.TypePrecedenceJSDoc) + } + } + p.writeSpace() + } + p.writePunctuation("}") + if node.IsArrayType { + p.writePunctuation("[") + p.writePunctuation("]") + } +} + +func (p *Printer) emitJSDocFullName(node *ast.JSDocFullName) { + switch node.Kind { + case ast.KindIdentifier: + p.emitIdentifierName(node.AsIdentifier()) + case ast.KindModuleDeclaration: + p.emitModuleDeclaration(node.AsModuleDeclaration()) + default: + panic(fmt.Sprintf("unhandled JSDoc full name: %v", node.Kind)) + } +} + +func jsDocTagBase(node *ast.Node) (*ast.IdentifierNode, *ast.NodeList) { + switch node.Kind { + case ast.KindJSDocTypeTag: + tag := node.AsJSDocTypeTag() + return tag.TagName, tag.Comment + case ast.KindJSDocUnknownTag: + tag := node.AsJSDocUnknownTag() + return tag.TagName, tag.Comment + case ast.KindJSDocTemplateTag: + tag := node.AsJSDocTemplateTag() + return tag.TagName, tag.Comment + case ast.KindJSDocReturnTag: + tag := node.AsJSDocReturnTag() + return tag.TagName, tag.Comment + case ast.KindJSDocPublicTag: + tag := node.AsJSDocPublicTag() + return tag.TagName, tag.Comment + case ast.KindJSDocPrivateTag: + tag := node.AsJSDocPrivateTag() + return tag.TagName, tag.Comment + case ast.KindJSDocProtectedTag: + tag := node.AsJSDocProtectedTag() + return tag.TagName, tag.Comment + case ast.KindJSDocReadonlyTag: + tag := node.AsJSDocReadonlyTag() + return tag.TagName, tag.Comment + case ast.KindJSDocOverrideTag: + tag := node.AsJSDocOverrideTag() + return tag.TagName, tag.Comment + case ast.KindJSDocDeprecatedTag: + tag := node.AsJSDocDeprecatedTag() + return tag.TagName, tag.Comment + case ast.KindJSDocSeeTag: + tag := node.AsJSDocSeeTag() + return tag.TagName, tag.Comment + case ast.KindJSDocImplementsTag: + tag := node.AsJSDocImplementsTag() + return tag.TagName, tag.Comment + case ast.KindJSDocAugmentsTag: + tag := node.AsJSDocAugmentsTag() + return tag.TagName, tag.Comment + case ast.KindJSDocSatisfiesTag: + tag := node.AsJSDocSatisfiesTag() + return tag.TagName, tag.Comment + case ast.KindJSDocThrowsTag: + tag := node.AsJSDocThrowsTag() + return tag.TagName, tag.Comment + case ast.KindJSDocThisTag: + tag := node.AsJSDocThisTag() + return tag.TagName, tag.Comment + case ast.KindJSDocImportTag: + tag := node.AsJSDocImportTag() + return tag.TagName, tag.Comment + case ast.KindJSDocCallbackTag: + tag := node.AsJSDocCallbackTag() + return tag.TagName, tag.Comment + case ast.KindJSDocOverloadTag: + tag := node.AsJSDocOverloadTag() + return tag.TagName, tag.Comment + case ast.KindJSDocTypedefTag: + tag := node.AsJSDocTypedefTag() + return tag.TagName, tag.Comment + case ast.KindJSDocParameterTag, ast.KindJSDocPropertyTag: + tag := node.AsJSDocParameterOrPropertyTag() + return tag.TagName, tag.Comment + default: + panic(fmt.Sprintf("unhandled JSDoc tag: %v", node.Kind)) + } } // diff --git a/tsc/internal/printer/printer_test.go b/tsc/internal/printer/printer_test.go index 1e9c174ca8559..9661afb2c8e35 100644 --- a/tsc/internal/printer/printer_test.go +++ b/tsc/internal/printer/printer_test.go @@ -590,6 +590,122 @@ func TestEmit(t *testing.T) { } } +func TestEmitJSDoc(t *testing.T) { + t.Parallel() + + var factory ast.NodeFactory + doc := factory.NewJSDoc( + factory.NewNodeList([]*ast.Node{ + factory.NewJSDocText([]string{"This is a function description"}), + }), + factory.NewNodeList([]*ast.Node{ + factory.NewJSDocParameterOrPropertyTag( + ast.KindJSDocParameterTag, + factory.NewIdentifier("param"), + factory.NewIdentifier("foo"), + false, /*isBracketed*/ + nil, /*typeExpression*/ + false, /*isNameFirst*/ + factory.NewNodeList([]*ast.Node{ + factory.NewJSDocText([]string{"The foo parameter"}), + }), + ), + }), + ) + actual := printer.NewPrinter( + printer.PrinterOptions{NewLine: core.NewLineKindLF}, + printer.PrintHandlers{}, + nil, + ).Emit(doc, nil) + expected := "/**\n * This is a function description\n * @param foo The foo parameter\n */" + if actual != expected { + t.Errorf("unexpected JSDoc output:\n got: %q\nwant: %q", actual, expected) + } + + file := parsetestutil.ParseTypeScript("/** function description */\nfunction f() {}", false) + emittestutil.CheckEmit(t, nil, file, "/** function description */\nfunction f() { }") +} + +func TestEmitJSDocSingleLine(t *testing.T) { + t.Parallel() + + var factory ast.NodeFactory + node := factory.NewJSDoc( + factory.NewNodeList([]*ast.Node{ + factory.NewJSDocText([]string{"A short description"}), + }), + nil, /*tags*/ + ) + actual := printer.NewPrinter( + printer.PrinterOptions{NewLine: core.NewLineKindLF}, + printer.PrintHandlers{}, + nil, + ).Emit(node, nil) + if actual != "/** A short description */" { + t.Errorf("unexpected single-line JSDoc output: %q", actual) + } +} + +func TestEmitJSDocTypeExpression(t *testing.T) { + t.Parallel() + + var factory ast.NodeFactory + node := factory.NewJSDocTypeExpression(factory.NewKeywordTypeNode(ast.KindNumberKeyword)) + actual := printer.NewPrinter( + printer.PrinterOptions{NewLine: core.NewLineKindLF}, + printer.PrintHandlers{}, + nil, + ).Emit(node, nil) + if actual != "{number}" { + t.Errorf("unexpected JSDoc type output: %q", actual) + } +} + +func TestEmitJSDocParameterType(t *testing.T) { + t.Parallel() + + var factory ast.NodeFactory + node := factory.NewJSDocParameterOrPropertyTag( + ast.KindJSDocParameterTag, + factory.NewIdentifier("param"), + factory.NewIdentifier("foo"), + false, /*isBracketed*/ + factory.NewKeywordTypeNode(ast.KindNumberKeyword), + false, /*isNameFirst*/ + nil, /*comment*/ + ) + actual := printer.NewPrinter( + printer.PrinterOptions{NewLine: core.NewLineKindLF}, + printer.PrintHandlers{}, + nil, + ).Emit(node, nil) + if actual != "@param {number} foo" { + t.Errorf("unexpected JSDoc parameter output: %q", actual) + } +} + +func TestEmitJSDocLink(t *testing.T) { + t.Parallel() + + var factory ast.NodeFactory + node := factory.NewJSDoc( + factory.NewNodeList([]*ast.Node{ + factory.NewJSDocText([]string{"See "}), + factory.NewJSDocLink(factory.NewIdentifier("Foo"), []string{"the docs"}), + }), + nil, /*tags*/ + ) + actual := printer.NewPrinter( + printer.PrinterOptions{NewLine: core.NewLineKindLF}, + printer.PrintHandlers{}, + nil, + ).Emit(node, nil) + expected := "/**\n * See {@link Foo the docs}\n */" + if actual != expected { + t.Errorf("unexpected JSDoc link output:\n got: %q\nwant: %q", actual, expected) + } +} + func TestParenthesizeDecorator(t *testing.T) { t.Parallel() From 4cc0ca7c01e5681bc1056934e88d989c331c7b05 Mon Sep 17 00:00:00 2001 From: el-j Date: Fri, 30 Oct 2026 17:03:56 +0100 Subject: [PATCH 2/3] fix(printer): address JSDoc printer review feedback Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- tsc/internal/ast/precedence.go | 2 + tsc/internal/printer/printer.go | 129 +++++++++++++++++---- tsc/internal/printer/printer_test.go | 161 +++++++++++++++++++++++++++ 3 files changed, 272 insertions(+), 20 deletions(-) diff --git a/tsc/internal/ast/precedence.go b/tsc/internal/ast/precedence.go index bfaaa679b63af..b99e9872005aa 100644 --- a/tsc/internal/ast/precedence.go +++ b/tsc/internal/ast/precedence.go @@ -658,6 +658,8 @@ func GetTypeNodePrecedence(n *TypeNode) TypePrecedence { return TypePrecedenceConditional case KindJSDocOptionalType, KindJSDocVariadicType: return TypePrecedenceJSDoc + case KindJSDocTypeExpression, KindJSDocNameReference, KindJSDocTypeLiteral, KindJSDocSignature: + return TypePrecedenceNonArray case KindFunctionType, KindConstructorType: return TypePrecedenceFunction case KindUnionType: diff --git a/tsc/internal/printer/printer.go b/tsc/internal/printer/printer.go index 781e9fa8cbe52..d7d76504c5c48 100644 --- a/tsc/internal/printer/printer.go +++ b/tsc/internal/printer/printer.go @@ -2383,12 +2383,11 @@ func (p *Printer) emitTypeNode(node *ast.TypeNode, precedence ast.TypePrecedence } p.writePunctuation("}") case ast.KindJSDocNameReference: - p.emitEntityName(node.AsJSDocNameReference().Name()) + p.emitJSDocNameReference(node.AsJSDocNameReference()) case ast.KindJSDocTypeLiteral: p.emitJSDocTypeLiteral(node.AsJSDocTypeLiteral()) case ast.KindJSDocSignature: - p.write("function") - p.emitSignature(node) + p.emitJSDocSignature(node.AsJSDocSignature()) case ast.KindJSDocNonNullableType: p.emitJSDocNonNullableType(node.AsJSDocNonNullableType()) case ast.KindJSDocNullableType: @@ -4626,12 +4625,11 @@ func (p *Printer) emitJSDocNode(node *ast.Node) { } p.writePunctuation("}") case ast.KindJSDocNameReference: - p.emitEntityName(node.AsJSDocNameReference().Name()) + p.emitJSDocNameReference(node.AsJSDocNameReference()) case ast.KindJSDocTypeLiteral: p.emitJSDocTypeLiteral(node.AsJSDocTypeLiteral()) case ast.KindJSDocSignature: - p.write("function") - p.emitSignature(node) + p.emitJSDocSignature(node.AsJSDocSignature()) case ast.KindJSDocText: p.write(node.Text()) case ast.KindJSDocLink, ast.KindJSDocLinkCode, ast.KindJSDocLinkPlain: @@ -4661,7 +4659,7 @@ func (p *Printer) emitJSDoc(node *ast.JSDoc) { if hasComment && !hasTags && len(node.Comment.Nodes) == 1 && text != "" && len(text) <= 80 && !strings.Contains(text, "\n") { p.writeSpace() - p.write(strings.TrimSpace(text)) + p.write(strings.TrimSuffix(text, "\r")) p.writeSpace() p.write("*/") return @@ -4692,13 +4690,21 @@ func (p *Printer) emitJSDocCommentLines(text string) { p.writeLine() } p.write(" *") - if line = strings.TrimSpace(line); line != "" { + line = strings.TrimSuffix(line, "\r") + if line != "" { p.writeSpace() p.write(line) } } } +func (p *Printer) emitJSDocNameReference(node *ast.JSDocNameReference) { + p.writeSpace() + p.writePunctuation("{") + p.emitEntityName(node.Name()) + p.writePunctuation("}") +} + func (p *Printer) writeJSDocCommentNode(text *strings.Builder, node *ast.Node) { switch node.Kind { case ast.KindJSDocText: @@ -4765,6 +4771,7 @@ func (p *Printer) emitJSDocType(node *ast.Node) { func (p *Printer) emitJSDocTag(node *ast.Node) { tagName, comment := jsDocTagBase(node) + var signature *ast.JSDocSignature p.write("@") if tagName != nil { p.write(tagName.Text()) @@ -4811,36 +4818,48 @@ func (p *Printer) emitJSDocTag(node *ast.Node) { p.writePunctuation(",") p.writeSpace() } - p.emitEntityName(typeParameter.AsTypeParameterDeclaration().Name()) + p.emitJSDocTemplateTypeParameter(typeParameter.AsTypeParameterDeclaration()) } } case ast.KindJSDocSeeTag: tag := node.AsJSDocSeeTag() if tag.NameExpression != nil { - p.writeSpace() - p.emitTypeNode(tag.NameExpression, ast.TypePrecedenceJSDoc) + if tag.NameExpression.Kind == ast.KindJSDocNameReference { + p.emitJSDocNameReference(tag.NameExpression.AsJSDocNameReference()) + } else { + p.writeSpace() + p.emitTypeNode(tag.NameExpression, ast.TypePrecedenceJSDoc) + } } case ast.KindJSDocImplementsTag: tag := node.AsJSDocImplementsTag() if tag.ClassName != nil { p.writeSpace() + p.writePunctuation("{") p.emitExpressionWithTypeArguments(tag.ClassName.AsExpressionWithTypeArguments()) + p.writePunctuation("}") } case ast.KindJSDocAugmentsTag: tag := node.AsJSDocAugmentsTag() if tag.ClassName != nil { p.writeSpace() + p.writePunctuation("{") p.emitExpressionWithTypeArguments(tag.ClassName.AsExpressionWithTypeArguments()) + p.writePunctuation("}") } case ast.KindJSDocCallbackTag: tag := node.AsJSDocCallbackTag() - p.emitJSDocType(tag.TypeExpression) if tag.Name() != nil { p.writeSpace() p.emitJSDocFullName(tag.Name()) } + if tag.TypeExpression != nil { + signature = tag.TypeExpression.AsJSDocSignature() + } case ast.KindJSDocOverloadTag: - p.emitJSDocType(node.AsJSDocOverloadTag().TypeExpression) + if typeExpression := node.AsJSDocOverloadTag().TypeExpression; typeExpression != nil { + signature = typeExpression.AsJSDocSignature() + } case ast.KindJSDocTypedefTag: tag := node.AsJSDocTypedefTag() p.emitJSDocType(tag.TypeExpression) @@ -4852,7 +4871,17 @@ func (p *Printer) emitJSDocTag(node *ast.Node) { tag := node.AsJSDocImportTag() if tag.ImportClause != nil { p.writeSpace() - p.emitImportClause(tag.ImportClause.AsImportClause()) + importClause := tag.ImportClause.AsImportClause() + if name := importClause.Name(); name != nil { + p.emitBindingIdentifier(name.AsIdentifier()) + if importClause.NamedBindings != nil { + p.writePunctuation(",") + p.writeSpace() + } + } + p.emitNamedImportBindings(importClause.NamedBindings) + p.writeSpace() + p.write("from") } if tag.ModuleSpecifier != nil { p.writeSpace() @@ -4869,17 +4898,20 @@ func (p *Printer) emitJSDocTag(node *ast.Node) { for _, commentNode := range comment.Nodes { p.writeJSDocCommentNode(&text, commentNode) } - lines := strings.Split(strings.TrimSpace(text.String()), "\n") + lines := strings.Split(text.String(), "\n") if len(lines) > 0 && lines[0] != "" { p.writeSpace() - p.write(strings.TrimSpace(lines[0])) + p.write(strings.TrimSuffix(lines[0], "\r")) for _, line := range lines[1:] { p.writeLine() p.write(" * ") - p.write(strings.TrimSpace(line)) + p.write(strings.TrimSuffix(line, "\r")) } } } + if signature != nil { + p.emitJSDocSignature(signature) + } } func (p *Printer) emitJSDocTypeLiteral(node *ast.JSDocTypeLiteral) { @@ -4893,12 +4925,21 @@ func (p *Printer) emitJSDocTypeLiteral(node *ast.JSDocTypeLiteral) { } tag := property.AsJSDocParameterOrPropertyTag() if tag.Name() != nil { - p.emitEntityName(tag.Name()) + p.emitJSDocPropertyName(tag.Name()) + if tag.IsBracketed { + p.writePunctuation("?") + } } if tag.TypeExpression != nil { p.writePunctuation(":") p.writeSpace() - p.emitTypeNode(tag.TypeExpression, ast.TypePrecedenceJSDoc) + typeNode := tag.TypeExpression + if typeNode.Kind == ast.KindJSDocTypeExpression { + typeNode = typeNode.AsJSDocTypeExpression().Type + } + if typeNode != nil { + p.emitTypeNode(typeNode, ast.TypePrecedenceJSDoc) + } } } p.writeSpace() @@ -4910,12 +4951,60 @@ func (p *Printer) emitJSDocTypeLiteral(node *ast.JSDocTypeLiteral) { } } +func (p *Printer) emitJSDocPropertyName(name *ast.EntityName) { + if ast.IsIdentifier(name) { + p.emitEntityName(name) + return + } + p.emitEntityName(name.AsQualifiedName().Right) +} + +func (p *Printer) emitJSDocTemplateTypeParameter(typeParameter *ast.TypeParameterDeclaration) { + if typeParameter.DefaultType != nil { + p.writePunctuation("[") + } + p.emitModifierList(typeParameter.AsNode(), typeParameter.Modifiers(), false /*allowDecorators*/) + p.emitBindingIdentifier(typeParameter.Name().AsIdentifier()) + if typeParameter.DefaultType != nil { + p.writePunctuation("=") + p.emitTypeNode(typeParameter.DefaultType, ast.TypePrecedenceJSDoc) + p.writePunctuation("]") + } +} + +func (p *Printer) emitJSDocSignature(signature *ast.JSDocSignature) { + if signature.TypeParameters != nil { + for _, typeParameter := range signature.TypeParameters.Nodes { + p.writeLine() + p.write(" * @template ") + p.emitJSDocTemplateTypeParameter(typeParameter.AsTypeParameterDeclaration()) + } + } + if signature.Parameters != nil { + for _, parameter := range signature.Parameters.Nodes { + p.writeLine() + p.write(" * ") + p.emitJSDocTag(parameter) + } + } + if signature.Type != nil { + p.writeLine() + p.write(" * ") + p.emitJSDocTag(signature.Type.AsNode()) + } +} + func (p *Printer) emitJSDocFullName(node *ast.JSDocFullName) { switch node.Kind { case ast.KindIdentifier: p.emitIdentifierName(node.AsIdentifier()) case ast.KindModuleDeclaration: - p.emitModuleDeclaration(node.AsModuleDeclaration()) + declaration := node.AsModuleDeclaration() + p.emitJSDocFullName(declaration.Name()) + if declaration.Body != nil && declaration.Body.Kind == ast.KindModuleDeclaration { + p.writePunctuation(".") + p.emitJSDocFullName(declaration.Body) + } default: panic(fmt.Sprintf("unhandled JSDoc full name: %v", node.Kind)) } diff --git a/tsc/internal/printer/printer_test.go b/tsc/internal/printer/printer_test.go index 9661afb2c8e35..dadf5d70fc105 100644 --- a/tsc/internal/printer/printer_test.go +++ b/tsc/internal/printer/printer_test.go @@ -706,6 +706,167 @@ func TestEmitJSDocLink(t *testing.T) { } } +func TestEmitJSDocReviewRegressions(t *testing.T) { + t.Parallel() + + data := []struct { + name string + input string + output string + }{ + { + name: "ObjectTypedefProperties", + input: `/** + * @typedef {Object} Options + * @property {number} count + */ +const options = {};`, + output: `/** + * @typedef {Object} Options + * @property {number} count + */ +const options = {};`, + }, + { + name: "CallbackSignature", + input: `/** + * @callback Handler + * @param {string} value The value + * @returns {number} The result + */ +const handler = () => 0;`, + output: `/** + * @callback Handler + * @param {string} value The value + * @returns {number} The result + */ +const handler = () => 0;`, + }, + { + name: "TemplateModifiersAndDefaults", + input: `/** + * @template const T + * @template [U=string] + */ +function f() {}`, + output: `/** + * @template const T + * @template [U=string] + */ +function f() { }`, + }, + { + name: "ImportAndQualifiedTypedef", + input: `/** + * @import { Foo } from "pkg" + * @typedef {Object} Namespace.Foo + * @see {Foo} + */ +const value = 0;`, + output: `/** + * @import { Foo } from "pkg" + * @typedef {Object} Namespace.Foo + * @see {Foo} + */ +const value = 0;`, + }, + } + + for _, rec := range data { + t.Run(rec.name, func(t *testing.T) { + t.Parallel() + file := parsetestutil.ParseTypeScript(rec.input, false) + emittestutil.CheckEmit(t, nil, file, rec.output) + }) + } +} + +func TestEmitJSDocTypedefRecord(t *testing.T) { + t.Parallel() + + var factory ast.NodeFactory + numberType := factory.NewJSDocTypeExpression(factory.NewKeywordTypeNode(ast.KindNumberKeyword)) + nestedProperty := factory.NewJSDocParameterOrPropertyTag( + ast.KindJSDocPropertyTag, + factory.NewIdentifier("property"), + factory.NewQualifiedName(factory.NewIdentifier("options"), factory.NewIdentifier("count")), + true, /*isBracketed*/ + numberType, + false, /*isNameFirst*/ + nil, /*comment*/ + ) + nestedType := factory.NewJSDocTypeLiteral([]*ast.Node{nestedProperty}, false) + optionsProperty := factory.NewJSDocParameterOrPropertyTag( + ast.KindJSDocPropertyTag, + factory.NewIdentifier("property"), + factory.NewIdentifier("options"), + false, /*isBracketed*/ + factory.NewJSDocTypeExpression(nestedType), + false, /*isNameFirst*/ + nil, /*comment*/ + ) + recordType := factory.NewJSDocTypeLiteral([]*ast.Node{optionsProperty}, false) + typedef := factory.NewJSDocTypedefTag( + factory.NewIdentifier("typedef"), + recordType, + factory.NewIdentifier("Options"), + nil, /*comment*/ + ) + doc := factory.NewJSDoc(nil, factory.NewNodeList([]*ast.Node{typedef})) + actual := printer.NewPrinter( + printer.PrinterOptions{NewLine: core.NewLineKindLF}, + printer.PrintHandlers{}, + nil, + ).Emit(doc, nil) + expected := "/**\n * @typedef {{ options: { count?: number } }} Options\n */" + if actual != expected { + t.Errorf("unexpected JSDoc typedef record:\n got: %q\nwant: %q", actual, expected) + } +} + +func TestEmitJSDocNameReference(t *testing.T) { + t.Parallel() + + var factory ast.NodeFactory + node := factory.NewJSDocNameReference(factory.NewIdentifier("Options")) + actual := printer.NewPrinter( + printer.PrinterOptions{NewLine: core.NewLineKindLF}, + printer.PrintHandlers{}, + nil, + ).Emit(node, nil) + if actual != " {Options}" { + t.Errorf("unexpected JSDoc name reference output: %q", actual) + } +} + +func TestEmitJSDocPreservesTextWhitespace(t *testing.T) { + t.Parallel() + + var factory ast.NodeFactory + node := factory.NewJSDoc( + factory.NewNodeList([]*ast.Node{ + factory.NewJSDocText([]string{" first line\n indented line\r"}), + }), + factory.NewNodeList([]*ast.Node{ + factory.NewJSDocUnknownTag( + factory.NewIdentifier("example"), + factory.NewNodeList([]*ast.Node{ + factory.NewJSDocText([]string{" tag text\n indented tag\r"}), + }), + ), + }), + ) + actual := printer.NewPrinter( + printer.PrinterOptions{NewLine: core.NewLineKindLF}, + printer.PrintHandlers{}, + nil, + ).Emit(node, nil) + expected := "/**\n * first line\n * indented line\n * @example tag text\n * indented tag\n */" + if actual != expected { + t.Errorf("unexpected JSDoc whitespace:\n got: %q\nwant: %q", actual, expected) + } +} + func TestParenthesizeDecorator(t *testing.T) { t.Parallel() From 7ae20f132819db0b7ae568117aa6e8ea0a270cbf Mon Sep 17 00:00:00 2001 From: el-j Date: Tue, 10 Nov 2026 17:16:47 +0100 Subject: [PATCH 3/3] fix(printer): address JSDoc emission review feedback - keep continuation lines when a tag comment starts with a newline - keep documented @property/@param children as separate tag lines - print the terminal identifier of qualified typedef/callback names - omit the stray space after {@link name} without text - test JSDoc emission by printing JSDoc nodes directly Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- tsc/internal/printer/printer.go | 65 +++++++++++++++++++--- tsc/internal/printer/printer_test.go | 83 ++++++++++++++++++++++------ 2 files changed, 121 insertions(+), 27 deletions(-) diff --git a/tsc/internal/printer/printer.go b/tsc/internal/printer/printer.go index d7d76504c5c48..fd31f92bb7ecb 100644 --- a/tsc/internal/printer/printer.go +++ b/tsc/internal/printer/printer.go @@ -4728,7 +4728,7 @@ func (p *Printer) writeJSDocCommentNode(text *strings.Builder, node *ast.Node) { text.WriteByte(' ') if name != nil { text.WriteString(jsDocEntityNameText(name)) - if linkText == "" || !strings.HasPrefix(linkText, "://") { + if linkText != "" && !strings.HasPrefix(linkText, "://") { text.WriteByte(' ') } } @@ -4759,7 +4759,12 @@ func (p *Printer) emitJSDocType(node *ast.Node) { } p.writeSpace() p.writePunctuation("{") - if node.Kind == ast.KindJSDocTypeExpression { + if literal := jsDocDocumentedTypeLiteral(node); literal != nil { + p.write("Object") + if literal.IsArrayType { + p.writePunctuation("[]") + } + } else if node.Kind == ast.KindJSDocTypeExpression { if typeNode := node.AsJSDocTypeExpression().Type; typeNode != nil { p.emitTypeNode(typeNode, ast.TypePrecedenceJSDoc) } @@ -4772,6 +4777,7 @@ func (p *Printer) emitJSDocType(node *ast.Node) { func (p *Printer) emitJSDocTag(node *ast.Node) { tagName, comment := jsDocTagBase(node) var signature *ast.JSDocSignature + var documentedProperties *ast.JSDocTypeLiteral p.write("@") if tagName != nil { p.write(tagName.Text()) @@ -4780,6 +4786,7 @@ func (p *Printer) emitJSDocTag(node *ast.Node) { switch node.Kind { case ast.KindJSDocParameterTag, ast.KindJSDocPropertyTag: tag := node.AsJSDocParameterOrPropertyTag() + documentedProperties = jsDocDocumentedTypeLiteral(tag.TypeExpression) if !tag.IsNameFirst { p.emitJSDocType(tag.TypeExpression) } @@ -4862,6 +4869,7 @@ func (p *Printer) emitJSDocTag(node *ast.Node) { } case ast.KindJSDocTypedefTag: tag := node.AsJSDocTypedefTag() + documentedProperties = jsDocDocumentedTypeLiteral(tag.TypeExpression) p.emitJSDocType(tag.TypeExpression) if tag.Name() != nil { p.writeSpace() @@ -4899,19 +4907,58 @@ func (p *Printer) emitJSDocTag(node *ast.Node) { p.writeJSDocCommentNode(&text, commentNode) } lines := strings.Split(text.String(), "\n") - if len(lines) > 0 && lines[0] != "" { + if lines[0] != "" { p.writeSpace() p.write(strings.TrimSuffix(lines[0], "\r")) - for _, line := range lines[1:] { - p.writeLine() - p.write(" * ") - p.write(strings.TrimSuffix(line, "\r")) - } + } + for _, line := range lines[1:] { + p.writeLine() + p.write(" * ") + p.write(strings.TrimSuffix(line, "\r")) } } if signature != nil { p.emitJSDocSignature(signature) } + if documentedProperties != nil { + for _, property := range documentedProperties.JSDocPropertyTags { + p.writeLine() + p.write(" * ") + p.emitJSDocTag(property) + } + } +} + +// jsDocDocumentedTypeLiteral returns the type literal of a tag's type expression if any of +// its properties (recursively) carry documentation, which an inline `{{ ... }}` type cannot hold. +func jsDocDocumentedTypeLiteral(typeExpression *ast.Node) *ast.JSDocTypeLiteral { + if typeExpression == nil { + return nil + } + if typeExpression.Kind == ast.KindJSDocTypeExpression { + typeExpression = typeExpression.AsJSDocTypeExpression().Type + } + if typeExpression == nil || typeExpression.Kind != ast.KindJSDocTypeLiteral { + return nil + } + literal := typeExpression.AsJSDocTypeLiteral() + if jsDocTypeLiteralHasDocumentation(literal) { + return literal + } + return nil +} + +func jsDocTypeLiteralHasDocumentation(literal *ast.JSDocTypeLiteral) bool { + for _, property := range literal.JSDocPropertyTags { + tag := property.AsJSDocParameterOrPropertyTag() + if tag.Comment != nil && len(tag.Comment.Nodes) > 0 { + return true + } + if jsDocDocumentedTypeLiteral(tag.TypeExpression) != nil { + return true + } + } + return false } func (p *Printer) emitJSDocTypeLiteral(node *ast.JSDocTypeLiteral) { @@ -5001,7 +5048,7 @@ func (p *Printer) emitJSDocFullName(node *ast.JSDocFullName) { case ast.KindModuleDeclaration: declaration := node.AsModuleDeclaration() p.emitJSDocFullName(declaration.Name()) - if declaration.Body != nil && declaration.Body.Kind == ast.KindModuleDeclaration { + if declaration.Body != nil { p.writePunctuation(".") p.emitJSDocFullName(declaration.Body) } diff --git a/tsc/internal/printer/printer_test.go b/tsc/internal/printer/printer_test.go index dadf5d70fc105..18bdb3da97fff 100644 --- a/tsc/internal/printer/printer_test.go +++ b/tsc/internal/printer/printer_test.go @@ -721,11 +721,26 @@ func TestEmitJSDocReviewRegressions(t *testing.T) { * @property {number} count */ const options = {};`, - output: `/** + output: "/**\n * @typedef {{ count: number }} Options\n */", + }, + { + name: "DocumentedTypedefProperties", + input: `/** * @typedef {Object} Options - * @property {number} count + * @property {number} count The item count + * @property {string} [label] Display {@link Label} */ const options = {};`, + output: "/**\n * @typedef {Object} Options\n * @property {number} count The item count\n * @property {string} [label] Display {@link Label}\n */", + }, + { + name: "DocumentedNestedParameterProperties", + input: `/** + * @param {Object} opts The options + * @param {number} opts.count The item count + */ +function f(opts) {}`, + output: "/**\n * @param opts {Object} The options\n * @param {number} opts.count The item count\n */", }, { name: "CallbackSignature", @@ -735,12 +750,16 @@ const options = {};`, * @returns {number} The result */ const handler = () => 0;`, - output: `/** - * @callback Handler - * @param {string} value The value - * @returns {number} The result + output: "/**\n * @callback Handler\n * @param {string} value The value\n * @returns {number} The result\n */", + }, + { + name: "QualifiedCallback", + input: `/** + * @callback Namespace.Handler + * @param {string} value */ const handler = () => 0;`, + output: "/**\n * @callback Namespace.Handler\n * @param {string} value\n */", }, { name: "TemplateModifiersAndDefaults", @@ -749,26 +768,17 @@ const handler = () => 0;`, * @template [U=string] */ function f() {}`, - output: `/** - * @template const T - * @template [U=string] - */ -function f() { }`, + output: "/**\n * @template const T\n * @template [U=string]\n */", }, { name: "ImportAndQualifiedTypedef", input: `/** - * @import { Foo } from "pkg" * @typedef {Object} Namespace.Foo * @see {Foo} - */ -const value = 0;`, - output: `/** * @import { Foo } from "pkg" - * @typedef {Object} Namespace.Foo - * @see {Foo} */ const value = 0;`, + output: "/**\n * @typedef {Object} Namespace.Foo\n * @see {Foo}\n * @import { Foo } from \"pkg\"\n */", }, } @@ -776,11 +786,48 @@ const value = 0;`, t.Run(rec.name, func(t *testing.T) { t.Parallel() file := parsetestutil.ParseTypeScript(rec.input, false) - emittestutil.CheckEmit(t, nil, file, rec.output) + docs := file.Statements.Nodes[0].JSDoc(file) + if len(docs) != 1 { + t.Fatalf("expected 1 JSDoc node, got %d", len(docs)) + } + actual := printer.NewPrinter( + printer.PrinterOptions{NewLine: core.NewLineKindLF}, + printer.PrintHandlers{}, + nil, + ).Emit(docs[0], file) + if actual != rec.output { + t.Errorf("unexpected JSDoc output:\n got: %q\nwant: %q", actual, rec.output) + } }) } } +func TestEmitJSDocTagCommentWithLeadingNewline(t *testing.T) { + t.Parallel() + + var factory ast.NodeFactory + node := factory.NewJSDoc( + nil, + factory.NewNodeList([]*ast.Node{ + factory.NewJSDocUnknownTag( + factory.NewIdentifier("example"), + factory.NewNodeList([]*ast.Node{ + factory.NewJSDocText([]string{"\nconsole.log('example');"}), + }), + ), + }), + ) + actual := printer.NewPrinter( + printer.PrinterOptions{NewLine: core.NewLineKindLF}, + printer.PrintHandlers{}, + nil, + ).Emit(node, nil) + expected := "/**\n * @example\n * console.log('example');\n */" + if actual != expected { + t.Errorf("unexpected JSDoc output:\n got: %q\nwant: %q", actual, expected) + } +} + func TestEmitJSDocTypedefRecord(t *testing.T) { t.Parallel()