/
go-clang-query.go
201 lines (158 loc) · 3.83 KB
/
go-clang-query.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
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
package main
import (
"bufio"
"encoding/json"
"errors"
"flag"
"gopkg.in/fatih/set.v0"
"io/ioutil"
"log"
"math"
"net"
"os/exec"
"runtime"
"strings"
)
func clangQuery(source string, query string, args []string) ([]Match, error) {
allArgs := append([]string{source}, args...)
proc := exec.Command("clang-query", allArgs...)
pin, _ := proc.StdinPipe()
pout, _ := proc.StdoutPipe()
perr, _ := proc.StderrPipe()
if err := proc.Start(); err != nil {
return nil, err
}
if _, err := pin.Write([]byte(query + "\n")); err != nil {
return nil, err
}
pin.Close()
out, _ := ioutil.ReadAll(pout)
if err := proc.Wait(); err != nil {
return nil, err
}
matches := ParseMatches(string(out))
errorMessage, _ := ioutil.ReadAll(perr)
if string(errorMessage) != "" {
log.Fatal(string(errorMessage))
return matches, errors.New(string(errorMessage))
}
return matches, nil
}
// Match a clang-query match
type Match struct {
info string
}
func (m Match) String() string {
return m.info
}
// ParseMatches parse matches from a clang-query output stream
func ParseMatches(matches string) []Match {
var results []Match
lines := strings.Split(matches, "\n")
if len(lines) < 6 {
return []Match{}
}
var match []string
activeMatch := false
for _, line := range lines {
if len(line) > 5 && line[0:5] == "Match" {
activeMatch = true
if len(match) != 0 { // the match on the stack is done
results = append(results, Match{strings.Join(match, "\n")})
match = []string{}
}
} else if activeMatch && line != "" {
match = append(match, line)
}
}
if len(match) != 0 {
// Store the currently processing match.
// The last line contains the number of matches which we do not care about.
results = append(results, Match{strings.Join(match[:int(math.Max(0., float64(len(match))))], "\n")})
}
return results
}
type flags struct {
Listen string
Files []string
ClangArgs []string
}
func getflags() flags {
listen := flag.String("listen", ":3333", "Where to listening for queries")
flag.Parse()
args := flag.Args()
files := []string{}
clangArgs := []string{}
for k, v := range args {
if v == "---" {
files = args[:k]
clangArgs = args[k+1:]
break
}
files = args
}
flags := &flags{
Listen: *listen,
Files: files,
ClangArgs: clangArgs}
return *flags
}
type clangError struct {
File string `json:"file"`
Error string `json:"error"`
}
type response struct {
Matches []string `json:"matches"`
}
func main() {
flags := getflags()
log.Println("Working on files:")
for _, file := range flags.Files {
log.Println(" " + file)
}
ln, _ := net.Listen("tcp", flags.Listen)
conn, _ := ln.Accept()
for {
query, _ := bufio.NewReader(conn).ReadString('\n')
log.Printf("Message Received: %s\n", query)
// result sets
results := set.New()
errors := set.New()
// limited concurrency, http://jmoiron.net/blog/limiting-concurrency-in-go/
concurrency := runtime.NumCPU()
sem := make(chan bool, concurrency)
// spawn workers
for _, file := range flags.Files {
sem <- true
go func(this_file string) {
defer func() { <-sem }()
matches, err := clangQuery(this_file, query, flags.ClangArgs)
if err != nil {
log.Fatal(err)
}
for _, match := range matches {
results.Add(match.String())
}
if err != nil {
errors.Add(clangError{this_file, err.Error()})
log.Println(err)
}
}(file)
}
// join workers
for i := 0; i < cap(sem); i++ {
sem <- true
}
response := &response{
Matches: []string{}}
// accumulate results
response.Matches = append(response.Matches, set.StringSlice(results)...)
jsonResponse, _ := json.Marshal(response)
if _, err := conn.Write([]byte(string(jsonResponse) + "\n")); err != nil {
panic(err)
}
log.Printf("Found %d matches", results.Size())
conn.Close()
conn, _ = ln.Accept()
}
}