This repository has been archived by the owner on Jun 9, 2021. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
main.go
332 lines (292 loc) · 7.12 KB
/
main.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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
// Copyright (c) 2017, Daniel Martí <mvdan@mvdan.cc>
// See LICENSE for licensing information
package main
import (
"bytes"
"flag"
"fmt"
"go/ast"
"go/build"
"go/printer"
"go/token"
"go/types"
"io"
"os"
"regexp"
"strconv"
"strings"
)
var usage = func() {
fmt.Fprint(os.Stderr, `usage: gogrep commands [packages]
gogrep performs a query on the given Go packages.
-r search dependencies recursively too
-tests search test files too (and direct test deps, with -r)
A command is one of the following:
-x pattern find all nodes matching a pattern
-g pattern discard nodes not matching a pattern
-v pattern discard nodes matching a pattern
-a attribute discard nodes without an attribute
-s pattern substitute with a given syntax tree
-p number navigate up a number of node parents
-w write the entire source code back
A pattern is a piece of Go code which may include dollar expressions. It can be
a number of statements, a number of expressions, a declaration, or an entire
file.
A dollar expression consist of '$' and a name. Dollar expressions with the same
name within a query always match the same node, excluding "_". Example:
-x '$x.$_ = $x' # assignment of self to a field in self
If '*' is before the name, it will match any number of nodes. Example:
-x 'fmt.Fprintf(os.Stdout, $*_)' # all Fprintfs on stdout
By default, the resulting nodes will be printed one per line to standard output.
To update the input files, use -w.
`)
}
func main() {
m := matcher{
out: os.Stdout,
ctx: &build.Default,
}
err := m.fromArgs(".", os.Args[1:])
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
type matcher struct {
out io.Writer
ctx *build.Context
fset *token.FileSet
parents map[ast.Node]ast.Node
recursive, tests bool
aggressive bool
// information about variables (wildcards), by id (which is an
// integer starting at 0)
vars []varInfo
// node values recorded by name, excluding "_" (used only by the
// actual matching phase)
values map[string]ast.Node
scope *types.Scope
*types.Info
stdImporter types.Importer
}
type varInfo struct {
name string
any bool
}
func (m *matcher) info(id int) varInfo {
if id < 0 {
return varInfo{}
}
return m.vars[id]
}
type exprCmd struct {
name string
src string
value interface{}
}
type strCmdFlag struct {
name string
cmds *[]exprCmd
}
func (o *strCmdFlag) String() string { return "" }
func (o *strCmdFlag) Set(val string) error {
*o.cmds = append(*o.cmds, exprCmd{name: o.name, src: val})
return nil
}
type boolCmdFlag struct {
name string
cmds *[]exprCmd
}
func (o *boolCmdFlag) String() string { return "" }
func (o *boolCmdFlag) Set(val string) error {
if val != "true" {
return fmt.Errorf("flag can only be true")
}
*o.cmds = append(*o.cmds, exprCmd{name: o.name})
return nil
}
func (o *boolCmdFlag) IsBoolFlag() bool { return true }
func (m *matcher) fromArgs(wd string, args []string) error {
m.fset = token.NewFileSet()
cmds, args, err := m.parseCmds(args)
if err != nil {
return err
}
pkgs, err := m.load(wd, args...)
if err != nil {
return err
}
var all []ast.Node
for _, pkg := range pkgs {
m.Info = pkg.TypesInfo
nodes := make([]ast.Node, len(pkg.Syntax))
for i, f := range pkg.Syntax {
nodes[i] = f
}
all = append(all, m.matches(cmds, nodes)...)
}
for _, n := range all {
fpos := m.fset.Position(n.Pos())
if strings.HasPrefix(fpos.Filename, wd) {
fpos.Filename = fpos.Filename[len(wd)+1:]
}
fmt.Fprintf(m.out, "%v: %s\n", fpos, singleLinePrint(n))
}
return nil
}
func (m *matcher) parseCmds(args []string) ([]exprCmd, []string, error) {
flagSet := flag.NewFlagSet("gogrep", flag.ExitOnError)
flagSet.Usage = usage
flagSet.BoolVar(&m.recursive, "r", false, "search dependencies recursively too")
flagSet.BoolVar(&m.tests, "tests", false, "search test files too (and direct test deps, with -r)")
var cmds []exprCmd
flagSet.Var(&strCmdFlag{
name: "x",
cmds: &cmds,
}, "x", "")
flagSet.Var(&strCmdFlag{
name: "g",
cmds: &cmds,
}, "g", "")
flagSet.Var(&strCmdFlag{
name: "v",
cmds: &cmds,
}, "v", "")
flagSet.Var(&strCmdFlag{
name: "a",
cmds: &cmds,
}, "a", "")
flagSet.Var(&strCmdFlag{
name: "s",
cmds: &cmds,
}, "s", "")
flagSet.Var(&strCmdFlag{
name: "p",
cmds: &cmds,
}, "p", "")
flagSet.Var(&boolCmdFlag{
name: "w",
cmds: &cmds,
}, "w", "")
flagSet.Parse(args)
paths := flagSet.Args()
if len(cmds) < 1 {
return nil, nil, fmt.Errorf("need at least one command")
}
for i, cmd := range cmds {
switch cmd.name {
case "w":
continue // no expr
case "p":
n, err := strconv.Atoi(cmd.src)
if err != nil {
return nil, nil, err
}
cmds[i].value = n
case "a":
m, err := m.parseAttrs(cmd.src)
if err != nil {
return nil, nil, fmt.Errorf("cannot parse mods: %v", err)
}
cmds[i].value = m
default:
node, err := m.parseExpr(cmd.src)
if err != nil {
return nil, nil, err
}
cmds[i].value = node
}
}
return cmds, paths, nil
}
type bufferJoinLines struct {
bytes.Buffer
last string
}
var rxNeedSemicolon = regexp.MustCompile(`([])}a-zA-Z0-9"'` + "`" + `]|\+\+|--)$`)
func (b *bufferJoinLines) Write(p []byte) (n int, err error) {
if string(p) == "\n" {
if b.last == "\n" {
return 1, nil
}
if rxNeedSemicolon.MatchString(b.last) {
b.Buffer.WriteByte(';')
}
b.Buffer.WriteByte(' ')
b.last = "\n"
return 1, nil
}
p = bytes.Trim(p, "\t")
n, err = b.Buffer.Write(p)
b.last = string(p)
return
}
func (b *bufferJoinLines) String() string {
return strings.TrimSuffix(b.Buffer.String(), "; ")
}
// inspect is like ast.Inspect, but it supports our extra nodeList Node
// type (only at the top level).
func inspect(node ast.Node, fn func(ast.Node) bool) {
// ast.Walk barfs on ast.Node types it doesn't know, so
// do the first level manually here
list, ok := node.(nodeList)
if !ok {
ast.Inspect(node, fn)
return
}
if !fn(list) {
return
}
for i := 0; i < list.len(); i++ {
ast.Inspect(list.at(i), fn)
}
fn(nil)
}
var emptyFset = token.NewFileSet()
func singleLinePrint(node ast.Node) string {
var buf bufferJoinLines
inspect(node, func(node ast.Node) bool {
bl, ok := node.(*ast.BasicLit)
if !ok || bl.Kind != token.STRING {
return true
}
if !strings.HasPrefix(bl.Value, "`") {
return true
}
if !strings.Contains(bl.Value, "\n") {
return true
}
bl.Value = strconv.Quote(bl.Value[1 : len(bl.Value)-1])
return true
})
printNode(&buf, emptyFset, node)
return buf.String()
}
func printNode(w io.Writer, fset *token.FileSet, node ast.Node) {
switch x := node.(type) {
case exprList:
if len(x) == 0 {
return
}
printNode(w, fset, x[0])
for _, n := range x[1:] {
fmt.Fprintf(w, ", ")
printNode(w, fset, n)
}
case stmtList:
if len(x) == 0 {
return
}
printNode(w, fset, x[0])
for _, n := range x[1:] {
fmt.Fprintf(w, "; ")
printNode(w, fset, n)
}
default:
err := printer.Fprint(w, fset, node)
if err != nil && strings.Contains(err.Error(), "go/printer: unsupported node type") {
// Should never happen, but make it obvious when it does.
panic(fmt.Errorf("cannot print node %T: %v", node, err))
}
}
}