Is it possible to compile an AST to a binary in Golang? Or does the API not expose that feature. The way libraries currently do this, such as Gisp, is to print out the AST using the go/printer package. Is there a way to skip this process and compile the AST directly to a binary?
Golang compile to binary from AST
Asked Answered
No, there is not currently a way to do that –
Pillar
this would be awesome to compile directly from AST... heh –
Leclerc
yes, or at least support generating source from AST. –
Cohleen
Not at the moment, no. Right now, although Go's compiler is written in Go, it's not exposed in the standard library.
The Gisp method, of printing the source and using go build
, is probably your best option.
well, gisp is really cool but theres a trick to use the original go parser to create that ast:
you can create a local symlink to the compiler/internal/syntax folder:
ln -s $GOROOT/src/cmd/compile/internal/syntax
now your code can read a file and create an ast out of it like this:
package main
import (
"fmt"
"github.com/me/gocomp/syntax"
"os"
)
func main() {
filename := "./main.go"
errh := syntax.ErrorHandler(
func(err error) {
fmt.Println(err)
})
ast, _ := syntax.ParseFile(
filename,
errh,
nil,
0)
f, _ := os.Create("./main.go.ast")
defer f.Close()
syntax.Fdump(f, ast) //<--this prints out your AST nicely
}
now i have no idea how you can compile it.. but hey, at least you got your AST ;-)
I was under the impression that the AST used by the compiler was quite different from the one in
go/ast
. If so, it may not preserve comments and formatting, and any examples/blogs/SO answers dealing with go/ast
will be of little help. –
Khaki © 2022 - 2024 — McMap. All rights reserved.