Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Go source code

I am looking for a way to generate Go source code.

I found go/parser to generate an AST form a Go source file but couldn't find a way to generate Go source from AST.

like image 232
Günter Zöchbauer Avatar asked Feb 06 '13 08:02

Günter Zöchbauer


People also ask

How do I create a go code?

Running the code generatorEnsure that the main program from the codegen_builder.go file and the templates are in the same directory. Then run go run codegen_builder.go in your terminal. Now the program will generate code with the help of the templates and output it in the ./tmp directory.

What is go generate in Golang?

go generate is a tool that comes with the go command. You write go generate directives in your source code and then run the directives by calling go generate on the command line (or using your IDE).

What is the go tool?

Running Code During development the go run tool is a convenient way to try out your code. It's essentially a shortcut that compiles your code, creates an executable binary in your /tmp directory, and then runs this binary in one step.

What is package go?

Go programs are organized into packages. A package is a collection of source files in the same directory that are compiled together. Functions, types, variables, and constants defined in one source file are visible to all other source files within the same package. A repository contains one or more modules.


1 Answers

To convert an AST to the source form one can use the go/printer package.

Example (adapted form of another example)

package main

import (
        "go/parser"
        "go/printer"
        "go/token"
        "os"
)

func main() {
        // src is the input for which we want to print the AST.
        src := `
package main
func main() {
        println("Hello, World!")
}
`

        // Create the AST by parsing src.
        fset := token.NewFileSet() // positions are relative to fset
        f, err := parser.ParseFile(fset, "", src, 0)
        if err != nil {
                panic(err)
        }

        printer.Fprint(os.Stdout, fset, f)

}

(also here)


Output:

package main

func main() {
        println("Hello, World!")
}
like image 90
zzzz Avatar answered Oct 06 '22 11:10

zzzz