Comments not in there position when converting ast to go program

All the comments of the original go program come to the last when I convert the AST to go program:

This is the test file: test.go

package main
import "fmt"

func main() {
    // comment here
    if true{
	  fmt.Println("needs to be treated")
    } else {
      fmt.Println("you done it")
   }
}

This is output I got: output.go

package main
import "fmt"

func main() {
        if true {
                fmt.Println("needs to be treated")
        } else {
                fmt.Println("you done it")
        }
}
// comment here

This is my code: main.go

package main
import (
	"bytes"
	"fmt"
	"go/format"
	"go/parser"
	"go/token"
	"log"
)

func main() {
	fs := token.NewFileSet()
	f, err := parser.ParseFile(fs, "test.go", nil, parser.ParseComments)
	if err != nil {
		log.Fatal(err)
	}

	fset := token.NewFileSet()

	var buf bytes.Buffer
	err = format.Node(&buf, fset, f)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(buf.String())
}

To run this code just do: go run ./main.go > output.go in terminal.

After doing this why comments are going down. Is there some other format function in go that will not do this?
If I see test.go as, I see that format function is reading the comment section which is art last in the ast file. Due to which comment is getting down.
So can somebody suggest if there is any other format function in go which can give comment in right place?

go/ast doesn’t handle comments properly. See the issue here. There’s a package to address the issue here.

2 Likes