Golang从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?

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 ;-)