// Parse a Go program's source code and generate its AST src := `package main import "fmt" func main() { fmt.Println("Hello World!") }` fileSet := token.NewFileSet() parsedFile, err := parser.ParseFile(fileSet, "", src, 0) if err != nil { log.Fatal(err) } // Get the first statement in the AST firstStmt := parsedFile.Decls[0].(*ast.FuncDecl).Body.List[0] fmt.Println(firstStmt)
// Generate a new Go file containing a new function with a switch statement import ( "go/ast" "go/parser" "go/token" ) func generateNewFunction() *ast.FuncDecl { // Create a new switch statement cases := []*ast.CaseClause{ &ast.CaseClause{ List: []ast.Expr{&ast.BasicLit{Kind: token.STRING, Value: "\"foo\""}}, Body: []ast.Stmt{&ast.ExprStmt{X: &ast.BasicLit{Kind: token.STRING, Value: "\"bar\""}}}, }, &ast.CaseClause{ List: []ast.Expr{&ast.BasicLit{Kind: token.STRING, Value: "\"baz\""}}, Body: []ast.Stmt{&ast.ExprStmt{X: &ast.BasicLit{Kind: token.STRING, Value: "\"qux\""}}}, }, } switchStmt := &ast.SwitchStmt{ Tag: &ast.Ident{Name: "s"}, Body: &ast.BlockStmt{List: []ast.Stmt{&ast.CaseClause{List: nil, Body: []ast.Stmt{&ast.ExprStmt{X: &ast.Ident{Name: "defaultCase"}}}}}}, } switchStmt.Body.List = append(switchStmt.Body.List, cases...) // Create a new function with the switch statement return &ast.FuncDecl{ Name: &ast.Ident{Name: "newFunction"}, Type: &ast.FuncType{Params: &ast.FieldList{}, Results: &ast.FieldList{}}, Body: &ast.BlockStmt{List: []ast.Stmt{switchStmt}}, } } func main() { // Parse an existing Go file and generate its AST src := `package main import "fmt" func main() { s := "baz" fmt.Println(newFunction()) }` fileSet := token.NewFileSet() parsedFile, err := parser.ParseFile(fileSet, "", src, 0) if err != nil { log.Fatal(err) } // Add the new function to the AST and print the updated program newFunc := generateNewFunction() parsedFile.Decls = append(parsedFile.Decls, newFunc) printer.Fprint(os.Stdout, fileSet, parsedFile) }In this example, we generate a new Go function containing a switch statement using the `ast.SwitchStmt` and `ast.CaseClause` structs from the go.ast package. We then parse an existing Go program's source code and generate its AST, add the new function to the AST, and print the updated program to the console. Package library: go.ast, go/parser, go/token.