go/ast: doc insufficient for inserting comments
I don't see a way to insert documentation comments for file declarations such that they appear just above their decls after printing with go/printer.Fprint or go/format.Node (or both, as explained below). Is it impossible? If so, it should be noted in the doc; if not, it should be noted how to do it, since a straightforward mutation of the comment fields and/or creation/mutation/saving of a CommentMap for File.Comments doesn't work. Also note the related problems pointed out in the code below.
My scenario is writing a tool that inserts // TODO doc comments for undocumented exported decls.
var fs = token.NewFileSet() var path = ... // path to .go file with exported decls with no doc var af, _ = parser.ParseFile(fs, path, nil, parser.DeclarationErrors|parser.ParseComments) var cm = ast.NewCommentMap(fs, af, af.Comments) if cm == nil { cm = ast.CommentMap{} // problem: doc doesn't say cm can be nil! bug? } for _, d := range af.Decls { switch d := d.(type) { case *ast.FuncDecl: d.Doc = ... // insert doc case *ast.GenDecl: for _, s := range d.Specs { switch s := s.(type) { case *ast.TypeSpec: s.Doc = ... // insert doc case *ast.ValueSpec: s.Doc = ... // insert doc } } } } af.Comments = cm.Comments() var b bytes.Buffer format.Node(&b, fs, af) // problem: doesn't format new func doc comments! bug? // func doc comments appear above their funcs correctly but replace blank line that was there before bs, _ := format.Source(b.Bytes()) // format again for func doc comments // var/const decl doc comments are put at the top of the file in one bunch