英文:
Golang compile to binary from AST
问题
在Golang中,将AST编译为二进制文件是可能的吗?或者API没有暴露这个功能。目前库(例如Gisp)是通过使用go/printer包将AST打印出来来实现这一点。是否有一种方法可以跳过这个过程,直接将AST编译为二进制文件?
英文:
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?
答案1
得分: 2
目前还没有。尽管Go的编译器是用Go编写的,但它并没有在标准库中公开。
使用Gisp方法,即打印源代码并使用go build
,可能是你最好的选择。
英文:
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.
答案2
得分: 2
嗯,gisp真的很酷,但是有一个技巧可以使用原始的Go解析器来创建AST:
你可以创建一个本地符号链接到compiler/internal/syntax文件夹:
ln -s $GOROOT/src/cmd/compile/internal/syntax
现在你的代码可以读取一个文件,并像这样创建一个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) // <-- 这样可以漂亮地打印出你的AST
}
现在我不知道你如何编译它...但是嘿,至少你有你的AST了;-)
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论