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?
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? Show activity on this post. Not at the moment, no. Right now, although Go's compiler is written in Go, it's not exposed in the standard library.
GoLang AST Package ast declares the types used to represent syntax trees for Go packages. It is imported (along with other important packages) as: 1
Go is well-known for having great tooling for analyzing code written in the language, right in the standard library with the go/* packages ( go/parser, go/ast, go/types etc.); in addition, the golang.org/x/tools module contains several supplemental packages that are even more powerful.
The code generation, which converts the Abstract Syntax Tree to machine code. Note: The packages we are going to be using (go/scanner, go/parser, go/token, go/ast, etc.) are not used by the Go compiler, but are mainly provided for use by tools to operate on Go source code. However, the actual Go compiler has very similar semantics.
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 ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With