Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang compile to binary from 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?

like image 740
eatonphil Avatar asked Oct 01 '15 01:10

eatonphil


People also ask

Is there a way to compile the AST directly to binary?

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? Show activity on this post. Not at the moment, no. Right now, although Go's compiler is written in Go, it's not exposed in the standard library.

What is AST in Go language?

GoLang AST Package ast declares the types used to represent syntax trees for Go packages. It is imported (along with other important packages) as: 1

What is the best tool to analyze Golang code?

Go is well-known for having great tooling for analyzing code written in the language, right in the standard library with the go/* packages ( go/parser, go/ast, go/types etc.); in addition, the golang.org/x/tools module contains several supplemental packages that are even more powerful.

What is the Go compiler?

The code generation, which converts the Abstract Syntax Tree to machine code. Note: The packages we are going to be using (go/scanner, go/parser, go/token, go/ast, etc.) are not used by the Go compiler, but are mainly provided for use by tools to operate on Go source code. However, the actual Go compiler has very similar semantics.


2 Answers

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.

like image 96
wgoodall01 Avatar answered Oct 16 '22 15:10

wgoodall01


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

like image 43
danfromisrael Avatar answered Oct 16 '22 16:10

danfromisrael