从AST编译为二进制的Golang代码

huangapple go评论63阅读模式
英文:

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 (
	&quot;fmt&quot;
	&quot;github.com/me/gocomp/syntax&quot;
	&quot;os&quot;
)

func main() {
	filename := &quot;./main.go&quot;
	errh := syntax.ErrorHandler(
		func(err error) {
			fmt.Println(err)
		})
	ast, _ := syntax.ParseFile(
		filename,
		errh,
		nil,
		0)
	f, _ := os.Create(&quot;./main.go.ast&quot;)
	defer f.Close()
	syntax.Fdump(f, ast) //&lt;--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编译为二进制的Golang代码

huangapple
  • 本文由 发表于 2015年10月1日 09:15:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/32877999.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定