x/tools/cmd/bundle: include comments inside functions

Fixes golang/go#20548

Change-Id: Ieff2323b63308cbc052a2883237520620965cf86
Reviewed-on: https://go-review.googlesource.com/45117
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
Run-TryBot: Brad Fitzpatrick <bradfitz@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
diff --git a/cmd/bundle/.gitignore b/cmd/bundle/.gitignore
new file mode 100644
index 0000000..caaeb09
--- /dev/null
+++ b/cmd/bundle/.gitignore
@@ -0,0 +1 @@
+testdata/out.got
diff --git a/cmd/bundle/main.go b/cmd/bundle/main.go
index e4b261f..02bd835 100644
--- a/cmd/bundle/main.go
+++ b/cmd/bundle/main.go
@@ -88,6 +88,7 @@
 	"go/build"
 	"go/format"
 	"go/parser"
+	"go/printer"
 	"go/token"
 	"go/types"
 	"io/ioutil"
@@ -348,18 +349,13 @@
 
 		// Pretty-print package-level declarations.
 		// but no package or import declarations.
-		//
-		// TODO(adonovan): this may cause loss of comments
-		// preceding or associated with the package or import
-		// declarations or not associated with any declaration.
-		// Check.
 		var buf bytes.Buffer
 		for _, decl := range f.Decls {
 			if decl, ok := decl.(*ast.GenDecl); ok && decl.Tok == token.IMPORT {
 				continue
 			}
 			buf.Reset()
-			format.Node(&buf, lprog.Fset, decl)
+			format.Node(&buf, lprog.Fset, &printer.CommentedNode{Node: decl, Comments: f.Comments})
 			// Remove each "@@@." in the output.
 			// TODO(adonovan): not hygienic.
 			out.Write(bytes.Replace(buf.Bytes(), []byte("@@@."), nil, -1))
diff --git a/cmd/bundle/testdata/out.golden b/cmd/bundle/testdata/out.golden
index 9374b2e..b76c5ae 100644
--- a/cmd/bundle/testdata/out.golden
+++ b/cmd/bundle/testdata/out.golden
@@ -26,7 +26,9 @@
 }
 
 // Function bar.
-func prefixbar(s *prefixS) { fmt.Println(s.prefixt, s.u) }
+func prefixbar(s *prefixS) {
+	fmt.Println(s.prefixt, s.u) // comment inside function
+}
 
 type prefixt int
 
diff --git a/cmd/bundle/testdata/src/initial/a.go b/cmd/bundle/testdata/src/initial/a.go
index 99cd145..5d0d190 100644
--- a/cmd/bundle/testdata/src/initial/a.go
+++ b/cmd/bundle/testdata/src/initial/a.go
@@ -12,4 +12,6 @@
 }
 
 // Function bar.
-func bar(s *S) { fmt.Println(s.t, s.u) }
+func bar(s *S) {
+	fmt.Println(s.t, s.u) // comment inside function
+}