DEV Community

Jainta Paul
Jainta Paul

Posted on

Go Source Code From AST Parser

I am trying to regenerate source code from ast of a go program. After regenerating the source code, I am trying to match that with the original source code. But the regenerated source code gives some extra spaces in some places of the code. The code is given below.

fs := token.NewFileSet()
f, err := parser.ParseFile(fs, filename, nil, parser.ParseComments)
if err != nil {
log.Println(err)
}
cfg := printer.Config{Mode: printer.RawFormat}
err = cfg.Fprint(&buffer, fs, f)
if err != nil {
log.Println(err)
}
source_code, err := os.ReadFile(filename)
if err != nil {
log.Println(err)
}
buffer_source_code := buffer.String()

Can someone help me what should I do to get the exact source code as the original from a ast?

Top comments (1)

Collapse
 
imkarthiknr profile image
KARTHIK N R

Hi, do you got a solution for this