From: Mateusz Poliwczak Date: Mon, 15 Sep 2025 17:37:04 +0000 (+0200) Subject: go/parser: Add TestBothLineAndLeadComment X-Git-Tag: go1.26rc1~843 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=bffe7ad9f1;p=gostls13.git 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 --- diff --git a/src/go/parser/parser_test.go b/src/go/parser/parser_test.go index 2516cedc88..87b7d7bbab 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) + } +}