-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathclangutils.go
More file actions
180 lines (155 loc) · 4.34 KB
/
clangutils.go
File metadata and controls
180 lines (155 loc) · 4.34 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
package clangutils
import (
"errors"
"os"
"os/exec"
"path/filepath"
"strings"
"unsafe"
"github.com/goplus/lib/c"
"github.com/goplus/lib/c/clang"
)
type Config struct {
File string
Temp bool
Args []string
IsCpp bool
Index *clang.Index
}
type Visitor func(cursor, parent clang.Cursor) clang.ChildVisitResult
type InclusionVisitor func(included_file clang.File, inclusions []clang.SourceLocation)
const TEMP_FILE = "temp.h"
func CreateTranslationUnit(config *Config) (*clang.Index, *clang.TranslationUnit, error) {
// default use the c/c++ standard of clang; c:gnu17 c++:gnu++17
// https://clang.llvm.org/docs/CommandGuide/clang.html
allArgs := append(defaultArgs(config.IsCpp), config.Args...)
cArgs := make([]*c.Char, len(allArgs))
for i, arg := range allArgs {
cArgs[i] = c.AllocaCStr(arg)
}
var index *clang.Index
if config.Index != nil {
index = config.Index
} else {
index = clang.CreateIndex(0, 0)
}
var unit *clang.TranslationUnit
if config.Temp {
content := c.AllocaCStr(config.File)
tempFile := &clang.UnsavedFile{
Filename: c.Str(TEMP_FILE),
Contents: content,
Length: c.Ulong(c.Strlen(content)),
}
unit = index.ParseTranslationUnit(
tempFile.Filename,
unsafe.SliceData(cArgs), c.Int(len(cArgs)),
tempFile, 1,
clang.DetailedPreprocessingRecord,
)
} else {
cFile := c.AllocaCStr(config.File)
unit = index.ParseTranslationUnit(
cFile,
unsafe.SliceData(cArgs), c.Int(len(cArgs)),
nil, 0,
clang.DetailedPreprocessingRecord,
)
}
if unit == nil {
return nil, nil, errors.New("failed to parse translation unit")
}
return index, unit, nil
}
func GetLocation(loc clang.SourceLocation) (file clang.File, line c.Uint, column c.Uint, offset c.Uint) {
loc.SpellingLocation(&file, &line, &column, &offset)
return
}
// Traverse up the semantic parents
func BuildScopingParts(cursor clang.Cursor) []string {
var parts []string
for cursor.IsNull() != 1 && cursor.Kind != clang.CursorTranslationUnit {
name := cursor.String()
qualified := c.GoString(name.CStr())
parts = append([]string{qualified}, parts...)
cursor = cursor.SemanticParent()
name.Dispose()
}
return parts
}
func VisitChildren(cursor clang.Cursor, fn Visitor) c.Uint {
return clang.VisitChildren(cursor, func(cursor, parent clang.Cursor, clientData unsafe.Pointer) clang.ChildVisitResult {
cfn := *(*Visitor)(clientData)
return cfn(cursor, parent)
}, unsafe.Pointer(&fn))
}
func GetInclusions(unit *clang.TranslationUnit, visitor InclusionVisitor) {
clang.GetInclusions(unit, func(inced clang.File, incin *clang.SourceLocation, incilen c.Uint, data c.Pointer) {
ics := unsafe.Slice(incin, incilen)
cfn := *(*InclusionVisitor)(data)
cfn(inced, ics)
}, unsafe.Pointer(&visitor))
}
// ComposeIncludes create Include list
// #include <file1.h>
// #include <file2.h>
func ComposeIncludes(files []string, outfile string) error {
var str string
for _, file := range files {
str += ("#include <" + file + ">\n")
}
return os.WriteFile(outfile, []byte(str), 0644)
}
func defaultArgs(isCpp bool) []string {
args := []string{"-x", "c"}
if isCpp {
args = []string{"-x", "c++"}
}
return args
}
type PreprocessConfig struct {
File string
IsCpp bool
Args []string
OutFile string
}
func Preprocess(cfg *PreprocessConfig) error {
args := []string{"-E"}
args = append(args, defaultArgs(cfg.IsCpp)...)
args = append(args, cfg.Args...)
args = append(args, cfg.File)
args = append(args, "-o", cfg.OutFile)
cmd := exec.Command("clang", args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
func GetIncludePaths(isCpp bool) []string {
args := []string{"-E", "-v"}
args = append(args, defaultArgs(isCpp)...)
args = append(args, "/dev/null")
cmd := exec.Command("clang", args...)
output, err := cmd.CombinedOutput()
if err != nil {
panic(err)
}
return ParseClangIncOutput(string(output))
}
func ParseClangIncOutput(output string) []string {
var paths []string
start := strings.Index(output, "#include <...> search starts here:")
end := strings.Index(output, "End of search list.")
if start == -1 || end == -1 {
return paths
}
content := output[start:end]
lines := strings.Split(content, "\n")
for _, line := range lines[1:] {
for _, item := range strings.Fields(line) {
if path := strings.TrimSpace(item); filepath.IsAbs(path) {
paths = append(paths, path)
}
}
}
return paths
}