[英]Golang compile to binary from AST
Is it possible to compile an AST to a binary in Golang? 是否可以在Golang中将AST编译为二进制文件? Or does the API not expose that feature.
或者API是否不公开该功能。 The way libraries currently do this, such as Gisp , is to print out the AST using the go/printer package.
库目前这样做的方式,如Gisp ,是使用go / printer软件包打印出AST。 Is there a way to skip this process and compile the AST directly to a binary?
有没有办法跳过这个过程并直接将AST编译成二进制文件?
well, gisp is really cool but theres a trick to use the original go parser to create that ast: 好吧,gisp非常酷,但使用原始的解析器来创建它是一个技巧:
you can create a local symlink to the compiler/internal/syntax folder: 您可以为compiler / internal / syntax文件夹创建一个本地符号链接:
ln -s $GOROOT/src/cmd/compile/internal/syntax
now your code can read a file and create an ast out of it like this: 现在你的代码可以读取一个文件,并像这样创建一个ast:
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 ;-) 现在我不知道你怎么能编译它..但是,嘿,至少你有你的AST ;-)
Not at the moment, no. 不是现在,不。 Right now, although Go's compiler is written in Go, it's not exposed in the standard library .
现在,尽管Go的编译器是用Go编写的,但它并没有在标准库中公开 。
The Gisp method, of printing the source and using go build
, is probably your best option. 打印源和使用
go build
的Gisp方法可能是您的最佳选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.