/
parse.go
88 lines (74 loc) · 1.96 KB
/
parse.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package parser
import (
"bytes"
"os"
"os/exec"
"strings"
"github.com/goplus/c2go/clang/ast"
jsoniter "github.com/json-iterator/go"
)
type Mode uint
// -----------------------------------------------------------------------------
type ParseError struct {
Err error
Stderr []byte
}
func (p *ParseError) Error() string {
if len(p.Stderr) > 0 {
return string(p.Stderr)
}
return p.Err.Error()
}
// -----------------------------------------------------------------------------
type Config struct {
Json *[]byte
Flags []string
Stderr bool
}
func DumpAST(filename string, conf *Config) (result []byte, warning []byte, err error) {
if conf == nil {
conf = new(Config)
}
skiperr := strings.HasSuffix(filename, "vfprintf.c.i")
stdout := NewPagedWriter()
stderr := new(bytes.Buffer)
args := []string{"-Xclang", "-ast-dump=json", "-fsyntax-only", filename}
if len(conf.Flags) != 0 {
args = append(conf.Flags, args...)
}
cmd := exec.Command("clang", args...)
cmd.Stdin = os.Stdin
cmd.Stdout = stdout
if conf.Stderr && !skiperr {
cmd.Stderr = os.Stderr
} else {
cmd.Stderr = stderr
}
err = cmd.Run()
errmsg := stderr.Bytes()
if err != nil && !skiperr {
return nil, nil, &ParseError{Err: err, Stderr: errmsg}
}
return stdout.Bytes(), errmsg, nil
}
// -----------------------------------------------------------------------------
var json = jsoniter.ConfigCompatibleWithStandardLibrary
func ParseFileEx(filename string, mode Mode, conf *Config) (file *ast.Node, warning []byte, err error) {
out, warning, err := DumpAST(filename, conf)
if err != nil {
return
}
if conf != nil && conf.Json != nil {
*conf.Json = out
}
file = new(ast.Node)
err = json.Unmarshal(out, file)
if err != nil {
err = &ParseError{Err: err}
}
return
}
func ParseFile(filename string, mode Mode) (file *ast.Node, warning []byte, err error) {
return ParseFileEx(filename, mode, nil)
}
// -----------------------------------------------------------------------------