Golang compile to binary from AST
Asked Answered
G

2

11

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?

Gantlet answered 1/10, 2015 at 1:15 Comment(3)
No, there is not currently a way to do thatPillar
this would be awesome to compile directly from AST... hehLeclerc
yes, or at least support generating source from AST.Cohleen
B
2

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.

Bookstore answered 13/11, 2018 at 0:18 Comment(0)
B
2

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

Badr answered 11/9, 2019 at 15:20 Comment(1)
I was under the impression that the AST used by the compiler was quite different from the one in go/ast. If so, it may not preserve comments and formatting, and any examples/blogs/SO answers dealing with go/ast will be of little help.Khaki

© 2022 - 2024 — McMap. All rights reserved.