/
ast_utils.go
42 lines (34 loc) · 986 Bytes
/
ast_utils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package main
import (
"bytes"
"go/ast"
"go/parser"
"go/printer"
"go/token"
"os"
"github.com/petergtz/goextract/util"
)
func astFromFile(filename string) (*token.FileSet, *ast.File) {
fileSet := token.NewFileSet()
astFile, err := parser.ParseFile(fileSet, filename, nil, parser.ParseComments)
util.PanicOnError(err)
return fileSet, astFile
}
func astFromInput(input string) (*token.FileSet, *ast.File) {
fileSet := token.NewFileSet()
astFile, err := parser.ParseFile(fileSet, "", input, parser.ParseComments)
util.PanicOnError(err)
return fileSet, astFile
}
func createAstFileDump(filename string, fileSet *token.FileSet, astFile *ast.File) {
file, err := os.Create(filename)
util.PanicOnError(err)
defer file.Close()
ast.Fprint(file, fileSet, astFile, ast.NotNilFilter)
}
func stringFrom(fileSet *token.FileSet, astFile *ast.File) string {
buf := new(bytes.Buffer)
err := printer.Fprint(buf, fileSet, astFile)
util.PanicOnError(err)
return buf.String()
}