From bffe7ad9f11b874429d6c2561b0383e931502164 Mon Sep 17 00:00:00 2001 From: Mateusz Poliwczak Date: Mon, 15 Sep 2025 19:37:04 +0200 Subject: [PATCH] go/parser: Add TestBothLineAndLeadComment I was wondering whether is is expected that both p.lineComment and p.leadComment might be populated at the same time. i.e. whether parser.go:275 can be changed from: if p.lineFor(p.pos) != endline || p.tok == token.SEMICOLON || p.tok == token.EOF to: if (p.tok != token.COMMENT && p.lineFor(p.pos) != endline) || p.tok == token.SEMICOLON || p.tok == token.EOF It turns out that we cannot do so. So while i am here, add a test case for that, since nothing else failed with that change. Change-Id: I6a6a6964f760237c068098db8a7b4b7aaf26c651 Reviewed-on: https://go-review.googlesource.com/c/go/+/703915 Reviewed-by: Michael Knyszek LUCI-TryBot-Result: Go LUCI Reviewed-by: Alan Donovan --- src/go/parser/parser_test.go | 50 ++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/src/go/parser/parser_test.go b/src/go/parser/parser_test.go index 2516cedc88d..87b7d7bbab7 100644 --- a/src/go/parser/parser_test.go +++ b/src/go/parser/parser_test.go @@ -896,3 +896,53 @@ func test() { t.Fatalf("unexpected f.Comments got:\n%v\nwant:\n%v", got.String(), want.String()) } } + +// TestBothLineAndLeadComment makes sure that we populate the +// p.lineComment field even though there is a comment after the +// line comment. +func TestBothLineAndLeadComment(t *testing.T) { + const src = `package test + +var _ int; /* line comment */ +// Doc comment +func _() {} + +var _ int; /* line comment */ +// Some comment + +func _() {} +` + + fset := token.NewFileSet() + f, _ := ParseFile(fset, "", src, ParseComments|SkipObjectResolution) + + lineComment := f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.ValueSpec).Comment + docComment := f.Decls[1].(*ast.FuncDecl).Doc + + if lineComment == nil { + t.Fatal("missing line comment") + } + if docComment == nil { + t.Fatal("missing doc comment") + } + + if lineComment.List[0].Text != "/* line comment */" { + t.Errorf(`unexpected line comment got = %q; want "/* line comment */"`, lineComment.List[0].Text) + } + if docComment.List[0].Text != "// Doc comment" { + t.Errorf(`unexpected line comment got = %q; want "// Doc comment"`, docComment.List[0].Text) + } + + lineComment2 := f.Decls[2].(*ast.GenDecl).Specs[0].(*ast.ValueSpec).Comment + if lineComment2 == nil { + t.Fatal("missing line comment") + } + if lineComment.List[0].Text != "/* line comment */" { + t.Errorf(`unexpected line comment got = %q; want "/* line comment */"`, lineComment.List[0].Text) + } + + docComment2 := f.Decls[3].(*ast.FuncDecl).Doc + if docComment2 != nil { + t.Errorf("unexpected doc comment %v", docComment2) + } +}