From a1b463eedbc7648dac27da896518d826341cc573 Mon Sep 17 00:00:00 2001 From: Mateusz Poliwczak Date: Tue, 24 Dec 2024 15:17:18 +0100 Subject: [PATCH] go/printer: do not set impliedSemi to false in print, when writing newlines Fixes #70978 Change-Id: I0cc54bd11bb4170235bb5a6d5eb6d8438beada58 --- src/go/printer/printer.go | 1 - src/go/printer/printer_test.go | 75 ++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 1 deletion(-) diff --git a/src/go/printer/printer.go b/src/go/printer/printer.go index 5a6127c6b40dd7..f8b4fe1816311a 100644 --- a/src/go/printer/printer.go +++ b/src/go/printer/printer.go @@ -1015,7 +1015,6 @@ func (p *printer) print(args ...any) { ch = '\f' // use formfeed since we dropped one before } p.writeByte(ch, n) - impliedSemi = false } } diff --git a/src/go/printer/printer_test.go b/src/go/printer/printer_test.go index 2a9c8be3003249..bde0089a245d43 100644 --- a/src/go/printer/printer_test.go +++ b/src/go/printer/printer_test.go @@ -16,6 +16,7 @@ import ( "io" "os" "path/filepath" + "strings" "testing" "time" ) @@ -863,3 +864,77 @@ func TestEmptyDecl(t *testing.T) { // issue 63566 } } } + +func TestIssue70978(t *testing.T) { + cases := []struct { + src string + want string + newName string + }{ + { + newName: "someotherfmtpackage", + src: `package main + +func main() { + // comment + + fmt.Println() // Comment +} +`, + want: `package main + +func main() { + // comment + + someotherfmtpackage.Println() // Comment +} +`, + }, + { + newName: "someotherfmtpkg", + src: `package main + +func main() { + // comment + + fmt.Println() // Comment +} +`, + want: `package main + +func main() { + // comment + + someotherfmtpkg.Println() // Comment +} +`, + }, + } + + for _, tt := range cases { + fset := token.NewFileSet() + f, err := parser.ParseFile(fset, "test.go", tt.src, parser.SkipObjectResolution|parser.ParseComments) + if err != nil { + t.Fatal(err) + } + + ast.Inspect(f, func(n ast.Node) bool { + switch n := n.(type) { + case *ast.SelectorExpr: + switch x := n.X.(type) { + case *ast.Ident: + x.Name = tt.newName + } + } + return true + }) + + var b strings.Builder + config := Config{Mode: UseSpaces | TabIndent, Tabwidth: 8} + config.Fprint(&b, fset, f) + got := b.String() + if got != tt.want { + t.Errorf("unexpected Fprint output:\n%s\nwant:\n%s", got, tt.want) + } + } +}